The FizzBuzz test is described here: http://c2.com/cgi/wiki?FizzBuzzTest
"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”."I'll implement a solution using slice assignment to demonstrate how it works.
Solution
Start with a list of numbers.
fizzbuzz = list(range(101))
Replace every multiple of 3 with the word "Fizz'. The length of the slice tells us how many replacement values we need,
fizzbuzz[3::3] = ['Fizz'] * len(fizzbuzz[3::3])
Do the same for the multiples of 5 and 15.
fizzbuzz[5::5] = ['Buzz'] * len(fizzbuzz[5::5])
fizzbuzz[15::15] = ['FizzBuzz'] * len(fizzbuzz[15::15])
Now print the results (skipping the first value of 0)
for i in fizzbuzz[1:]:
print(i)
You can paste this code into Python Tutor if you want to step through it line by line.
You can paste this code into Python Tutor if you want to step through it line by line.
Other solutions
Compare this solutions to others you might have seen. For example
for n in range(1, 101): line = "" if n%3 == 0: line = line + "Fizz" if n%5 == 0: line = line + "Buzz" if line: print line else: print n
Which one do you prefer? Why?
What if I told you the slice based solution runs 6X faster? Does that change your opinion?
You can find more tips and tricks in my book Mastering Python Lists.
No comments:
Post a Comment