My super "rigid" 78% Python solution


  • 0
    X
    def fractionAddition(self, expression):
        exp = expression.replace('+', ' +').replace('-', ' -').split()
        res = '0/1'
        for i in range(len(exp)):
            res = self.add(res, exp[i])
        return res
    def gcd(self, a, b):
        a, b = abs(a), abs(b)
        if a < b:
            return self.gcd(b, a)
        while b:
            a, b = b, a % b
        return a
    def lcm(self, a, b):
        a, b = abs(a), abs(b)
        if a < b:
            return self.lcm(b, a)
        if a % b == 0:
            return a
        for i in range(2, b):
            if a * i % b == 0:
                return a * i
        return a * b
    def add(self, a, b):
        a_tmp1,  a_tmp2 = int(a.split('/')[0]), int(a.split('/')[1])
        b_tmp1,  b_tmp2 = int(b.split('/')[0]), int(b.split('/')[1])
        a_n, a_d = a_tmp1 / self.gcd(a_tmp1,  a_tmp2), a_tmp2 / self.gcd(a_tmp1,  a_tmp2)
        b_n, b_d = b_tmp1 / self.gcd(b_tmp1,  b_tmp2), b_tmp2 / self.gcd(b_tmp1,  b_tmp2)
        res_tmp2 = self.lcm(a_d, b_d)
        res_tmp1 = a_n * (self.lcm(a_d, b_d) / a_d) + b_n * (self.lcm(a_d, b_d) / b_d)
        res_n, res_d = res_tmp1 / self.gcd(res_tmp1,  res_tmp2), res_tmp2 / self.gcd(res_tmp1,  res_tmp2)
        return '{}/{}'.format(res_n, res_d)

Log in to reply
 

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