|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +# This One Liner solution to the Fizz Buzz problem |
| 4 | +# was found by a student on the internet |
| 5 | + |
| 6 | +for i in range(1,101): print([i,'Fizz','Buzz','FizzBuzz'][(i%3==0)+2*(i%5==0)]) |
| 7 | + |
| 8 | +# this is a good example of why the most compact code is not always the |
| 9 | +# best -- readability counts! |
| 10 | +# And this is pretty impenatrable. |
| 11 | +# but it's also pretty nifty logic, so below, |
| 12 | +# It's unpacked to make it easeir to understand. |
| 13 | + |
| 14 | +# first, add some white space to make it pep8 compatible, and more readable. |
| 15 | + |
| 16 | +for i in range(1, 101): print([i, 'Fizz', 'Buzz', 'FizzBuzz'][(i % 3 == 0) + 2 * (i % 5 == 0)]) |
| 17 | + |
| 18 | +# second, take the for loop off one line -- that really makes no difference: |
| 19 | + |
| 20 | +for i in range(1, 101): |
| 21 | + print([i, 'Fizz', 'Buzz', 'FizzBuzz'][(i % 3 == 0) + 2 * (i % 5 == 0)]) |
| 22 | + |
| 23 | +# so we are looping through the numbers, and the contents of the print() |
| 24 | +# is deciding what to print for i |
| 25 | + |
| 26 | +# unpack that line: |
| 27 | + |
| 28 | +for i in range(1, 101): |
| 29 | + options_to_print = [i, 'Fizz', 'Buzz', 'FizzBuzz'] |
| 30 | + index = 0 # default index is zero |
| 31 | + index += (i % 3 == 0) # add one to index if it's a multiple of 3 |
| 32 | + index += (2 * (i % 5 == 0)) # add two to the index if a multiple of 5 |
| 33 | + print(options_to_print[index]) # print the selection. |
| 34 | + |
| 35 | +# there are 4 possible options that might get printed on each line: |
| 36 | +# 1) the number, i |
| 37 | +# 2) Fizz |
| 38 | +# 3) Buzz |
| 39 | +# 4) FizzBuzz |
| 40 | + |
| 41 | +# we now need an index to pick which of these to print |
| 42 | +# |
| 43 | +# remember that True and False are also the integers 1 and 0: |
| 44 | +# so (i % 3 == 0) will return 1 (True) if i is a multiple of 3 |
| 45 | +# and 0 (False) if not |
| 46 | +# and (i % 5 == 0) will do the same for 5 |
| 47 | +# so (2 * (i % 5 == 0)) will return either 0 or 2 |
| 48 | +# |
| 49 | +# so if the number is a multiple of neither, index will be zero, |
| 50 | +# and we'll get the zeroth element of the list: i |
| 51 | +# |
| 52 | +# if i is a multiple of three (i % 3 == 0), then the index will be 1 |
| 53 | +# |
| 54 | +# and if i is a multiple of 5 the index will then be 3 (1+2) |
| 55 | +# if it wasn't a multiple of three, then it will be 2 (0+2) |
| 56 | +# |
| 57 | +# so using the index will get the right element from the options list. |
| 58 | +# |
| 59 | +# pretty slick! |
0 commit comments