This question already has answers here:
Sum the digits of a number
(11 answers)
Write the digits of a number into an array
(4 answers)
Closed 4 months ago.
how to divide num of digit by digit number?
e.g : 4228 is true because 4+2+2+8=16 can divide by 4, 2, 8
3425 false because 3+4+2+5=14 can't divide by 3, 4, 2, 5
numbers = int(input('input number : '))
result = 0
# NUM of digit
while numbers > 0 :
digit = numbers % 10
result = result + digit
numbers = numbers // 10
factors = result
#factors of "NUM of digit"
for factor_result in range(1,factors + 1) :
if factors % factor_result == 0 :
print(factor_result)
please help me;(
thank you a lot:))
A simple way to do it is to calculate the sum of the digits then check if the modulo is 0.
In python, we could parse the number to a str, then convert every digit (which is a single char) back to an int and create a list of these digits
input_numbers = int(input('input number : '))
# parse the number to a str, then map each char back to an integer
# and create a list of int for each digit
numbers = list(map(int, str(input_numbers )))
Now, just use the built-in sum() method to get the result you wish. The next part is just a loop over every digit on the numbers list and check the module.
result = sum(numbers)
is_divisible = True
for number in numbers:
if number == 0 or result % int(number) != 0:
is_divisible = False
print(is_divisible)
From your description it sounds like you want a function like this
# determine if sum of integers comprising an integer is divisible by its part
def divisor_check(num):
# check that input num is integer
if not isinstance(num,int):
print('warning: input is not an integer')
return False
# break num into component integers by convert to string first
stringafied_num = str(num)
# split the string-afied num to get component integers
components = [*stringafied_num]
# evaluate the components to get integers back
components = [eval(v) for v in components]
# sum components
total=sum(components)
# try dividing total by each component
for c in components:
if total%c != 0:
return False
return True
This function breaks up the input into its component integers, sums them, and computes the desired divisor check.
If you evaluate this function for your examples you get the desired results
divisor_check(4228) --> True
divisor_check(3425) --> False
num = 4220
res = [int(x) for x in str(num)]
can_devided = True
for r in res:
if r == 0:
continue
if sum(res) % r != 0:
can_devided = False
print (can_devided)
Related
I need to make a program in Python that do this:
Write a program that, for a given sequence of digits, prints the number of different three-digit even numbers that can be formed from the given digits. When forming each three-digit even number, each element of the sequence of digits can be used at most once.
The first line of the standard input contains the number of digits N, such that 3≤N≤50000. In the second row is N digits separated by one space.
Print only one number to the standard output, the requested number of three-digit numbers.
n=int(input())
num=[]
for i in range (n):
num.append ()
Input
4
2 4 2 2
Output
4
Explanation
From the digits 2, 4, 2, 2, 4 different three-digit even numbers can be formed, namely 222, 224, 242, 422.
This is a general solution that checks all permutations of these digits and print even numbers out of them:
from itertools import permutations
k = 3
c = 0
n = int(input())
num = input().strip().split(" ")
perms = set(permutations(num, k))
for perm in perms:
t = int("".join(perm))
if t % 2 == 0 and len(str(t)) == k:
print(t)
c += 1
print(c)
This is another solution if you don't want to use this generalized approach and just want to solve it for 3 digits:
c = 0
n = int(input())
num = [int(x) for x in input().strip().split(" ")]
r = set()
for i in range(n):
for j in range(n):
for k in range(n):
if i == j or i == k or j == k:
continue
t = num[i] * 100 + num[j] * 10 + num[k]
if t % 2 == 0 and len(str(t)) == 3:
r.add(t)
print(r)
print(len(r))
First You should declare which user input u expect and how to handle false input.
Then the inputString is split into a list of Strings aka inputList. Now You can loop through each of those inputItem and check if they fit your expectations (is int and smaller then 10 ). Since You still deal with String Items You can try to cast ( convert them) into Int. That can fail and a unhandled failure could cripple Your script so it has to happen in an try- catch-block. If the casting works You wanna make sure to check your matchList if You allready added a simular number before You add the new Number to Your matchList.You do so again by looping through each item. If there is mo such number yet there is a last check for if the number is uneven or 0. In that case there is one possible combination less for each number that is 0 or uneven so they are counted in the variable minusOneCombi. That will be substrated from the maximum amount of combinations which is the amount of numbers in you matchList multiplied with itself (pow(2)). Be very careful with the Indentations. In Python they are determining the ends of if blocks and loops.
InputString=(input("Enter your number stream eg 1 0 0 5 ( non numeric signs and numbers greater 9 will be ignored): "))
inputList= inputString.split(‘ ’)
matchList=[]
minusOneCombi= 0
for inputItem in inputList:
try:
anInt= int(inputItem)
except ValueError:
# Handle the exception
print(“item is not an integer and therefore ignored”)
NotYetinMatchList= True
for MatchItem in MatchList:
If matchItem == inputItem:
notYetinMatchList= False
Break
If notYetinMatchList:
matchList.append(anInt)
if ((anInt % 2) != 0) OR (anInt ==0):
minusOneCombi++
NumofMatches=matchList.count()
NumOfMatchesPow= pow(NumofMatches,2)
Result=NumOfMatchesPow -minusOneCombi
Print(Result)
I need to take a number, lets say 6, and then find the smallest 4 digit number, whose digits do not repeat and add up to 6.
For example(These will not add up to the same number):
1023
3045
2345
These numbers are all ok because their digits do not repeat and are four digits
While:
1122
3344
123
These are not ok, because they either are not four digits or their numbers repeat
I'm currently at a roadblock where I can find said four digit number, but one: it is in a list which the program i need to plug this into wont accept and two: the digits aren't in the same order as the answers on the program (ie the smallest four digit number that does not have repeat digits, but adds up to six is 1023, but my program returns 0123, which is incorret.
Here is my current code:
x = 6
Sum = 0
#Find the four digit number
for i in range (999, 10000):
#Find the sum of those numbers
Sum = sum(map(int, str(i)))
#Check if sum is = to x
if Sum == x:
num = i
#Get rid of any identical numbers
result = list(set(map(int, str(num))))
#Make sure the length is 4
if len(result) == 4:
print(result)
#Output [0,1,2,3]
Any help on how I could change this to work for what I want would be great
Using recursive algorithm:
def get_num(n, s, v=""):
for el in range(1 if v=="" else 0, 10):
if str(el) not in v:
temp_sum=sum(int(l) for l in v+str(el))
if(temp_sum>s):
break
elif len(v)==n-1:
if(temp_sum==s):
return v+str(el)
else:
ret=get_num(n, s, v+str(el))
if(ret): return ret
Outputs:
print(get_num(4,6))
>> 1023
I've changed your program to print i instead of result, and break out of the loop when it finds the first number (which logically must be the smallest):
x = 6
Sum = 0
#Find the four digit number
for i in range (999, 10000):
#Find the sum of those numbers
Sum = sum(map(int, str(i)))
#Check if sum is = to x
if Sum == x:
num = i
#Get rid of any identical numbers
result = list(set(map(int, str(num))))
#Make sure the length is 4
if len(result) == 4:
print(i)
break
This program will print 1023.
You could neaten it up a bit by turning it into a function with x as a parameter and returning the result instead of breaking and printing. Also it looks as if the num variable is redundant, you can just stick with i.
Changed your code a little:
x = 6
Sum = 0
result={}
#Find the four digit number
for i in range (999, 10000):
#Find the sum of those numbers
Sum = sum(map(int, str(i)))
#Check if sum is = to x
if Sum == x:
num = i
aux = ''.join(list(set(map(str, str(num)))))
if not aux in result:
result[aux] = []
result[aux].append(i)
for k in result:
print(k, min(result[k]))
You might be interested in itertools package which is designed for solving combinatoric problems like yours.
for n in combinations(range(10),4):
if sum(n)==6 and n[0]!=0:
print(n)
break
combinations method used here returns a generator of all tuples of length 4 that contains distinct digits from 0 to 9, they are sorted alphabetically.
You need to use from itertools import combinations to make it work.
Since you need the smallest integer, you can stop the search at the first encountered with a break:
sum=6 # The sum of digits required.
found=0
for i in range(1000, 10000): # i from 1000 to 9999.
a=i%10;
b=i//10%10
c=i//100%10
d=i//1000%10
if (a!=b)&(a!=c)&(a!=d)&(b!=c)&(b!=d)&(c!=d)&(a+b+c+d==sum):
found=True
break
if found:
print(i)
else:
print('Not found such a number.')
This question already has answers here:
How does one add the digits of a large number?
(3 answers)
Closed 3 years ago.
How would I split an 11 into to 1's to add together?
sums = int(input("Enter page sum: "))
page = 0
page2 = 0
tf = False
while(tf == False):
page = page + 1
page2 = page2 + page
if (page2 == sums):
break
print(page)
This is my current code. I need to change page2 to one digit if it goes over 9
You could turn it into a string, then break it up. For example:
number = 11
[int(c) for c in str(number)]
Or you could do it the mathematical way, with integer division and modulo:
number // 10, number % 10
Both of these give you a sequence of two 1's.
If I understand what you're trying to do properly, you could try this:
sum(n//10 + n%10 for n in range(1, sums + 1))
Which gives 51 when sums is 12. If you want to accept more digits, you'll have to add n // 100 etc as well.
number = int(input("Please input a number: "))
sum = 0
counter = 0 # will count from 1-9, and reset if it goes too far
for n in range(number):
if counter > 9:
counter = 1 # limit the counter
sum += counter
This will count up to the number you input, it will store the sum of the sequence from 1-9 that is managed by the counter.
Hope this is what you are looking for,
sums = int(input("Enter page sum: ")) #Get the input
lst=map(str,list(range(1,sums+1))) #Map int list to string
lst_concat = ''.join(lst) #Merging the elements in the list together
lst2=list(lst_concat) #Make it into a list again
sum(map(int,lst2)) #Sum the elements of the digit
I am trying to implement Luhn algorithm in Python. Here is my code
def validate(n):
if len(str(n)) > 16:
return False
else:
if len(str(n)) % 2 == 0:
for i in str(n[0::2]):
digit = int(str(n[i])) * 2
while digit > 9:
digit = sum(map(int, str(digit)))
dig_sum = sum(map(int, str(n)))
return True if dig_sum % 10 == 0 else False
elif len(str(n)) % 2 != 0:
for i in str(n[1::2]):
digit = int(str(n[i])) * 2
while digit > 9:
digit = sum(map(int, str(digit)))
dig_sum = sum(map(int, str(n)))
return True if dig_sum % 10 == 0 else False
I keep getting the error
TypeError: 'int' object has no attribute '__getitem__
Following is python implementation of Lunh Algorith to detect a valid credit card number. Function takes a number as string and return whether its valid credit card or not.
Its based on the steps mentioned in the following link: https://www.codeproject.com/Tips/515367/Validate-credit-card-number-with-Mod-algorithm
Step 1 - Starting with the check digit double the value of every other digit (right to left every 2nd digit)
Step 2 - If doubling of a number results in a two digits number, add up the digits to get a single digit number. This will results in eight single digit numbers.
Step 3 - Now add the un-doubled digits to the odd places
Step 4 - Add up all the digits in this number
If the final sum is divisible by 10, then the credit card number is valid. If it is not divisible by 10, the number is invalid.
def luhn(ccn):
c = [int(x) for x in ccn[::-2]]
u2 = [(2*int(y))//10+(2*int(y))%10 for y in ccn[-2::-2]]
return sum(c+u2)%10 == 0
#Test
print(luhn("49927398716"))
It is hard to tell without the complete error message, but it is likely because you confused in some places where you put the indexing and where you put the string conversion, for example: for i in str(**n[1::2]**) and digit = int(str(**n[i]**)) * 2
A good way to handle it is to just create a temporary variable n_str = str(n), and use it instead of str(n) over and over again.
I am currently trying to use the luhn method to determine whether a credit card is valid or not in python and here is what I have so far:
print('What is your Credit Card number? :) (please put a space between each number)')
a = [int(x) for x in input().split()]
lengthy = len(a)
print(lengthy)
a.reverse()
print(a)
listx2 = []
listx1 = []
for x in range(len(a)):
modulus = x % 2
print(x, a[x])
if modulus != 0:
listx2.append(a[x]*2)
else:
listx1.append(a[x])
print(listx2)
print(listx1)
I don't know how to do the next step which is getting the sum of all of the digits of the numbers multiplied by two.(listx2) I have looked at different programs with the luhn method but I just can't seem to pick that part out. Thanks!
This is my interpretation of the Luhn algo.
def luhn(sequence):
digits = [int(digit) for digit in str(sequence)] # converts a full string of nums to a list comp of individual numbers
odd = digits[-1::-2] # string stepping (-1) indicates last item in list (-2) means to travel back another 2
even = digits[-2::-2]
checksum = 0
checksum += sum(odd)
evenmod = []
for digit in even:
if digit * 2 > 9:
digit = digit * 2
digit = int(str(digit)[0]) + int(str(digit)[1])
else:digit = digit * 2
evenmod.append(digit)
checksum += sum(evenmod)
if checksum % 10 == 0:
return True
else:
return False
print luhn(378282246310005)
print luhn(111111111111111)
print luhn(4751290083628479)
print luhn(5573485043994670)
Separate the even and the odd indeces to separate lists, then use a for statement to loop through the list, multiplying the list entries by two.
Notice the if statement that catches the issue with (e.g) 8 * 2 = 16.
Use sum:
summed_x2 = sum(listx2)