Fraction Addition and Subtraction LeetCode solution in Python

1
# Runtime: 35 ms (Top 88.02%) | Memory: 14.1 MB (Top 5.79%)
2
"""
3
approach:
4
first replace - with +- in the string so that implementation gets
5
a little easy
6
"""
7

8

9
class Solution:
10
def fractionAddition(self, expression: str) -> str:
11
expression = expression.replace("-", "+-")
12
parts = [item for item in expression.split("+") if item != ""]
13
numes, denoms, denom_set, lcm = [], [], set(), 1
14

15
def get_lcm(a, b):
16
if a == 1:
17
return b
18
if b == 1:
19
return a
20
if a < b:
21
if b % a == 0:
22
return a * get_lcm(1, b / a)
23
else:
24
return a * get_lcm(1, b)
25
else:
26
if a % b == 0:
27
return b * get_lcm(a / b, 1)
28
else:
29
return b * get_lcm(a, 1)
30

31
for part in parts:
32
num, den = part.split("/")
33
numes.append(int(num))
34
denoms.append(int(den))
35
lcm = get_lcm(lcm, int(den))
36

37
result = 0
38
for num, den in zip(numes, denoms):
39
result += num * int(lcm / den)
40

41
def get_gcd(a, b):
42
if a == 0:
43
return b
44
if b == 0:
45
return a
46
if a == b:
47
return a
48
elif a < b:
49
return get_gcd(a, b - a)
50
else:
51
return get_gcd(a - b, b)
52

53
gcd = get_gcd(abs(result), lcm)
54
return str(int(result / gcd)) + "/" + str(int(lcm / gcd))

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0