[Python] Try to read the cool answer to the FizzBuzz problem

Introduction

In the class I am currently taking to learn the basics of Python

** "Let's write the FizzBuzz problem in two or more ways!" **

There was a problem.

I was very impressed when I was learning the basics when I saw the answer given by the instructor as one of the model answers.

Here is an example of the answer.

FizzBuzz's cool answer


end = 100
for i in range(1, end + 1):
    print('FizzBuzz'[(4 if i % 3 else 0):(4 if i % 5 else 8)] or i)

Uh, beautiful ... You can write in just 3 lines. (More to say, two lines are enough)

But ** I don't know what you're talking about. ** **

I'm frustrated, so I decided to read this description. It was packed with various essences that I had seen somewhere before, and when I was able to read it, I was completely satisfied.

In this article, I'll try to explain it with the aim of "understanding what this script is saying." Let's read it together!

FizzBuzz problem

FizzBuzz


Logs are output from 1 to 100 in order. However,
・ When the number is a multiple of 3, "Fizz" instead of the number
・ When the number is a multiple of 5, "Buzz" instead of the number
・ When the number is a multiple of 3 and a multiple of 5, "FizzBuzz" is used instead.

Please output as.

If you've never done this problem, try scripting it first! It appears in various introductory books and algorithm books.

This article is written on the assumption that you can answer this question for the time being, so please read on. (I wish I could use the for and ʻif` statements in a basic way.)

Orthodox answer example

For the time being, this is an orthodox example of the answer to the FizzBuzz problem. There are various ways to write, so this is not the case.

FizzBuzz answer example


end = 100
for i in range(1, end + 1):
    if i % 3 == 0 and i % 5 == 0:
        print('FizzBuzz', end='\n')
    elif i % 3 == 0:
        print('Fizz', end=' ')
    elif i % 5 == 0:
        print('Buzz', end=' ')
    else:
        print(i, end=' ')

Petit technique learned:

--By specifying a character string with the print () function with the ʻend option, you can display the character string ( \ nline feed,\ t` tab, etc.) to make it easier to see. ――I learned that it will be easier to see by breaking lines every multiple of 15 that "FizzBuzz" is output, so I tried using it.

Read about this cool answer

It's a cool answer I wrote at the beginning, but I don't know what the third line says.

I'm not sure the script on the third line


print('FizzBuzz'[(4 if i % 3 else 0):(4 if i % 5 else 8)] or i)

If you read it while looking it up, this sentence will

-(1) Slice of character string 'hogehoge' [a: b] -(2) Ternary operator x if conditional expression else y -(3) Logical operation of character strings and numerical values x or y

This area seems to be included as a point.

... ... and the prerequisite knowledge before that.

(0) Prerequisite knowledge: Boolean value of numerical value / character string

As necessary knowledge, ** "Numeric value / False value of character string" ** will be organized.

When a numerical value is used as a conditional expression, it returns as a true / false value of True or False. And about the truth,

--Number 0, when empty string => False --Other times => True

It will be. I want to get used to it because the code becomes simple by using it in the conditional expression of the ʻif` statement.

(1) Slice of character string

Let's break down the previous sentence further and start from the point where it seems easy to understand!

'FizzBuzz'[(4 if i % 3 else 0):(4 if i % 5 else 8)] 

In this part, if you ignore the details and write only the structure,

'FizzBuzz'[a:b]

It is in the form of ** "Slice of string" **.

By applying a slice to the string FizzBuzz this time,

print('FizzBuzz'[0:8]) #① => FizzBuzz
print('FizzBuzz'[0:4]) #② => Fizz 
print('FizzBuzz'[4:8]) #③ => Buzz
print('FizzBuzz'[4:4]) #④ => (Nothing is displayed)

Can be expressed well.

First of all, this is the first point.

(2) Conditional expression (ternary operator) ʻif-ʻelse

The next thing I want to read is ʻa, bwhen I wrote'FizzBuzz' [a: b]`.

