aboutsummaryrefslogtreecommitdiff
path: root/fraction_addition_subtraction.py
diff options
context:
space:
mode:
authorJack Sangdahl <[email protected]>2024-08-22 19:42:58 -0600
committerJack Sangdahl <[email protected]>2024-08-22 19:42:58 -0600
commit9ec4c81450f3fb9429db5bac26d8400e4b8264d6 (patch)
treef031efbe76400f9d40d84f29164512d251bfdce4 /fraction_addition_subtraction.py
parent515d837f3d923eb5c360386e0ae03a31ddcea9b0 (diff)
downloadleetcode-9ec4c81450f3fb9429db5bac26d8400e4b8264d6.tar.gz
leetcode-9ec4c81450f3fb9429db5bac26d8400e4b8264d6.zip
592. fraction addition and subtraction
Diffstat (limited to 'fraction_addition_subtraction.py')
-rw-r--r--fraction_addition_subtraction.py36
1 files changed, 36 insertions, 0 deletions
diff --git a/fraction_addition_subtraction.py b/fraction_addition_subtraction.py
new file mode 100644
index 0000000..f7cb8d1
--- /dev/null
+++ b/fraction_addition_subtraction.py
@@ -0,0 +1,36 @@
+# 592. Fraction Addition and Subtraction
+from re import findall
+from math import gcd
+
+"""
+given a string 'expression' representing an expression of fraction addition
+and subtraction, return the calculation result in string format. the final
+result should an irreducible fraction. if your final result is an integer,
+change it to the format of a fraction has a denominator 1. so in this case, 2
+should be converted to "2/1"
+"""
+
+
+class Solution(object):
+ def fractionAddition(self, expression):
+ """
+ :type expression: str
+ :rtype: str
+ """
+ nums = map(int, findall("[+-]?\d+", expression))
+ a, b = 0, 1
+ for i in nums:
+ j = next(nums)
+ a = a * j + i * b
+ b *= j
+ g = gcd(a, b)
+ a //= g
+ b //= g
+ return "%d/%d" % (a, b)
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.fractionAddition(expression="-1/2+1/2"))
+ print(obj.fractionAddition(expression="-1/2+1/2+1/3"))
+ print(obj.fractionAddition(expression="1/3-1/2"))