-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem2.py
More file actions
70 lines (51 loc) · 1.89 KB
/
Copy pathproblem2.py
File metadata and controls
70 lines (51 loc) · 1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
problem = "problem2"
student_name = "Abudi Alshamam"
student_numer = "N1212353"
import math
class Fraction:
def __init__(self, numerator, denominator):
self.numerator = numerator
self.denominator = denominator
def __str__(self):
return f"{self.numerator}/{self.denominator}"
def __add__(self, other):
new_numerator = self.numerator * other.denominator + self.denominator * other.numerator
new_denominator = self.denominator * other.denominator
return Fraction(new_numerator, new_denominator)
def __sub__(self, other):
new_numerator = self.numerator * other.denominator - self.denominator * other.numerator
new_denominator = self.denominator * other.denominator
return Fraction(new_numerator, new_denominator)
def __float__(self):
return self.numerator / self.denominator
def __truediv__(self, other):
new_numerator = self.numerator * other.denominator
new_denominator = self.denominator * other.numerator
return Fraction(new_numerator, new_denominator)
def inverse(self):
return Fraction(self.denominator, self.numerator)
def reduce(self):
gcd = math.gcd(self.numerator, self.denominator)
self.numerator //= gcd
self.denominator //= gcd
return self
def test_fraction_methods():
f1 = Fraction(3, 4)
f2 = Fraction(2, 5)
print("Testing Fraction class methods:")
print(f"f1: {f1}")
print(f"f2: {f2}")
# Test addition
print(f"{f1} + {f2} = {f1 + f2}")
# Test subtraction
print(f"{f1} - {f2} = {f1 - f2}")
# Test float conversion
print(f"float({f1}) = {float(f1)}")
# Test division
print(f"{f1} / {f2} = {f1 / f2}")
# Test inverse
print(f"inverse of {f1} = {f1.inverse()}")
# Test reduction
f3 = Fraction(8, 12)
print(f"{f3} Reduced = {f3.reduce()}")
test_fraction_methods()