On May 11, 4:36 am, Grant Edwards <[EMAIL PROTECTED]> wrote: > On 2008-05-11, John Machin <[EMAIL PROTECTED]> 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 >
Let's not forget to generalise the problem and code it OOP-style :) class FizzBuzzer(object): def __init__(self, *fizzles): self.fizzles = fizzles def translate(self, n): return ''.join(val for (p, val) in self.fizzles if not n%p) or n def range(self, start, stop=None, step=None): if stop is None: start, stop = 0, start if step is None: step = 1 for n in xrange(start, stop, step): yield self.translate(n) def __getitem__(self, obj): if isinstance(obj, slice): return self.range(obj.start, obj.stop, obj.step) else: return self.translate(obj) # FizzBuzzer in action: >>> fizzbuzz = FizzBuzzer((3, 'Fizz'), (5, 'Buzz')) >>> for val in fizzbuzz[1:21]: ... print val ... 1 21 1 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz >>> abc = FizzBuzzer((2, 'Ah'), (3, 'Bee'), (5, 'Cee')) >>> list(abc[25:35]) 25 35 1 ['Cee', 'Ah', 'Bee', 'Ah', 29, 'AhBeeCee', 31, 'Ah', 'Bee', 'Ah'] >>> -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list