complex.py 1.3 KB

123456789101112131415161718192021222324252627282930313233
  1. import re
  2. import math
  3. class Complex(object):
  4. def __init__(self, val):
  5. regex = re.compile(r'^(?:(?:([+-])\s*)?(\d+)(?:\s*([+-])\s*(\d+)i))|(?:([+-])\s*)?(\d+)i|(?:([+-])\s*)?(\d+)$')
  6. matches = re.search(regex, val)
  7. nbGroups = matches.lastindex
  8. if ( nbGroups == 8 ):
  9. #real pure
  10. self.__imaginary = 0
  11. self.__real = self.__detectSign(matches.group(7)) * int(matches.group(8))
  12. elif ( nbGroups == 6 ):
  13. #imaginary pure
  14. self.__real = 0
  15. self.__imaginary = self.__detectSign(matches.group(5)) * int(matches.group(6))
  16. elif (nbGroups == 4) :
  17. #mixed
  18. self.__real = self.__detectSign(matches.group(1)) * int(matches.group(2))
  19. self.__imaginary = self.__detectSign(matches.group(3)) * int(matches.group(4))
  20. def __repr__(self):
  21. return (self.__invertedDetectSign(self.__real) + str(self.__real) + self.__invertedDetectSign(self.__imaginary) + str(self.__imaginary) + 'i')
  22. def __detectSign(self, sign):
  23. return -1 if (sign == "-") else 1
  24. def __invertedDetectSign(self, val):
  25. return '' if (val < 0) else '+'
  26. def getModule(self):
  27. return math.sqrt(self.__real**2 + self.__imaginary**2)