Four kinds of value exchange method in Python

 

 

Exchange value of the method of two variables, the face questions if you write only one course, very simple, nothing can be said.

Today, this interview is to ask if you have several ways to implement the exchange value of two variables.

Before the start did not see specific answers, you can first think about

The following are several ways that this is

method one

By adding new intermediate variable temp way, this method is the simplest, each language are applicable.

 

Method Two
Python unique method, one line of code can get directly to two variables into tuples.

 

Method three
of this method using subtraction exchanged. Without regard to efficiency, to achieve the effect of exchange on the line

Method IV
using the XOR operation, this is not the look relatively tall. Bitwise exclusive OR operation by exchanging the value of two variables, definitions of the variables can be reduced.

Bitwise exclusive-OR operation i.e., the computer will first decimal numbers into binary numbers and the binary numbers speak lines from right to left with a number starting from 1, then the number of compare two binary values ​​of the same position, if the same result is 0, At the same time the result is not 1.

“1^1=01^0=10^0=0°

Such as: 10,101,111

The result is 0101

 

Guess you like

Origin www.cnblogs.com/oldfish123/p/11780271.html