Search code examples
pythonfunctionsumradix

write a function to get the sum of base n numbers in base n in python


I want to write a function that gets base and some numbers that are in base n as its input and returns sum of the args in base n. I thought I first get the first digit of the numbers and calculate the sum and then the other digit and so on... but the thing is I can't get the second digit and my code just adds the first digit: (n between 2 and 10)

def sum_base(base, *args):
tot = 0
s = "" 

for num in args:
    rem = num % base
    tot += rem
if tot >= base:
    tot = tot % base
    carry = tot // base
s += str(tot)    

num = num // 10

return s


print(sum_base(2, 1111,1111,11111,10111))

could anyone help me modify the code? Thanks


Solution

  • you can do this if you want a solution without library:

    def sum_base(base, *args):
        def numberToBase(n, b):
            if n == 0:
                return [0]
            digits = []
            while n:
                digits.append(int(n % b))
                n //= b
            # at this point, digits[::-1] is the list of digits of n at base b
            return int(''.join(map(str, digits[::-1]))) # convert a list of digits into a int
            
        # first, convert all number to base 10 and take the sum
        sum_base10 = sum([int(str(number), base) for number in args])
        
        # second, convert the base10 sum into base b with the function numberToBase define above
        return numberToBase(sum_base10, base)
    
    
    print(sum_base(2, 1111,1111,11111,10111)) # binary
    print(sum_base(10, 10,12,6,3))            # decimal
    print(sum_base(8, 325, 471))              # octal
    

    output:

    1010100
    31
    1016