Some thougts on cartesian products

Christoph Zwerschke cito at online.de
Sun Jan 22 22:45:50 EST 2006


Jean-Paul Calderone wrote:
> Christoph Zwerschke <cito at online.de> wrote:
>>
>> BTW: What is the shortest way to get the binary representation of a
>> number in Python? Is there really not something like itoa() anywhere in
>> the standard libs?
> 
> I'm somewhat partial to this implementation:
> 
> binary = lambda i,c = (lambda i,c: i and (c(i>>1, c) + str(i&1)) or ''): 
> c(i,c)

Took me some time to understand how it works. If you make a full 
featured itoa out of it, it becomes even more horrible:

itoa = lambda i, radix = 10, c = (lambda i, radix, c: i and (c(i/radix, 
radix, c) + (i % radix < 10 and str(i % radix) or chr(i % radix - 10 + 
ord('A')))) or ''): c(i, radix, c)

 > Fortunately for you, I guess, it looks like Python 2.5 will have
 > either a bin() builtin or a '%b' format character or something like
 > that in order to do this.

Nice. But still no itoa()? There are some use cases for radix 26 and 
radix 36 conversion (e.g. converting long numbers efficiently to 
strings, see also http://en.wikipedia.org/wiki/Base_36). And it would be 
the inverse function of int() which also can handle up to radix 36.

-- Christoph



-- Christoph



More information about the Python-list mailing list