Advertisement
JmihPodvalbniy

Untitled

Nov 5th, 2024 (edited)
20
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.49 KB | Software | 0 0
  1. """Дз от 30.10.2024г."""
  2. #1)
  3. class MyFraction:
  4.  
  5.     def __init__(self, num, den):
  6.         if num == 0 or den == 0:
  7.             raise ValueError('Числитель и знаменатель не могут быть равны нулю')
  8.         self.num = num
  9.         self.den = den
  10.         self._simplify()
  11.  
  12.     def _simplify(self):
  13.  
  14.         gcd = self._gcd(self.num, self.den)
  15.         self.num //= gcd
  16.         self.den //= gcd
  17.  
  18.     def _gcd(self, a, b):
  19.  
  20.         while b:
  21.             a, b = b, a % b
  22.         return a
  23.  
  24.     # Генерация дробей
  25.     @staticmethod
  26.     def generate(num_min, num_max, den_min, den_max):
  27.  
  28.         import random
  29.         num = random.randint(num_min, num_max)
  30.         den = random.randint(den_min, den_max)
  31.         return MyFraction(num, den)
  32.  
  33.     # Строковое представление
  34.     def __str__(self):
  35.         return f'{self.num}/{self.den}'
  36.  
  37.     # Операции
  38.     def __mul__(self, other):
  39.         if isinstance(other, MyFraction):
  40.             return MyFraction(self.num * other.num, self.den * other.den)
  41.         elif isinstance(other, int):
  42.             return MyFraction(self.num * other, self.den)
  43.         else:
  44.             raise TypeError('Можно умножать только на дробь или целое число')
  45.  
  46.     def __truediv__(self, other):
  47.         if isinstance(other, MyFraction):
  48.             return MyFraction(self.num * other.den, self.den * other.num)
  49.         elif isinstance(other, int):
  50.             return MyFraction(self.num, self.den * other)
  51.         else:
  52.             raise TypeError('Можно делить только на дробь или целое число')
  53.  
  54. """Тестирование"""
  55.  
  56. fraction1 = MyFraction.generate(1, 10, 1, 10)
  57. fraction2 = MyFraction.generate(1, 10, 1, 10)
  58.  
  59. # Вывод дробей
  60. print(f'Дробь 1: {fraction1}')
  61. print(f'Дробь 2: {fraction2}')
  62.  
  63. # Умножение дробей
  64. product1 = fraction1 * fraction2
  65. print(f'Умножение дробей: {product1}')
  66.  
  67. # Деление дробей
  68. quotient1 = fraction1 / fraction2
  69. print(f'Деление дробей: {quotient1}')
  70.  
  71. # Умножение на целое число
  72. product2 = fraction1 / 2
  73. print(f'Умножение на целое число: {product2}')
  74.  
  75. # Деление на целое число
  76. quotient2 = fraction1 / 2
  77. print(f'Деление на целое число: {quotient2}')
  78.  
  79. #2)
  80.  
  81. from abc import ABC, abstractmethod
  82.  
  83. class AbstractTovar(ABC):
  84.     @abstractmethod
  85.     def print_menu(self):
  86.         pass
  87.  
  88. class Tovar(AbstractTovar):
  89.     def __init__(self, name, price):
  90.         self.name = name
  91.         self.price = price
  92.         self.selected = False
  93.  
  94.     def print_menu(self):
  95.         print(f'{self.name}: {self.price} руб.')
  96.  
  97.     def select(self):
  98.         self.selected = True
  99.  
  100.     def unselect(self):
  101.         self.selected = False
  102.  
  103. def show_price_list(tovars):
  104.     """Отображает прайс-лист товаров, разбивая их на страницы по 5 товаров."""
  105.     page_size = 5
  106.     total_pages = (len(tovars) + page_size - 1) // page_size
  107.     for page in range(total_pages):
  108.         print(f'\nСтраница {page + 1} из {total_pages}')
  109.         for i in range(page * page_size, min((page + 1) * page_size, len(tovars))):
  110.             tovars[i].print_menu()
  111.  
  112. def select_tovar(tovars):
  113.     """Позволяет пользователю выбрать товар по названию."""
  114.     name = input('Введите название товара: ')
  115.     for tovar in tovars:
  116.         if tovar.name.lower() == name.lower():
  117.             tovar.select()
  118.             print(f'Товар {tovar.name} выбран.')
  119.             return
  120.     print(f'Товар {name} не найден.')
  121.  
  122. def print_check(tovars):
  123.     """Печатает чек с выбранными товарами."""
  124.     total_sum = 0
  125.     print("\nЧек:")
  126.     for tovar in tovars:
  127.         if tovar.selected:
  128.             print(f'{tovar.name}: {tovar.price} руб.')
  129.             total_sum += tovar.price
  130.     print(f'Итого: {total_sum} руб.')
  131.  
  132. def main():
  133.     """Главная функция приложения."""
  134.     tovars = [
  135.         Tovar('Молоко', 60),
  136.         Tovar('Хлеб', 35),
  137.         Tovar('Яйца', 80),
  138.         Tovar('Сыр', 200),
  139.         Tovar('Масло', 150),
  140.         Tovar('Сок', 100),
  141.         Tovar('Печенье', 50),
  142.         Tovar('Чай', 120),
  143.         Tovar('Кофе', 180),
  144.         Tovar('Сахар', 40)
  145.     ]
  146.  
  147.     while True:
  148.         print('\nМеню:')
  149.         print('1. Показать прайс-лист')
  150.         print('2. Выбрать товар')
  151.         print('3. Напечатать чек')
  152.         print('4. Выйти')
  153.  
  154.         try:
  155.             choice = int(input('Введите номер действия: '))
  156.         except ValueError:
  157.             print('Неверный ввод. Пожалуйста, введите число.')
  158.             continue
  159.  
  160.         if choice == 1:
  161.             show_price_list(tovars)
  162.         elif choice == 2:
  163.             select_tovar(tovars)
  164.         elif choice == 3:
  165.             print_check(tovars)
  166.         elif choice == 4:
  167.             print('Выход из приложения.')
  168.             break
  169.         else:
  170.             print('Неверный ввод. Пожалуйста, выберите номер действия из меню.')
  171.  
  172. if __name__ == '__main__':
  173.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement