advanced listcomprehenions?
Duncan Booth
duncan.booth at invalid.invalid
Thu Jun 19 14:54:31 CEST 2008
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)]
>
> (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)]
:)
--
Duncan Booth http://kupuguy.blogspot.com
More information about the Python-list
mailing list