Given a list
of integers representing the digits of a number in base b
, how do I convert this list
to an int
for any b
most efficiently?
numlist = [1, 2, 3, 4, 5]
def list2int(numList, b):
if b == 10: return int(''.join(map(str, numList)))
else: ?
print list2int(numList, 7)
>>> 3267
I can only think of the naive approach to do this but this scales really horribly.
def list2int(numList, b):
num = 0
for i, ii in enumerate(numList): num += ii * b**(len(numList) - i - 1)
return num
Are there any better ways?
You could use reduce
:
In [3]: reduce(lambda x,y:7*x+y, numlist)
Out[3]: 3267
where 7
is the base.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With