(4 if i % 3 else 0)
(4 if i % 5 else 8)

This notation.

I've heard the expression "postfix ʻif`" somehow, but it seems to call it ** "conditional expression" ** or ** "ternary operator" **. 6. Expressions — Python 3.8.3 Documentation

Isn't it better to keep it as ** if ~ else can be written in one line ** for use?

reference: Ternary operator (Python)-Qiita

Applying this, the above two writing styles

(4 if i % 3 else 0) => "If the value of i% 3 is True (when the value of the remainder of dividing i by 3 is other than 0, that is, it is not divisible by 3), it is 4, otherwise (when it is divisible by 3) is 0"

(4 if i % 5 else 8) => "If the value of i is 5 is True (when the value of the remainder of dividing i by 5 is other than 0, that is, it is not divisible by 35), it is 4, otherwise (when it is divisible by 3) is 8"

It is an expression that represents a numerical value that changes depending on the conditions. (If 0 is handled in the conditional expression, the boolean value will be False (precondition))

** I don't know. ** **

... ... Specifically, if you think about the FizzBuzz of this issue, the story so far seems to be connected somehow.

ʻI` can be divided into cases depending on whether it is a multiple of 3, a multiple of 5, a multiple of 3 and a multiple of 5 (a multiple of 15).

print('FizzBuzz'[0:8]) #①=>FizzBuzz (when i is a multiple of 3 and a multiple of 5)
print('FizzBuzz'[0:4]) #② =>Fizz (when i is a multiple of 3 and not a multiple of 5)
print('FizzBuzz'[4:8]) #③ =>buzz (when i is a multiple of 5 and not a multiple of 3)
print('FizzBuzz'[4:4]) #④ => (Nothing is displayed)(When i is neither a multiple of 3 nor a multiple of 5)

The result of these 4 patterns

'FizzBuzz'[(4 if i % 3 else 0):(4 if i % 5 else 8)]

It can be expressed in this one line.

However, with this alone, the character strings of Fizz, Buzz, and FizzBuzz can be output, but the numbers cannot be output.

So, here is the next point.

(3) Logical operation of numerical values and character strings

It will be another breath when you reach here. There was another part I didn't see.

I'm not sure the script on the third line


print('FizzBuzz'[(4 if i % 3 else 0):(4 if i % 5 else 8)] or i)

A mystery remains in this last expression, ʻ or i`. So, if I omit the details and write only the structure,

print('FizzBuzz'[a:b] or i)

It has a structure called.

This ʻor is **" logical operator "**, but it seems that the usage and appearance of ʻor is intuitively understood in this expression.

How to use the general logical operator ʻor`

Conditional expression or conditional expression => Returns True or False Example) 1 <10 or 2> 20 => True

In this way, ʻoris a conditional expression, and if any one is correct,True is returned, and if all are incorrect, False` is returned, which is an operation that returns a boolean value. This is intuitively easy to understand.

However, this expression is

Character string / number or character string / number => Returns either value (character string or number) Example) 'FizzBuzz' or 3 => FizzBuzz Example) '' or 3 => 3

It is an operation that returns one of the values lined up in ʻor. In the above example "When the value before ʻor is true and the value after it is true, the previous value is returned as a whole." "When the value before ʻor` is false and the value after it is true, the value after it is returned as a whole." It is a rule. 6. Expressions — Python 3.8.3 documentation

reference: Python ♪ How to use logical operators (and, or, not) and logical operations on numbers and strings \ | Snow Tree in June

** I don't know. ** **

... ... I will learn detailed grammar in the future, but this time I will give priority to reading and say "There is such a rule". (The evaluation method called "short-circuit evaluation (short circuit)" is used.)

Specifically, when applied to this problem, the four patterns considered in (2) can be further considered as follows.

