-
Notifications
You must be signed in to change notification settings - Fork 260
for_challenges и for_dict_challenges на проверку #42
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
a9e8691
ddaa3e4
a90923a
4f42a44
1fc6c28
bda67dd
c4f3907
8ca0a4a
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 |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| env/ |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -2,7 +2,8 @@ | |
| # Необходимо вывести имена всех учеников из списка с новой строки | ||
|
|
||
| names = ['Оля', 'Петя', 'Вася', 'Маша'] | ||
| # ??? | ||
| print('\nЗадание 1') | ||
| [print(name) for name in names] | ||
|
|
||
|
|
||
| # Задание 2 | ||
|
|
@@ -12,7 +13,8 @@ | |
| # Петя: 4 | ||
|
|
||
| names = ['Оля', 'Петя', 'Вася', 'Маша'] | ||
| # ??? | ||
| print('\nЗадание 2') | ||
| [print(f'{name}: {len(name)}') for name in names] | ||
Maksimous777 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
|
|
||
| # Задание 3 | ||
|
|
@@ -24,8 +26,16 @@ | |
| 'Вася': True, | ||
| 'Маша': False, | ||
| } | ||
| names = ['Оля', 'Петя', 'Вася', 'Маша'] | ||
| # ??? | ||
| names = ['Оля', 'Петя', 'Вася', 'Маша', 'Максим'] | ||
| print('\nЗадание 3') | ||
| for name in names: | ||
| try: | ||
| if is_male[name]: | ||
| print(f'{name}: Мужской') | ||
| else: | ||
| print(f'{name}: Женский') | ||
| except KeyError: | ||
| print(f'Не знаю такого имени: {name}') | ||
|
Comment on lines
+32
to
+38
Author
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. #42 (comment) |
||
|
|
||
|
|
||
| # Задание 4 | ||
|
|
@@ -40,7 +50,10 @@ | |
| ['Вася', 'Маша', 'Саша', 'Женя'], | ||
| ['Оля', 'Петя', 'Гриша'], | ||
| ] | ||
| # ??? | ||
| print('\nЗадание 4') | ||
| print(f'Всего {len(groups)} группы') | ||
| for index, group in enumerate(groups, start=1): | ||
| print(f"Группа {index}: {len(group)} ученика") | ||
|
|
||
|
|
||
| # Задание 5 | ||
|
|
@@ -54,4 +67,6 @@ | |
| ['Оля', 'Петя', 'Гриша'], | ||
| ['Вася', 'Маша', 'Саша', 'Женя'], | ||
| ] | ||
| # ??? | ||
| print('\nЗадание 5') | ||
| [print(f"Группа {index}: {', '.join(group)}") | ||
| for index, group in enumerate(groups, start=1)] | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,4 @@ | ||
| from collections import Counter | ||
| # Задание 1 | ||
| # Дан список учеников, нужно посчитать количество повторений каждого имени ученика | ||
| # Пример вывода: | ||
|
|
@@ -12,7 +13,19 @@ | |
| {'first_name': 'Маша'}, | ||
| {'first_name': 'Петя'}, | ||
| ] | ||
| # ??? | ||
|
|
||
| print('Задание 1') | ||
| unique_students = {} | ||
| for student in students: | ||
| student = student['first_name'] | ||
| if unique_students.get(student): | ||
| unique_students[student] += 1 | ||
| else: | ||
| unique_students[student] = 1 | ||
|
|
||
| for name, qty in unique_students.items(): | ||
| print(f"{name}: {qty}") | ||
| print() | ||
|
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. Fair enough. |
||
|
|
||
|
|
||
| # Задание 2 | ||
|
|
@@ -26,7 +39,12 @@ | |
| {'first_name': 'Маша'}, | ||
| {'first_name': 'Оля'}, | ||
| ] | ||
| # ??? | ||
|
|
||
| print('Задание 2') | ||
| most_common_student = Counter(student['first_name'] | ||
| for student in students).most_common(1) | ||
| print( | ||
| f'Самое частое имя среди учеников: {most_common_student[0][0]}\n') | ||
|
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. Хорошо! |
||
|
|
||
|
|
||
| # Задание 3 | ||
|
|
@@ -44,26 +62,35 @@ | |
| {'first_name': 'Маша'}, | ||
| {'first_name': 'Маша'}, | ||
| {'first_name': 'Оля'}, | ||
| ],[ # это – третий класс | ||
| ], [ # это – третий класс | ||
| {'first_name': 'Женя'}, | ||
| {'first_name': 'Петя'}, | ||
| {'first_name': 'Женя'}, | ||
| {'first_name': 'Саша'}, | ||
| ], | ||
| ] | ||
| # ??? | ||
|
|
||
| print('Задание 3') | ||
| for grade in range(len(school_students)): | ||
| max_students = Counter(student['first_name'] | ||
| for student in school_students[grade]).most_common(1) | ||
| print( | ||
| f'Самое частое имя в классе {grade + 1}: {max_students[0][0]}') | ||
| print() | ||
|
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. 👍 |
||
|
|
||
| # Задание 4 | ||
| # Для каждого класса нужно вывести количество девочек и мальчиков в нём. | ||
| # Пример вывода: | ||
| # Класс 2a: девочки 2, мальчики 0 | ||
| # Класс 2a: девочки 2, мальчики 0 | ||
| # Класс 2б: девочки 0, мальчики 2 | ||
|
|
||
| school = [ | ||
| {'class': '2a', 'students': [{'first_name': 'Маша'}, {'first_name': 'Оля'}]}, | ||
| {'class': '2б', 'students': [{'first_name': 'Олег'}, {'first_name': 'Миша'}]}, | ||
| {'class': '2б', 'students': [{'first_name': 'Даша'}, {'first_name': 'Олег'}, {'first_name': 'Маша'}]}, | ||
| {'class': '2a', 'students': [ | ||
| {'first_name': 'Маша'}, {'first_name': 'Оля'}]}, | ||
| {'class': '2б', 'students': [ | ||
| {'first_name': 'Олег'}, {'first_name': 'Миша'}]}, | ||
| {'class': '2б', 'students': [{'first_name': 'Даша'}, { | ||
| 'first_name': 'Олег'}, {'first_name': 'Маша'}]}, | ||
| ] | ||
| is_male = { | ||
| 'Олег': True, | ||
|
|
@@ -72,24 +99,53 @@ | |
| 'Миша': True, | ||
| 'Даша': False, | ||
| } | ||
| # ??? | ||
|
|
||
|
|
||
| print('Задание 4') | ||
| for grade in school: | ||
| male = 0 | ||
| female = 0 | ||
| for student in grade['students']: | ||
| if is_male[student['first_name']]: | ||
| male += 1 | ||
| else: | ||
| female += 1 | ||
| print( | ||
| f"Класс {grade['class']}: девочки {female}, мальчики {male}") | ||
| print() | ||
|
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. 👍 |
||
| # Задание 5 | ||
| # По информации о учениках разных классов нужно найти класс, в котором больше всего девочек и больше всего мальчиков | ||
| # Пример вывода: | ||
| # Больше всего мальчиков в классе 3c | ||
| # Больше всего девочек в классе 2a | ||
|
|
||
| school = [ | ||
| {'class': '2a', 'students': [{'first_name': 'Маша'}, {'first_name': 'Оля'}]}, | ||
| {'class': '3c', 'students': [{'first_name': 'Олег'}, {'first_name': 'Миша'}]}, | ||
| {'class': '2a', 'students': [ | ||
| {'first_name': 'Маша'}, {'first_name': 'Оля'}]}, | ||
| {'class': '3c', 'students': [ | ||
| {'first_name': 'Олег'}, {'first_name': 'Миша'}]}, | ||
| ] | ||
| is_male = { | ||
| 'Маша': False, | ||
| 'Оля': False, | ||
| 'Олег': True, | ||
| 'Миша': True, | ||
| } | ||
| # ??? | ||
| print('Задание 5') | ||
| male = [] | ||
| female = [] | ||
| for grade in range(len(school)): | ||
| male.append(0) | ||
| female.append(0) | ||
| for student in school[grade]['students']: | ||
| if is_male[student['first_name']]: | ||
| male[grade] += 1 | ||
| else: | ||
| female[grade] += 1 | ||
|
|
||
| most_male_index = male.index(max(male)) | ||
| most_male_class = school[most_male_index]['class'] | ||
| most_female_index = female.index(max(female)) | ||
| most_female_class = school[most_female_index]['class'] | ||
| print( | ||
| f"Больше всего мальчиков в классе {most_male_class}") | ||
| print( | ||
| f"Больше всего девочек в классе {most_female_class}") | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -35,6 +35,7 @@ | |
| import datetime | ||
|
|
||
| import lorem | ||
| from pprint import pprint | ||
|
|
||
|
|
||
| def generate_chat_history(): | ||
|
|
@@ -66,5 +67,114 @@ def generate_chat_history(): | |
| return messages | ||
|
|
||
|
|
||
| # Задание 1 | ||
| users_messages_counter = {} | ||
|
|
||
|
|
||
| def count_user_messages(message): | ||
| if users_messages_counter.get(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. Такая конструкция в данном случае сработает хорошо, но в других ситуациях может сыграть злую шутку. |
||
| users_messages_counter[message['sent_by']] += 1 | ||
| else: | ||
| users_messages_counter[message['sent_by']] = 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. Да, так хорошо. Далее для упрощения можно пользоваться defaultdict |
||
|
|
||
|
|
||
| def get_max_posts_id(messages_dict): | ||
| max_messages_user_index = max( | ||
| messages_dict, key=users_messages_counter.get) | ||
| return max_messages_user_index | ||
|
|
||
|
|
||
| # Задание 2 | ||
| user_by_message = {} # для 2 задания | ||
| user_replied_amount = {} # для 2 задания | ||
|
|
||
|
|
||
| def count_replies(message): | ||
| user_by_message[message['id']] = message['sent_by'] | ||
| if message.get('reply_for'): | ||
| quoted_user_id = user_by_message[message['reply_for']] | ||
| user_replied_amount[quoted_user_id] = user_replied_amount.get( | ||
| quoted_user_id, 0) + 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. Отлично. Изящно получилось |
||
| return user_replied_amount | ||
|
|
||
|
|
||
| def get_most_replied_user(replied_users_dict): | ||
| return max(replied_users_dict, key=replied_users_dict.get) | ||
|
|
||
|
|
||
| # Задание 3 | ||
| users_seen_by = {} # для 3 задания | ||
|
|
||
|
|
||
| def count_message_views(message): | ||
| users_seen_by.setdefault(message['sent_by'], 0) | ||
| users_seen_by[message['sent_by']] += len(message.get('seen_by')) | ||
| return users_seen_by | ||
|
|
||
|
|
||
| def count_max_views(seen_by_dict): | ||
|
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 max(seen_by_dict, key=seen_by_dict.get) | ||
|
|
||
|
|
||
| # Задание 4 | ||
| messages_by_time = { | ||
| 'morning': 0, | ||
| 'afternoon': 0, | ||
| 'evening': 0 | ||
| } | ||
|
|
||
|
|
||
| def count_messages_by_time_periods(message): | ||
| if message['sent_at'].hour < 12: | ||
| messages_by_time['morning'] += 1 | ||
| elif message['sent_at'].hour < 18: | ||
| messages_by_time['afternoon'] += 1 | ||
| else: | ||
| messages_by_time['evening'] += 1 | ||
|
|
||
|
|
||
| def get_most_messaged_time_period(time_periods_counter): | ||
| return max(messages_by_time, key=messages_by_time.get) | ||
|
|
||
|
|
||
| # Задание 5 | ||
| most_replied_messages = {} | ||
|
|
||
|
|
||
| def count_replied_messages(message): | ||
| most_replied_messages[message['id']] = [] | ||
| if message.get('reply_for'): | ||
| most_replied_messages[message['reply_for']].append( | ||
| message['id']) | ||
| for answers in most_replied_messages.values(): | ||
| if message.get('reply_for') in answers: | ||
| answers.append(message['id']) | ||
| return most_replied_messages | ||
|
|
||
|
|
||
| def get_max_replied_messages(replied_messages, amount=5): | ||
| sorted_messages = sorted( | ||
| replied_messages.items(), key=lambda item: len(item[1]), reverse=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. 👍 |
||
| sorted_messages = sorted_messages[:(amount)] | ||
| sorted_messages = [message[0] for message in sorted_messages] | ||
| return [f'Number {index} by replied messages: {message}' for index, message in enumerate(sorted_messages, start=1)] | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| print(generate_chat_history()) | ||
| for index, message in enumerate(generate_chat_history()): | ||
| count_user_messages(message) # Задание 1 | ||
| count_replies(message) # Задание 2 | ||
| count_message_views(message) # Задание 3 | ||
| count_messages_by_time_periods(message) # Задание 4 | ||
| count_replied_messages(message) # Задание 5 | ||
|
|
||
| print('Max posts id: ', get_max_posts_id( | ||
| users_messages_counter)) # Задание 1 | ||
| print('Most replied id: ', get_most_replied_user( | ||
| user_replied_amount)) # Задание 2 | ||
| print('Most viewed user: ', count_max_views( | ||
| users_seen_by)) # Задание 3 | ||
| print('Most messages are in the: ', get_most_messaged_time_period( | ||
| messages_by_time)) # Задание 4 | ||
| pprint(get_max_replied_messages( | ||
| most_replied_messages, 3)) # Задание 5 | ||
|
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. В целом все круто и технично. Над чем важно поработать: чистые и грязные функции. Сейчас у тебя почти все функции грязные так как пользуются глобальными переменными. Уже на таком объеме, читая с нуля становится сложно контролировать какой словарь в какой момент был создан и когда менялся. Более чистое решение выглядело бы так или так |
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,28 +1,45 @@ | ||
| # Вывести последнюю букву в слове | ||
| word = 'Архангельск' | ||
| # ??? | ||
| print(f"В слове {word} последняя буква: {word[-1:]}\n") | ||
|
|
||
|
|
||
| # Вывести количество букв "а" в слове | ||
| word = 'Архангельск' | ||
| # ??? | ||
| cymbol_to_count = 'а' | ||
| cymbols_in_word = word.lower().count(cymbol_to_count) | ||
| print( | ||
| f'Количество букв "{cymbol_to_count}" в слове {word}: {cymbols_in_word}\n') | ||
|
|
||
|
|
||
| # Вывести количество гласных букв в слове | ||
| word = 'Архангельск' | ||
| # ??? | ||
| vowels = 'аеёиоуыэюя' | ||
| vowels_sum = 0 | ||
| for symbol in word: | ||
| if symbol.lower() in vowels: | ||
| vowels_sum += 1 | ||
| print( | ||
| f'Количество гласных букв в слове {word}: {vowels_sum}\n') | ||
|
|
||
|
|
||
| # Вывести количество слов в предложении | ||
| sentence = 'Мы приехали в гости' | ||
| # ??? | ||
| words_quantity = sentence.count(' ') + 1 | ||
| print( | ||
| f"Количество слов в тексте: '{sentence}' - {words_quantity}\n") | ||
|
|
||
|
|
||
| # Вывести первую букву каждого слова на отдельной строке | ||
| sentence = 'Мы приехали в гости' | ||
| # ??? | ||
| print(f"Первые буквы в словах из: '{sentence}'") | ||
| [print(word[0]) for word in sentence.split()] | ||
| print() | ||
|
|
||
|
|
||
| # Вывести усреднённую длину слова в предложении | ||
| sentence = 'Мы приехали в гости' | ||
| # ??? | ||
| words_num = len(sentence.split()) | ||
| symbols_sum = sum([len(word) for word in sentence.split()]) | ||
| avg_cymbols_in_sentence = symbols_sum // words_num | ||
| print( | ||
| f"Средняя длина слова в предложении: '{sentence}' - {avg_cymbols_in_sentence}") |
Uh oh!
There was an error while loading. Please reload this page.