In general swap means "to exchange".
Here i am going to write a code for swapping of 2 numbers in python, but before going to it lets see the logic of how to swap 2 numbers with and with out using third variable.
Logic for swapping of values of 2 variables with using third variable:
let,
a = 4, b = 7 and lets take a third variable as c.
now,
c = a
a = b
b = c
now if you see the result then we can see the value of a and b got swapped.
i.e,
a = 7 and b = 4
Logic for swapping of values of 2 variables without using third variable:
let,
a = 4 and b = 7
now,
a = a+b
b = a-b
a = a-b
now if you see the result then we can see the value of a and b got swapped.
i.e,
a = 7 and b = 4
The above logic is what we will use in c or any other programming language.
But , in python we have a special functionality for comma (",").
The code in python is:
let,
a = 4, b = 7 and lets take a third variable as c.
now,
a,b = b,a
now if you see the result then we can see the value of a and b got swapped.
i.e,
a = 7 and b = 4
Even the above logic also works in python.
For watching the swapping in live you can watch my youtube channel:
https://www.youtube.com/channel/UCkA5xUrlbkdBpZV5WJ2iM0w
Also you can watch the swapping video :
https://www.youtube.com/watch?v=2stFc_u8o6Q
Here i am going to write a code for swapping of 2 numbers in python, but before going to it lets see the logic of how to swap 2 numbers with and with out using third variable.
Logic for swapping of values of 2 variables with using third variable:
let,
a = 4, b = 7 and lets take a third variable as c.
now,
c = a
a = b
b = c
now if you see the result then we can see the value of a and b got swapped.
i.e,
a = 7 and b = 4
Logic for swapping of values of 2 variables without using third variable:
let,
a = 4 and b = 7
now,
a = a+b
b = a-b
a = a-b
now if you see the result then we can see the value of a and b got swapped.
i.e,
a = 7 and b = 4
The above logic is what we will use in c or any other programming language.
But , in python we have a special functionality for comma (",").
The code in python is:
let,
a = 4, b = 7 and lets take a third variable as c.
now,
a,b = b,a
now if you see the result then we can see the value of a and b got swapped.
i.e,
a = 7 and b = 4
Even the above logic also works in python.
For watching the swapping in live you can watch my youtube channel:
https://www.youtube.com/channel/UCkA5xUrlbkdBpZV5WJ2iM0w
Also you can watch the swapping video :
https://www.youtube.com/watch?v=2stFc_u8o6Q
Nice post. Anyone can understand easily and keep updating.
ReplyDeletepython training