"number-in-base" ``oneliner''

Alex Martelli aleaxit at yahoo.com
Fri Oct 29 23:58:47 CEST 2004

I hesitate a bit to post this, but... on the Italian Python NG, somebody
was asking whether there was any way to convert an integer number x into
a string which represents it in an arbitrary base N (given a sequence
with a len of N that gives the digits to use) as "a single expression".

I haven't found a really general way, much less a clear one, but, the
best I have so far is...:

def number_in_base(x, N, digits, maxlen=99):
    return '-'[x>=0:] + (
        (x and ''.join([digits[k%N] for i in range(maxlen) 
                        for k in [abs(x)//N**i] if k>0])[::-1]
        ) or digits[0])

Besides the lack of clarity, the obvious defect of this approach is that
darned 'maxlen' parameter -- but then, since I can have only a 'for',
not a 'while', in a list comprehension or generator expression, and I
don't think recursion qualifies as 'a single expression'...:-(

Anyway, improvements and suggestions welcome, thanks!


More information about the Python-list mailing list