"number-in-base" ``oneliner''
Bengt Richter
bokr at oz.net
Sat Oct 30 05:02:14 EDT 2004
On Sat, 30 Oct 2004 07:48:34 GMT, bokr at oz.net (Bengt Richter) wrote:
>On Sat, 30 Oct 2004 06:07:23 GMT, bokr at oz.net (Bengt Richter) wrote:
>[...]
>>Maybe something useful in this? Not very tested (and not terribly clear either ;-)
>>
>> >>> def number_in_base(x, N, digits):
>> ... return x==0 and digits[0] or '-'[:x<0] + ''.join([d for d in iter(
>> ... lambda qr=[abs(x),0]:qr[0] and (
>> ... qr.__setslice__(0,2,divmod(qr[0],N)) or digits[qr[1]])
>> ... , 0)][::-1])
>> ...
>
>Alternatively, a little more compactly (though I feel guilty about the -1 ;-):
>
> >>> def number_in_base(x, N=10, digits='0123456789ABCDEF'):
> ... return '-'[:x<0] + ''.join(list(iter(lambda qr=[abs(x),-1]: (qr[0] or qr[1]<0) and (
> ... qr.__setslice__(0,2,divmod(qr[0],N)) or digits[qr[1]]), False))[::-1])
> ...
Yet another, prefixing digits instead of joining reversed list:
>>> def number_in_base(x, N=10, digits='0123456789ABCDEF'):
... return '-'[:x<0]+reduce(lambda s,c:c+s, iter(lambda qr=[abs(x),-1]: (qr[0] or qr[1]<0)
... and (qr.__setslice__(0,2,divmod(qr[0],N)) or digits[qr[1]]), False))
...
>>> number_in_base( 0 , 2, '01')
'0'
>>> number_in_base( 1 , 2, '01')
'1'
>>> number_in_base(126, 2, '01')
'1111110'
>>> number_in_base(-126, 2, '01')
'-1111110'
Regards,
Bengt Richter
More information about the Python-list
mailing list