It's been a while since I've posted any blogs and vlogs. I've been trying to record videos for Planet of Codes Youtube channel, but there's quite a lot of noise whenever I try to record, so I thought why not I communicate through these blogs instead till I am able to record something for Youtube.
So here we are, blogging for something that I actually tried to record in the form of a video.
Usually in high schools and colleges, when most of us initially learn programming, we get a programming problem to swap two numbers. Usually the solution looks something like the below.
num1 = 32
num2 = 87
temp = num1
num1 = num2
num2 = temp
print(num1)
print(num2)
Note: Usually institutions ask students to write this program in C or C++ in first semester, however the above program is in Python, because, It's the logic that matters. This program can be written in any other programming language too.
Well, here we are using a temporary variable "temp".
This problem can actually be solved without using this temporary variable. One of my former classmate taught that to me when I was in the first semester of my bachelors course.
In order to do this, we need to remember that we are dealing with integers, so we can perform mathematical operations on these and we are going take advantage of that here. So, this is how it's done.
num1 = 32
num2 = 87
num1 = num1 + num2 #119
num2 = num1 - num2 # 119 - 87 = 32
num1 = num1 - num2 # 119 - 32 = 87
print(num1)
print(num2)
Comments
Post a Comment