-
Notifications
You must be signed in to change notification settings - Fork 259
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 9 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 |
|---|---|---|
| @@ -1,19 +1,30 @@ | ||
| from collections import Counter | ||
|
|
||
|
|
||
| # Задание 1 | ||
| # Дан список учеников, нужно посчитать количество повторений каждого имени ученика | ||
| # Пример вывода: | ||
| # Вася: 1 | ||
| # Маша: 2 | ||
| # Петя: 2 | ||
|
|
||
| # создадим функцию, которая возвращает список студентов по ключу 'first_name' | ||
| def student_list(lst): | ||
|
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. нэйминг надо поправить. пример: get_students_first_names(student_list): То есть в идеале, название функции должно отражать тот смысл который ты передаешь комментарием. |
||
| return [student['first_name'] for student in lst] | ||
|
|
||
|
|
||
| students = [ | ||
| {'first_name': 'Вася'}, | ||
| {'first_name': 'Петя'}, | ||
| {'first_name': 'Маша'}, | ||
| {'first_name': 'Маша'}, | ||
| {'first_name': 'Петя'}, | ||
| ] | ||
| # ??? | ||
|
|
||
| for name, count_students in Counter(student_list(students)).items(): | ||
| print(f'{name}: {count_students}') | ||
|
|
||
| print('_' * 75) | ||
|
|
||
| # Задание 2 | ||
| # Дан список учеников, нужно вывести самое часто повторящееся имя | ||
|
|
@@ -26,9 +37,17 @@ | |
| {'first_name': 'Маша'}, | ||
| {'first_name': 'Оля'}, | ||
| ] | ||
| # ??? | ||
|
|
||
|
|
||
| # Создадим функцию, которая принимает list для нахождения максимального повторяющегося элемента в данном списке | ||
| def maximum_frequency(lst): | ||
| return Counter(lst).most_common(1)[0][0] | ||
|
|
||
|
|
||
| print(f'Самое частое имя среди учеников: {maximum_frequency(student_list(students))}') | ||
|
|
||
| print('_' * 75) | ||
|
|
||
| # Задание 3 | ||
| # Есть список учеников в нескольких классах, нужно вывести самое частое имя в каждом классе. | ||
| # Пример вывода: | ||
|
|
@@ -44,20 +63,23 @@ | |
| {'first_name': 'Маша'}, | ||
| {'first_name': 'Маша'}, | ||
| {'first_name': 'Оля'}, | ||
| ],[ # это – третий класс | ||
| ], [ # это – третий класс | ||
| {'first_name': 'Женя'}, | ||
| {'first_name': 'Петя'}, | ||
| {'first_name': 'Женя'}, | ||
| {'first_name': 'Саша'}, | ||
| ], | ||
| ] | ||
| # ??? | ||
|
|
||
| for class_number, students in enumerate(school_students, start=1): | ||
| print(f'Самое частое имя в классе {class_number}: {maximum_frequency(student_list(students))}') | ||
|
|
||
| print('_' * 75) | ||
|
|
||
| # Задание 4 | ||
| # Для каждого класса нужно вывести количество девочек и мальчиков в нём. | ||
| # Пример вывода: | ||
| # Класс 2a: девочки 2, мальчики 0 | ||
| # Класс 2a: девочки 2, мальчики 0 | ||
| # Класс 2б: девочки 0, мальчики 2 | ||
|
|
||
| school = [ | ||
|
|
@@ -72,9 +94,21 @@ | |
| 'Миша': True, | ||
| 'Даша': False, | ||
| } | ||
| # ??? | ||
|
|
||
|
|
||
| def find_girls(): | ||
|
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. нэйминг. название функции должно отражать, что ты возвращаешь подсчитанное число. И передавай group явно, через аргументы. |
||
| return [is_male[girls["first_name"]] for girls in group["students"]].count(False) | ||
|
|
||
|
|
||
| def find_boys(): | ||
| return [is_male[boys["first_name"]] for boys in group["students"]].count(True) | ||
|
|
||
|
|
||
| for group in school: | ||
| print(f'Класс {group["class"]}: девочки {find_girls()}, мальчики {find_boys()}') | ||
|
|
||
| print('_' * 75) | ||
|
|
||
| # Задание 5 | ||
| # По информации о учениках разных классов нужно найти класс, в котором больше всего девочек и больше всего мальчиков | ||
| # Пример вывода: | ||
|
|
@@ -91,5 +125,8 @@ | |
| 'Олег': True, | ||
| 'Миша': True, | ||
| } | ||
| # ??? | ||
|
|
||
| for group in school: | ||
| if find_boys() > find_girls(): | ||
| print(f'Больше всего мальчиков в классе: {group["class"]}') | ||
|
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. Тут надо было найти класс, в котором наибольшее количество мальчиков, а не все классы в которых мальчиков больше чем девочек. |
||
| else: | ||
| print(f'Больше всего девочек в классе: {group["class"]}') | ||
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
| @@ -1,3 +1,10 @@ | ||||||
| import random | ||||||
| import uuid | ||||||
| import datetime | ||||||
| import lorem | ||||||
| from itertools import groupby | ||||||
| from collections import Counter | ||||||
|
|
||||||
| """ | ||||||
| Пожалуйста, приступайте к этой задаче после того, как вы сделали и получили ревью ко всем остальным задачам | ||||||
| в этом репозитории. Она значительно сложнее. | ||||||
|
|
@@ -30,11 +37,11 @@ | |||||
|
|
||||||
| Весь код стоит разбить на логические части с помощью функций. | ||||||
| """ | ||||||
| import random | ||||||
| import uuid | ||||||
| import datetime | ||||||
|
|
||||||
| import lorem | ||||||
|
|
||||||
| # Создадим функцию, которая принимает list для нахождения максимального повторяющегося элемента в данном списке | ||||||
| def maximum_frequency(lst): | ||||||
| return Counter(lst).most_common(1)[0][0] | ||||||
|
|
||||||
|
|
||||||
| def generate_chat_history(): | ||||||
|
|
@@ -66,5 +73,72 @@ def generate_chat_history(): | |||||
| return messages | ||||||
|
|
||||||
|
|
||||||
| # Создает список значений по ключу | ||||||
| def create_list_by_key(key_name: str, messages): | ||||||
| return [message[key_name] for message in messages if message[key_name] is not None] | ||||||
|
|
||||||
|
|
||||||
| def find_id_who_write_the_most_messages(messages): | ||||||
| return maximum_frequency(create_list_by_key('sent_by', messages)) | ||||||
|
|
||||||
|
|
||||||
| def find_id_who_got_the_most_replies(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. Классный нейминг! |
||||||
| for message in messages: | ||||||
| if message['id'] == maximum_frequency(create_list_by_key('reply_for', messages)): | ||||||
| return message["sent_by"] | ||||||
|
|
||||||
|
|
||||||
| def find_id_saw_unique_users(messages): | ||||||
| id_unique = {} | ||||||
| for message in messages: | ||||||
| if message['sent_by'] not in id_unique: | ||||||
| id_unique[message['sent_by']] = set(message['seen_by']) | ||||||
| else: | ||||||
| id_unique[message['sent_by']] = set(id_unique[message['sent_by']]) | set(message['seen_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. Это кажется дорогая операция, много раз пересоздаешь сет.
Suggested change
Если использовать id_unique.get(message['sent_by'], set()), то можно еще и от if избавиться. |
||||||
|
|
||||||
| # создаем переменную с отсортированными айди по убыванию кол-ва просмотров уникальными пользователями | ||||||
| sorted_id_user_and_count_saw_users = sorted(id_unique.items(), reverse=True, key=lambda x: len(x[1])) | ||||||
| return [id_user for id_user, count in sorted_id_user_and_count_saw_users] | ||||||
|
|
||||||
|
|
||||||
| def what_time_more_messages(messages): | ||||||
| times = { | ||||||
| 'morning': [], | ||||||
| 'day': [], | ||||||
| 'evening': [] | ||||||
| } | ||||||
|
|
||||||
| for message in messages: | ||||||
| hour_of_writing = message["sent_at"].hour | ||||||
| if hour_of_writing < 12: | ||||||
| times['morning'].append(hour_of_writing) | ||||||
|
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. Не вижу как словарь тут упрощает что-то. |
||||||
| elif 18 > hour_of_writing > 12: | ||||||
| times['day'].append(hour_of_writing) | ||||||
| else: | ||||||
| times['evening'].append(hour_of_writing) | ||||||
|
|
||||||
| return max(times.items(), key=lambda x: len(x[1]))[0] | ||||||
|
|
||||||
|
|
||||||
| def maximum_thread_length(messages): | ||||||
| result = [] | ||||||
|
|
||||||
| for id_reply_for, thread_length in groupby( | ||||||
| [message['reply_for'] for message in messages if message['reply_for'] is not None]): | ||||||
| length = len(list(thread_length)) | ||||||
| if length > 1: | ||||||
| result.append(id_reply_for) | ||||||
|
|
||||||
| return result | ||||||
|
|
||||||
|
|
||||||
| if __name__ == "__main__": | ||||||
| print(generate_chat_history()) | ||||||
| print(find_id_who_write_the_most_messages(generate_chat_history())) | ||||||
| print('_' * 75) | ||||||
| print(find_id_who_got_the_most_replies(generate_chat_history())) | ||||||
| print('_' * 75) | ||||||
| print(find_id_saw_unique_users(generate_chat_history())) | ||||||
| print('_' * 75) | ||||||
| print(what_time_more_messages(generate_chat_history())) | ||||||
| print('_' * 75) | ||||||
| print(maximum_thread_length(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.
Тот редкий случай когда строчка комментария не помешала бы.