"number-in-base" ``oneliner''
Bengt Richter
bokr at oz.net
Sat Oct 30 23:11:07 EDT 2004
On Sat, 30 Oct 2004 09:02:14 GMT, bokr at oz.net (Bengt Richter) wrote:
>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))
> ...
My best shot so far (unless I goofed ;-):
>>> def number_in_base(x, N=10, digits='0123456789ABCDEF'):
... return '-'[:x<0]+''.join([digits[r] for x in [[abs(x)]]
... for x[0],r in iter(lambda:divmod(x[0], 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