+ 1

swapping numbers in python

using bitwise operator (xor), a = a ^ b b = b ^ a a = a ^ b will swap the numbers is a one liner not possible? like: a ^= b ^= a ^= b I tried, but got some error reference: https://code.sololearn.com/c26o4pSfqFJL/?ref=app

14th Jan 2022, 11:43 PM
Harsha S
Harsha S - avatar
8 Antworten
+ 4
Harsha S 1. a,b=b,a 👍 2. 😵 a,b=a^b^a,b^a^b 😲 3. 😵 a^=b^(b:=b^a^b) 😲
15th Jan 2022, 7:10 AM
Solo
Solo - avatar
+ 10
I presume you already know that swapping in Python is hassle free assignment with the RHS expression position flipped a, b = b, a So why go through the bitwise hassle?
15th Jan 2022, 12:51 AM
Ipang
+ 7
15th Jan 2022, 4:35 AM
Tibor Santa
Tibor Santa - avatar
+ 4
Ipang yeah, i know that. I was just trying to explore various other methods of swapping.
15th Jan 2022, 3:03 AM
Harsha S
Harsha S - avatar
+ 3
Harsha S, you ask the question: "Is one liner impossible? for example: a ^= b ^= a ^= b". And then you give an example of properly working code with the same line. So what's the problem?
15th Jan 2022, 3:44 AM
Solo
Solo - avatar
+ 1
Solo by "correct" what do you mean is correct? the code i linked has the one-liner bitwise operation to swap two variables.
15th Jan 2022, 3:05 AM
Harsha S
Harsha S - avatar
+ 1
a,b =b,a
16th Jan 2022, 1:44 PM
Tanisha Biswas
Tanisha Biswas - avatar
0
Solo the code i have given is in c++ I want to implement it in python
15th Jan 2022, 5:05 AM
Harsha S
Harsha S - avatar