Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def gcd(a, b):
- while b != 0:
- b, a = a % b, b
- return a
- def lcm(a, b):
- return abs( a * b // gcd(a, b))
- class Fraction:
- objCounter = 0
- def __init__(self, *args): # (self, counter, denominator) params
- if len(args) == 1 : # decimal fraction
- self.counter = args[0]*10
- # print(args[0])
- self.denominator = 10
- elif len(args) == 2:
- self.counter = args[0]
- self.denominator = args[1]
- if(self.denominator == 0):
- raise ValueError("denominator: 0 (zero value ecpt)")
- else:
- raise OverflowError("Unexpected param number, try again with 1 or 2 params to func")
- # self.counter = counter
- # self.denominator = denominator
- Fraction.objCounter = Fraction.objCounter + 1
- def __del__(self):
- Fraction.i = Fraction.objCounter - 1
- def __mul__(self, other):
- return Fraction(self.counter * other.counter, self.denominator * other.denominator)
- def __truediv__(self, other):
- return Fraction(self.counter * other.denominator, self.denominator * other.counter)
- def __str__(self):
- return str(int(self.counter)) + "/" + str(int(self.denominator))
- def __add__(self, other):
- if(self.denominator != other.denominator):
- m = lcm(self.denominator, other.denominator)
- l = (m / self.denominator * self.counter) + (m / other.denominator * other.counter)
- return Fraction(l,m)
- else:
- return (self.counter + other.counter, self.denominator)
- def __sub__(self, other):
- if(self.denominator != other.denominator):
- m = lcm(self.denominator, other.denominator)
- l = (m / self.denominator * self.counter) - (m / other.denominator * other.counter)
- return Fraction(l,m)
- else:
- return(self.counter + other.counter, self.denominator)
- u = Fraction(0.1)
- print(u)
- u2 = Fraction(3, 4)
- print(u.__add__(u2))
- print( 'NumOfObj:', Fraction.objCounter)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement