在本教程中,我們將討論在 Python 程序中交換兩個變量(n1 和 n2)而不使用第三個變量的不同方法。
示例:
P: 112
Q: 211
After swapping P and Q:
P: 211
Q: 112
方法 1:通過使用內置方法
內置方法可以處理任何數據類型值,如字符串、浮點、it。這種方法很容易使用。
Left, Right = Right, Left
示例:
P = JavaTpoint
Q = Tutorial
print ("Variables Value Before Swapping: ")
print ("Value of P: ", P)
print ("Value of Q: ", Q)
# Method to swap 'P' and 'Q'
P, Q = Q, P
print ("Variables Value After Swapping: ")
print ("Value of P: ", P)
print ("Value of Q: ", Q)
輸出:
Variables Value Before Swapping:
Value of P: JavaTpoint
Value of Q: Tutorial
Variables Value After Swapping:
Value of P: Tutorial
Value of Q: JavaTpoint
方法 2:通過使用按位異或運算符
按位異或方法僅適用於整數,並且它的工作速度更快,因為它使用的位操作是針對相同的值結果= 0 和不同的值結果= 1。
P ^= Q
Q ^= P
P ^= Q
示例:
P = 5 # P = 0101
Q = 10 # Q = 1010
print ("Variables Value Before Swapping: ")
print ("Value of P: ", P)
print ("Value of Q: ", Q)
# Method to swap 'P' and 'Q'
P ^= Q # P = 1111, Q = 1010
Q ^= P # Q = 0101, P = 1111
P ^= Q # P = 1010, Q = 0101
print ("Variables Value After Swapping: ")
print ("Value of P: ", P)
print ("Value of Q: ", Q)
輸出:
Variables Value Before Swapping:
Value of P: 5
Value of Q: 10
Variables Value After Swapping:
Value of P: 10
Value of Q: 5
方法 3:通過使用加法和減法運算符
此方法只能用於數值。
P = P + Q
Q = P - Q
P = P - Q
示例:
P = 112
Q = 211
print ("Variables Value Before Swapping: ")
print ("Value of P: ", P)
print ("Value of Q: ", Q)
# Method to swap 'P' and 'Q'
P = P + Q # P = 323, Q = 211
Q = P - Q # P = 323, Q = 112
P = P - Q # P = 211, Q = 112
print ("Variables Value After Swapping: ")
print ("Value of P: ", P)
print ("Value of Q: ", Q)
輸出:
Variables Value Before Swapping:
Value of P: 112
Value of Q: 211
Variables Value After Swapping:
Value of P: 112
Value of Q: 211
方法 4:通過使用乘法和除法運算符
此方法只能用於除 0 以外的數值。
P = P * Q
Q = P / Q
P = P / Q
示例:
P = 11.2
Q = 21.1
print ("Variables Value Before Swapping: ")
print ("Value of P: ", P)
print ("Value of Q: ", Q)
# Method to swap 'P' and 'Q'
P = P * Q # P = 236.32, Q = 21.1
Q = P / Q # P = 236.32, Q = 11.2
P = P / Q # P = 21.1, Q = 11.2
print ("Variables Value After Swapping: ")
print ("Value of P: ", P)
print ("Value of Q: ", Q)
輸出:
Variables Value Before Swapping:
Value of P: 11.2
Value of Q: 21.1
Variables Value After Swapping:
Value of P: 21.1
Value of Q: 11.2
方法 5:通過使用按位運算符和算術運算符
在這個方法中,我們將同時使用按位運算符和算術運算符。此方法僅適用於整數,不適用於浮點類型。
示例:
P = 112
Q = 211
print ("Variables Value Before Swapping: ")
print ("Value of P: ", P)
print ("Value of Q: ", Q)
# Same as P = P + Q
P = (P & Q) + (P | Q) ;
# Same as Q = P - Q
Q = P + (~Q) + 1 ;
# Same as P = P - Q
P = P + (~Q) + 1 ;
print ("Variables Value After Swapping: ")
print ("Value of P: ", P)
print ("Value of Q: ", Q)
輸出:
Variables Value Before Swapping:
Value of P: 112
Value of Q: 211
Variables Value After Swapping:
Value of P: 211
Value of Q: 112
結論
在本教程中,我們討論了在不使用第三個變量的情況下交換兩個變量的值的不同方法。
原創文章,作者:DJGCH,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/317340.html