-3

In the below code I am not getting the desired result:

#!/bin/python3

import math

import os

import random

import re

import sys


class comp:

    def __init__(self,real,img):
        self.real=real
        self.img=img
        
    def add(self,p2):
        r= p1.real+p2.real
        i= p1.img+p2.img
        print("Sum of the two Complex numbers :"+str(r)+'+'+str(i)+'i')
        
    def sub(self,p2):
        r= p1.real-p2.real
        i= p1.img-p2.img
        print("Subtraction of the two Complex numbers :"+str(r)+'+'+str(i)+'i')  
        
        
if __name__ == '__main__':
    
    real1 = int(input().strip())
    img1 = int(input().strip())
    
    real2 = int(input().strip())
    img2 = int(input().strip())
    
    p1 = comp(real1,img1)
    p2 = comp(real2,img2)

    p1.add(p2)
    p1.sub(p2)

The code works but when the imaginary field takes a result in -2, it is printing 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"

How can I get rid of it?

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
  • No idea what your problem is. Maybe add some inputs and what you want to get out vs what the program does? Seems to be a controlflow issue if you calculate something that is incorrect fix your calculations..... – Patrick Artner Dec 23 '21 at 10:36
  • @PatrickArtner I would want to get the answer printed as -2-2i in the console. But it is printing as -2+-2i Also, the code is working fine for other test cases. So I couldn't understand what can be done. – Bhavya Sri Chundru Dec 23 '21 at 10:42
  • Please take a moment to understand how code-formatting works in Markdown - the code in this post has been repaired twice by community members now. – halfer Dec 23 '21 at 23:20
  • Consider looking at your code carefully and using conditionals – Mad Physicist Jan 02 '22 at 01:54
  • 1
    Are you aware that complex numbers are a built-in datatype in Python? `i1 = 1+2j` / `i2 = 3+4j` / `print(i1-i2)` works right out of the box. – Tim Roberts Jan 02 '22 at 01:59

1 Answers1

0

You can use conditional printing - either with an if clause or by leveraging an inlined ternary expression:

r = 5
for i in (-2,0,2):
    print(f"Subtraction : {r}{'+' if i >= 0 else ''}{i}i") 

Output:

Subtraction : 5-2i
Subtraction : 5+0i
Subtraction : 5+2i

You may want to make a print function though, to handle 0*i and 1*i more gracefully

kaya3
  • 47,440
  • 4
  • 68
  • 97
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69