Created
October 22, 2017 21:11
-
-
Save cixuuz/57682860578139d5b0644fb519d1307a to your computer and use it in GitHub Desktop.
[592. Fraction Addition and Subtraction] #leetcode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
class Solution(object): | |
def fractionAddition(self, expression): | |
""" | |
:type expression: str | |
:rtype: str | |
""" | |
signs = list() | |
if expression[0] != "-": | |
signs.append("+") | |
signs.extend([c for c in expression if c in "+-"]) | |
prev_num = 0 | |
prev_den = 1 | |
i = 0 | |
for sub in re.split("(\\+)|(-)", expression): | |
if sub and sub not in "-+": | |
fraction = sub.split("/") | |
num = int(fraction[0]) | |
den = int(fraction[1]) | |
g = abs(self.gcd(den, prev_den)) | |
if signs[i] == "+": | |
prev_num = prev_num * den / g + num * prev_den / g | |
else: | |
prev_num = prev_num * den / g - num * prev_den / g | |
i += 1 | |
prev_den = den * prev_den / g | |
g = abs(self.gcd(prev_den, prev_num)) | |
prev_num /= g | |
prev_den /= g | |
return "{:d}/{:d}".format(int(prev_num), int(prev_den)) | |
@staticmethod | |
def gcd(a, b): | |
while b != 0: | |
a, b = b, a % b | |
return a |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment