-
Notifications
You must be signed in to change notification settings - Fork 262
Badriev A. (Basic_exercises) #36
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: main
Are you sure you want to change the base?
Changes from 7 commits
7eabf14
f3d43f8
a3d77c9
19e2ef3
eb457db
340e25e
24a75a7
29014c5
5e8c03b
ec1b21b
c115653
2d839db
84f10c7
3fcdf93
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 |
|---|---|---|
|
|
@@ -2,8 +2,7 @@ | |
| # Необходимо вывести имена всех учеников из списка с новой строки | ||
|
|
||
| names = ['Оля', 'Петя', 'Вася', 'Маша'] | ||
| # ??? | ||
|
|
||
| print(*names, sep='\n') | ||
|
|
||
| # Задание 2 | ||
| # Необходимо вывести имена всех учеников из списка, рядом с именем показать количество букв в нём | ||
|
|
@@ -12,8 +11,8 @@ | |
| # Петя: 4 | ||
|
|
||
| names = ['Оля', 'Петя', 'Вася', 'Маша'] | ||
| # ??? | ||
|
|
||
| for name in names: | ||
| print(f'{name}: {len(name)}') | ||
|
|
||
| # Задание 3 | ||
| # Необходимо вывести имена всех учеников из списка, рядом с именем вывести пол ученика | ||
|
|
@@ -25,8 +24,8 @@ | |
| 'Маша': False, | ||
| } | ||
| names = ['Оля', 'Петя', 'Вася', 'Маша'] | ||
| # ??? | ||
|
|
||
| for name in names: | ||
| print(f'{name}: {"мужской" if is_male[name] else "женский"}') | ||
|
|
||
| # Задание 4 | ||
| # Даны группу учеников. Нужно вывести количество групп и для каждой группы – количество учеников в ней | ||
|
|
@@ -40,8 +39,21 @@ | |
| ['Вася', 'Маша', 'Саша', 'Женя'], | ||
| ['Оля', 'Петя', 'Гриша'], | ||
| ] | ||
| # ??? | ||
|
|
||
| group_token = lambda group_to: ( | ||
| (group_to in range(5, 20)) and 'групп' or | ||
| (1 in (group_to, (diglast := group_to % 10))) and 'группа' or | ||
| ({group_to, diglast} & {2, 3, 4}) and 'группы' or 'групп') | ||
|
|
||
| student_token = lambda student_to: ( | ||
| (student_to in range(5, 20)) and 'учеников' or | ||
| (1 in (student_to, (diglast := student_to % 10))) and 'ученик' or | ||
|
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. Классно что было интересно заняться этим, но это не подразумевалось в задании. |
||
| ({student_to, diglast} & {2, 3, 4}) and 'ученика' or 'учеников') | ||
|
|
||
| print(f'Всего {len(groups)} {group_token(len(groups))}.') | ||
|
|
||
| for key, value in dict(enumerate(groups, start=1)).items(): | ||
| print(f'Группа {key}: {len(value)} {student_token(len(value))}.') | ||
|
|
||
| # Задание 5 | ||
| # Для каждой пары учеников нужно с новой строки перечислить учеников, которые в неё входят | ||
|
|
@@ -54,4 +66,6 @@ | |
| ['Оля', 'Петя', 'Гриша'], | ||
| ['Вася', 'Маша', 'Саша', 'Женя'], | ||
| ] | ||
| # ??? | ||
|
|
||
| for key, value in dict(enumerate(groups, start=1)).items(): | ||
|
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. вот тут не нужен dict().items() |
||
| print(f'Группа {key}:', ", ".join(value)) | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,6 @@ | ||
| import pandas as pd | ||
| from collections import Counter | ||
|
|
||
| # Задание 1 | ||
| # Дан список учеников, нужно посчитать количество повторений каждого имени ученика | ||
| # Пример вывода: | ||
|
|
@@ -12,8 +15,12 @@ | |
| {'first_name': 'Маша'}, | ||
| {'first_name': 'Петя'}, | ||
| ] | ||
| # ??? | ||
| names = [] | ||
| for student in students: | ||
| names.append(student['first_name']) | ||
|
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. Можно ли переделать с использование list comprehension? |
||
|
|
||
| for key, value in Counter(names).items(): | ||
| print(f'{key}: {value}') | ||
|
|
||
| # Задание 2 | ||
| # Дан список учеников, нужно вывести самое часто повторящееся имя | ||
|
|
@@ -26,8 +33,16 @@ | |
| {'first_name': 'Маша'}, | ||
| {'first_name': 'Оля'}, | ||
| ] | ||
| # ??? | ||
| names = [] | ||
| for student in students: | ||
| names.append(student['first_name']) | ||
|
|
||
| print('_' * 75) | ||
|
|
||
| # print(pd.DataFrame(names).mode()[0][0]) | ||
| print(f'Самое частое имя среди учеников: {max(names, key=lambda x: names.count(x))}') | ||
|
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('_' * 75) | ||
|
|
||
| # Задание 3 | ||
| # Есть список учеников в нескольких классах, нужно вывести самое частое имя в каждом классе. | ||
|
|
@@ -44,16 +59,18 @@ | |
| {'first_name': 'Маша'}, | ||
| {'first_name': 'Маша'}, | ||
| {'first_name': 'Оля'}, | ||
| ],[ # это – третий класс | ||
| ], [ # это – третий класс | ||
| {'first_name': 'Женя'}, | ||
| {'first_name': 'Петя'}, | ||
| {'first_name': 'Женя'}, | ||
| {'first_name': 'Саша'}, | ||
| ], | ||
| ] | ||
| # ??? | ||
|
|
||
| for key, value in dict(enumerate(school_students, start=1)).items(): | ||
|
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. dict().items не нужен |
||
| print(f'Самое частое имя в классе {key}: ' | ||
| f'{(lambda x: max([x["first_name"] for x in value], key=lambda y: x.count(y)))(value)}') | ||
|
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('_' * 75) | ||
| # Задание 4 | ||
| # Для каждого класса нужно вывести количество девочек и мальчиков в нём. | ||
| # Пример вывода: | ||
|
|
@@ -72,8 +89,12 @@ | |
| 'Миша': True, | ||
| 'Даша': False, | ||
| } | ||
| # ??? | ||
| for group in school: | ||
| print(f'Класс {group["class"]}: девочки ' | ||
| f'{(lambda x: [is_male[x["first_name"]] for x in group["students"]])(group).count(False)}, мальчики ' | ||
|
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. Переделай через обычные именованные функции. |
||
| f'{(lambda x: [is_male[x["first_name"]] for x in group["students"]])(group).count(True)}') | ||
|
|
||
| print('_' * 75) | ||
|
|
||
| # Задание 5 | ||
| # По информации о учениках разных классов нужно найти класс, в котором больше всего девочек и больше всего мальчиков | ||
|
|
@@ -91,5 +112,13 @@ | |
| 'Олег': True, | ||
| 'Миша': True, | ||
| } | ||
| # ??? | ||
| girls_boys = [] | ||
|
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. нэйминг, сделай так, что бы название переменной отражало что в ней лежит и как ей пользоваться. |
||
| for group in school: | ||
| girls_boys.append({ | ||
| 'class': group['class'], | ||
| 'girls': (lambda x: [is_male[x["first_name"]] for x in group["students"]])(group).count(False), | ||
| 'boys': (lambda x: [is_male[x["first_name"]] for x in group["students"]])(group).count(True) | ||
| }) | ||
|
|
||
| print(f"Больше всего мальчиков в классе: {max(girls_boys, key=lambda x: x['boys'])['class']}") | ||
| print(f"Больше всего девочек в классе: {max(girls_boys, key=lambda x: x['girls'])['class']}") | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,11 @@ | ||
| import random | ||
| import uuid | ||
| import datetime | ||
| import lorem | ||
| from collections import Counter | ||
| from itertools import groupby | ||
|
|
||
|
|
||
| """ | ||
| Пожалуйста, приступайте к этой задаче после того, как вы сделали и получили ревью ко всем остальным задачам | ||
| в этом репозитории. Она значительно сложнее. | ||
|
|
@@ -30,11 +38,7 @@ | |
|
|
||
| Весь код стоит разбить на логические части с помощью функций. | ||
| """ | ||
| import random | ||
| import uuid | ||
| import datetime | ||
|
|
||
| import lorem | ||
|
|
||
|
|
||
| def generate_chat_history(): | ||
|
|
@@ -66,5 +70,72 @@ def generate_chat_history(): | |
| return messages | ||
|
|
||
|
|
||
| def task1(messages): | ||
| users_list = [message['sent_by'] for message in messages] | ||
| return f'{max(users_list, key=lambda x: users_list.count(x))} - ' \ | ||
|
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. возвращай просто значение, без сообщения. И не разрывай так строки. Используй (), если надо. Но лучше не разрывать вообще. |
||
| f'айди пользователя, который написал больше всех сообщений' | ||
|
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 task2(messages): | ||
| answers_list = [message['reply_for'] for message in messages if message['reply_for'] is not None] | ||
| for message in messages: | ||
| if message['id'] == max(answers_list, key=lambda x: answers_list.count(x)): | ||
| return f'{message["sent_by"]} - айди пользователя, на сообщения которого больше всего отвечали' | ||
|
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 task3(messages): | ||
| id_unique = {} | ||
| for message in messages: | ||
| if message['sent_by'] not in id_unique: | ||
| id_unique[message['sent_by']] = message['seen_by'] | ||
| else: | ||
| id_unique[message['sent_by']] = id_unique[message['sent_by']] + message['seen_by'] | ||
|
|
||
| for key, value in id_unique.items(): | ||
| print(f'Сообщения от пользователя под айди {key}, видело {len(set(value))} уникальных пользователей') | ||
|
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 task4(messages): | ||
|
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. Название должно отражать что функция возвращает. |
||
| times = { | ||
| 'утром (до 12 часов)': [], | ||
|
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. ключи должны быть простыми вроде: morning, day, evening |
||
| 'днём (12-18 часов)': [], | ||
| 'вечером (после 18 часов)': [] | ||
| } | ||
|
|
||
| for message in messages: | ||
| if float(message["sent_at"].strftime('%H.%M')) < 12: | ||
|
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. Это очень непрямой способ проверять время. |
||
| times['утром (до 12 часов)'].append(float(message["sent_at"].strftime('%H.%M'))) | ||
| elif 18 > float(message["sent_at"].strftime('%H.%M')) > 12: | ||
| times['днём (12-18 часов)'].append(float(message["sent_at"].strftime('%H.%M'))) | ||
| else: | ||
| times['вечером (после 18 часов)'].append(float(message["sent_at"].strftime('%H.%M'))) | ||
|
|
||
| return f'В чате больше всего сообщений: {max(times, key=lambda x: len(times[x]))}' | ||
|
|
||
| def task5(messages): | ||
| result = [] | ||
|
|
||
| for k, g in groupby([message['reply_for'] for message in messages]): | ||
|
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. k, g - плохие имена |
||
| length = len(list(g)) | ||
| result.append((k, length)) | ||
|
|
||
| lst = [(key, value) for key, value in sorted(result, key=lambda x: x[1], reverse=True) if | ||
| key is not None and value > 1] | ||
|
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? |
||
|
|
||
| if len(lst) > 0: | ||
| for key, value in lst: | ||
| print(f'Сообщение под айди: "{key}" стало началом для самых длинных тредов (цепочек ответов), а именно ' | ||
|
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 instead of print |
||
| f'{value}.') | ||
| else: | ||
| print('Максимальная длина тредов (цепочек ответов) составляет 1.') | ||
|
|
||
| if __name__ == "__main__": | ||
| print(generate_chat_history()) | ||
| print(task1(generate_chat_history())) | ||
| print('_' * 75) | ||
| print(task2(generate_chat_history())) | ||
| print('_' * 75) | ||
| task3(generate_chat_history()) | ||
| print('_' * 75) | ||
| print(task4(generate_chat_history())) | ||
| print('_' * 75) | ||
| task5(generate_chat_history()) | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,28 +1,25 @@ | ||
| # Вывести последнюю букву в слове | ||
| word = 'Архангельск' | ||
| # ??? | ||
|
|
||
| print(word[-1]) | ||
|
|
||
| # Вывести количество букв "а" в слове | ||
| word = 'Архангельск' | ||
| # ??? | ||
|
|
||
| print(word.lower().count('а')) | ||
|
|
||
| # Вывести количество гласных букв в слове | ||
| word = 'Архангельск' | ||
| # ??? | ||
|
|
||
| vowels = 'аеиоуэюяыё' | ||
|
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(len([letter for letter in word.lower() if letter in vowels])) | ||
|
|
||
| # Вывести количество слов в предложении | ||
| sentence = 'Мы приехали в гости' | ||
| # ??? | ||
|
|
||
| print(len(sentence.split())) | ||
|
|
||
| # Вывести первую букву каждого слова на отдельной строке | ||
| sentence = 'Мы приехали в гости' | ||
| # ??? | ||
|
|
||
| for word in sentence.split(): | ||
| print(word[0]) | ||
|
|
||
| # Вывести усреднённую длину слова в предложении | ||
| sentence = 'Мы приехали в гости' | ||
| # ??? | ||
| print(int(sum([len(word) for word in sentence.split()]) / len(sentence.split()))) | ||
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.
Не используй лямбда функции без острой необходимости
К тому же здесь ты даже ей имя даешь. Обычный def будет читаемее
https://towardsdatascience.com/the-python-lambda-function-has-become-a-devil-d0340404abcb
Переделай в обычные функции