-1

How to properly print the output str

class Complex(object):
    def __init__(self, real, imaginary):
        self.real = real
        self.imaginary = imaginary

    def __add__(self, other):
        return Complex(self.real+other.real, self.imaginary+other.imaginary)

    def __sub__(self, other):
        return Complex(self.real-other.real, self.imaginary-other.imaginary)

    def __str__(self):
        return '{} & {}i'.format(self.real, self.imaginary)
if __name__ == '__main__':
    c = map(float, input().split())
    d = map(float, input().split())
    x = Complex(*c)
    #print (x)
    y = Complex(*d)
    #print (y)
    print(*map(str, [x+y, x-y]), sep='\n')

Input

2 1 5 6

Output

7.0 & 7.0i -3.0 & -5.0i

Expected out if for addtion it should print + and for substraction it should print -

7.00+7.00i -3.00-5.00i

3 Answers3

0

Use this in your str implementation.

def __str__(self):
        return f"{self.real}{ '+' if self.imaginary >= 0 else ''}{self.imaginary}i"
satyam soni
  • 259
  • 1
  • 9
0

Instead of this:

def __str__(self):
        return '{} & {}i'.format(self.real, self.imaginary)

You could do this:

def __str__(self):
    def __map_imaginary(imag):
        if imag > 0:
            return "+{:2f}i".format(imag)
        if imag < 0:
            return "{:2f}i".format(imag)
        if imag == 0:
            return ""
    return "{}{}".format(self.real, __map_imaginary(self.imag))

I have assumed that you don't want to print imaginary part if it equals to 0. You can change that at will.

Farhood ET
  • 1,432
  • 15
  • 32
0
class Complex(object):
    def __init__(self, real, imaginary):
        self.real = real
        self.imaginary = imaginary

    def __add__(self, other):
        return Complex(self.real+other.real, self.imaginary+other.imaginary)

    def __sub__(self, other):
        return Complex(self.real-other.real, self.imaginary-other.imaginary)

    def __str__(self):
        return '{:.2f}{}{:.2f}i'.format(self.real, '+' if self.imaginary >= 0 else '', self.imaginary)
if __name__ == '__main__':
    c = map(float, input().split())
    d = map(float, input().split())
    x = Complex(*c)
    #print (x)
    y = Complex(*d)
    #print (y)
    print(*map(str, [x+y, x-y]), sep='\n')
  1. You should manually add sign, if var is positive.
  2. Also in your expected result you have 2 decimal points, so you need to add {:.2f}.