-
Notifications
You must be signed in to change notification settings - Fork 474
Badriev A. (learn-homework-1) #141
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: master
Are you sure you want to change the base?
Changes from 12 commits
155cfa0
3760b21
0f6beb7
622fd30
fba9203
afccf42
3a5f427
6053d5e
50de0a0
4fc46f3
c11fa6a
a46892c
6bba719
2151f54
414b4bb
578b88b
406af7b
b8a0cee
182b329
6053d08
da7fa26
fa0366f
696e07f
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 |
|---|---|---|
|
|
@@ -5,22 +5,39 @@ | |
| Условный оператор: Сравнение строк | ||
|
|
||
| * Написать функцию, которая принимает на вход две строки | ||
| * Проверить, является ли то, что передано функции, строками. | ||
| * Проверить, является ли то, что передано функции, строками. | ||
| Если нет - вернуть 0 | ||
| * Если строки одинаковые, вернуть 1 | ||
| * Если строки разные и первая длиннее, вернуть 2 | ||
| * Если строки разные и вторая строка 'learn', возвращает 3 | ||
| * Вызвать функцию несколько раз, передавая ей разные праметры | ||
| * Вызвать функцию несколько раз, передавая ей разные праметры | ||
| и выводя на экран результаты | ||
|
|
||
| """ | ||
|
|
||
|
|
||
| def strings(str1, str2): | ||
| if isinstance(str1, str) and isinstance(str2, str): | ||
|
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. А можно сделать код менее вложенным? Вложенный условия сложно понимать. Совершенно не вижу причины для трех уровней вложенности тут. |
||
| if str1 == str2: | ||
| return 1 | ||
| else: | ||
| if len(str1) > len(str2) and str2 != 'learn': | ||
| return 2 | ||
| elif str2.lower() == 'learn': | ||
| return 3 | ||
| return f'Для строк "{str1}" и "{str2}" нет вывода' | ||
|
|
||
| return 0 | ||
|
|
||
|
|
||
| def main(): | ||
| """ | ||
| Эта функция вызывается автоматически при запуске скрипта в консоли | ||
| В ней надо заменить pass на ваш код | ||
| """ | ||
| pass | ||
|
|
||
| print(strings('hello', 1)) | ||
| print(strings('hello', 'world')) | ||
| print(strings('qwerty', '123')) | ||
| print(strings('learn', 'learn')) | ||
| print(strings('learn_python', 'learn')) | ||
| print(strings(None, None)) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,5 @@ | ||
| import numpy as np | ||
|
|
||
| """ | ||
|
|
||
| Домашнее задание №1 | ||
|
|
@@ -6,7 +8,7 @@ | |
|
|
||
| * Дан список словарей с данными по колличеству проданных телефонов | ||
| [ | ||
| {'product': 'iPhone 12', 'items_sold': [363, 500, 224, 358, 480, 476, 470, 216, 270, 388, 312, 186]}, | ||
| {'product': 'iPhone 12', 'items_sold': [363, 500, 224, 358, 480, 476, 470, 216, 270, 388, 312, 186]}, | ||
| {'product': 'Xiaomi Mi11', 'items_sold': [317, 267, 290, 431, 211, 354, 276, 526, 141, 453, 510, 316]}, | ||
| {'product': 'Samsung Galaxy 21', 'items_sold': [343, 390, 238, 437, 214, 494, 441, 518, 212, 288, 272, 247]}, | ||
| ] | ||
|
|
@@ -16,12 +18,39 @@ | |
| * Посчитать и вывести среднее количество продаж всех товаров | ||
| """ | ||
|
|
||
|
|
||
| def sum_sales_for_each_product(lsts): | ||
| for lst in lsts: | ||
| print(f'Cуммарное количество продаж товара: "{lst["product"]}" составляет {sum(lst["items_sold"])} шт.') | ||
|
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. print наружу из функции, тут делаем return |
||
|
|
||
|
|
||
| def avg_sales_for_each_product(lsts): | ||
| for lst in lsts: | ||
| print(f'Среднее количество продаж товара: "{lst["product"]}" составляет {round(np.average(lst["items_sold"]))} шт.') | ||
|
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. Попробуй решить без numpy. Использование нампи не дает большой выгоды тут, и в продакшен коде * такое использовать не принято |
||
|
|
||
|
|
||
| def sum_sales_for_all_product(lsts): | ||
| return f'Суммарное количество продаж товаров: "{", ".join([lst["product"] for lst in lsts])}" составляет {sum([sum(lst["items_sold"]) for lst in lsts])} шт.' | ||
|
|
||
|
|
||
| def avg_sales_for_all_product(lsts): | ||
| return f'Среднее количество продаж товаров: "{", ".join([lst["product"] for lst in lsts])}" составляет {round(np.average([np.average(lst["items_sold"]) for lst in lsts]))} шт.' | ||
|
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. Кажется среднее средних не тоже самое что просили посчитать в задаче. |
||
|
|
||
|
|
||
| def main(): | ||
| """ | ||
| Эта функция вызывается автоматически при запуске скрипта в консоли | ||
| В ней надо заменить pass на ваш код | ||
| """ | ||
| pass | ||
|
|
||
| sales = [ | ||
| {'product': 'iPhone 12', 'items_sold': [363, 500, 224, 358, 480, 476, 470, 216, 270, 388, 312, 186]}, | ||
| {'product': 'Xiaomi Mi11', 'items_sold': [317, 267, 290, 431, 211, 354, 276, 526, 141, 453, 510, 316]}, | ||
| {'product': 'Samsung Galaxy 21', 'items_sold': [343, 390, 238, 437, 214, 494, 441, 518, 212, 288, 272, 247]}, | ||
| ] | ||
| sum_sales_for_each_product(sales) | ||
| print('_' * 75) | ||
| avg_sales_for_each_product(sales) | ||
| print('_' * 75) | ||
| print(sum_sales_for_all_product(sales)) | ||
| print('_' * 75) | ||
| print(avg_sales_for_all_product(sales)) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,5 @@ | ||
| import random | ||
|
|
||
| """ | ||
|
|
||
| Домашнее задание №1 | ||
|
|
@@ -12,16 +14,31 @@ | |
|
|
||
| Пользователь: Что делаешь? | ||
| Программа: Программирую | ||
|
|
||
| """ | ||
| import time | ||
|
|
||
| questions_and_answers = {'как дела': ('Отлично!!!', 'Хорошо)', 'Так себе('), 'кто ты': ('ИИ', 'Не знаю', 'Программа'), | ||
| 'что делаешь': ('Программирую', 'Ничего', 'Секрет'), | ||
| 'как тебя зовут': ('У меня много имен', 'Секрет')} | ||
|
|
||
| questions_and_answers = {} | ||
|
|
||
| def ask_user(answers_dict): | ||
| """ | ||
| Замените pass на ваш код | ||
| """ | ||
| pass | ||
|
|
||
| while True: | ||
|
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. В этом цикле все смешалось в кучу, логика, ввод-вывод, задержки. |
||
| time.sleep(0.7) | ||
| question = input('Введите вопрос:\nUser: ').strip().lower() | ||
| if question in questions_and_answers: | ||
| print(f'AI: {random.choice(questions_and_answers[question])}') | ||
| elif question.lower() in ['хватит', 'стоп', 'stop']: | ||
| break | ||
| else: | ||
| time.sleep(0.7) | ||
| print('Такого вопроса нет в общей базе') | ||
| time.sleep(1) | ||
| print('Придумайте свой ответ на этот вопрос') | ||
| time.sleep(1) | ||
| questions_and_answers[question] = (input('Введите ответ на вопрос:\nUser: '.strip()),) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| ask_user(questions_and_answers) | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -10,19 +10,42 @@ | |
| * Первые два нужно приводить к вещественному числу при помощи float(), | ||
| а третий - к целому при помощи int() и перехватывать исключения | ||
| ValueError и TypeError, если приведение типов не сработало. | ||
|
|
||
| """ | ||
| import sys | ||
|
|
||
|
|
||
| def discounted(price, discount, max_discount=20): | ||
| try: | ||
| price = abs(float(price)) | ||
| except (ValueError, TypeError): | ||
| return f'Произошла ошибка {sys.exc_info()[0]}. Проверьте корректность введенной цены товара {price=}.' | ||
|
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. Можно проще получать текущее исключение, в except блоке добавляешь as ex, и используешь переменную ex |
||
|
|
||
| try: | ||
| discount = abs(float(discount)) | ||
| except (ValueError, TypeError): | ||
| return f'Произошла ошибка {sys.exc_info()[0]}. Проверьте корректность введенной скидки на товар {discount=}.' | ||
|
|
||
| try: | ||
| max_discount = abs(int(max_discount)) | ||
| except (ValueError, TypeError): | ||
| return f'Произошла ошибка {sys.exc_info()[0]}. Проверьте корректность введенной максимальной ' \ | ||
| f'скидки на товар {max_discount=}.' | ||
|
|
||
| if max_discount >= 100: | ||
| raise ValueError("Слишком большая максимальная скидка") | ||
| if discount >= max_discount: | ||
| return price | ||
| else: | ||
| return price - (price * discount / 100) | ||
|
|
||
|
|
||
| def discounted(price, discount, max_discount=20) | ||
| """ | ||
| Замените pass на ваш код | ||
| """ | ||
| pass | ||
|
|
||
| if __name__ == "__main__": | ||
| print(discounted(100, 2)) | ||
| print(discounted(100, "3")) | ||
| print(discounted("100", "4.5")) | ||
| print(discounted("five", 5)) | ||
| print(discounted("сто", "десять")) | ||
| print(discounted(100.0, 5, "10")) | ||
| print(discounted(None, 5, "10.0")) | ||
| print(discounted(100, 5, None)) | ||
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.
когда ты оборачиваешь range в tuple, ты заставляешь программу хранить в память все 60 чисел, в несортированном тупле. Это и памяти много занимает, и перебор он делает последовательно по всем числам в списках.
По крайней мере оставь просто range, должно работать.
Но вообще задача была про сделать цепочку if.
C одной стороны у тебя классный, расширяемый подход. С другой стороны цепочка if понятнее, и работает быстрее. Если тебе не нужно вытаскивать произвольный список правил из БД, то я бы сказал что эта абстрактность тут ни к чему - она только усложняет код.