-
Notifications
You must be signed in to change notification settings - Fork 0
Python practice develop #1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: python_practice_master
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| #1. Написать функцию, которая проверяет является ли строка палиндромом. | ||
| def palindrome(s): | ||
| # Приводим строку к нижнему регистру и удаляем пробелы | ||
| s = s.lower().replace(' ', '') | ||
| # Сравниваем строку с её перевёрнутой версией | ||
| return s == s[::-1] | ||
|
|
||
| print(palindrome("Лидер Венере не вредил")) | ||
| print(palindrome("python")) | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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)) |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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 "Первая фигура имеет большую площадь, чем вторая." | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Лучше булевый результат возвращать, вместо строки. Иначе в вызвыающем коде придется писать проверки по типу |
||
| 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)) | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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: | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Оценок тоже касается |
||
| return 6000 | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Хардкодить литералы плохо, нужно выносить в константы |
||
| 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)) | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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() |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| 10 | ||
| 15 |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| 25 |
This file was deleted.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Желательно ставить типизацию везде