There are several ways Python exchange value of the two variables?

Original link: https://www.jianshu.com/u/8f2987e2f9fb

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

The following were it said this in several ways:

1, a method

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

def swap(a,b):
    temp = a
    a = b
    b = temp
    print(a,b)

2. Method Two

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

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:857662006 寻找有志同道合的小伙伴,
互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
def swap2(a,b):
    a,b = b,a
    print(a,b)

3. Method Three

This method is not a few people think, in exchange for the use of addition and subtraction. We do not consider efficiency, can achieve the effect of exchange on the line.

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:857662006 寻找有志同道合的小伙伴,
互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
def swap3(a, b):
    a = a + b
    b = a - b
    a = a - b
    print(a, b)

4. Method Four

Using exclusive-OR operation, this is not the look relatively tall. Bitwise exclusive OR operation by exchanging the value of two variables, defined variables can be reduced, while reducing the analysis time of the computer code.

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

Such as:
1010
1111

The result is 0101

def swap4(a,b):
    a = a ^ b
    b = a ^ b
    a = a ^ b
    print(a,b)

These four methods, whether we have already mastered? If you do not have to agree with the reference to the answer, we can point to and complement welcome in the comments area!

Guess you like

Origin blog.csdn.net/qdPython/article/details/102665995