Advertisement
fevzi02

ПЗ - 2. Задание 1.

Oct 25th, 2021
1,024
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.02 KB | None | 0 0
  1. """ Задание 1: расширить класс Fraction методами сложения двух дробей, вычитания двух дробей, деления двух дробей и сокращения """
  2. class Fraction:
  3.     def __init__(self, num, denum):
  4.         self.num = num
  5.         self.denum = denum
  6.  
  7.     def gcd(self, a, b):
  8.         m = b
  9.         if a < b:
  10.             m = a
  11.         for i in range(m, 1, -1):
  12.             if a % i == 0 and b % i == 0:
  13.                 return i
  14.         return 1
  15.  
  16.     def reduction(self, t):
  17.         temp = Fraction(1,1)
  18.         k = self.gcd(t.num, t.denum)
  19.         temp.num = t.num // k
  20.         temp.denum = t.denum // k
  21.         return temp
  22.  
  23.     def multiplication(self, t):
  24.         temp = Fraction(1,1)
  25.         temp.num = self.num * t.num
  26.         temp.denum = self.denum * t.denum
  27.         return self.reduction(temp)
  28.  
  29.     def division(self, t):
  30.         if t.denum != 0:
  31.             temp = Fraction(1,1)
  32.             temp.num = self.num * t.denum
  33.             temp.denum = self.denum * t.num
  34.         else:
  35.             temp = Fraction(0,0)
  36.         return self.reduction(temp)
  37.  
  38.     def addition(self, t):
  39.         temp = Fraction(1,1)
  40.         temp.num = self.num * t.denum + t.num * self.denum
  41.         temp.denum = self.denum * t.denum
  42.         return self.reduction(temp)
  43.  
  44.     def subtraction(self, t):
  45.         temp = Fraction(1,1)
  46.         temp.num = self.num * t.denum - t.num * self.denum
  47.         temp.denum = self.denum * t.denum
  48.         return self.reduction(temp)
  49.  
  50.     def print_fractoin(self):
  51.         if self.denum != 0:
  52.             print ("{}/{}".format(self.num, self.denum))
  53.         else:
  54.             print("ERR")
  55. #-------------------------------------------------------------------------------
  56. f1 = Fraction(10,10)
  57. f2 = Fraction(10,10)
  58.  
  59. f_add = f1.addition(f2)
  60. f_add.print_fractoin()
  61.  
  62. f_sub = f1.subtraction(f2)
  63. f_sub.print_fractoin()
  64.  
  65. f_mult = f1.multiplication(f2)
  66. f_mult.print_fractoin()
  67.  
  68. f_div = f1.division(f2)
  69. f_div.print_fractoin()
  70.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement