How do I find out the numbers with same no of digits in a set of given numbers

Given n integers, write an algorithm and the subsequent Python code to print all numbers that are sum-equivalent to the first number. Two numbers and n are said to be sum-equivalent if m and n have the same number of digits and the sum of the digits in and n are equal. 12381 is sum-equivalent to 10545. Here both the numbers are five digit numbers. Sum of the digits in 12381 is 1+2+3+8+1=15. Similarly, the sum of the digits in 10545 is 15.

1 answer

  • answered 2018-11-08 07:50 Rudolf Morkovskyi

    from collections import defaultdict
    a = [12345,124,34567,2346,98985,10545,12381]
    def sum_digits(n):
        s = 0
        while n:
            s += n % 10
            n //= 10
        return s    
    for number in a:
    result=[d[n] for n in sorted(d, reverse=True)]