complex no operations

import math class complex_no(object): def __init__(self, real, imaginary): self.real = real self.imaginary = imaginary def __add__(self, no): real = self.real + no.real imaginary = self.imaginary + no.imaginary return complex_no(real, imaginary) def __sub__(self, no): real = self.real - no.real imaginary = self.imaginary - no.imaginary return complex_no(real, imaginary) def __mul__(self, no): real = self.real * no.real - self.imaginary * no.imaginary imaginary = self.imaginary * no.real + self.real * no.imaginary return complex_no(real, imaginary) def __div__(self, no): real = (self.real * no.real + self.imaginary * no.imaginary) / (no.imaginary ** 2 + no.real ** 2) imaginary = (self.imaginary * no.real - self.real * no.imaginary) / (no.real ** 2 + no.imaginary ** 2) return complex_no(real, imaginary) def mod(self): real = math.sqrt(self.real ** 2 + self.imaginary ** 2) return complex_no(real, 0) def __str__(self): if self.imaginary == 0: result = "%.2f" % (self.real) elif self.real == 0: result = "%.2fi" % (self.imaginary) elif self.imaginary > 0: result = "%.2f + %.2fi" % (self.real, self.imaginary) else: result = "%.2f - %.2fi" % (self.real, abs(self.imaginary)) return result c = map(float, raw_input().split()) d = map(float, raw_input().split()) x = complex_no(*c) y = complex_no(*d) final = [x + y, x - y, x * y, x / y, x.mod(), y.mod()] print '\n'.join(map(str, final))

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.