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
Related
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)
This question already has answers here:
How to make loop repeat until the sum is a single digit?
(10 answers)
Closed 9 months ago.
num = 15
split = ([int(single) for single in str(num)])
total = 0
iteration = 0
while iteration < len(split):
total = total + split[iteration]
iteration += 1
print(total)
I'm trying to write this program where an input is given (ex. 74837)
The number would be split into individual digits within a list [7,4,8,3,7]
It would then be added (29), then split again [2,9], and then added again until the sum is under 10, so 11, [1,1], finally turning into 2 as the final number
Any help would be awesome. :)
I think that I've figured out splitting and adding, but splitting and adding again until below 10, is confusing me.
It's a simple while loop:
n = 23452436
while n >= 10:
print(n)
n = sum(int(i) for i in str(n))
print(n)
This is a suitable place to use a recursive method.
def digit_sum(n: int):
curr_sum = sum(int(digit) for digit in str(n))
if curr_sum < 10:
return curr_sum
else:
return digit_sum(curr_sum)
Here's a fun iterative way to do it without any string conversion:
num = 15
def boilItDown(num):
while num >= 10:
total = 0
while num:
d, m = divmod(num, 10)
num, total = d, total + m
num = total
return num
Test code:
print(boilItDown(15))
print(boilItDown(155))
print(boilItDown(1555))
print(boilItDown(15555))
print(boilItDown(155555))
print(boilItDown(1555555))
print(boilItDown(15555555))
Output:
6
2
7
3
8
4
9
I was just trying to calculate the arithmetic median of a list. Odd list length works but my program has problems with even list length.
here's an example:
The example for the even numbers
Here is what I tried:
#the sorted list
number = int(input('How many numbers do you want to put in? '))
print("")
values = []
for i in range(number):
values.append(int(input('Please enter a value: ')))
print("")
sort = sorted(values)
print("Sorted list:", sort)
#the function
firstMid = int(len(sort)) / 2
secoundMid = (int(len(sort)) / 2) + 1
if isOdd(len(values)) == True:
print("Zentralwert:", values[int(len(sort)/2)]) #odd numbers
else:
print("Zentralwert:", (firstMid + secoundMid) / 2)
It seems you are trying to find median.
For odd numbers, it's the middle number.
[1,2,3,4,5,6,7,8,9] -> Median is 5 at index 4 means index = len(arr) // 2 # // is integer division in python and returns floor value. So 9/2 = 4.5 but 9//2 = 4
Now for even numbers, median would be mean of middle two numbers ie (4+5)/2.
Now here we need to target the correct elements using correct index.
For 8 elements, the correct number would be at index len(arr)//2 8//2 = 4 and len(arr)//2 - 1 8//2 -1 = 4-1=3
Your code should now be this.
#the function
firstMidIndex = int(len(sort)) // 2
secoundMidIndex = (int(len(sort)) // 2) - 1
if isOdd(len(values)) == True:
print("Zentralwert:", sort[firstMidIndex] #odd numbers
else:
print("Zentralwert:", (sort[firstMidIndex] + sort[secoundMidIndex]) / 2)
Probably you want,
#the sorted list
number = int(input('How many numbers do you want to put in? '))
print("")
values = []
for i in range(number):
values.append(int(input('Please enter a value: ')))
print("")
sort = sorted(values)
print("Sorted list:", sort)
#the function
firstMid = int(len(sort)) / 2
secoundMid = (int(len(sort)) / 2) + 1
if isOdd(len(values)) == True:
print("Zentralwert:", sort[int(len(sort)/2)]) #odd numbers
else:
print("Zentralwert:", (sort[firstMid] + sort[secoundMid]) / 2)
I am trying to get all of the even numbers from the list, using two nested loops and using str(). My code works, just not how I am intending it to and it is short of what I am looking for.
def evnNmbr ():
a = int(input("Enter 1st integer (lower) "))
b = int(input("Enter 2nd integer (higher) "))
evnCnt = 0
for i in range (a, b):
if i % 2 == 0:
evnCnt += 1
s = str(i)
print("Even number count is , ", s, evnCnt)
evnNmbr()
Ex
Enter 1st integer (lower) 0
Enter 2nd integer (higher) 21
Even number count is , 0 1
Even number count is , 2 2
Even number count is , 4 3
Even number count is , 6 4
Even number count is , 8 5
Even number count is , 10 6
Even number count is , 12 7
Even number count is , 14 8
Even number count is , 16 9
Even number count is , 18 10
Even number count is , 20 11
I would like to get the total number of even numbers between the range of numbers a and b. ie: (2, 4, 6, 8 = 4 even numbers
You just need to print the result evn_cnt once at the end
def evnNmbr():
a = int(input("Enter 1st integer (lower) "))
b = int(input("Enter 2nd integer (higher) "))
evn_cnt = 0
for i in range(a, b):
if i % 2 == 0:
evn_cnt += 1
print("Even number count is", evn_cnt)
See
Enter 1st integer (lower) 10
Enter 2nd integer (higher) 88
Even number count is 39
This is going to be your simplest solution
def find_evens(a,b):
l = []
for i in range(a,b):
if i % 2 == 0:
l.append(i)
answer = len(l)
return answer
print(find_evens(1,21))
I added range of b + 1, because the range function excludes the last value, so if you put an even number at the end it wouldn't count. The only thing you have to modify really is to print separately the evnCnt variable, so it only shows the total value.
def evnNmbr ():
a = int(input("Enter 1st integer (lower) "))
b = int(input("Enter 2nd integer (higher) "))
evnCnt = 0
for i in range (a, (b + 1)):
if i % 2 == 0:
evnCnt += 1
# s = str(i)
# print("Even number count is , ", s)
# if you still want to visualize every number separately you can uncomment the lines
print(f"Even number count is: {evnCnt}")
evnNmbr()
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)