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

From: Andrea Griffini (agriff_at_tin.it)
Date: 10/30/04


Date: Sat, 30 Oct 2004 12:12:36 GMT

On Fri, 29 Oct 2004 23:34:42 GMT, exarkun@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