写一个函数来获取python中以n为底的n底数的总和

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

我想编写一个函数,获取基数和一些以 n 为基数的数字作为其输入,以及 returns 以 n 为基数的参数总和。我以为我首先得到数字的第一位数字并计算总和然后计算另一个数字等等......但问题是我无法获得第二位数字并且我的代码只是添加第一位数字:(n之间2 和 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))

谁能帮我修改一下代码? 谢谢

我不确定这是否有帮助,因为我不完全清楚你想做什么。

但是如果你想添加数字,我会这样做:

将数字转换为具有给定基数的整数:

int(str(number), base)

这个 returns 一个以 10 为底数的整数。底数必须是数字,数字应该是字符串(或者可以使用 str() 将其转换为字符串)。

然后我会将您的参数中的所有数字相加,或者对整个列表求和。

此后可以使用 numpy 转换回具有给定基数的字符串: https://numpy.org/doc/stable/reference/generated/numpy.base_repr.html.

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

例子:

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'

二进制 111 是以 10 为底数的 7,7 乘以 3 次等于 21(以 10 为底数)等于 1* 1 + 1* 4 + 1* 16 在二进制中 (10101)。

如果你想要一个没有库的解决方案,你可以这样做:

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

输出:

1010100
31
1016