Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python One Line FizzBuzz
1
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:
  • For each number divisible by three you print
    Code:
    "Fizz"
    ,

  • For each number divisible by five you print
    Code:
    "Buzz"
    , and

  • 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:
join
function with the newline character as a delimiter. Here’s a short explanation of the function:

The
Code:
string.join(iterable)
method concatenates all the string elements in the
Code:
iterable
(such as a list, string, or tuple) and returns the result as a new string. The
Code:
string
on which you call it is the delimiter string—and it separates the individual elements. For example,
Code:
'-'.join(['hello', 'world'])
returns the joined string
Code:
'hello-world'
.

So, what’s the iterable, you pass into the
Code:
join()
function? It’s a generator expression of the form:
Code:
expression for variable in context
. You go over all integer values in the context 1 to 100 using the
Code:
range()
function. So, you obtain the remaining
Code:
expression for i in range(1, 101)
. What’s the expression part?

It consists of three elements:
  • Code:
    'Fizz' * (i%3==0)
    — The moduloexpression
    Code:
    i%3==0
    returns
    Code:
    True
    only if the integer
    Code:
    i
    is divisible by 3, otherwise it returns
    Code:
    False
    . So, you multiply the string
    Code:
    'Fizz'
    either with
    Code:
    True
    (=1) or with
    Code:
    False
    (=0). As a result, you obtain the empty string
    Code:
    ''
    in all cases except if the integer
    Code:
    i
    is divisible by 3—in which case you obtain the string
    Code:
    'Fizz'
    .

  • Code:
    'Buzz' * (i%5==0)
    — The moduloexpression
    Code:
    i%5==0
    returns
    Code:
    True
    only if the integer
    Code:
    i
    is divisible by 5, otherwise it returns
    Code:
    False
    . So, you multiply the string
    Code:
    'Buzz'
    either with
    Code:
    True
    (=1) or with
    Code:
    False
    (=0). As a result, you obtain the empty string
    Code:
    ''
    in all cases except if the integer
    Code:
    i
    is divisible by 5—in which case you obtain the string
    Code:
    'Buzz'
    .

  • You use string concatenation to glue together the previously obtained strings. In most cases, this will be the empty string. If
    Code:
    i
    is divisible by 3, you obtain the string
    Code:
    'Fizz'
    . If
    Code:
    i
    is divisible by 5, you obtain the string
    Code:
    'Buzz'
    . And if
    Code:
    i
    is divisible by 3 and 5, you obtain the string
    Code:
    'FizzBuzz'
    .

  • Code:
    or str(i)
    — In the case you obtained a non-empty string in
    Code:
    {'Fizz', 'Buzz', 'FizzBuzz'}
    in the previous step, the
    Code:
    or
    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.

  • But if the string is empty, it is interpreted as a logical
    Code:
    False
    . Thus, Python returns the second operand of the
    Code:
    or
    operation. The second operand simply is the string representation of the integer
    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
    Code:
    i=1
    to
    Code:
    i=100
    and print a string. So far so good.

  • You use the
    Code:
    or
    operation and slicing to determine the string
    Code:
    'FizzBuzz'[start:end] or i
    generates the output.

  • You use the property of short circuiting in Python: If
    Code:
    'FizzBuzz'[start:end]
    is empty, the integer
    Code:
    i
    is returned, otherwise, the non-empty string is returned.

  • You carve out a substring from
    Code:
    'FizzBuzz'
    using slicingas follows.

Slicing is a concept to carve out a substring from a given string. Use slicing notation
Code:
s[start:stop:step]
to access every
Code:
step
-th element starting from index
Code:
start
(included) and ending in index
Code:
stop
(excluded). All three arguments are optional, so you can skip them to use the default values (
Code:
start=0
,
Code:
stop=len(lst)
,
Code:
step=1
). For example, the expression
Code:
s[2:4]
from string
Code:
'hello'
carves out the slice
Code:
'll'
and the expression
Code:
s[:3:2]
carves out the slice
Code:
'hl'
.

In the example, you have the slicing operation
Code:
'FizzBuzz'[i*i%3*4:8--i**4%5]
.
  • Code:
    start = i*i%3*4
    — Note that the multiplication
    Code:
    *
    and modulo operation
    Code:
    %
    have the same priority, so they are evaluated from left to right. If integer
    Code:
    i
    is divisible by 3,
    Code:
    i*i
    is also divisible by 3, and the start index is 0. In all other cases, the start index is 4. Thus, the slice either starts with
    Code:
    'Fizz'
    or
    Code:
    'Buzz'
    .

  • Code:
    stop = 8--i**4%5
    — This is 4 in all cases except if the number
    Code:
    i
    is divisible by 5, in which case this is 8.

So, there are four cases:
  • The number is divisible only by 3:
    Code:
    start=0
    ,
    Code:
    stop=4
    –>
    Code:
    'Fizz'

  • The number is divisible only by 5:
    Code:
    start=4
    ,
    Code:
    stop=8
    –>
    Code:
    'Buzz'

  • The number is divisible by both 3 and 5:
    Code:
    start=0
    ,
    Code:
    stop=8
    –>
    Code:
    'FizzBuzz'

  • The number is divisible by neither 3 nor 5:
    Code:
    start = 4
    ,
    Code:
    stop=4
    –>
    Code:
    ''

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):

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:
i
can take.

Python One-Liners Book

Python programmers will improve their computer science skills with these useful one-liners.

[Image: 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!!
Reply

Users browsing this thread:
1 Guest(s)


Forum Jump: