Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Program in Python with proper indentation and syntax Design a class in Python th

ID: 3858055 • Letter: P

Question

Program in Python with proper indentation and syntax

Design a class in Python that represents complex numbers and supports important operations such as addition, subtraction, multiplication and division. For the Pyhton version you will need to implement the following functions for each operation:

op: Complex × Complex Complex

op: Complex × double Complex

op: double × Complex Complex

Where op is one of +, -, *, or /. In addition, you will need to overload the stream insertion operator << to print objects of this type.

A constructor must be defined as well as overloading the assignment operator to allow for implicit conversion from doubles to Complex. Any other methods you deem appropriate should also be included. The more complete your class the better.

The Python version you should also include functions for converting from complexes to strings.

The required files for this project are: a complex.h file that contains the declaration of the complex class, The python files required are a complex.py file.

this is an example code:

Explanation / Answer

import math

class Mycomplex(object):
def __init__(self, real, img):
self.real = real
self.img = img

def __add__(self, no):
real = self.real + no.real
img = self.img + no.img
return Mycomplex(real, img)

def __sub__(self, no):
real = self.real - no.real
img = self.img - no.img
return Mycomplex(real, img)

def __mul__(self, no):
real = self.real * no.real - self.img * no.img
img = self.real * no.img + self.img * no.real
return Mycomplex(real, img)

def __div__(self, no):
x = float(no.real ** 2 + no.img ** 2)
y = self * Mycomplex(no.real, -no.img)
real = y.real / x
img = y.img / x
return Mycomplex(real, img)

def mod(self):
real = math.sqrt(self.real ** 2 + self.img ** 2)
return Mycomplex(real, 0)
def __str__(self):
if self.img == 0:
result = "%.2f" % (self.real)
elif self.real == 0:
result = "%.2fi" % (self.img)
elif self.img > 0:
result = "%.2f + %.2fi" % (self.real, self.img)
else:
result = "%.2f - %.2fi" % (self.real, abs(self.img))
return result


C = map(float, raw_input().split())
D = map(float, raw_input().split())
x = Mycomplex(*C)
y = Mycomplex(*D)
result = [x+y, x-y, x*y, x/y, x.mod(), y.mod()]
print ' '.join(map(str, result))

========================================

akshay@akshay-Inspiron-3537:~/Chegg$ python complex.py
1 2
3 4
4.00 + 6.00i
-2.00 - 2.00i
-5.00 + 10.00i
0.44 + 0.08i
2.24
5.00

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Chat Now And Get Quote