Fizz Bang python coding challenge
Very late, I know, but finally I sat down to the Python focus group homework which T4 started to run recently. The first challenge was:
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).
I started with implementation which uses IF statements just to get a feel for the problem and then I moved to a solution using datastructures, starting with the dictionary where key mapped to a function. Something like:
dict = {
1: f x: x,
2: f x: x,
3: f x: 'FIZZ',
4: f x: x,
5: f x: 'BANG',
6: f x: 'FIZZ',
7: f x: x,
8: f x: x,
9: f x: 'FIZZ',
10: f x: 'BANG'
}
Each key would map to a function which returns a correct value for that index. Then for a given index we could print the value as follows:
print dict[n](n)
It works for numbers from 1 to 10 only but as first cut that’s ok. You can see straight away that mapping to function is not really needed. Simple values in an array would be enough. Now we have to only make it more robust and use modulo on the value. After some time of struggling I got to this outcome (which is very similar to Kerry’s and Nigel’s solutions):
for n in range(1, 101):
print ['FIZZ','',''][n%3] + ['BANG','','','',''][n%5] or n
There is already a second challenge waiting.
Popularity: 34% [?]
