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

From: Bengt Richter (bokr_at_oz.net)
Date: 10/31/04


Date: Sun, 31 Oct 2004 03:11:07 GMT

On Sat, 30 Oct 2004 09:02:14 GMT, bokr@oz.net (Bengt Richter) wrote:

>On Sat, 30 Oct 2004 07:48:34 GMT, bokr@oz.net (Bengt Richter) wrote:
>
>>On Sat, 30 Oct 2004 06:07:23 GMT, bokr@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



Relevant Pages

  • Re: tallit katan
    ... I wouldn't say shot down, either, but more of a shot ... >>> For example, I would consider myself a religious Reform Jew, though ... I am actively engaged in my religious practice and study. ... >> Best regards, ...
    (soc.culture.jewish.moderated)
  • Re: McLaughlins Weird, Neurotic Fixation On Foxes & Fox Hunters
    ... Any domestic dog proven to disturb or kill any livestock can be shot. ...
    (soc.genealogy.britain)
  • Re: Unwanted .Net framework dependency
    ... Sometimes a shot in the dark works! ... one library was needlessly set as "managed". ... > Many regards, ...
    (microsoft.public.dotnet.framework)
  • Re: FRS nto Stable [WP]
    ... I'll give t a shot and post here. ... Regards, ... > Doesn't matter if it's in an erroneous state, ...
    (microsoft.public.windows.server.active_directory)
  • Re: Owen
    ... HJ> another shot. ... Little bollox. ... With best regards, pablo. ...
    (uk.sport.football.clubs.liverpool)