09-10-2020, 05:52 AM
Python One Line FizzBuzz
The FizzBuzzproblem is a common exercise posed in code interviews to test your proficiency in writing simple Python code.
Problem: Print all numbers from 1-100 to the shell with three exceptions:
Example: The first 15 numbers of the FizzBuzz sequence are the following.
How to write a Python one-liner that solves this problem?
Here’s an interactive overview:
https://repl.it/@finxter/RashMintyConstants?lite=true
Exercise: Do both one-liners produce the same results? Run the code to check!
Let’s dive into those one-liners to gain a deeper understanding and improve your Python skills!
FizzBuzz One-Liner 1: Generator Expression + String Concatenation + Short Circuiting
The following one-liner solves the problem in an elegant way using a fine understanding of more advanced Python features (source).
The one-liner creates a string using the function with the newline character as a delimiter. Here’s a short explanation of the function:
The method concatenates all the string elements in the (such as a list, string, or tuple) and returns the result as a new string. The on which you call it is the delimiter string—and it separates the individual elements. For example, returns the joined string .
So, what’s the iterable, you pass into the function? It’s a generator expression of the form: . You go over all integer values in the context 1 to 100 using the function. So, you obtain the remaining . What’s the expression part?
It consists of three elements:
A very interesting implementation of the FizzBuzz problem indeed!
FizzBuzz One-Liner 2: Slicing
An alternative is given in the following nice one-liner (source):
Wow—what a short and concise one-liner solution! But how does it work?
Slicing is a concept to carve out a substring from a given string. Use slicing notation to access every -th element starting from index (included) and ending in index (excluded). All three arguments are optional, so you can skip them to use the default values (, , ). For example, the expression from string carves out the slice and the expression carves out the slice .
In the example, you have the slicing operation.
So, there are four cases:
Phew! This was a hard nut to crack, wasn’t it?
Python One-Liner 3: Map + Lambda
You can find detailed tutorials on the map and lambda functions here:
Those two functions can be used to solve the FizzBuzz problem (source):
It’s similar to Method 1 and by now you’re able to figure it out. Think of the different values the integer can take.
Python One-Liners Book
Python programmers will improve their computer science skills with these useful one-liners.
![[Image: 3D_cover-1024x944.jpg]](https://blog.finxter.com/wp-content/uploads/2020/06/3D_cover-1024x944.jpg)
Python One-Linerswill teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.
The book’s five chapters cover tips and tricks, regular expressions, machine learning, core data science topics, and useful algorithms. Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments. You’ll also learn how to:
• Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
• Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
• Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
• Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
• Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting
By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.
Get your Python One-Liners Now!!
The FizzBuzzproblem is a common exercise posed in code interviews to test your proficiency in writing simple Python code.
Problem: Print all numbers from 1-100 to the shell with three exceptions:
- For each number divisible by three you print ,Code:
"Fizz"
- For each number divisible by five you print , andCode:
"Buzz"
- For each number divisible by three and five you print .Code:
"FizzBuzz"
Example: The first 15 numbers of the FizzBuzz sequence are the following.
Code:
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
...How to write a Python one-liner that solves this problem?
Here’s an interactive overview:
https://repl.it/@finxter/RashMintyConstants?lite=true
Exercise: Do both one-liners produce the same results? Run the code to check!
Let’s dive into those one-liners to gain a deeper understanding and improve your Python skills!
FizzBuzz One-Liner 1: Generator Expression + String Concatenation + Short Circuiting
The following one-liner solves the problem in an elegant way using a fine understanding of more advanced Python features (source).
Code:
print('\n'.join('Fizz' * (i%3==0) + 'Buzz' * (i%5==0) or str(i) for i in range(1,101)))The one-liner creates a string using the
Code:
joinThe
Code:
string.join(iterable)Code:
iterableCode:
stringCode:
'-'.join(['hello', 'world'])Code:
'hello-world'So, what’s the iterable, you pass into the
Code:
join()Code:
expression for variable in contextCode:
range()Code:
expression for i in range(1, 101)It consists of three elements:
- — The moduloexpressionCode:
'Fizz' * (i%3==0)returnsCode:i%3==0only if the integerCode:Trueis divisible by 3, otherwise it returnsCode:i. So, you multiply the stringCode:Falseeither withCode:'Fizz'(=1) or withCode:True(=0). As a result, you obtain the empty stringCode:Falsein all cases except if the integerCode:''is divisible by 3—in which case you obtain the stringCode:i.Code:'Fizz'
- — The moduloexpressionCode:
'Buzz' * (i%5==0)returnsCode:i%5==0only if the integerCode:Trueis divisible by 5, otherwise it returnsCode:i. So, you multiply the stringCode:Falseeither withCode:'Buzz'(=1) or withCode:True(=0). As a result, you obtain the empty stringCode:Falsein all cases except if the integerCode:''is divisible by 5—in which case you obtain the stringCode:i.Code:'Buzz'
- You use string concatenation to glue together the previously obtained strings. In most cases, this will be the empty string. If is divisible by 3, you obtain the stringCode:
i. IfCode:'Fizz'is divisible by 5, you obtain the stringCode:i. And ifCode:'Buzz'is divisible by 3 and 5, you obtain the stringCode:i.Code:'FizzBuzz'
- — In the case you obtained a non-empty string inCode:
or str(i)in the previous step, theCode:{'Fizz', 'Buzz', 'FizzBuzz'}operation simply returns this string. This is called short circuiting—and it’s used in many programming languages such as Python to improve efficiency of logical operations.Code:or
- But if the string is empty, it is interpreted as a logical . Thus, Python returns the second operand of theCode:
Falseoperation. The second operand simply is the string representation of the integerCode:or.Code:i
A very interesting implementation of the FizzBuzz problem indeed!
FizzBuzz One-Liner 2: Slicing
An alternative is given in the following nice one-liner (source):
Code:
for i in range(1, 101): print('FizzBuzz'[i*i%3*4:8--i**4%5] or i)Wow—what a short and concise one-liner solution! But how does it work?
- You iterate over all values from toCode:
i=1and print a string. So far so good.Code:i=100
- You use the operation and slicing to determine the stringCode:
orgenerates the output.Code:'FizzBuzz'[start:end] or i
- You use the property of short circuiting in Python: If is empty, the integerCode:
'FizzBuzz'[start:end]is returned, otherwise, the non-empty string is returned.Code:i
- You carve out a substring from using slicingas follows.Code:
'FizzBuzz'
Slicing is a concept to carve out a substring from a given string. Use slicing notation
Code:
s[start:stop:step]Code:
stepCode:
startCode:
stopCode:
start=0Code:
stop=len(lst)Code:
step=1Code:
s[2:4]Code:
'hello'Code:
'll'Code:
s[:3:2]Code:
'hl'In the example, you have the slicing operation
Code:
'FizzBuzz'[i*i%3*4:8--i**4%5]- — Note that the multiplicationCode:
start = i*i%3*4and modulo operationCode:*have the same priority, so they are evaluated from left to right. If integerCode:%is divisible by 3,Code:iis also divisible by 3, and the start index is 0. In all other cases, the start index is 4. Thus, the slice either starts withCode:i*iorCode:'Fizz'.Code:'Buzz'
- — This is 4 in all cases except if the numberCode:
stop = 8--i**4%5is divisible by 5, in which case this is 8.Code:i
So, there are four cases:
- The number is divisible only by 3: ,Code:
start=0–>Code:stop=4Code:'Fizz'
- The number is divisible only by 5: ,Code:
start=4–>Code:stop=8Code:'Buzz'
- The number is divisible by both 3 and 5: ,Code:
start=0–>Code:stop=8Code:'FizzBuzz'
- The number is divisible by neither 3 nor 5: ,Code:
start = 4–>Code:stop=4Code:''
Phew! This was a hard nut to crack, wasn’t it?
Python One-Liner 3: Map + Lambda
You can find detailed tutorials on the map and lambda functions here:
- https://blog.finxter.com/daily-python-pu...-function/Mastering the Python Map Function
- https://blog.finxter.com/a-simple-introd...in-python/Lambda Functions in Python
Those two functions can be used to solve the FizzBuzz problem (source):
Code:
print(list(map(lambda i: "Fizz"*(i%3==0)+"Buzz"*(i%5==0) or str(i), range(1,101))))It’s similar to Method 1 and by now you’re able to figure it out. Think of the different values the integer
Code:
iPython One-Liners Book
Python programmers will improve their computer science skills with these useful one-liners.
![[Image: 3D_cover-1024x944.jpg]](https://blog.finxter.com/wp-content/uploads/2020/06/3D_cover-1024x944.jpg)
Python One-Linerswill teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.
The book’s five chapters cover tips and tricks, regular expressions, machine learning, core data science topics, and useful algorithms. Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments. You’ll also learn how to:
• Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
• Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
• Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
• Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
• Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting
By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.
Get your Python One-Liners Now!!

