diff --git a/1/palindrome.py b/1/palindrome.py new file mode 100644 index 0000000..e484e67 --- /dev/null +++ b/1/palindrome.py @@ -0,0 +1,9 @@ +#1. Написать функцию, которая проверяет является ли строка палиндромом. +def palindrome(s): + # Приводим строку к нижнему регистру и удаляем пробелы + s = s.lower().replace(' ', '') + # Сравниваем строку с её перевёрнутой версией + return s == s[::-1] + +print(palindrome("Лидер Венере не вредил")) +print(palindrome("python")) diff --git a/2/lambda.py b/2/lambda.py new file mode 100644 index 0000000..bf86370 --- /dev/null +++ b/2/lambda.py @@ -0,0 +1,20 @@ +#2. Написать функцию, которая принимает два аргумента: лямбда функция для фильтрации массива, массив строк. Сделать вызов данной функции для следующих функций фильтрации: +#• Исключить строки с пробелами +#• Исключить строки, начинающиеся с буквы “a” +#• Исключить строки, длина которых меньше 5 + +def filter_strings(filter_func, string_list): + return list(filter(filter_func, string_list)) + +string_list = ["привет мир", "апельсин", "яблоко", "банан", "кошка", "собака", "слон", "рыба"] +# Исключить строки с пробелами +no_spaces = lambda s: " " not in s +print(filter_strings(no_spaces, string_list)) + +# Исключить строки, начинающиеся с буквы “a” +no_a = lambda s: not s.startswith("а") +print(filter_strings(no_a, string_list)) + +# Исключить строки, длина которых меньше 5 +long_enough = lambda s: len(s) >= 5 +print(filter_strings(long_enough, string_list)) \ No newline at end of file diff --git a/3/figures.py b/3/figures.py new file mode 100644 index 0000000..f8a1243 --- /dev/null +++ b/3/figures.py @@ -0,0 +1,86 @@ +from math import pi + +class Shape: + def area(self): + pass + + def perimeter(self): + pass + + def compare_area(self, other_shape): + if self.area() > other_shape.area(): + return "Первая фигура имеет большую площадь, чем вторая." + elif self.area() < other_shape.area(): + return "Первая фигура имеет меньшую площадь, чем вторая." + else: + return "Обе фигуры имеют одинаковую площадь." + + def compare_perimeter(self, other_shape): + if self.perimeter() > other_shape.perimeter(): + return "Первая фигура имеет больший периметр, чем вторая." + elif self.perimeter() < other_shape.perimeter(): + return "Первая фигура имеет меньший периметр, чем вторая." + else: + return "Обе фигуры имеют одинаковый периметр." + +class Square(Shape): + def __init__(self, side): + self.side = side + + def area(self): + return self.side ** 2 + + def perimeter(self): + return 4 * self.side + + +class Rectangle(Shape): + def __init__(self, length, width): + self.length = length + self.width = width + + def area(self): + return self.length * self.width + + def perimeter(self): + return 2 * (self.length + self.width) + + +class Triangle(Shape): + def __init__(self, base, height, side1, side2, side3): + self.base = base + self.height = height + self.side1 = side1 + self.side2 = side2 + self.side3 = side3 + + def area(self): + return 0.5 * self.base * self.height + + def perimeter(self): + return self.side1 + self.side2 + self.side3 + + +class Circle(Shape): + def __init__(self, radius): + self.radius = radius + + def area(self): + return pi * (self.radius ** 2) + + def perimeter(self): + return 2 * pi * self.radius + + +# example usage + +square1 = Square(5) +print("Площадь квадрата:", square1.area()) +print("Периметр квадрата:", square1.perimeter()) + + +rect1 = Rectangle(8, 4) +print("Площадь прямоугольника:", rect1.area()) +print("Периметр прямоугольника:", rect1.perimeter()) + +print(square1.compare_area(rect1)) diff --git a/4/students.py b/4/students.py new file mode 100644 index 0000000..0612b21 --- /dev/null +++ b/4/students.py @@ -0,0 +1,63 @@ +#4. Создать классы студент, аспирант. Студент содержит свойства: номер группы, средний балл. Аспирант отличается от студента наличием научной работы (название работы в виде строки). Реализовать в классах следующие методы: +#• вывести информацию (фио, возраст) +#• вывести размер стипендии. Если средняя оценка равна 5, то стипендия 8000р для аспиранта и 6000р для студента, если меньше 5, то стипендия для аспиранта 6000р, для студента 4000р, в других случаях стипендия 0р +#• Сравнение размера стипендии с другим студентом/аспирантом (больше или меньше) + + +class Student: + def __init__(self, name, age, group_number, average_grade): + self.name = name + self.age = age + self.group_number = group_number + self.average_grade = average_grade + + def get_info(self): + print("Name: {}, Age: {}".format(self.name, self.age)) + + def get_scholarship(self): + if self.average_grade == 5: + return 6000 + elif self.average_grade < 5: + return 4000 + else: + return 0 + + def compare_scholarship(self, other_student): + if self.get_scholarship() > other_student.get_scholarship(): + return "{}'s scholarship is bigger".format(self.name) + elif self.get_scholarship() < other_student.get_scholarship(): + return "{}'s scholarship is smaller".format(self.name) + else: + return "{}'s scholarship is the same as {}".format(self.name, other_student.name) + + +class Aspirant(Student): + def __init__(self, name, age, group_number, average_grade, research_title): + super().__init__(name, age, group_number, average_grade) + self.research_title = research_title + + def get_info(self): + super().get_info() + print("Research Title: {}".format(self.research_title)) + + def get_scholarship(self): + if self.average_grade == 5: + return 8000 + elif self.average_grade < 5: + return 6000 + else: + return 0 + + +# example usage +student1 = Student("Jack Yar", 20, "31245", 5) +student2 = Student("Will Smith", 21, "31245", 4.5) +aspirant1 = Aspirant("Ryan Gosling", 26, "52315", 5, "Development of a gesture classifier using a webcam.") + +student1.get_info() +aspirant1.get_info() + +print(student1.get_scholarship()) +print(aspirant1.get_scholarship()) + +print(student1.compare_scholarship(aspirant1)) \ No newline at end of file diff --git a/5/decorator.py b/5/decorator.py new file mode 100644 index 0000000..d214cef --- /dev/null +++ b/5/decorator.py @@ -0,0 +1,30 @@ +import time + +def timer(func): + def wrapper(*args, **kwargs): + start_time = time.time() + result = func(*args, **kwargs) + end_time = time.time() + print("Function {} took {:.6f} seconds to execute".format(func.__name__, end_time - start_time)) + return result + return wrapper + +@timer +def sum_numbers(a, b): + time.sleep(1) # simulate some processing time + result = a + b + print("The sum of {} and {} is {}".format(a, b, result)) + +@timer +def read_and_sum_numbers(): + with open("input.txt", "r") as f: + a = int(f.readline()) + b = int(f.readline()) + result = a + b + with open("output.txt", "w") as f: + f.write(str(result)) + print("The sum of {} and {} has been written to output.txt".format(a, b)) + +# example usage +sum_numbers(5, 10) +read_and_sum_numbers() \ No newline at end of file diff --git a/5/input.txt b/5/input.txt new file mode 100644 index 0000000..13b64cb --- /dev/null +++ b/5/input.txt @@ -0,0 +1,2 @@ +10 +15 \ No newline at end of file diff --git a/5/output.txt b/5/output.txt new file mode 100644 index 0000000..410b14d --- /dev/null +++ b/5/output.txt @@ -0,0 +1 @@ +25 \ No newline at end of file diff --git a/main.py b/main.py deleted file mode 100644 index 5596b44..0000000 --- a/main.py +++ /dev/null @@ -1,16 +0,0 @@ -# This is a sample Python script. - -# Press Shift+F10 to execute it or replace it with your code. -# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings. - - -def print_hi(name): - # Use a breakpoint in the code line below to debug your script. - print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint. - - -# Press the green button in the gutter to run the script. -if __name__ == '__main__': - print_hi('PyCharm') - -# See PyCharm help at https://www.jetbrains.com/help/pycharm/