Answer to Question #275891 in Python for Happpy

Question #275891

Magic number: If the summation of even indexed digits is equal to the summation of odd indexed digits, then the number is

a magic number.

Now, write a Python program that will take a string of numbers where each number is separated by a comma. The program should

print a tuple containing two sub-tuples, where the first sub-tuple will hold the magic numbers and the second sub-tuple will hold

the non-magic numbers.

Sample Input1:

"1232, 4455, 1234, 9876, 1111"

Sample Output1:

((1232, 4455, 1111), (1234, 9876))



1
Expert's answer
2021-12-05T11:22:21-0500
def is_magic(x):
    x =abs(x)
    even_sum = 0
    odd_sum = 0
    odd = True
    while x > 0:
        d = x % 10
        x = x // 10
        if odd:
            odd = False
            odd_sum += d
        else:
            odd = True
            even_sum += d
    return odd_sum == even_sum

def separate_num(line):
    L = [int(s) for s in line.split(',')]
    magic = []
    non_magic = []
    for x in L:
        if is_magic(x):
            magic.append(x)
        else:
            non_magic.append(x)
    return tuple(magic), tuple(non_magic)

def main():
    line = input()
    result = separate_num(line)
    print(result)

if __name__ == '__main__':
    main()

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS