Python Program to Complex Numbers Sum and Product with Explanation
Python
Medium
OOP Basics
14 views
1 min read
118 words
This problem helps you practice core Python fundamentals in a practical way. It builds intuition around complex, sum, product. Let’s break it down step by step so you can implement it confidently.
Problem Statement
Read two complex numbers as a b and c d, meaning (a+bi) and (c+di). Create Complex class with add and mul. Output sum then product as 'x y' for real and imag.
Input Format
One line: a b c d.
Output Format
Two lines: sumReal sumImag then prodReal prodImag.
Constraints
|values|
Code Solution
This explanation is written for learning purposes and to help beginners understand the concept clearly.
import sys
p=sys.stdin.read().strip().split()
if len(p)<4: sys.exit(0)
a=int(p[0]); b=int(p[1]); c=int(p[2]); d=int(p[3])
class Complex:
def __init__(self,re,im):
self.re=re
self.im=im
def add(self,other):
return Complex(self.re+other.re, self.im+other.im)
def mul(self,other):
return Complex(self.re*other.re - self.im*other.im, self.re*other.im + self.im*other.re)
x=Complex(a,b)
y=Complex(c,d)
s=x.add(y)
m=x.mul(y)
print(f'{s.re} {s.im}')
print(f'{m.re} {m.im}')
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Solution Guide
Problem
Read two complex numbers as a b and c d, meaning (a+bi) and (c+di). Create Complex class with add and mul. Output sum then product as 'x y' for real and imag.
Input / Output
Output
Two lines: sumReal sumImag then prodReal prodImag.
Details
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Official Solution
import sys
p=sys.stdin.read().strip().split()
if len(p)<4: sys.exit(0)
a=int(p[0]); b=int(p[1]); c=int(p[2]); d=int(p[3])
class Complex:
def __init__(self,re,im):
self.re=re
self.im=im
def add(self,other):
return Complex(self.re+other.re, self.im+other.im)
def mul(self,other):
return Complex(self.re*other.re - self.im*other.im, self.re*other.im + self.im*other.re)
x=Complex(a,b)
y=Complex(c,d)
s=x.add(y)
m=x.mul(y)
print(f'{s.re} {s.im}')
print(f'{m.re} {m.im}')
Solutions (0)
No solutions submitted yet. Be the first!