Re: "number-in-base" ``oneliner''
From: Alex Martelli (aleaxit_at_yahoo.com)
Date: 10/30/04
- Next message: Arun Sivakumaran: "Re: running a python script in the background"
- Previous message: Alex Martelli: "Re: New to Python: Features"
- In reply to: exarkun_at_divmod.com: "Re: "number-in-base" ``oneliner''"
- Next in thread: Andrea Griffini: "Re: "number-in-base" ``oneliner''"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Sat, 30 Oct 2004 10:37:06 +0200
<exarkun@divmod.com> wrote:
...
> > def number_in_base(x, N, digits, maxlen=99):
> > return '-'[x>=0:] + (
> > (x and ''.join([digits[k%N] for i in range(maxlen)
> > for k in [abs(x)//N**i] if k>0])[::-1]
> > ) or digits[0])
...
> range(maxlen) can be replaced with range(int(math.log(x) / math.log(N))
+ 1).
Right! I had missed that because I was focusing on builtin names only.
Thanks!
> Also, and perhaps you are already aware, number_in_base(x, 1, '0')
Yes, I was aware that the pre condition N>=2 (as well as other
preconditions, such as len(digits) >= N) are not checked; sorry for not
making that clear.
> doesn't produce the correct output with the above algorithm, although I
> believe it will if you switch to using math.log().
With math.log it raises a ZeroDivisionError -- arguably more correct
than a bunch of 0's, yes. It's interesting that the math.log
application does catch such errors as N<2;-).
Alex
- Next message: Arun Sivakumaran: "Re: running a python script in the background"
- Previous message: Alex Martelli: "Re: New to Python: Features"
- In reply to: exarkun_at_divmod.com: "Re: "number-in-base" ``oneliner''"
- Next in thread: Andrea Griffini: "Re: "number-in-base" ``oneliner''"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]