print('FizzBuzz'[0:8] or i) #① =>FizzBuzz (returns the previous value when the value before or is true and the value after it is true)
print('FizzBuzz'[0:4] or i) #② =>Fizz (same as above)
print('FizzBuzz'[4:8] or i) #③ =>buzz (same as above)
print('FizzBuzz'[4:4] or i) #④ =>i (returns the value after or when the value before it is false and the value after it is true)

The output results of ① to ③ are the same as in (2), but the output results are different only in ④.

'FizzBuzz'[(4 if i % 3 else 0):(4 if i % 5 else 8)] or i

It became possible to output a numerical value in one line just by using ʻor`.

in conclusion

was fun. that's all. If you read this far and run the script for the cool FizzBuzz answer at the beginning again, it will look a little different.

I felt frustrated that I couldn't explain it intuitively, so I thought I should devote myself. I think that each of the grammars I've seen this time is a fairly familiar way of writing, so I'd like to master these things so that I can write simple scripts in python.

FizzBuzz It's interesting. Also, once I learned a new concept, I thought it would be interesting as a practice to dare to make a FizzBuzz that makes use of it.

Recommended Posts

[Python] Try to read the cool answer to the FizzBuzz problem
Try to solve the fizzbuzz problem with Keras
Try to solve the Python class inheritance problem
Try to solve the internship assignment problem with Python
The first algorithm to learn with Python: FizzBuzz problem
Python amateurs try to summarize the list ①
My friend seems to do python, so think about the problem ~ fizzbuzz ~
Try to calculate a statistical problem in Python
Try to solve the man-machine chart with Python
Try to solve the traveling salesman problem with a genetic algorithm (Python code)
Try to solve the programming challenge book with python3
Template of python script to read the contents of the file
Read the xml file by referring to the Python tutorial
I tried to solve the problem with Python Vol.1
Try to understand Python self
Try to get the function list of Python> os package
How to switch the configuration file to be read by Python
[Python] I asked LINE BOT to answer the weather forecast.
Try to automate the operation of network devices with Python
Try to decipher the garbled attachment file name with Python
[Python] Solving the import problem due to the difference in entry points
Try the Python LINE Pay SDK
[Cloudian # 9] Try to display the metadata of the object in Python (boto3)
[Python] Try to graph from the image of Ring Fit [OCR]
Try to operate Facebook with Python
The 15th offline real-time how to write reference problem in Python
First python ② Try to write code while examining the features of python
Try to solve the N Queens problem with SA of PyQUBO
In the python command python points to python3.8
How to read the SNLI dataset
How to get the Python version
[Cloudian # 2] Try to display the object storage bucket in Python (boto3)
Try to introduce the theme to Pelican
Try to calculate Trace in Python
[Python] How to import the library
Have python read the command output
Try converting cloudmonkey CLI to python3 -1
Try running the basic information Python sample problem only in the browser
Review of the basics of Python (FizzBuzz)
Read the old Gakushin DC application Word file (.doc) from Python and try to operate it.
I wanted to solve the ABC164 A ~ D problem with Python
Part 1 I wrote the answer to the reference problem of how to write offline in real time in Python
Try using the Python Cmd module
Cython to try in the shortest
The 14th offline real-time how to write reference problem in python
Try to implement and understand the segment tree step by step (python)
[Python] Read the Flask source code
The fastest way to try EfficientNet
Try to solve the shortest path with Python + NetworkX + social data
The 18th offline real-time how to write reference problem in Python
The easiest way to try PyQtGraph
[Python] Change the alphabet to numbers
Try to solve the function minimization problem using particle swarm optimization
Put Cabocha 0.68 on Windows and try to analyze the dependency with Python
The 17th offline real-time how to write reference problem implemented in Python
The 16th offline real-time how to write reference problem to solve with Python
Try to image the elevation data of the Geographical Survey Institute with Python
Try using the Python web framework Django (1)-From installation to server startup
Try to solve the traveling salesman problem with a genetic algorithm (Theory)
The 19th offline real-time how to write reference problem to solve with Python
The 15th offline real-time how to write problem was solved with python