two python solutions


  • 0
    F

    method 1:

        def fractionAddition(self, expression):
            """
            :type expression: str
            :rtype: str
            """
            import re
    
            def gcd(x, y):
                while y:
                    x, y = y, x % y
                return x
    
            nums = map(int, re.findall('[+-]?\d+', expression))
            A, B = 0, 1
            for a, b in zip(nums[::2], nums[1::2]):
                A = A * b + B * a
                B *= b
                g = gcd(A, B)
                A /= g
                B /= g
            return '{0}/{1}'.format(A, B)
    

    method 2:

        def fractionAddition1(self, expression):
            """
            :type expression: str
            :rtype: str
            """
            from fractions import Fraction
            result = sum(map(Fraction, expression.replace('+', ' +').replace('-', ' -').split()))
            return '{0}/{1}'.format(result.numerator, result.denominator)

Log in to reply
 

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