Class for calculation with fractions
def gcd(a, b):
if a == b:
return a
elif a > b:
if a % b != 0:
return gcd(b, a % b)
else:
return b
else:
return gcd(b, a)
def lcm(a, b):
return a * b // gcd(a, b)
class Fraction:
def __init__(self, numerator, denominator):
g = gcd(numerator, denominator)
self.top = numerator // g
self.bottom = denominator // g
#Equality test
def __eq__(self, other):
first_num = self.top * other.bottom
second_num = other.top * self.bottom
return first_num == second_num
def __add__(self, other):
sum_denom = lcm(self.bottom, other.bottom)
first_num = sum_denom * self.top // self.bottom
second_num = sum_denom * other.top // other.bottom
sum_num = first_num + second_num
return Fraction(sum_num, sum_denom)
def __sub__(self, other):
dif_denom = lcm(self.bottom, other.bottom)
first_num = sum_denom * self.top // self.bottom
second_num = sum_denom * other.top // other.bottom
dif_num = first_num - second_num
return Fraction(dif_num, dif_denom)
def __mul__(self, other):
return Fraction(self.top * other.top, self.bottom * other.bottom)
def __truediv__(self, other):
return Fraction(self.top * other.bottom, self.bottom * other.top)
def __str__(self):
return str(self.top) + "/" + str(self.bottom)
# TODO: Replace examples and use TDD development by writing your own tests
# These are some of the methods available:
# test.expect(boolean, [optional] message)
# test.assert_equals(actual, expected, [optional] message)
# test.assert_not_equals(actual, expected, [optional] message)
# You can use Test.describe and Test.it to write BDD style test groupings
Arithmetic
Mathematics
Algorithms
Logic
Numbers
def greatest_common_divisor(*args):
def gcd(a, b):
if a == b: return a
elif a > b:
return (gcd(b, a % b) if a % b != 0 else b)
else:
return gcd(b, a)
res = gcd(args[0], args[1])
if len(args) > 2:
for i in range(2, len(args)):
res = gcd(res, args[i])
return res
test.assert_equals(greatest_common_divisor(6, 4), 2)
test.assert_equals(greatest_common_divisor(2, 4, 8), 2)
test.assert_equals(greatest_common_divisor(2, 3, 5, 7, 11), 1)
test.assert_equals(greatest_common_divisor(3, 9, 3, 9), 3)