Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit c40e5bd

Browse files
committed
swap two element without extra variable
1 parent f1d8e96 commit c40e5bd

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

algorithm/swap.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# of course a,b = b,a is the perfect solution
2+
# this is show how to do swap without third variable
3+
4+
def swap1(a, b):
5+
print a,b
6+
a = a + b
7+
b = a - b
8+
a = a - b
9+
print a,b
10+
11+
def swap2(a,b):
12+
print a,b
13+
a ^= b
14+
b ^= a
15+
a ^= b
16+
print a,b
17+
18+
if __name__ == '__main__':
19+
swap1(1,2)
20+
swap2(1,2)

0 commit comments

Comments
 (0)