4

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?

Marcel Tesch
  • 184
  • 3
  • 15
  • See http://stackoverflow.com/questions/2267362/convert-integer-to-a-string-in-a-given-numeric-base-in-python – mockinterface Feb 14 '14 at 14:41
  • @mockinterface: that looks like the opposite of what the OP is trying to do... – Wooble Feb 14 '14 at 14:43
  • how do you define the representation of a number in an arbitrary base (especially if the base is > 10) on digits ? – njzk2 Feb 14 '14 at 14:47

2 Answers2

5

You could use reduce:

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

where 7 is the base.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
3

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
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • 1
    Considering you can't represent the digits of a base higher than 10 as single-digit `int`s to begin with, only going up to base 36 is hardly a problem :) – Wooble Feb 14 '14 at 14:42
  • And what do single-digit ints have to do with the question? His input is a list of arbitrary integer coefficients. – Hyperboreus Feb 14 '14 at 14:49