Thursday 17 April 2008

Python homework

As part of a 'Python study group' at work, we were given the following challenge:


Exercise 1:

Write a program that processes a list of numbers from 1 to 100. For each number, if the number is a multiple of 3, print “FIZZ”; if the number is a multiple of 5, print “BANG”; otherwise, print the number.

You are *NOT* allowed to use any *IF/ELSE* statements in your code. You can use the list-accessing ternary operator hack, but whilst I’ll accept your homework if you do, you’ll miss out on the prize (alcoholic), which goes to the most concise code (not including whitespace).

Have fun!


Here's my final solution:


for i in range(1, 101):
f = (i % 3 == 0) and "FIZZ" or ""
b = (i % 5 == 0) and f + "BANG" or f + ""
n = (len(b) > 0) and b or i
print n

1 comment:

Anonymous said...

Hello,

what about this?
It's a little bit faster.

d={0:'FIZZBANG',3:'FIZZ',5:'BANG',6:'FIZZ',9:'FIZZ',10:'BANG',12:'FIZZ'}
for i in range(1,101): print d.get(i % 15,i)

jarka