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

Bengt Richter bokr at oz.net
Sun Oct 31 04:28:52 CET 2004


On Sat, 30 Oct 2004 09:02:14 GMT, bokr at oz.net (Bengt Richter) wrote:
[... previous versions ...]

Silly last best shot put the quotient in an unneeded box. Sorry for all the
self-followups. I think I'll call this my best version (so far ;-):

 >>> def number_in_base(x, N=10, digits='0123456789ABCDEF'):
 ...     return '-'[:x<0]+''.join([digits[r] for q in [abs(x)]
 ...             for q,r in iter(lambda:divmod(q, N), (0,0))][::-1]) or '0'
 ...
 >>> number_in_base( 126, 2)
 '1111110'
 >>> number_in_base(-126, 2)
 '-1111110'
 >>> number_in_base(-126, 8)
 '-176'
 >>> number_in_base(-126,16)
 '-7E'
 >>> number_in_base(   1,16)
 '1'
 >>> number_in_base(   1, 2)
 '1'
 >>> number_in_base(   0, 2)
 '0'

Regards,
Bengt Richter



More information about the Python-list mailing list