There was a situation where I wanted to receive a variable containing either 1 or 2 and return 2 for 1 and 1 for 2.
I learned a convenient way to write 1 and 2 that can be used in such a case, so make a note.
As pointed out in the comments, there was a simpler way to write it.
n = 1
print(3-n) # 2
m = 2
print(3-m) # 1
n = 0
print(1-n) # 1
m = 1
print(1-m) # 0
When $ x $ is either $ n $ or $ n-1 $
\begin{eqnarray}
f(x) &=& 2n-1-x\\&=&\left\{
\begin{array}{ll}
n & (x = n-1) \\
n-1 & (x =n)
\end{array}\right.
\end{eqnarray}
Obvious without proof.
So, ** The story so far is enough, so you don't have to read the rest. ** **
I will leave the original article for the time being.
n = 1
print(n%2+1) # 2
m = 2
print(m%2+1) # 1
only this.
This alone is not an article, so let's think about other numbers as a brain teaser.
Consider swapping 0s and 1s. There is no such thing as handling with bool.
n = 1
print((n+1)%2) # 0
m = 0
print((m+1)%2) # 1
did it.
In the same way, replace 2 with 3 and 3 with 2.
n = 2
print((n+1)%2+2) # 3
m = 3
print((m+1)%2+2) # 2
Try replacing 3 with 4 and 4 with 3.
n = 3
print(n%2+3) # 4
m = 4
print(m%2+3) # 3
The calculation formula changes depending on whether $ 2n $ and $ 2n-1 $ are exchanged or $ 2n $ and $ 2n + 1 $ are exchanged.
When swapping $ 2n $ and $ 2n-1 $
\begin{eqnarray}
f(x) &=&x \bmod 2 +2n-1 \\&=& \left\{
\begin{array}{ll}
2n & (x = 2n-1) \\
2n-1 & (x =2n)
\end{array}
\right.
\end{eqnarray}
When swapping $ 2n $ and $ 2n + 1 $
\begin{eqnarray}
f(x) &=&(x+1) \bmod 2 +2n \\&=& \left\{
\begin{array}{ll}
2n & (x = 2n+1) \\
2n+1 & (x =2n)
\end{array}
\right.
\end{eqnarray}
~~ I'm thinking while writing appropriately, so there may be a more efficient way of writing. There was ~~ (top of the article).
If in doubt, use an if statement.
Recommended Posts