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

Alex Martelli aleaxit at yahoo.com
Sat Oct 30 10:37:06 CEST 2004

<exarkun at divmod.com> wrote:
> > 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])
>   range(maxlen) can be replaced with range(int(math.log(x) / math.log(N))
+ 1).

Right!  I had missed that because I was focusing on builtin names only.

>   Also, and perhaps you are already aware, number_in_base(x, 1, '0')

Yes, I was aware that the pre condition N>=2 (as well as other
preconditions, such as len(digits) >= N) are not checked; sorry for not
making that clear.

> doesn't produce the correct output with the above algorithm, although I
> believe it will if you switch to using math.log().

With math.log it raises a ZeroDivisionError -- arguably more correct
than a bunch of 0's, yes.  It's interesting that the math.log
application does catch such errors as N<2;-).


More information about the Python-list mailing list