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

exarkun at divmod.com exarkun at divmod.com
Sat Oct 30 01:34:42 CEST 2004


On Fri, 29 Oct 2004 23:58:47 +0200, aleaxit at yahoo.com (Alex Martelli) wrote:
>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'...:-(

  range(maxlen) can be replaced with range(int(math.log(x) / math.log(N)) + 1).

  Also, and perhaps you are already aware, number_in_base(x, 1, '0') doesn't produce the correct output with the above algorithm, although I believe it will if you switch to using math.log().

  Jp



More information about the Python-list mailing list