do you fail at FizzBuzz? simple prog test

Grant Edwards grante at visi.com
Sat May 10 23:36:36 EDT 2008


On 2008-05-11, John Machin <sjmachin at lexicon.net> wrote:

>> "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".
>> 
>> for i in range(1,101):
>>     if i%3 == 0 and i%5 != 0:
>>         print "Fizz"
>>     elif i%5 == 0 and i%3 != 0:
>>         print "Buzz"
>>     elif i%5 == 0 and i%3 == 0:
>>         print "FizzBuzz"
>>     else:
>>         print i
>> 
>> 
>> is there a better way than my solution? is mine ok?
>
> Try doing it using %3 and %5 only once each.

for i in xrange(101):
    print (("","Fizz")[i%3==0] + ("","Buzz")[i%5==0]) or str(i)

His is better though, since it's more obvious what's intended.

Here's one that's less opaque

for i in xrange(101):
    s = ""
    if i%3 == 0: s += "Fizz"
    if i%5 == 0: s += "Buzz"
    if s:
        print s
    else:
        print i
        
There are dozens of other ways to do it.
-- 
Grant Edwards                   grante             Yow!  ... or were you
                                  at               driving the PONTIAC that
                               visi.com            HONKED at me in MIAMI last
                                                   Tuesday?



More information about the Python-list mailing list