advanced listcomprehenions?
Terry Reedy
tjreedy at udel.edu
Thu Jun 19 21:29:53 EDT 2008
Duncan Booth wrote:
> Mark Wooding <mdw at distorted.org.uk> wrote:
>
>> This is still inelegant, though. We can glue the results mod 3 and 5
>> together using the Chinese Remainder Theorem and working mod 15
>> instead. For example,
>>
>> [['Fizz', 'FizzBuzz', False, None, 'Buzz'][(pow(i, 4, 15) + 1)%7] or
>> str(i) for i in xrange(1, 101)]
The lookup table is a constant. If made a tuple, it will be compiled as
a constant (as least in 2.6, maybe 2.5). In any case, it could (and to
me should) be lifted out of the string comp.
>>
>> (A less mathematical approach would just use i%15 to index a table. But
>> that's not interesting. ;-) )
>>
>
> Ooh. Doesn't having 5 elements make you shudder? (Even though you did
> change one to avoid a repeated value.) You have 4 options for output, so
> for elegance that list should also have 4 elements:
>
> [[str(i), 'FizzBuzz', 'Fizz', 'Buzz'][25/(pow(i, 4, 15) + 1)%4] for i in
> xrange(1, 101)]
>
> I feel it is even more elegant with the lookup table in its natural order:
>
> [['Fizz', 'Buzz', 'FizzBuzz', str(i)][62/(pow(i, 4, 15) + 1)%4] for i in
> xrange(1, 101)]
These make the lookup table variable, so it has to be recalculated for
each i.
tjr
More information about the Python-list
mailing list