'Python Real and imaginary : How to print -2-2i
Can you please help me with the below code where I am not getting the desired result:
class comp:
def __init__(self, real, imag):
self.real=real
self.imag=imag
def add(self,other):
print('Sum of the two Complex numbers :{}+{}i'.format(self.real+other.real,self.imag+other.imag))
def sub(self, other):
print('Subtraction of the two Complex numbers :{}+{}i'.format(self.real-other.real, self.imag-other.imag))
The code works but when the imaginary field takes a result in -2, I know it will print the result as +-2i
Result eg: 1+2i - 3+4i = -2-2i (but as it is hard coded as + in the comment it is resulting in -2+-2i
Help me understand how to get rid of it?
Solution 1:[1]
I suggest adding an if
statement within each function. Specifically if self.imag+other.imag < 0 :
for the addition. Then add the print
statement of print('Sum of the two Complex numbers :{}{}i'.format(self.real+other.real,self.imag+other.imag))
. You would need to do this with the subtraction function as well. This solution doesn't keep the function at one line but should solve the problem.
Solution 2:[2]
The problem is that you're explicitly asking to separate the real and imaginary part with a plus sign.
here's a short version
class comp(complex):
def add(self, other):
print(f'Sum of the two Complex numbers: {self+other}')
def sub(self, other):
print(f'Subtraction of the two Complex numbers: {self-other}')
x = comp(1, 2)
y = comp(3, 4)
x.add(y)
# Sum of the two Complex numbers: (4+6j)
x.sub(y)
# Subtraction of the two Complex numbers: (-2-2j)
otherwise
def sign(x):
return '+' if x>=0 else ''
class comp:
def __init__(self, real, imag):
self.real=real
self.imag=imag
def add(self, other):
r = self.real + other.real
i = self.imag + other.imag
print(f'Sum of the two Complex numbers: {r}{sign(i)}{i}i')
def sub(self, other):
r = self.real - other.real
i = self.imag - other.imag
print(f'Subtraction of the two Complex numbers: {r}{sign(i)}{i}i')
x = comp(1, 2)
y = comp(3, 4)
x.add(y)
# Sum of the two Complex numbers: 4+6i
x.sub(y)
# Subtraction of the two Complex numbers: -2-2i
Solution 3:[3]
def sign(x):
return '+' if x>=0 else ''
class comp:
def __init__(self, real, imag):
self.real=real
self.imag=imag
def add(self,other):
print('Sum of the two Complex numbers :{}{}{}i'.format(self.real+other.real,sign(self.imag+other.imag),self.imag+other.imag))
def sub(self, other):
print('Subtraction of the two Complex numbers :{}{}{}i'.format(self.real-other.real,sign(self.imag-other.imag),self.imag-other.imag))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | tboggs300 |
Solution 2 | kendfss |
Solution 3 |