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
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.)
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.
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.
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.
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.
-ʻ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.
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
** 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`.
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