+ 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
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) 😲
+ 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?
+ 7
Harsha S
You can do the bitwise trick with walrus operator
(a := (b := (a := b ^ a) ^ b) ^ a)
https://code.sololearn.com/cHUjIao4hGKY/?ref=app
https://realpython.com/JUMP_LINK__&&__python__&&__JUMP_LINK-walrus-operator/
+ 4
Ipang yeah, i know that. I was just trying to explore various other methods of swapping.
+ 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?
+ 1
Solo by "correct" what do you mean is correct?
the code i linked has the one-liner bitwise operation to swap two variables.
+ 1
a,b =b,a