1
votes

I would like to double the value of every second digit and then add up the digits that are in their tens. Finally adding all the digits together E.g: 123456789 -> 1 4 3 8 5 12 7 16 9 -> 1 4 3 8 5 3 7 7 9 -> 47

edit: the user would input any number and the function would still work eg: 5153 -> 5 2 5 6 -> 18

-SORRY first post I'm still getting used to this- So I would like my function to
1. Reverse the inputted number
2. Double the value of the second digit
3. Sum all the digits together
4. Check if it's divisible by 7

Here is my code so far

my testing
def checksum(num):

#print(rev)
odd_digit = ""
even_digit = ""
even_sum = 0
odd_sum = 0
total_sum = 0

if num < 10 and num != 7:
    return False
else:
    return True

rev = (num[::-1])
for i in range(len(rev)):
    if i % 2 == 0:
        odd_digit += rev[i]
    else:
        even_digit += rev[i]

#print(even_digit)
even_digit = int(even_digit)
while even_digit > 0:
    even_digit, even_sum = even_digit//10,even_sum+(even_digit%10)
#print(even_sum)
even_sum_2 = even_sum * 2
#print(even_sum_2)

odd_digit = int(odd_digit)
while odd_digit > 0:
    odd_digit, odd_sum = odd_digit//10,odd_sum+(odd_digit%10)
#print(odd_sum)

total_sum = even_sum_2 + odd_sum
#print(total_sum)

if total_sum % 7 == 0:
    return True
else:
    return False

print(checksum(12345678901))

2
Please provide python code you have tried so far - Chris
According to the question statement step 1: double the second digit then if input is 123456789 this should be 1 4 3 8 5 12 7 16 9 . But you have mentioned 14 instead of 16. - user5777975

2 Answers

2
votes

Try using this sum with a map, and a list comprehension:

>>> sum(map(int,''.join([str(int(v)*2) if i%2 else v for i,v in enumerate(s)])))
47

Or use:

>>> sum([sum(map(int,str(int(v)*2))) if i%2 else int(v) for i,v in enumerate(s)])
47
0
votes
sum([sum(map(int, str(i * 2))) if i % 2 == 0 else i for i in range(1, 10)])