From 460acd2d5ae131c58925685d58ccf68f09f1e003 Mon Sep 17 00:00:00 2001 From: Alexey Date: Mon, 22 May 2023 21:58:40 +0300 Subject: [PATCH 1/4] Challenging challenges --- .gitignore | 7 ++ README.md | 14 --- for_challenges.py | 112 +++++++++++++-------- for_dict_challenges.py | 188 +++++++++++++++++++++-------------- for_dict_challenges_bonus.py | 153 +++++++++++++++++++++------- string_challenges.py | 43 ++++---- 6 files changed, 329 insertions(+), 188 deletions(-) create mode 100644 .gitignore delete mode 100644 README.md diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..cd3e80fa --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +settings.py +*.log +.vscode/ +.idea/ +env/ +.DS_Store +__pycache__/ \ No newline at end of file diff --git a/README.md b/README.md deleted file mode 100644 index 30ed1314..00000000 --- a/README.md +++ /dev/null @@ -1,14 +0,0 @@ -LearnPython: Дополнительные тренировочные задания -================================ - -### Как выполнять задание - -1. На github в правом верхнем углу нажмите Fork ![](https://learn.python.ru/lessons/img/homework1_1.png) -2. Репозиторий продублируется у вас на аккаунте -3. В своем репозитории нажмите зеленую кнопку Clone or Download и скопируйте ссылку ![](https://learn.python.ru/lessons/img/homework1_2.png) -4. В командной строке у себя на копьютере перейдите в папку `C:\projects` на Windows или `~/projects` на Linux и Mac -5. Наберите команду `git clone СКОПРИОВАННЫЙ URL` -6. Код урока появится в папке `basic_exercises` -7. Выполните задания в каждом из файлов, сделайте commit и push и оправьте ссылки на ваш репозиторий куратору - -Если у вас возникли сложности при выполнении задания - напишите своему куратору! diff --git a/for_challenges.py b/for_challenges.py index 997754da..a66392fa 100644 --- a/for_challenges.py +++ b/for_challenges.py @@ -1,57 +1,87 @@ -# Задание 1 -# Необходимо вывести имена всех учеников из списка с новой строки +# Задание 1. Необходимо вывести имена всех учеников из списка с новой строки +def names_new_line(names_array): + return '\n'.join(names_array) -names = ['Оля', 'Петя', 'Вася', 'Маша'] -# ??? +# Задание 2. Необходимо вывести имена всех учеников из списка, рядом с именем показать количество букв в нём +def names_with_len(names_array): + return [f'{name}: {len(name)} \n' for name in names_array] -# Задание 2 -# Необходимо вывести имена всех учеников из списка, рядом с именем показать количество букв в нём -# Пример вывода: -# Оля: 3 -# Петя: 4 -names = ['Оля', 'Петя', 'Вася', 'Маша'] -# ??? +# Задание 3. Необходимо вывести имена всех учеников из списка, рядом с именем вывести пол ученика +def male_or_female(names_array, mf_dict): + result = [] + for stud in names_array: + if stud in mf_dict and mf_dict[stud]: + is_stud_male = 'Мужской' + elif stud in mf_dict and not mf_dict[stud]: + is_stud_male = 'Женский' + else: + is_stud_male = 'Нет информации' + result.append(f'Имя: {stud}, Пол: {is_stud_male}') + return result -# Задание 3 -# Необходимо вывести имена всех учеников из списка, рядом с именем вывести пол ученика +# Задание 4. Даны группу учеников. Нужно вывести количество групп и для каждой группы – количество учеников в ней +def groups_count(groups_array): + group_counter = 0 + if 11 <= len(groups_array) <= 14: + inflection = '' + elif len(groups_array) % 10 == 1: + inflection = 'а' + elif 2 <= len(groups_array) % 10 <= 4: + inflection = 'ы' + else: + inflection = '' + for_output = [f'Всего {len(groups_array)} групп{inflection}:',] + for group in groups_array: + group_counter += 1 + if 11 <= len(group) <= 14: + inflection = 'ов' + elif len(group) % 10 == 1: + inflection = '' + elif 2 <= len(group) % 10 <= 4: + inflection = 'а' + else: + inflection = 'ов' + for_output.append(f'Группа {group_counter}: {len(group)} ученик{inflection}') + return for_output -is_male = { - 'Оля': False, # если False, то пол женский - 'Петя': True, # если True, то пол мужской - 'Вася': True, - 'Маша': False, -} -names = ['Оля', 'Петя', 'Вася', 'Маша'] -# ??? +# Задание 5. Для каждой группы учеников нужно с новой строки перечислить учеников, которые в неё входят +def groups_members(groups_array): + group_counter = 0 + for_output = [] + for group in groups_array: + group_counter += 1 + for_output.append(f"Группа {group_counter}: {', '.join(group)}") + return for_output -# Задание 4 -# Даны группу учеников. Нужно вывести количество групп и для каждой группы – количество учеников в ней -# Пример вывода: -# Всего 2 группы. -# Группа 1: 2 ученика. -# Группа 2: 4 ученика. -groups = [ +def main(): + names = ['Оля', 'Петя', 'Вася', 'Маша'] + is_male = { + 'Оля': False, + 'Петя': True, + 'Вася': True, + 'Маша': False, + } + groups1 = [ ['Вася', 'Маша'], ['Вася', 'Маша', 'Саша', 'Женя'], ['Оля', 'Петя', 'Гриша'], -] -# ??? - - -# Задание 5 -# Для каждой пары учеников нужно с новой строки перечислить учеников, которые в неё входят -# Пример вывода: -# Группа 1: Вася, Маша -# Группа 2: Оля, Петя, Гриша - -groups = [ + ] + groups2 = [ ['Вася', 'Маша'], ['Оля', 'Петя', 'Гриша'], ['Вася', 'Маша', 'Саша', 'Женя'], -] -# ??? \ No newline at end of file + ] + print(names_new_line(names), end='\n\n') + print(*names_with_len(names), sep='', end='\n') + print(*male_or_female(names, is_male), sep='\n', end='\n\n') + print(*groups_count(groups1), sep='\n', end='\n\n') + print(*groups_members(groups2), sep='\n') + + +if __name__ == '__main__': + main() diff --git a/for_dict_challenges.py b/for_dict_challenges.py index 96062ebc..fce2b6f6 100644 --- a/for_dict_challenges.py +++ b/for_dict_challenges.py @@ -1,95 +1,129 @@ -# Задание 1 -# Дан список учеников, нужно посчитать количество повторений каждого имени ученика -# Пример вывода: -# Вася: 1 -# Маша: 2 -# Петя: 2 +# Задание 1. Дан список учеников, нужно посчитать количество повторений каждого имени ученика +def names_count(names_dict_array): + names, used_names, names_output = [], [], [] + for name_dict in names_dict_array: + names.append(name_dict['first_name']) + for name in names: + if name not in used_names: + names_output.append(f'{name}: {names.count(name)}') + used_names.append(name) + return names_output -students = [ - {'first_name': 'Вася'}, - {'first_name': 'Петя'}, - {'first_name': 'Маша'}, - {'first_name': 'Маша'}, - {'first_name': 'Петя'}, -] -# ??? +# Задание 2. Дан список учеников, нужно вывести самое часто повторящееся имя +def find_most_recurrent(names_dict_array): + names, used_names = [], [] + max_recurring = None + for name_dict in names_dict_array: + names.append(name_dict['first_name']) + for name in names: + if name not in used_names: + used_names.append(name) + recurring = names.count(name) + if max_recurring is None or recurring > max_recurring[1]: + max_recurring = (name, recurring) + return max_recurring[0] -# Задание 2 -# Дан список учеников, нужно вывести самое часто повторящееся имя -# Пример вывода: -# Самое частое имя среди учеников: Маша -students = [ - {'first_name': 'Вася'}, - {'first_name': 'Петя'}, - {'first_name': 'Маша'}, - {'first_name': 'Маша'}, - {'first_name': 'Оля'}, -] -# ??? +# Задание 3. Есть список учеников в нескольких классах, нужно вывести самое частое имя в каждом классе. +def find_most_recurrent_in_groups(school_array): + result = [] + head = 'Самое частое имя в классе ' + group_counter = 0 + for group in school_array: + group_counter += 1 + result.append(f'{head}{group_counter}: {find_most_recurrent(group)}\n') + return result -# Задание 3 -# Есть список учеников в нескольких классах, нужно вывести самое частое имя в каждом классе. -# Пример вывода: -# Самое частое имя в классе 1: Вася -# Самое частое имя в классе 2: Маша -school_students = [ - [ # это – первый класс +# Задание 4. Для каждого класса нужно вывести количество девочек и мальчиков в нём. +def mf_count(school_group, mf_dict): + m_counter = 0 + f_counter = 0 + for student in school_group['students']: + if mf_dict.get(student['first_name']) == True: + m_counter += 1 + elif mf_dict.get(student['first_name']) == False: + f_counter += 1 + return (school_group['class'], m_counter, f_counter) + + +def mf_count_in_groups(school_array, mf_dict): + result = [] + for group in school_array: + gr_stat = mf_count(group, mf_dict) + result.append(f'Класс {gr_stat[0]}: девочки {gr_stat[2]}, мальчики {gr_stat[1]}') + return result + + +# Задание 5. По информации об учениках разных классов нужно найти класс, в котором больше всего девочек и больше всего мальчиков +def mf_max(school_array, mf_dict): + groups = [] + for group in school_array: + groups.append(mf_count(group, mf_dict)) + m_max = None + f_max = None + for group_stat in groups: + if m_max == None or group_stat[1] > m_max[1]: + m_max = (group_stat[0], group_stat[1]) + if f_max == None or group_stat[2] > f_max[1]: + f_max = (group_stat[0], group_stat[2]) + return m_max + f_max + + +def main(): + students1 = [ {'first_name': 'Вася'}, + {'first_name': 'Петя'}, + {'first_name': 'Маша'}, + {'first_name': 'Маша'}, + {'first_name': 'Петя'}, + ] + students2 = [ {'first_name': 'Вася'}, - ], - [ # это – второй класс + {'first_name': 'Петя'}, {'first_name': 'Маша'}, {'first_name': 'Маша'}, {'first_name': 'Оля'}, - ],[ # это – третий класс - {'first_name': 'Женя'}, - {'first_name': 'Петя'}, - {'first_name': 'Женя'}, - {'first_name': 'Саша'}, - ], -] -# ??? - - -# Задание 4 -# Для каждого класса нужно вывести количество девочек и мальчиков в нём. -# Пример вывода: -# Класс 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': 'Маша'}]}, -] -is_male = { + ] + school_students = [ + [ + {'first_name': 'Вася'}, + {'first_name': 'Вася'}, + ], + [ + {'first_name': 'Маша'}, + {'first_name': 'Маша'}, + {'first_name': 'Оля'}, + ], + [ + {'first_name': 'Женя'}, + {'first_name': 'Петя'}, + {'first_name': 'Женя'}, + {'first_name': 'Саша'}, + ], + ] + school = [ + {'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, 'Маша': False, 'Оля': False, 'Миша': True, 'Даша': False, -} -# ??? - + } + head = 'Самое частое имя среди учеников: ' + max_classes = mf_max(school, is_male) + print(*names_count(students1), sep='\n', end='\n\n') + print(f'{head}{find_most_recurrent(students2)}', end='\n\n') + print(*find_most_recurrent_in_groups(school_students), sep='', end='\n') + print(*mf_count_in_groups(school, is_male), sep='\n', end='\n\n') + print(f'Больше всего мальчиков в классе {max_classes[0]} ({max_classes[1]})') + print(f'Больше всего девочек в классе {max_classes[2]} ({max_classes[3]})') -# Задание 5 -# По информации о учениках разных классов нужно найти класс, в котором больше всего девочек и больше всего мальчиков -# Пример вывода: -# Больше всего мальчиков в классе 3c -# Больше всего девочек в классе 2a - -school = [ - {'class': '2a', 'students': [{'first_name': 'Маша'}, {'first_name': 'Оля'}]}, - {'class': '3c', 'students': [{'first_name': 'Олег'}, {'first_name': 'Миша'}]}, -] -is_male = { - 'Маша': False, - 'Оля': False, - 'Олег': True, - 'Миша': True, -} -# ??? +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/for_dict_challenges_bonus.py b/for_dict_challenges_bonus.py index 9f35a0a0..2b2af9f2 100644 --- a/for_dict_challenges_bonus.py +++ b/for_dict_challenges_bonus.py @@ -1,39 +1,6 @@ -""" -Пожалуйста, приступайте к этой задаче после того, как вы сделали и получили ревью ко всем остальным задачам -в этом репозитории. Она значительно сложнее. - - -Есть набор сообщений из чата в следующем формате: - -``` -messages = [ - { - "id": "efadb781-9b04-4aad-9afe-e79faef8cffb", - "sent_at": datetime.datetime(2022, 10, 11, 23, 11, 11, 721), - "sent_by": 46, # id пользователя-отправителя - "reply_for": "7b22ae19-6c58-443e-b138-e22784878581", # id сообщение, на которое это сообщение является ответом (может быть None) - "seen_by": [26, 91, 71], # идентификаторы пользователей, которые видели это сообщение - "text": "А когда ревью будет?", - } -] -``` - -Так же есть функция `generate_chat_history`, которая вернёт список из большого количества таких сообщений. -Установите библиотеку lorem, чтобы она работала. - -Нужно: -1. Вывести айди пользователя, который написал больше всех сообщений. -2. Вывести айди пользователя, на сообщения которого больше всего отвечали. -3. Вывести айди пользователей, сообщения которых видело больше всего уникальных пользователей. -4. Определить, когда в чате больше всего сообщений: утром (до 12 часов), днём (12-18 часов) или вечером (после 18 часов). -5. Вывести идентификаторы сообщений, который стали началом для самых длинных тредов (цепочек ответов). - -Весь код стоит разбить на логические части с помощью функций. -""" import random import uuid import datetime - import lorem @@ -66,5 +33,123 @@ def generate_chat_history(): return messages +# Вывести айди пользователя, который написал больше всех сообщений +def find_most_active(chat_history): + ids, used_ids = [], [] + max_msg = None + for message in chat_history: + ids.append(message['sent_by']) + for id in ids: + if id not in used_ids: + msg = ids.count(id) + if max_msg is None or msg > max_msg[1]: + max_msg = (id, msg) + used_ids.append(id) + return max_msg + + +# Вывести айди пользователя, на сообщения которого больше всего отвечали +def find_most_replied(chat_history): + replies_ids = [] + replied_usrs = [] + max_replies = None + for message in chat_history: + if message['reply_for'] is not None: + replies_ids.append(message['reply_for']) + for rpld_message in chat_history: + if rpld_message['id'] in replies_ids: + replied_usrs.append(rpld_message['sent_by']) + for id in replied_usrs: + replies = replied_usrs.count(id) + if max_replies is None or replies > max_replies[1]: + max_replies = (id, replies) + return max_replies + + +# Вывести айди пользователей, сообщения которых видело больше всего уникальных пользователей +def find_most_popular(chat_history): + users_output = [] + users_seen_by = {} + for message in chat_history: + if message['sent_by'] in users_seen_by: + users_seen_by[message['sent_by']] += message['seen_by'] + else: + users_seen_by[message['sent_by']] = message['seen_by'] + max_seen = None + for user in users_seen_by: + seen = len(set(users_seen_by[user])) + if max_seen is None or seen > max_seen: + max_seen = seen + users_output = [user,] + elif seen == max_seen: + users_output.append(user) + return (users_output, max_seen) + + +# Определить, когда в чате больше всего сообщений: утром (до 12 часов), днём (12-18 часов) или вечером (после 18 часов) +def find_preferred_time(chat_history): + morning_count = 0 + day_count = 0 + everning_count = 0 + preferred = None + for message in chat_history: + msg_hour = int(str(message['sent_at'].time())[0:2]) + if msg_hour < 12: + morning_count += 1 + elif msg_hour <= 18: + day_count += 1 + else: + everning_count += 1 + max_count = max(morning_count, day_count, everning_count) + if morning_count == max_count: + preferred = 'morning' + elif day_count == max_count: + preferred = 'day' + else: + preferred = 'everning' + return (morning_count, day_count, everning_count, preferred) + + +# Вывести идентификаторы сообщений, который стали началом для самых длинных тредов (цепочек ответов) +def find_thread_starters(chat_history): + replied_ranks = {} + ids_output = [] + for message in chat_history: + if message['reply_for'] is not None: + if message['reply_for'] in replied_ranks: + replied_ranks[message['reply_for']] += 1 + else: + replied_ranks[message['reply_for']] = 1 + max_rank = None + for id in replied_ranks: + rank = replied_ranks[id] + if max_rank is None or rank > max_rank: + max_rank = rank + ids_output = [id,] + elif rank == max_rank: + ids_output.append(id) + return (ids_output, max_rank) + + +def main(): + my_chat = generate_chat_history() + most_active_user = find_most_active(my_chat) + most_replied_user = find_most_replied(my_chat) + most_popular_users = find_most_popular(my_chat) + preferred_time = find_preferred_time(my_chat) + thread_starters = find_thread_starters(my_chat) + print(f'Most active user id: {most_active_user[0]}.', end=' ') + print(f'They have written {most_active_user[1]} messages.', end='\n\n') + print(f'Most replied user id: {most_replied_user[0]}.', end=' ') + print(f'They were replied {most_replied_user[1]} times.', end='\n\n') + print(f"Most seen users id(s): {', '.join(map(str, most_popular_users[0]))}.") + print(f'{most_popular_users[1]} other users have seen their messages.', end='\n\n') + print(f"Users' favourite time for chatting is {preferred_time[3]}.") + print(f'{preferred_time[0]} messages were sent in the morning,', end=' ') + print(f'{preferred_time[1]} during the day, {preferred_time[2]} in the everning', end='\n\n') + print(f"Longest thread starters' id(s): {', '.join(map(str, thread_starters[0]))}.") + print(f'These messages had {thread_starters[1]} answers.') + + if __name__ == "__main__": - print(generate_chat_history()) + main() diff --git a/string_challenges.py b/string_challenges.py index 856add2d..957ed3c1 100644 --- a/string_challenges.py +++ b/string_challenges.py @@ -1,28 +1,27 @@ -# Вывести последнюю букву в слове -word = 'Архангельск' -# ??? +def count_vowels(your_word): + vowels = 0 + for character in ('а', 'е', 'ё', 'и', 'о', 'у', 'ы', 'э', 'ю', 'я'): + vowels += your_word.lower().count(character) + return vowels -# Вывести количество букв "а" в слове -word = 'Архангельск' -# ??? +def average_word_len(usr_sentence): + symbols = 0 + for word in usr_sentence.split(): + symbols += len(word) + return '{0:.2f}'.format(symbols / len(usr_sentence.split())) -# Вывести количество гласных букв в слове -word = 'Архангельск' -# ??? +def main(): + word = 'Архангельск' + sentence = 'Мы приехали в гости' + print(word[-1], end='\n\n') + print(word.lower().count('а'), end='\n\n') + print(count_vowels(word), end='\n\n') + print(len(sentence.split()), end='\n\n') + print(*[f'{word[0]}' for word in sentence.split()], sep='\n', end='\n\n') + print(f'Average word length: {average_word_len(sentence)}') -# Вывести количество слов в предложении -sentence = 'Мы приехали в гости' -# ??? - - -# Вывести первую букву каждого слова на отдельной строке -sentence = 'Мы приехали в гости' -# ??? - - -# Вывести усреднённую длину слова в предложении -sentence = 'Мы приехали в гости' -# ??? \ No newline at end of file +if __name__ == '__main__': + main() From d44cbcac662f8c743a1e063ee3a46fdea77c9140 Mon Sep 17 00:00:00 2001 From: Alexey Date: Fri, 26 May 2023 21:26:20 +0300 Subject: [PATCH 2/4] Really challenging --- for_challenges.py | 104 +++++++++++----------- for_dict_challenges.py | 97 +++++++++------------ for_dict_challenges_bonus.py | 161 ++++++++++++++++------------------- string_challenges.py | 21 ++--- 4 files changed, 174 insertions(+), 209 deletions(-) diff --git a/for_challenges.py b/for_challenges.py index a66392fa..b438d4da 100644 --- a/for_challenges.py +++ b/for_challenges.py @@ -1,86 +1,78 @@ # Задание 1. Необходимо вывести имена всех учеников из списка с новой строки def names_new_line(names_array): - return '\n'.join(names_array) + print('\n'.join(names_array)) # Задание 2. Необходимо вывести имена всех учеников из списка, рядом с именем показать количество букв в нём def names_with_len(names_array): - return [f'{name}: {len(name)} \n' for name in names_array] + print(*[f'{name}: {len(name)}' for name in names_array], sep='\n') # Задание 3. Необходимо вывести имена всех учеников из списка, рядом с именем вывести пол ученика -def male_or_female(names_array, mf_dict): - result = [] - for stud in names_array: - if stud in mf_dict and mf_dict[stud]: - is_stud_male = 'Мужской' - elif stud in mf_dict and not mf_dict[stud]: - is_stud_male = 'Женский' +def male_or_female(names_array, male_or_not_dict): + for student in names_array: + if student in male_or_not_dict and male_or_not_dict[student]: + is_student_male = 'Мужской' + elif student in male_or_not_dict and not male_or_not_dict[student]: + is_student_male = 'Женский' else: - is_stud_male = 'Нет информации' - result.append(f'Имя: {stud}, Пол: {is_stud_male}') - return result + is_student_male = 'Нет информации' + print(f'Имя: {student}. Пол: {is_student_male}') -# Задание 4. Даны группу учеников. Нужно вывести количество групп и для каждой группы – количество учеников в ней -def groups_count(groups_array): - group_counter = 0 - if 11 <= len(groups_array) <= 14: - inflection = '' - elif len(groups_array) % 10 == 1: - inflection = 'а' - elif 2 <= len(groups_array) % 10 <= 4: - inflection = 'ы' +# Задание 4. Даны группы учеников. Нужно вывести количество групп и для каждой группы – количество учеников в ней +def inflect(quantity, if_one, if_two_to_four, if_others): + if 11 <= quantity <= 14: + return if_others + elif quantity % 10 == 1: + return if_one + elif 2 <= quantity % 10 <= 4: + return if_two_to_four else: - inflection = '' - for_output = [f'Всего {len(groups_array)} групп{inflection}:',] - for group in groups_array: - group_counter += 1 - if 11 <= len(group) <= 14: - inflection = 'ов' - elif len(group) % 10 == 1: - inflection = '' - elif 2 <= len(group) % 10 <= 4: - inflection = 'а' - else: - inflection = 'ов' - for_output.append(f'Группа {group_counter}: {len(group)} ученик{inflection}') - return for_output + return if_others + + +def groups_count(groups_array): + inflection = inflect(len(groups_array), 'а', 'ы', '') + print(f'Всего {len(groups_array)} групп{inflection}:') + for group in enumerate(groups_array, start=1): + inflection = inflect(len(group[1]), '', 'а', 'ов') + print(f'Группа {group[0]}: {len(group[1])} ученик{inflection}') # Задание 5. Для каждой группы учеников нужно с новой строки перечислить учеников, которые в неё входят def groups_members(groups_array): - group_counter = 0 - for_output = [] - for group in groups_array: - group_counter += 1 - for_output.append(f"Группа {group_counter}: {', '.join(group)}") - return for_output + for group in enumerate(groups_array, start=1): + print(f"Группа {group[0]}: {', '.join(group[1])}") def main(): names = ['Оля', 'Петя', 'Вася', 'Маша'] is_male = { - 'Оля': False, - 'Петя': True, - 'Вася': True, - 'Маша': False, + 'Оля': False, + 'Петя': True, + 'Вася': True, + 'Маша': False, } groups1 = [ - ['Вася', 'Маша'], - ['Вася', 'Маша', 'Саша', 'Женя'], - ['Оля', 'Петя', 'Гриша'], + ['Вася', 'Маша'], + ['Вася', 'Маша', 'Саша', 'Женя'], + ['Оля', 'Петя', 'Гриша'], ] groups2 = [ - ['Вася', 'Маша'], - ['Оля', 'Петя', 'Гриша'], - ['Вася', 'Маша', 'Саша', 'Женя'], + ['Вася', 'Маша'], + ['Оля', 'Петя', 'Гриша'], + ['Вася', 'Маша', 'Саша', 'Женя'], ] - print(names_new_line(names), end='\n\n') - print(*names_with_len(names), sep='', end='\n') - print(*male_or_female(names, is_male), sep='\n', end='\n\n') - print(*groups_count(groups1), sep='\n', end='\n\n') - print(*groups_members(groups2), sep='\n') + names_new_line(names) + print() + names_with_len(names) + print() + male_or_female(names, is_male) + print() + groups_count(groups1) + print() + groups_members(groups2) if __name__ == '__main__': diff --git a/for_dict_challenges.py b/for_dict_challenges.py index fce2b6f6..9b332ba1 100644 --- a/for_dict_challenges.py +++ b/for_dict_challenges.py @@ -1,21 +1,18 @@ # Задание 1. Дан список учеников, нужно посчитать количество повторений каждого имени ученика def names_count(names_dict_array): - names, used_names, names_output = [], [], [] - for name_dict in names_dict_array: - names.append(name_dict['first_name']) + names = [name_dict['first_name'] for name_dict in names_dict_array] + used_names = [] for name in names: if name not in used_names: - names_output.append(f'{name}: {names.count(name)}') - used_names.append(name) - return names_output + used_names.append(name) + print(f'{name}: {names.count(name)}') # Задание 2. Дан список учеников, нужно вывести самое часто повторящееся имя def find_most_recurrent(names_dict_array): - names, used_names = [], [] + used_names = [] max_recurring = None - for name_dict in names_dict_array: - names.append(name_dict['first_name']) + names = [name_dict['first_name'] for name_dict in names_dict_array] for name in names: if name not in used_names: used_names.append(name) @@ -27,48 +24,35 @@ def find_most_recurrent(names_dict_array): # Задание 3. Есть список учеников в нескольких классах, нужно вывести самое частое имя в каждом классе. def find_most_recurrent_in_groups(school_array): - result = [] - head = 'Самое частое имя в классе ' - group_counter = 0 - for group in school_array: - group_counter += 1 - result.append(f'{head}{group_counter}: {find_most_recurrent(group)}\n') - return result + for group in enumerate(school_array, start=1): + max_recurring = find_most_recurrent(group[1]) + print(f'Самое частое имя в классе {group[0]}: {max_recurring}') # Задание 4. Для каждого класса нужно вывести количество девочек и мальчиков в нём. -def mf_count(school_group, mf_dict): - m_counter = 0 - f_counter = 0 +def boys_and_girls_count(school_group, male_or_not_dict): + male_counter = 0 + female_counter = 0 for student in school_group['students']: - if mf_dict.get(student['first_name']) == True: - m_counter += 1 - elif mf_dict.get(student['first_name']) == False: - f_counter += 1 - return (school_group['class'], m_counter, f_counter) + if male_or_not_dict.get(student['first_name']): + male_counter += 1 + elif not male_or_not_dict.get(student['first_name']): + female_counter += 1 + return school_group['class'], male_counter, female_counter -def mf_count_in_groups(school_array, mf_dict): - result = [] +def boys_and_girls_count_in_groups(school_array, male_or_not_dict): for group in school_array: - gr_stat = mf_count(group, mf_dict) - result.append(f'Класс {gr_stat[0]}: девочки {gr_stat[2]}, мальчики {gr_stat[1]}') - return result + group_stat = boys_and_girls_count(group, male_or_not_dict) + print(f'Класс {group_stat[0]}: девочки {group_stat[2]}, мальчики {group_stat[1]}') # Задание 5. По информации об учениках разных классов нужно найти класс, в котором больше всего девочек и больше всего мальчиков -def mf_max(school_array, mf_dict): - groups = [] - for group in school_array: - groups.append(mf_count(group, mf_dict)) - m_max = None - f_max = None - for group_stat in groups: - if m_max == None or group_stat[1] > m_max[1]: - m_max = (group_stat[0], group_stat[1]) - if f_max == None or group_stat[2] > f_max[1]: - f_max = (group_stat[0], group_stat[2]) - return m_max + f_max +def genders_max(school_array, male_or_not_dict): + groups = [boys_and_girls_count(group, male_or_not_dict) for group in school_array] + male_max = max(groups, key = lambda group : group[1]) + female_max = max(groups, key = lambda group : group[2]) + return male_max + female_max def main(): @@ -106,23 +90,26 @@ def main(): 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': '2в', 'students': [{'first_name': 'Даша'}, {'first_name': 'Олег'}, {'first_name': 'Маша'}]}, ] is_male = { - 'Олег': True, - 'Маша': False, - 'Оля': False, - 'Миша': True, - 'Даша': False, + 'Олег': True, + 'Маша': False, + 'Оля': False, + 'Миша': True, + 'Даша': False, } - head = 'Самое частое имя среди учеников: ' - max_classes = mf_max(school, is_male) - print(*names_count(students1), sep='\n', end='\n\n') - print(f'{head}{find_most_recurrent(students2)}', end='\n\n') - print(*find_most_recurrent_in_groups(school_students), sep='', end='\n') - print(*mf_count_in_groups(school, is_male), sep='\n', end='\n\n') - print(f'Больше всего мальчиков в классе {max_classes[0]} ({max_classes[1]})') - print(f'Больше всего девочек в классе {max_classes[2]} ({max_classes[3]})') + leaders = genders_max(school, is_male) + names_count(students1) + print() + print('Самое частое имя среди учеников:', find_most_recurrent(students2)) + print() + find_most_recurrent_in_groups(school_students) + print() + boys_and_girls_count_in_groups(school, is_male) + print() + print(f'Больше всего мальчиков в классе {leaders[0]} ({leaders[1]})') + print(f'Больше всего девочек в классе {leaders[3]} ({leaders[5]})') if __name__ == '__main__': diff --git a/for_dict_challenges_bonus.py b/for_dict_challenges_bonus.py index 2b2af9f2..b9447fb9 100644 --- a/for_dict_challenges_bonus.py +++ b/for_dict_challenges_bonus.py @@ -2,6 +2,7 @@ import uuid import datetime import lorem +from collections import Counter, defaultdict def generate_chat_history(): @@ -35,121 +36,105 @@ def generate_chat_history(): # Вывести айди пользователя, который написал больше всех сообщений def find_most_active(chat_history): - ids, used_ids = [], [] - max_msg = None + message_authors = Counter() for message in chat_history: - ids.append(message['sent_by']) - for id in ids: - if id not in used_ids: - msg = ids.count(id) - if max_msg is None or msg > max_msg[1]: - max_msg = (id, msg) - used_ids.append(id) - return max_msg + message_authors[message['sent_by']] += 1 + return message_authors.most_common(1) # Вывести айди пользователя, на сообщения которого больше всего отвечали def find_most_replied(chat_history): - replies_ids = [] - replied_usrs = [] - max_replies = None + replies = [] + replies_counter = Counter() for message in chat_history: if message['reply_for'] is not None: - replies_ids.append(message['reply_for']) - for rpld_message in chat_history: - if rpld_message['id'] in replies_ids: - replied_usrs.append(rpld_message['sent_by']) - for id in replied_usrs: - replies = replied_usrs.count(id) - if max_replies is None or replies > max_replies[1]: - max_replies = (id, replies) - return max_replies - + replies.append(message['reply_for']) + for replied_message in chat_history: + if replied_message['id'] in replies: + replies_counter[replied_message['sent_by']] += 1 + return replies_counter.most_common(1) + # Вывести айди пользователей, сообщения которых видело больше всего уникальных пользователей def find_most_popular(chat_history): - users_output = [] - users_seen_by = {} + seen_by = defaultdict(set) + seen_by_counter = Counter() for message in chat_history: - if message['sent_by'] in users_seen_by: - users_seen_by[message['sent_by']] += message['seen_by'] - else: - users_seen_by[message['sent_by']] = message['seen_by'] - max_seen = None - for user in users_seen_by: - seen = len(set(users_seen_by[user])) - if max_seen is None or seen > max_seen: - max_seen = seen - users_output = [user,] - elif seen == max_seen: - users_output.append(user) - return (users_output, max_seen) + for reader in message['seen_by']: + seen_by[message['sent_by']].add(reader) + for user_seen_by in seen_by: + seen_by_counter[user_seen_by] = len(seen_by[user_seen_by]) + maximum = lambda item : item[1] == seen_by_counter.most_common(1)[0][1] + return dict(filter(maximum, seen_by_counter.items())) # Определить, когда в чате больше всего сообщений: утром (до 12 часов), днём (12-18 часов) или вечером (после 18 часов) def find_preferred_time(chat_history): - morning_count = 0 - day_count = 0 - everning_count = 0 - preferred = None + time_posted = Counter() for message in chat_history: - msg_hour = int(str(message['sent_at'].time())[0:2]) - if msg_hour < 12: - morning_count += 1 - elif msg_hour <= 18: - day_count += 1 + message_hour = int(str(message['sent_at'].time())[0:2]) + if message_hour < 12: + time_posted['morning'] += 1 + elif message_hour <= 18: + time_posted['day'] += 1 else: - everning_count += 1 - max_count = max(morning_count, day_count, everning_count) - if morning_count == max_count: - preferred = 'morning' - elif day_count == max_count: - preferred = 'day' - else: - preferred = 'everning' - return (morning_count, day_count, everning_count, preferred) + time_posted['everning'] += 1 + return time_posted # Вывести идентификаторы сообщений, который стали началом для самых длинных тредов (цепочек ответов) +def find_message(chat_history, message_id): + for message in chat_history: + if message['id'] == message_id: + return message + + +def find_ancestor(chat_history, message, thread_length): + if message['reply_for'] is None: + return thread_length + else: + elder_message = find_message(chat_history, message['reply_for']) + return find_ancestor(chat_history, elder_message, thread_length + 1) + + def find_thread_starters(chat_history): - replied_ranks = {} - ids_output = [] + thread_starters = [] + longest_thread = None for message in chat_history: - if message['reply_for'] is not None: - if message['reply_for'] in replied_ranks: - replied_ranks[message['reply_for']] += 1 - else: - replied_ranks[message['reply_for']] = 1 - max_rank = None - for id in replied_ranks: - rank = replied_ranks[id] - if max_rank is None or rank > max_rank: - max_rank = rank - ids_output = [id,] - elif rank == max_rank: - ids_output.append(id) - return (ids_output, max_rank) + thread_length = find_ancestor(chat_history, message, 0) + if longest_thread is None or thread_length > longest_thread: + longest_thread = thread_length + thread_starters = [message['id'],] + elif thread_length == longest_thread: + thread_starters.append(message['id']) + return thread_starters, longest_thread def main(): my_chat = generate_chat_history() - most_active_user = find_most_active(my_chat) - most_replied_user = find_most_replied(my_chat) - most_popular_users = find_most_popular(my_chat) - preferred_time = find_preferred_time(my_chat) + most_active = find_most_active(my_chat) + most_replied = find_most_replied(my_chat) + most_popular = find_most_popular(my_chat) + best_time = find_preferred_time(my_chat) thread_starters = find_thread_starters(my_chat) - print(f'Most active user id: {most_active_user[0]}.', end=' ') - print(f'They have written {most_active_user[1]} messages.', end='\n\n') - print(f'Most replied user id: {most_replied_user[0]}.', end=' ') - print(f'They were replied {most_replied_user[1]} times.', end='\n\n') - print(f"Most seen users id(s): {', '.join(map(str, most_popular_users[0]))}.") - print(f'{most_popular_users[1]} other users have seen their messages.', end='\n\n') - print(f"Users' favourite time for chatting is {preferred_time[3]}.") - print(f'{preferred_time[0]} messages were sent in the morning,', end=' ') - print(f'{preferred_time[1]} during the day, {preferred_time[2]} in the everning', end='\n\n') - print(f"Longest thread starters' id(s): {', '.join(map(str, thread_starters[0]))}.") - print(f'These messages had {thread_starters[1]} answers.') - + print(f'Most active user id: {most_active[0][0]}') + print(f'They have written {most_active[0][1]} messages') + print() + print(f'Most replied user id: {most_replied[0][0]}') + print(f'They were replied {most_replied[0][1]} times') + print() + print(f"Most seen users id(s): {', '.join(map(str, most_popular))}") + print(list((most_popular.values()))[0], 'users have seen their messages') + print() + print(f"Best time for chatting is {best_time.most_common(1)[0][0]}") + print(f"{best_time['morning']} messages were sent in the morning,", end=' ') + print(f"{best_time['day']} during the day,", end=' ') + print(f"{best_time['everning']} in the everning") + print() + print(f"Longest thread starters' id(s):", end=' ') + print(', '.join(map(str, thread_starters[0]))) + print(f'Their threads are {thread_starters[1]} messages long') + if __name__ == "__main__": main() diff --git a/string_challenges.py b/string_challenges.py index 957ed3c1..3e3e91df 100644 --- a/string_challenges.py +++ b/string_challenges.py @@ -5,23 +5,24 @@ def count_vowels(your_word): return vowels -def average_word_len(usr_sentence): +def average_word_len(user_sentence): symbols = 0 - for word in usr_sentence.split(): + for word in user_sentence.split(): symbols += len(word) - return '{0:.2f}'.format(symbols / len(usr_sentence.split())) + return '{0:.2f}'.format(symbols / len(user_sentence.split())) def main(): word = 'Архангельск' sentence = 'Мы приехали в гости' - print(word[-1], end='\n\n') - print(word.lower().count('а'), end='\n\n') - print(count_vowels(word), end='\n\n') - print(len(sentence.split()), end='\n\n') - print(*[f'{word[0]}' for word in sentence.split()], sep='\n', end='\n\n') - print(f'Average word length: {average_word_len(sentence)}') - + print(f'Последняя буква слова: {word[-1]}.') + print(f"Букв 'а' в слове: {word.lower().count('а')}.") + print(f'Гласных в слове: {count_vowels(word)}.') + print(f'Слов в предложении: {len(sentence.split())}.') + print(f'Средняя длина слова в предложении: {average_word_len(sentence)}') + print('Первые буквы слов предложения:') + print(*[f'{one_word[0]}' for one_word in sentence.split()], sep='\n') + if __name__ == '__main__': main() From 1b27f4f91e1997b6e6893007cc4d8b0b90d718f9 Mon Sep 17 00:00:00 2001 From: Alexey Date: Mon, 29 May 2023 01:34:53 +0300 Subject: [PATCH 3/4] Per rectum ad astra --- for_challenges.py | 48 +++++++++++++++++++----------------- for_dict_challenges.py | 30 ++++++++++++---------- for_dict_challenges_bonus.py | 44 ++++++++++++++++----------------- string_challenges.py | 11 ++++++--- 4 files changed, 70 insertions(+), 63 deletions(-) diff --git a/for_challenges.py b/for_challenges.py index b438d4da..95feb323 100644 --- a/for_challenges.py +++ b/for_challenges.py @@ -1,53 +1,55 @@ +def inflect(quantity, if_one, if_two_to_four, if_others): + if 11 <= quantity <= 14: + return if_others + elif quantity % 10 == 1: + return if_one + elif 2 <= quantity % 10 <= 4: + return if_two_to_four + else: + return if_others + + # Задание 1. Необходимо вывести имена всех учеников из списка с новой строки def names_new_line(names_array): - print('\n'.join(names_array)) + for name in names_array: + print(name) # Задание 2. Необходимо вывести имена всех учеников из списка, рядом с именем показать количество букв в нём def names_with_len(names_array): - print(*[f'{name}: {len(name)}' for name in names_array], sep='\n') + for name in names_array: + print(f"{name}: {len(name)} букв{inflect(len(name), 'а', 'ы', '')}") # Задание 3. Необходимо вывести имена всех учеников из списка, рядом с именем вывести пол ученика def male_or_female(names_array, male_or_not_dict): for student in names_array: if student in male_or_not_dict and male_or_not_dict[student]: - is_student_male = 'Мужской' + student_gender = 'Мужской' elif student in male_or_not_dict and not male_or_not_dict[student]: - is_student_male = 'Женский' + student_gender = 'Женский' else: - is_student_male = 'Нет информации' - print(f'Имя: {student}. Пол: {is_student_male}') + student_gender = 'Нет информации' + print(f'Имя: {student}. Пол: {student_gender}') # Задание 4. Даны группы учеников. Нужно вывести количество групп и для каждой группы – количество учеников в ней -def inflect(quantity, if_one, if_two_to_four, if_others): - if 11 <= quantity <= 14: - return if_others - elif quantity % 10 == 1: - return if_one - elif 2 <= quantity % 10 <= 4: - return if_two_to_four - else: - return if_others - - def groups_count(groups_array): inflection = inflect(len(groups_array), 'а', 'ы', '') print(f'Всего {len(groups_array)} групп{inflection}:') - for group in enumerate(groups_array, start=1): - inflection = inflect(len(group[1]), '', 'а', 'ов') - print(f'Группа {group[0]}: {len(group[1])} ученик{inflection}') + for group_number, group_members in enumerate(groups_array, start=1): + inflection = inflect(len(group_members), '', 'а', 'ов') + print(f'Группа {group_number}: {len(group_members)} ученик{inflection}') # Задание 5. Для каждой группы учеников нужно с новой строки перечислить учеников, которые в неё входят def groups_members(groups_array): - for group in enumerate(groups_array, start=1): - print(f"Группа {group[0]}: {', '.join(group[1])}") + for group_number, group_members in enumerate(groups_array, start=1): + print(f"Группа {group_number}: {', '.join(group_members)}") def main(): - names = ['Оля', 'Петя', 'Вася', 'Маша'] + names = ['Оля', 'Петя', 'Вася', 'Маша', 'Женя'] is_male = { 'Оля': False, 'Петя': True, diff --git a/for_dict_challenges.py b/for_dict_challenges.py index 9b332ba1..f624545d 100644 --- a/for_dict_challenges.py +++ b/for_dict_challenges.py @@ -31,28 +31,31 @@ def find_most_recurrent_in_groups(school_array): # Задание 4. Для каждого класса нужно вывести количество девочек и мальчиков в нём. def boys_and_girls_count(school_group, male_or_not_dict): - male_counter = 0 - female_counter = 0 + males_in_group = 0 + females_in_group = 0 for student in school_group['students']: if male_or_not_dict.get(student['first_name']): - male_counter += 1 + males_in_group += 1 elif not male_or_not_dict.get(student['first_name']): - female_counter += 1 - return school_group['class'], male_counter, female_counter + females_in_group += 1 + return school_group['class'], males_in_group, females_in_group def boys_and_girls_count_in_groups(school_array, male_or_not_dict): for group in school_array: group_stat = boys_and_girls_count(group, male_or_not_dict) - print(f'Класс {group_stat[0]}: девочки {group_stat[2]}, мальчики {group_stat[1]}') + print(f'Класс {group_stat[0]}: мальчики {group_stat[1]}, девочки {group_stat[2]}') # Задание 5. По информации об учениках разных классов нужно найти класс, в котором больше всего девочек и больше всего мальчиков -def genders_max(school_array, male_or_not_dict): +def gender_max(school_array, male_or_not_dict, gender): groups = [boys_and_girls_count(group, male_or_not_dict) for group in school_array] - male_max = max(groups, key = lambda group : group[1]) - female_max = max(groups, key = lambda group : group[2]) - return male_max + female_max + max_boys_group = max(groups, key = lambda group : group[1]) + max_girls_group = max(groups, key = lambda group : group[2]) + if gender.lower() == 'boys': + return max_boys_group[0], max_boys_group[1] + elif gender.lower() == 'girls': + return max_girls_group[0], max_girls_group[2] def main(): @@ -99,7 +102,8 @@ def main(): 'Миша': True, 'Даша': False, } - leaders = genders_max(school, is_male) + max_boys = gender_max(school, is_male, 'boys') + max_girls = gender_max(school, is_male, 'girls') names_count(students1) print() print('Самое частое имя среди учеников:', find_most_recurrent(students2)) @@ -108,8 +112,8 @@ def main(): print() boys_and_girls_count_in_groups(school, is_male) print() - print(f'Больше всего мальчиков в классе {leaders[0]} ({leaders[1]})') - print(f'Больше всего девочек в классе {leaders[3]} ({leaders[5]})') + print(f'Больше всего мальчиков в классе {max_boys[0]} ({max_boys[1]})') + print(f'Больше всего девочек в классе {max_girls[0]} ({max_girls[1]})') if __name__ == '__main__': diff --git a/for_dict_challenges_bonus.py b/for_dict_challenges_bonus.py index b9447fb9..adb4f048 100644 --- a/for_dict_challenges_bonus.py +++ b/for_dict_challenges_bonus.py @@ -39,20 +39,17 @@ def find_most_active(chat_history): message_authors = Counter() for message in chat_history: message_authors[message['sent_by']] += 1 - return message_authors.most_common(1) + return message_authors.most_common(1)[0] # Вывести айди пользователя, на сообщения которого больше всего отвечали def find_most_replied(chat_history): - replies = [] replies_counter = Counter() - for message in chat_history: - if message['reply_for'] is not None: - replies.append(message['reply_for']) + replies_ids = [message['reply_for'] for message in chat_history if message['reply_for'] is not None] for replied_message in chat_history: - if replied_message['id'] in replies: + if replied_message['id'] in replies_ids: replies_counter[replied_message['sent_by']] += 1 - return replies_counter.most_common(1) + return replies_counter.most_common(1)[0] # Вывести айди пользователей, сообщения которых видело больше всего уникальных пользователей @@ -64,15 +61,16 @@ def find_most_popular(chat_history): seen_by[message['sent_by']].add(reader) for user_seen_by in seen_by: seen_by_counter[user_seen_by] = len(seen_by[user_seen_by]) - maximum = lambda item : item[1] == seen_by_counter.most_common(1)[0][1] - return dict(filter(maximum, seen_by_counter.items())) + maximum = seen_by_counter.most_common(1)[0][1] + most_popular = [user_id for user_id, was_seen_by in seen_by_counter.items() if was_seen_by == maximum] + return most_popular, maximum # Определить, когда в чате больше всего сообщений: утром (до 12 часов), днём (12-18 часов) или вечером (после 18 часов) def find_preferred_time(chat_history): time_posted = Counter() for message in chat_history: - message_hour = int(str(message['sent_at'].time())[0:2]) + message_hour = int(message['sent_at'].strftime('%H')) if message_hour < 12: time_posted['morning'] += 1 elif message_hour <= 18: @@ -89,19 +87,19 @@ def find_message(chat_history, message_id): return message -def find_ancestor(chat_history, message, thread_length): - if message['reply_for'] is None: - return thread_length - else: - elder_message = find_message(chat_history, message['reply_for']) - return find_ancestor(chat_history, elder_message, thread_length + 1) +def find_thread_length(chat_history, message): + thread_length = 0 + while message['reply_for'] is not None: + thread_length += 1 + message = find_message(chat_history, message['reply_for']) + return thread_length def find_thread_starters(chat_history): thread_starters = [] longest_thread = None for message in chat_history: - thread_length = find_ancestor(chat_history, message, 0) + thread_length = find_thread_length(chat_history, message) if longest_thread is None or thread_length > longest_thread: longest_thread = thread_length thread_starters = [message['id'],] @@ -117,14 +115,14 @@ def main(): most_popular = find_most_popular(my_chat) best_time = find_preferred_time(my_chat) thread_starters = find_thread_starters(my_chat) - print(f'Most active user id: {most_active[0][0]}') - print(f'They have written {most_active[0][1]} messages') + print(f'Most active user id: {most_active[0]}') + print(f'They have written {most_active[1]} messages') print() - print(f'Most replied user id: {most_replied[0][0]}') - print(f'They were replied {most_replied[0][1]} times') + print(f'Most replied user id: {most_replied[0]}') + print(f'They were replied {most_replied[1]} times') print() - print(f"Most seen users id(s): {', '.join(map(str, most_popular))}") - print(list((most_popular.values()))[0], 'users have seen their messages') + print(f"Most seen users id(s): {', '.join(map(str, most_popular[0]))}") + print(f'{most_popular[1]} users have seen their messages') print() print(f"Best time for chatting is {best_time.most_common(1)[0][0]}") print(f"{best_time['morning']} messages were sent in the morning,", end=' ') diff --git a/string_challenges.py b/string_challenges.py index 3e3e91df..f7dd118d 100644 --- a/string_challenges.py +++ b/string_challenges.py @@ -6,12 +6,15 @@ def count_vowels(your_word): def average_word_len(user_sentence): - symbols = 0 - for word in user_sentence.split(): - symbols += len(word) + symbols = sum([len(word) for word in user_sentence.split()]) return '{0:.2f}'.format(symbols / len(user_sentence.split())) +def first_symbols_of_sentence(user_sentence): + for one_word in user_sentence.split(): + print(one_word[0]) + + def main(): word = 'Архангельск' sentence = 'Мы приехали в гости' @@ -21,7 +24,7 @@ def main(): print(f'Слов в предложении: {len(sentence.split())}.') print(f'Средняя длина слова в предложении: {average_word_len(sentence)}') print('Первые буквы слов предложения:') - print(*[f'{one_word[0]}' for one_word in sentence.split()], sep='\n') + first_symbols_of_sentence(sentence) if __name__ == '__main__': From d9b505d67423f27effdf7b0fa0b14338f73ea64b Mon Sep 17 00:00:00 2001 From: Alexey Date: Mon, 29 May 2023 17:14:37 +0300 Subject: [PATCH 4/4] minor changes --- for_challenges.py | 3 ++- for_dict_challenges_bonus.py | 2 ++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/for_challenges.py b/for_challenges.py index 95feb323..1a41acc5 100644 --- a/for_challenges.py +++ b/for_challenges.py @@ -18,7 +18,8 @@ def names_new_line(names_array): # Задание 2. Необходимо вывести имена всех учеников из списка, рядом с именем показать количество букв в нём def names_with_len(names_array): for name in names_array: - print(f"{name}: {len(name)} букв{inflect(len(name), 'а', 'ы', '')}") + inflection = inflect(len(name), 'а', 'ы', '') + print(f'{name}: {len(name)} букв{inflection}') # Задание 3. Необходимо вывести имена всех учеников из списка, рядом с именем вывести пол ученика diff --git a/for_dict_challenges_bonus.py b/for_dict_challenges_bonus.py index adb4f048..8a2debf4 100644 --- a/for_dict_challenges_bonus.py +++ b/for_dict_challenges_bonus.py @@ -70,7 +70,9 @@ def find_most_popular(chat_history): def find_preferred_time(chat_history): time_posted = Counter() for message in chat_history: + message_hour = int(str(message['sent_at'].time())[0:2]) message_hour = int(message['sent_at'].strftime('%H')) + message_hour = message['sent_at'].hour if message_hour < 12: time_posted['morning'] += 1 elif message_hour <= 18: