Python 3 - OOP solution with multiplication overriding


  • 0
    E
    class Complex(object):
        def __init__(self, real, imaginary):
            self.real = real
            self.imaginary = imaginary
        
        def __mul__(self, other):
            #assuming other is a Complex object. Though we can run a check if we want
            real = (self.real*other.real - self.imaginary*other.imaginary)
            imaginary = (self.real*other.imaginary+other.real*self.imaginary)
            return Complex(real, imaginary)
            
        @staticmethod
        def from_string(text):
            parts = text.split('+')
            real = int(parts[0])
            imaginary = int(parts[1][:-1])
            return Complex(real, imaginary)
            
        def __repr__(self):
            return "{}+{}i".format(self.real, self.imaginary)
            
    class Solution(object):
        def complexNumberMultiply(self, a, b):
            """
            :type a: str
            :type b: str
            :rtype: str
            """
            a = Complex.from_string(a)
            b = Complex.from_string(b)
            return str(a*b)
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.