import re import math class Complex(object): def __init__(self, val): regex = re.compile(r'^(?:(?:([+-])\s*)?(\d+)(?:\s*([+-])\s*(\d+)i))|(?:([+-])\s*)?(\d+)i|(?:([+-])\s*)?(\d+)$') matches = re.search(regex, val) nbGroups = matches.lastindex if ( nbGroups == 8 ): #real pure self.__imaginary = 0 self.__real = self.__detectSign(matches.group(7)) * int(matches.group(8)) elif ( nbGroups == 6 ): #imaginary pure self.__real = 0 self.__imaginary = self.__detectSign(matches.group(5)) * int(matches.group(6)) elif (nbGroups == 4) : #mixed self.__real = self.__detectSign(matches.group(1)) * int(matches.group(2)) self.__imaginary = self.__detectSign(matches.group(3)) * int(matches.group(4)) def __repr__(self): return (self.__invertedDetectSign(self.__real) + str(self.__real) + self.__invertedDetectSign(self.__imaginary) + str(self.__imaginary) + 'i') def __detectSign(self, sign): return -1 if (sign == "-") else 1 def __invertedDetectSign(self, val): return '' if (val < 0) else '+' def getModule(self): return math.sqrt(self.__real**2 + self.__imaginary**2)