You could use reduce
:
In [3]: reduce(lambda x,y:7*x+y, numlist)
Out[3]: 3267
where 7
is the base.
Question
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?
Solution
You could use reduce
:
In [3]: reduce(lambda x,y:7*x+y, numlist)
Out[3]: 3267
where 7
is the base.
OTHER TIPS
You can pass the base to int()
, but this will work only up to base 36:
>>> int(''.join(map(str, numlist)), 7)
3267
>>> int(''.join(map(str, numlist)), 15)
58115
>>> int(''.join(map(str, numlist)), 36)
1776965