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

Andrea Griffini agriff at tin.it
Sat Oct 30 08:12:36 EDT 2004


On Fri, 29 Oct 2004 23:34:42 GMT, exarkun at divmod.com wrote:

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

Log accepts the base as second argument.

def number_in_base(x, N=10, digits="0123456789ABCDEF"):
    return '-'[x>=0:]+"".join(
     [digits[abs(x)/N**i%N]
      for i in xrange(1+int(math.log(abs(x)+1,N)))
      if N**i<=abs(x)][::-1]) or digits[0]

>  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().

It doesn't handle roman numerals either... but so ?
You can't count using base 1 with positional systems.

Andrea



More information about the Python-list mailing list