Consider a class Complex that simulates the built-in complex data type. The class en- ables operations on so-called complex numbers. These are numbers of the form realPart + imag- inaryPart * i, where i has the value ?-1

a) Modify the class to enable output of complex numbers in the form (realPart, imaginary-Parti), through the overloaded __str__ method.
b) Overload the multiplication operator to enable multiplication of two complex numbers as in algebra, using the equation
(a, bi) * (c, di) = (a*c - b*d, (a*d + b*c)i)
c) Overload the == operator to allow comparisons of complex numbers. [Note: (a, bi) is equal to (c, di) if a is equal to c and b is equal to d.

```
# Complex number class.

class Complex:
"""Complex numbers of the form realPart + imaginaryPart * i"""

def __init__( self, real = 0, imaginary = 0 ):
"""Assigns values to realPart and imaginaryPart"""

self.realPart = real
self.imaginaryPart = imaginary

def __add__( self, other ):
"""Returns the sum of two Complex instances"""

real = self.realPart + other.realPart
imaginary = self.imaginaryPart + other.imaginaryPart

# create and return new complexNumber
return Complex( real, imaginary )

def __sub__( self, other ):
"""Returns the difference of two Complex instance"""

real = self.realPart - other.realPart
imaginary = self.imaginaryPart - other.imaginaryPart

# create and return new complexNumber
return Complex( real, imaginary )

def __mul__( self, other ):
"""Returns the product of two Complex instances"""

real = self.realPart * other.realPart - \
self.imaginaryPart * other.imaginaryPart
imaginary = self.realPart * other.imaginaryPart + \
self.imaginaryPart * other.realPart

return Complex( real, imaginary )

def __str__( self ):
"""Represent Complex instance in form
( realPart, imaginaryParti )"""

return "(%d,%di)" % ( self.realPart, self.imaginaryPart )

def __eq__( self, other ):
"""Overloads equality operator"""

if self.realPart == other.realPart and \
self.imaginaryPart == other.imaginaryPart:
return 1
else:
return 0.
```
>>> c1 = Complex( 2, 3 )
>>> c2 = Complex( 1, -3 )
>>> c3 = Complex( 2, 3 )
>>> print "c1 =", c1
c1 = (2,3i)
>>> print c1 * c2
(11,-3i)
>>> if c1 == c3:
... print "c1 is equal to c3"
... else:
... print "c1 is not equal to c3"
...
c1 is equal to c3

Computer Science & Information Technology

You might also like to view...

Answer the following statement(s) true (T) or false (F)

The storm-control command is a type of flood guard that is available on most major network switch vendor platforms.

Computer Science & Information Technology

Because ____ are cumbersome to revise and can support unstructured programming practices easily, they have fallen out of favor by professional programmers.

a. algorithms b. formulas c. pseudocodes d. flowcharts

Computer Science & Information Technology