"number-in-base" ``oneliner''
Dan Bishop
danb_83 at yahoo.com
Mon Nov 1 00:12:49 EST 2004
Andrea Griffini <agriff at tin.it> wrote in message news:<nl07o0lr3dvunoq2j0avuvmftnc837fvoc at 4ax.com>...
> 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...
That's easy enough to implement ;-)
roman = lambda n: 'M' * (n // 1000) + ('', 'C', 'C', 'CCC', 'CD', 'D',
'DC', 'DCC', 'DCCC', 'CM')[n // 100 % 10] + ('', 'X', 'XX', 'XXX',
'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC')[n // 10 % 10] + ('', 'I', 'II',
'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX')[n % 10]
I'm sure there's a shorter way, though.
More information about the Python-list
mailing list