Advertisement
Guest User

Klasa ułamki bez main'a

a guest
Apr 8th, 2020
198
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.19 KB | None | 0 0
  1.  
  2. def gcd(a, b):
  3.   while b != 0:
  4.       b, a = a % b, b
  5.   return a
  6.  
  7. def lcm(a, b):
  8.   return abs( a * b // gcd(a, b))
  9.  
  10. class Fraction:
  11.       objCounter = 0
  12.       def __init__(self, *args): # (self, counter, denominator) params
  13.             if len(args) == 1 : # decimal fraction
  14.                 self.counter = args[0]*10
  15.                 # print(args[0])
  16.                 self.denominator = 10
  17.             elif len(args) == 2:
  18.                 self.counter = args[0]
  19.                 self.denominator = args[1]
  20.                 if(self.denominator == 0):
  21.                       raise ValueError("denominator: 0 (zero value ecpt)")
  22.             else:
  23.                 raise OverflowError("Unexpected param number, try again with 1 or 2 params to func")
  24.             # self.counter = counter
  25.             # self.denominator = denominator
  26.             Fraction.objCounter = Fraction.objCounter + 1
  27.  
  28.       def __del__(self):
  29.             Fraction.i = Fraction.objCounter - 1
  30.  
  31.       def __mul__(self, other):
  32.             return Fraction(self.counter * other.counter, self.denominator * other.denominator)
  33.  
  34.       def __truediv__(self, other):
  35.             return Fraction(self.counter * other.denominator, self.denominator * other.counter)
  36.  
  37.       def __str__(self):
  38.             return str(int(self.counter)) + "/" + str(int(self.denominator))
  39.  
  40.       def __add__(self, other):
  41.             if(self.denominator != other.denominator):
  42.                 m = lcm(self.denominator, other.denominator)
  43.                 l = (m / self.denominator * self.counter) + (m / other.denominator * other.counter)
  44.                 return Fraction(l,m)
  45.             else:
  46.                   return (self.counter + other.counter, self.denominator)
  47.  
  48.       def __sub__(self, other):
  49.             if(self.denominator != other.denominator):
  50.                 m = lcm(self.denominator, other.denominator)
  51.                 l = (m / self.denominator * self.counter) - (m / other.denominator * other.counter)
  52.                 return Fraction(l,m)
  53.             else:
  54.                   return(self.counter + other.counter, self.denominator)
  55.  
  56. u = Fraction(0.1)
  57. print(u)
  58. u2 = Fraction(3, 4)
  59. print(u.__add__(u2))
  60. print( 'NumOfObj:', Fraction.objCounter)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement