advanced listcomprehenions?
Gabriel Genellina
gagsl-py2 at yahoo.com.ar
Wed Jun 18 18:55:16 EDT 2008
En Wed, 18 Jun 2008 18:42:00 -0300, cirfu <circularfunc at yahoo.se> escribió:
> I am wondering if it is possible to write advanced listcomprehensions.
>
> For example:
> """Write a program that prints the numbers from 1 to 100. But for
> multiples of three print "Fizz" instead of the number and for the
> multiples of five print "Buzz". For numbers which are multiples of
> both three and five print "FizzBuzz"."""
> Obv it doesnt have to be a list according tot hat definition but
> suppose i want to generate that list.
Go to http://groups.google.com/group/comp.lang.python and search for "fizz
buzz"...
> or to generate a lisrt but not by listcomprehsnion:
> map(lambda x: (not x%3 and not x%5 and "FizzBuzz") or (not x%3 and
> "Fizz")
> or (not x%5 and "Buzz") or x, xrange(1,101))
You can translate that into a list comprehension - in general, map(f,
items) is the same as [f(x) for x in items]. We have then:
[(not x%3 and not x%5 and "FizzBuzz") or (not x%3 and "Fizz") or (not x%5
and "Buzz") or x for x in xrange(1,101)]
Quite unreadable IMHO. Just to add another variant to the zillion ones
already posted:
def fb(x):
mult3 = x%3 == 0
mult5 = x%5 == 0
if mult3 and mult5: return "FizzBuzz"
elif mult3: return "Fizz"
elif mult5: return "Buzz"
return str(x)
[fb(x) for x in range(1,101)]
--
Gabriel Genellina
More information about the Python-list
mailing list