How to call python in swap valued function of two variables

How to call python in swap valued function of two variables

All versions of the code to implement in python3.7.1

Examples The following two variables by the user input, and exchange:

 method one:
DEF swap (A, b): 
  # Create a temporary variable, and exchange the TEMP
= A A = b b = the TEMP Print (A, b)

The above example, we created a temporary variable temp, the temp variable, then assign the value of y and a value of a storage, final temp is assigned to the variable b.

 

Method Two:

DEF swap2 (A, B):
 # without using temporary variables 
    A, B = B, A
     Print (A, B)

Python reference management objects, you can exchange quote, but usually can not exchange value of the object in memory.

In function, because a, b int is the object of type atomic are immutable parameters, direct their "reference" value is passed, and incorporated herein should be passed by value.

 

Method three:

 

def swap3(a,b):
    """
    ^异或运算 1^1=0 1^0=1 0^0=0 x^0=x  x^x=0
    """
    a = a^b  
    b = a^b  # b = (a^b)^b = a
    a = a^b  # a = (a^b)^a = b
    print(a,b)
Exclusive-OR operation, 0 is the same, the number of different non-zero, for example, 1 ^ 1 = 0 1 ^ 0 = 1 0 ^ 0 = 0 x ^ 0 = xx ^ x = 0 
Method III A ^ B = A,
     B = (a ^ b) ^ b = a,
     a = (a ^ b) ^ a = b

recommend the second wording, because it is a characteristic of the python language. Third writing, looks cow B, B can be used to brag, the way a package B.

 

Guess you like

Origin www.cnblogs.com/f67373mama/p/11370094.html