-
Notifications
You must be signed in to change notification settings - Fork 260
Shalapugin Dmitry #35
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 all commits
884c8cc
93c3aa6
e7901d1
206062b
280ba49
222cfb6
4f67043
e2f6375
1e9a453
70f736d
a7e2911
e022ad4
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 |
|---|---|---|
|
|
@@ -12,8 +12,13 @@ | |
| {'first_name': 'Маша'}, | ||
| {'first_name': 'Петя'}, | ||
| ] | ||
| # ??? | ||
|
|
||
| from collections import Counter | ||
|
|
||
| list_students = [name['first_name'] for name in students] | ||
| print(list_students) | ||
| for name, number in Counter(list_students).items(): | ||
| print(f'{name}: {number}') | ||
|
|
||
| # Задание 2 | ||
| # Дан список учеников, нужно вывести самое часто повторящееся имя | ||
|
|
@@ -26,8 +31,11 @@ | |
| {'first_name': 'Маша'}, | ||
| {'first_name': 'Оля'}, | ||
| ] | ||
| # ??? | ||
| from collections import Counter | ||
|
|
||
| student_names = (name['first_name'] for name in students) | ||
| most_common_name = Counter(student_names).most_common(1) | ||
| print(f'Самое частое имя среди учеников: {most_common_name[0][0]}') | ||
|
|
||
| # Задание 3 | ||
| # Есть список учеников в нескольких классах, нужно вывести самое частое имя в каждом классе. | ||
|
|
@@ -44,15 +52,20 @@ | |
| {'first_name': 'Маша'}, | ||
| {'first_name': 'Маша'}, | ||
| {'first_name': 'Оля'}, | ||
| ],[ # это – третий класс | ||
| ], [ # это – третий класс | ||
| {'first_name': 'Женя'}, | ||
| {'first_name': 'Петя'}, | ||
| {'first_name': 'Женя'}, | ||
| {'first_name': 'Саша'}, | ||
| ], | ||
| ] | ||
| # ??? | ||
| from collections import Counter | ||
|
|
||
| count = 0 | ||
|
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 безопаснее чем индексы, потому что точно не выйдет за пределы, и не пропустит ничего. |
||
| for klass in school_students: | ||
| most_common_name = Counter(name['first_name'] for name in school_students[count]).most_common(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. school_students[count] это klass. Лучше использовать klass, и избавиться от count совсем. |
||
| print(f'Самое частое имя в классе {count + 1}: {most_common_name[0][0]}') | ||
| count += 1 | ||
|
|
||
| # Задание 4 | ||
| # Для каждого класса нужно вывести количество девочек и мальчиков в нём. | ||
|
|
@@ -72,17 +85,29 @@ | |
| 'Миша': True, | ||
| 'Даша': False, | ||
| } | ||
| # ??? | ||
|
|
||
|
|
||
| def mens_count(): | ||
| return [is_male[men_person['first_name']] for men_person in klass['students']].count(True) | ||
|
|
||
|
|
||
| def womens_count(): | ||
|
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. klass должен передаваться явно как аргумент (можно еще и назвать его по другому, что бы точно не было сомнений. |
||
| return [is_male[women_person['first_name']] for women_person in klass['students']].count(False) | ||
|
|
||
|
|
||
| for klass in school: | ||
| print( | ||
| f"Класс {klass['class']}: мальчики {mens_count()} " | ||
| f"девочки {womens_count()}") | ||
|
|
||
| # Задание 5 | ||
| # По информации о учениках разных классов нужно найти класс, в котором больше всего девочек и больше всего мальчиков | ||
| # Пример вывода: | ||
| # Больше всего мальчиков в классе 3c | ||
| # Больше всего девочек в классе 2a | ||
|
|
||
| school = [ | ||
| {'class': '2a', 'students': [{'first_name': 'Маша'}, {'first_name': 'Оля'}]}, | ||
| {'class': '2a', 'students': [{'first_name': 'Маша'}, {'first_name': 'Оля'}, {'first_name': 'Оля'}]}, | ||
| {'class': '3c', 'students': [{'first_name': 'Олег'}, {'first_name': 'Миша'}]}, | ||
| ] | ||
| is_male = { | ||
|
|
@@ -91,5 +116,8 @@ | |
| 'Олег': True, | ||
| 'Миша': True, | ||
| } | ||
| # ??? | ||
|
|
||
| for klass in school: | ||
| if mens_count() > womens_count(): | ||
| print(f"Больше всего мальчиков в классе {klass['class']}") | ||
| else: | ||
| print(f"Больше всего девочек в классе {klass['class']}") | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -66,5 +66,30 @@ def generate_chat_history(): | |
| return messages | ||
|
|
||
|
|
||
| def zadacha(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. Разбей код на несколько максимально независимых функций, вынеси print наружу. Назови переменные понятными именами: ab, ac, ac, i, j, k - плохие названия для переменных, потому что не показывают что в них лежит и как будут использоваться. 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. Код не разбит |
||
|
|
||
| from collections import Counter | ||
| sum_user = Counter(user['sent_by'] for user in messages).most_common(1) | ||
| print(f'Больше всего сообщений написал пользователь ID - {sum_user[0][0]}') | ||
|
|
||
| sum_user = Counter(commentator['reply_for'] for commentator in messages).most_common(2) | ||
| print(f'Больше всего ответов - {sum_user[1][0]}') | ||
| for id in messages: | ||
| if id['id'] == sum_user[1][0]: | ||
| print(f"{id['sent_by']} айди пользователя, на сообщения которого больше всего отвечали") | ||
|
|
||
|
|
||
| new_dict = {} | ||
| for message in messages: | ||
| if message['sent_by'] not in new_dict: | ||
| new_dict[message['sent_by']] = message['seen_by'] | ||
| else: | ||
| new_dict[message['sent_by']] = new_dict[message['sent_by']] + message['seen_by'] | ||
| for key_new_dict, value in new_dict.items(): | ||
| print(key_new_dict, len(set(value))) | ||
|
|
||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| print(generate_chat_history()) | ||
| zadacha(generate_chat_history()) | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,28 +1,39 @@ | ||
| # Вывести последнюю букву в слове | ||
| word = 'Архангельск' | ||
| # ??? | ||
| print(word[-1]) | ||
|
|
||
|
|
||
|
|
||
| # Вывести количество букв "а" в слове | ||
| word = 'Архангельск' | ||
| # ??? | ||
| print(word.lower().count('а')) | ||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
||
| # Вывести количество гласных букв в слове | ||
| word = 'Архангельск' | ||
| # ??? | ||
| vowels = ['а', 'е', 'у', 'ы', 'о', 'э', 'я', 'и', 'ю'] | ||
| print(len([letter for letter in word if letter.lower() not in vowels])) | ||
|
|
||
|
|
||
|
|
||
| # Вывести количество слов в предложении | ||
| sentence = 'Мы приехали в гости' | ||
| # ??? | ||
|
|
||
| print(len(sentence.split())) | ||
|
|
||
|
|
||
| # Вывести первую букву каждого слова на отдельной строке | ||
| sentence = 'Мы приехали в гости' | ||
| # ??? | ||
| for word in sentence.split(): | ||
| print(word[0]) | ||
|
|
||
|
|
||
| # Вывести усреднённую длину слова в предложении | ||
| sentence = 'Мы приехали в гости' | ||
| # ??? | ||
| words = [] | ||
| for letter in sentence.split(): | ||
| words.append(len(letter)) | ||
| print(int(sum(words)/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.
распакуй же сразу:
И в остальных местах тоже. Эта техника называется list unpacking, кода ты паре переменных присваиваешь значение листа.