Clear and Naive Python Solution


  • 0

    10!=3628800

    from fractions import gcd
    class Solution(object):
        def fractionAddition(self, expression):
            """
            :type expression: str
            :rtype: str
            """
            # exp = ''.join([('+' if c=='-' else '') + c for c in expression])
            exp = expression.replace('-', '+-') # Thanks ManuelP. This is more clear than the above.
            # print exp
            exp = exp.split('+')
            # print exp
            a = [(int(s.split('/')[0])*3628800//int(s.split('/')[1])) if s else 0 for s in exp]
            # print a
            s = sum(a)
            b = 3628800
            
            if a==0:
                return '0/1'
            
            g = gcd(s,b)
            return str(s//g) + '/' + str(b//g)
    

  • 1

    I don't think exp = ''.join([('+' if c=='-' else '') + c for c in expression]) is "clear". I think it would be far clearer to instead use exp = expression.replace('-', '+-'). Also, it's unclear why you have those two ifs with return '0/1' and the print comments.


  • 0

    @ManuelP You are right. Thank you for your advice.


Log in to reply
 

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