Straightforward and short Python solution using regex and `fractions` module


  • 2

    With the fractions module, doing rational number arithmetic becomes really trivial.

    class Solution(object):
      def fractionAddition(self, expression):
        """
        :type expression: str
        :rtype: str
        """
        import re
        from fractions import Fraction
        # Append + to start if first fraction is positive for easier parsing.
        expression = ('+' + expression) if expression[0] != '-' else expression
        splitted = re.split('([-|\+]\d+\/\d+)', expression)
        splitted = [fragment for fragment in splitted if fragment.strip() != '']
      
        def parse_fraction(fraction):
          sign = fraction[0]
          numer, denom = [int(part) for part in fraction[1:].split('/')]
          return Fraction(numer if sign == '+' else -numer, denom)
      
        result = 0
        for fraction in [parse_fraction(part) for part in splitted]:
          result += fraction
        return "{}/{}".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.