In this article, we will learn about how to write python program to swap two complex numbers without using third variable.
Getting Started
The task is to swap two complex numbers in python without using third variable.
For example,
Assume a = 50.1 + 30j and b = 60.3 – 20j, then output should be a = 60.3 – 20j and b = 50.1 + 30j
Now, we need to write python program to swap two complex numbers without using third variable.
There are multiple ways to achieve above tasks.
- Using Tuple Packing and Unpacking
- Using Multiplication and Division Operation
1. Using Tuple Packing and Unpacking
This is simplest way to swap complex numbers without using third variable. Here, we use tuple packing and unpacking technique.
It can be done as shown below –
print ( "Before swap: a =" , a, "b =" , b) |
print ( "After swap: a =" , a, "b =" , b) |
Here,
- Statement a, b = b, a does the actual swapping process.
Output:
Before swap: a = (50.1+30j) b = (60.3-20j) |
After swap: a = (60.3-20j) b = (50.1+30j) |
2. Using Multiplication and Division Operation
We can also use multiplication and division operation too. This is similar to what we have seen in above program. Using multiplication and division operation, below is the sample python program to swap two complex numbers without third variable.
It can be shown as below –
a_input = input ( "Enter the complex number for a (e.g., 3+2j): " ) |
b_input = input ( "Enter the complex number for b (e.g., 1-5j): " ) |
print ( "Before swapping:" ) |
print ( "Value of a:" , a, "and b:" , b) |
print ( "Value of a:" , a, "and b:" , b) |
Output:
Enter the complex number for a (e.g., 3+2j): |
Enter the complex number for b (e.g., 1-5j): |
Value of a: (4+2j) and b: (5+6j) |
Value of a: (5+6j) and b: (4+2j) |
We have also covered many other ways to swap two complex numbers in python. You can have a look at them if you want. Learn more about python at official site.