Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

list of arbitrary-base digits to int

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?

like image 807
Marcel Tesch Avatar asked Feb 14 '23 19:02

Marcel Tesch


1 Answers

You could use reduce:

In [3]: reduce(lambda x,y:7*x+y, numlist)
Out[3]: 3267

where 7 is the base.

like image 197
NPE Avatar answered Feb 17 '23 01:02

NPE