[PYTHON] Swap 1 and 2 without using an if statement

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.

Postscript

As pointed out in the comments, there was a simpler way to write it.

Swap 1 and 2

n = 1
print(3-n) # 2
m = 2
print(3-m) # 1 

Swap 0 and 1

n = 0
print(1-n) # 1
m = 1
print(1-m) # 0 

Generalization

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. ** **

The one you don't have to read (original article)

I will leave the original article for the time being.

How to write by swapping 1 and 2

n = 1
print(n%2+1) # 2
m = 2
print(m%2+1) # 1 

only this.

Think about other numbers

This alone is not an article, so let's think about other numbers as a brain teaser.

Swap 0 and 1

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.

Swap 2 and 3

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

Swap 3 and 4

Try replacing 3 with 4 and 4 with 3.

n = 3
print(n%2+3) # 4
m = 4
print(m%2+3) # 3 

Let's generalize

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

Summary

If in doubt, use an if statement.

Recommended Posts

Swap 1 and 2 without using an if statement
When using if and when using while
[Python] File operation using if statement
Python if statement
Unfamiliar if statement
[Python] if statement
Modulo without using%
When writing an if statement with a regular expression
Bubble sort without using sort
Write FizzBuzz without using "="
Quicksort without using sort
With and without WSGI
Python basic if statement
How to swap elements in an array in Python, and how to reverse an array.
Consider If Programming Was An Anime in Python and C
[Python] How to write an if statement in one sentence.