-
Notifications
You must be signed in to change notification settings - Fork 262
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 9 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 |
|---|---|---|
|
|
@@ -2,7 +2,8 @@ | |
| # Необходимо вывести имена всех учеников из списка с новой строки | ||
|
|
||
| names = ['Оля', 'Петя', 'Вася', 'Маша'] | ||
| # ??? | ||
| for name in names: | ||
| print(name) | ||
|
|
||
|
|
||
| # Задание 2 | ||
|
|
@@ -12,7 +13,8 @@ | |
| # Петя: 4 | ||
|
|
||
| names = ['Оля', 'Петя', 'Вася', 'Маша'] | ||
| # ??? | ||
| for name in names: | ||
| print(f'{name}: {len(name)}') | ||
|
|
||
|
|
||
| # Задание 3 | ||
|
|
@@ -25,7 +27,12 @@ | |
| 'Маша': False, | ||
| } | ||
| names = ['Оля', 'Петя', 'Вася', 'Маша'] | ||
| # ??? | ||
| for name in names: | ||
| if name == 'Петя' or name == 'Вася': | ||
| print(f'{name} пол мужской') | ||
| else: | ||
| print(f'{name} пол женский') | ||
|
|
||
|
|
||
|
|
||
| # Задание 4 | ||
|
|
@@ -40,7 +47,11 @@ | |
| ['Вася', 'Маша', 'Саша', 'Женя'], | ||
| ['Оля', 'Петя', 'Гриша'], | ||
| ] | ||
| # ??? | ||
| counter_1 = 0 | ||
| for group in groups: | ||
| counter_1 += 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. Используй enumerate, вместо того что бы считать индекс руками |
||
| print(f'Группа {counter_1}: {len(group)} ученика') | ||
|
|
||
|
|
||
|
|
||
| # Задание 5 | ||
|
|
@@ -54,4 +65,7 @@ | |
| ['Оля', 'Петя', 'Гриша'], | ||
| ['Вася', 'Маша', 'Саша', 'Женя'], | ||
| ] | ||
| # ??? | ||
| count_groups = 0 | ||
| for group in groups: | ||
|
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. enumerate |
||
| count_groups += 1 | ||
| print(f'Группа {count_groups}: {", ".join(group)}') | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -12,8 +12,12 @@ | |
| {'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 +30,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 +51,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,8 +84,10 @@ | |
| 'Миша': True, | ||
| 'Даша': False, | ||
| } | ||
| # ??? | ||
|
|
||
| for klass in school: | ||
| print( | ||
| f"Класс {klass['class']}: мальчики {[is_male[men_person['first_name']] for men_person in klass['students']].count(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. Вынеси функцию расчета числа мальчиков и девочек в отдельную функцию, так что бы можно было ее переиспользовать в следующих задачах. |
||
| f"девочки {[is_male[women_person['first_name']] for women_person in klass['students']].count(False)}") | ||
|
|
||
| # Задание 5 | ||
| # По информации о учениках разных классов нужно найти класс, в котором больше всего девочек и больше всего мальчиков | ||
|
|
@@ -82,7 +96,7 @@ | |
| # Больше всего девочек в классе 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 +105,8 @@ | |
| 'Олег': True, | ||
| 'Миша': True, | ||
| } | ||
| # ??? | ||
|
|
||
| for klass in school: | ||
| if [is_male[men_person['first_name']] for men_person in klass['students']].count(True) > [is_male[women_person['first_name']] for women_person in klass['students']].count(False): | ||
| print(f"Больше всего мальчиков в классе {klass['class']}") | ||
| else: | ||
| print(f"Больше всего девочек в классе {klass['class']}") | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -66,5 +66,28 @@ 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'] | ||
| print(new_dict) | ||
| for k, value in new_dict.items(): | ||
| print(k, len(set(value))) # решение на 3 задачу | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| print(generate_chat_history()) | ||
| zadacha(generate_chat_history()) | ||
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
| @@ -1,28 +1,34 @@ | ||||||
| # Вывести последнюю букву в слове | ||||||
| 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 = 'Мы приехали в гости' | ||||||
| # ??? | ||||||
| spisok = [] | ||||||
|
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
|
||||||
| for letter in sentence.split(): | ||||||
| spisok.append(len(letter)) | ||||||
| print(int(sum(spisok)/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.
здесь надо использовать is_male.
А что если мы хотим больше имен добавить в программу. Должно быть одно место в программе ответственное за вычисление пола по имени.