1

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

Yasaman Shokri
  • 145
  • 1
  • 1
  • 11

2 Answers2

3

I am not sure if this helps, since it is not entirely clear to me what you want to do.

But if you want to add numbers this is what I would do:

Convert number to integer with given base:

int(str(number), base)

This returns an integer with base 10. The base has to be a number and number should be a string (or one can convert it to string using str()).

Then I would add all numbers in your arguments, or sum the whole list.

Thereafter one can use numpy to convert back to a string with a given base: https://numpy.org/doc/stable/reference/generated/numpy.base_repr.html.

import numpy as np
np.base_repr(sum, base=base)

The example:

def sum_base(base, *args):
    l = [int(str(num), base) for num in args]
    return np.base_repr(sum(l), base=base)

sum_base(2, 111, 111, 111)
'10101'

binary 111 is 7 with base 10, three times 7 is 21 (in base 10) which equal 1* 1 + 1* 4 + 1* 16 in binary (10101).

3dSpatialUser
  • 2,034
  • 1
  • 9
  • 18
0

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
patate1684
  • 639
  • 3
  • 17