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

Steven Bethard steven.bethard at gmail.com
Mon Nov 1 02:07:37 EST 2004


Bengt Richter <bokr <at> oz.net> writes:
>
> BTW, will anything that works in a list comprehension work in a generator 
> expression (assuming one does not depend on the generator expression having 
> leftover outside side effect bindings like the LC version)?

Well, I'm not confident enough to say *anything* (though I've used them freely
in my code since 2.4a1 was released and have never had any problems) but they
seem to work for this problem:

>>> def number_in_base(n, b=10, digits='0123456789ABCDEF'):
...     return '-'[:n<0]+''.join(reversed(list(
...         digits[r]                
...         for q in [abs(n)]
...         for q, r in iter(lambda: divmod(q, b), (0, 0))))) or digits[0]
... 
>>> number_in_base(100, 16)
'64'
>>> number_in_base(100, 2)
'1100100'

Of course, you don't really gain anything by doing this with a generator
expression since you have to reverse the list.

In Python 3000, the list(genexp) syntax will be exactly equivalent to a list
comprehension[1], at which point, it won't matter. ;)

Steve

[1] http://www.python.org/peps/pep-3000.html#core-language




More information about the Python-list mailing list