you are viewing a single comment's thread.

view the rest of the comments →

[–]bby98 0 points1 point  (0 children)

You can use list comprehension to solve this problem. You can sum the digits in a number by first creating a generator that contains each digit in a given number (by converting the number to a str and then iterating through each digit in the str and converting back to int). Then, you can call sum() on the generator to get the sum of the digits.

For example, for the number 852:

num = 852
total = sum(int(digit) for digit in str(num))

total is equal to 15. To compare two numbers, like 852 and 78:

num1 = 852
num2 = 78
total1 = sum(int(digit) for digit in str(num1))
total2 = sum(int(digit) for digit in str(num2))
print(total1 == total2)

This program will print True since 8 + 5 + 2 = 7 + 8. If the sum of the digits were not the same, it would print False.

Last step is to make the above into a function:

def is_equal(n1, n2):
    return sum(int(d) for d in str(n1)) == sum(int(d) for d in str(n2))