-
Notifications
You must be signed in to change notification settings - Fork 262
Do homework #51
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?
Do homework #51
Changes from 2 commits
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,6 +2,8 @@ | |
| # Необходимо вывести имена всех учеников из списка с новой строки | ||
|
|
||
| names = ['Оля', 'Петя', 'Вася', 'Маша'] | ||
| for name in names: | ||
| print(name) | ||
| # ??? | ||
|
|
||
|
|
||
|
|
@@ -12,6 +14,8 @@ | |
| # Петя: 4 | ||
|
|
||
| names = ['Оля', 'Петя', 'Вася', 'Маша'] | ||
| for name in names: | ||
| print(f'{name}: {len(name)}') | ||
| # ??? | ||
|
|
||
|
|
||
|
|
@@ -25,6 +29,11 @@ | |
| 'Маша': False, | ||
| } | ||
| names = ['Оля', 'Петя', 'Вася', 'Маша'] | ||
| for name in names: | ||
| if is_male[name]: | ||
| print(f'{name} мужской') | ||
| else: | ||
| print(f'{name} женский') | ||
| # ??? | ||
|
|
||
|
|
||
|
|
@@ -40,6 +49,11 @@ | |
| ['Вася', 'Маша', 'Саша', 'Женя'], | ||
| ['Оля', 'Петя', 'Гриша'], | ||
| ] | ||
| print(f'Всего {len(groups)} группы') | ||
| group_number = 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, это более pythonic way. Плюс меньше ошибок, и другим разработчикам будет сразу понятно что мы просто последовательно все элементы нумеруем (а не что-то более хитрое) |
||
| for group in groups: | ||
| print(f'Группа {group_number}: {len(group)} человека.') | ||
| group_number += 1 | ||
| # ??? | ||
|
|
||
|
|
||
|
|
@@ -54,4 +68,8 @@ | |
| ['Оля', 'Петя', 'Гриша'], | ||
| ['Вася', 'Маша', 'Саша', 'Женя'], | ||
| ] | ||
| group_number = 1 | ||
| for group in groups: | ||
| print(f'Группа {group_number}: {", ".join(group)}') | ||
| group_number += 1 | ||
| # ??? | ||
| Original file line number | Diff line number | Diff line change | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -12,8 +12,16 @@ | |||||||||||
| {'first_name': 'Маша'}, | ||||||||||||
| {'first_name': 'Петя'}, | ||||||||||||
| ] | ||||||||||||
| names = dict() | ||||||||||||
| for student in students: | ||||||||||||
| if student['first_name'] not in names: | ||||||||||||
| names[student['first_name']] = 1 | ||||||||||||
| else: | ||||||||||||
| names[student['first_name']] += 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. Как продвинутый вариант можно использовать get с аргументом по умолчанию 0:
Suggested change
|
||||||||||||
| for name, num in names.items(): | ||||||||||||
| print(f'{name}: {num}') | ||||||||||||
| # ??? | ||||||||||||
|
|
||||||||||||
|
|
||||||||||||
| # Задание 2 | ||||||||||||
| # Дан список учеников, нужно вывести самое часто повторящееся имя | ||||||||||||
|
|
@@ -26,6 +34,21 @@ | |||||||||||
| {'first_name': 'Маша'}, | ||||||||||||
| {'first_name': 'Оля'}, | ||||||||||||
| ] | ||||||||||||
| names = dict() | ||||||||||||
| for student in students: | ||||||||||||
| if student['first_name'] not in names: | ||||||||||||
| names[student['first_name']] = 1 | ||||||||||||
| else: | ||||||||||||
| names[student['first_name']] += 1 | ||||||||||||
|
|
||||||||||||
| result_name = list(names.keys())[0] | ||||||||||||
| num_of_names = names.pop(result_name) | ||||||||||||
|
|
||||||||||||
| for name, num in names.items(): | ||||||||||||
| if num > num_of_names: | ||||||||||||
| result_name = name | ||||||||||||
| num_of_names = num | ||||||||||||
| print(result_name) | ||||||||||||
| # ??? | ||||||||||||
|
|
||||||||||||
|
|
||||||||||||
|
|
@@ -51,8 +74,26 @@ | |||||||||||
| {'first_name': 'Саша'}, | ||||||||||||
| ], | ||||||||||||
| ] | ||||||||||||
| # ??? | ||||||||||||
| class_number = 1 | ||||||||||||
| for group in school_students: | ||||||||||||
| names = dict() | ||||||||||||
| for student in group: | ||||||||||||
| if student['first_name'] not in names: | ||||||||||||
| names[student['first_name']] = 1 | ||||||||||||
| else: | ||||||||||||
| names[student['first_name']] += 1 | ||||||||||||
|
|
||||||||||||
| result_name = list(names.keys())[0] | ||||||||||||
| num_of_names = names.pop(result_name) | ||||||||||||
|
|
||||||||||||
| for name, num in names.items(): | ||||||||||||
| if num > num_of_names: | ||||||||||||
| result_name = name | ||||||||||||
| num_of_names = num | ||||||||||||
| print(f'Самое частое имя в классе {class_number}: {result_name}') | ||||||||||||
| class_number += 1 | ||||||||||||
| # ??? | ||||||||||||
| print() | ||||||||||||
|
|
||||||||||||
| # Задание 4 | ||||||||||||
| # Для каждого класса нужно вывести количество девочек и мальчиков в нём. | ||||||||||||
|
|
||||||||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -33,12 +33,13 @@ | |
| import random | ||
| import uuid | ||
| import datetime | ||
| import pprint | ||
|
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. 👍 |
||
|
|
||
| import lorem | ||
|
|
||
|
|
||
| def generate_chat_history(): | ||
| messages_amount = random.randint(200, 1000) | ||
| messages_amount = random.randint(10, 20) | ||
| users_ids = list( | ||
| {random.randint(1, 10000) for _ in range(random.randint(5, 20))} | ||
| ) | ||
|
|
@@ -67,4 +68,111 @@ def generate_chat_history(): | |
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| print(generate_chat_history()) | ||
| messages = generate_chat_history() | ||
| # pprint.pprint(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. Старайся не забывать удалять закоментированый дебажный код. |
||
|
|
||
| # Вывести айди пользователя, который написал больше всех сообщений. | ||
|
|
||
| def find_most_messages_user(messages): | ||
| users = {} | ||
| for message in messages: | ||
| if message['sent_by'] not in users: | ||
| users[message['sent_by']] = 1 | ||
| else: | ||
| users[message['sent_by']] += 1 | ||
|
|
||
| most_num_of_messages = 0 | ||
| for user, number_of_messages in users.items(): | ||
| if number_of_messages > most_num_of_messages: | ||
| user_id = user | ||
| most_num_of_messages = number_of_messages | ||
| return user_id | ||
|
|
||
| print(f'Больше всего сообщений написал пользователь с id: {find_most_messages_user(messages)}') | ||
|
|
||
| # Вывести айди пользователя, на сообщения которого больше всего отвечали. | ||
|
|
||
| def find_most_answers_user(messages): | ||
| answers = {} | ||
| for message in messages: | ||
| if message['reply_for'] == None: | ||
| continue | ||
| elif message['reply_for'] not in answers: | ||
| answers[message['reply_for']] = 1 | ||
| else: | ||
| answers[message['reply_for']] += 1 | ||
|
|
||
| most_num_of_messages = 0 | ||
| for message, number_of_answers in answers.items(): | ||
| if number_of_answers > most_num_of_messages: | ||
| message_id = message | ||
| most_num_of_messages = number_of_answers | ||
|
|
||
| for message in messages: | ||
| if message['id'] == message_id: | ||
| return(message['sent_by']) | ||
| print(f'Больше всего отвечали на сообщения пользователя с id: {find_most_answers_user(messages)}') | ||
|
|
||
| # Вывести айди пользователей, сообщения которых видело больше всего уникальных пользователей. | ||
|
|
||
| def find_most_viewed_user(messages): | ||
| users = {} | ||
| for message in messages: | ||
| if message['sent_by'] not in users: | ||
| users[message['sent_by']] = message['seen_by'] | ||
| else: | ||
| users[message['sent_by']] += message['seen_by'] | ||
| for id, messages in users.items(): | ||
| print(id, len(set(messages))) | ||
| find_most_viewed_user(messages) | ||
|
|
||
| # Определить, когда в чате больше всего сообщений: утром (до 12 часов), днём (12-18 часов) или вечером (после 18 часов). | ||
|
|
||
| def determine_time(messages): | ||
| sent_time = {'утром': 0, | ||
| 'днём': 0, | ||
| 'вечером': 0} | ||
| for message in messages: | ||
| if int(datetime.datetime.strftime(message['sent_at'], '%H')) < 12: | ||
| sent_time['утром'] += 1 | ||
| elif 12 <= int(datetime.datetime.strftime(message['sent_at'], '%H')) < 18: | ||
| sent_time['днём'] += 1 | ||
| else: | ||
| sent_time['вечером'] += 1 | ||
| number_of_message = 0 | ||
| for time, number in sent_time.items(): | ||
| if number > number_of_message: | ||
| day_time = time | ||
| number_of_message = number | ||
| print(f'Больше всего сообщений пишут {day_time}') | ||
|
|
||
| determine_time(messages) | ||
|
|
||
| # Вывести идентификаторы сообщений, который стали началом для самых длинных тредов (цепочек ответов). | ||
|
|
||
| def create_message_id_dict(messages): | ||
| message_reply = {} | ||
| for message in messages: | ||
| message_reply[message['id']] = message['reply_for'] | ||
| return message_reply | ||
|
|
||
| def find_message_tree(message_reply, message_id, answers): | ||
| for key, value in message_reply.items(): | ||
| if message_id == value: | ||
| answers.append(key) | ||
| find_message_tree(message_reply, key, answers) | ||
| return answers | ||
|
|
||
| message_reply = create_message_id_dict(messages) | ||
|
|
||
| message_tree = {} | ||
| for message_id in message_reply: | ||
| answers = [] | ||
| message_tree[message_id] = find_message_tree(message_reply, message_id, answers) | ||
|
|
||
| num_of_answers = 0 | ||
| for key, value in message_tree.items(): | ||
| if len(value) > num_of_answers: | ||
| num_of_answers = len(value) | ||
| most_reply_id = key | ||
| print(most_reply_id) | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,28 +1,43 @@ | ||
| # Вывести последнюю букву в слове | ||
| word = 'Архангельск' | ||
| print(word[-1]) | ||
| # ??? | ||
|
|
||
|
|
||
| # Вывести количество букв "а" в слове | ||
| word = 'Архангельск' | ||
| print(word.lower().count('а')) | ||
| # ??? | ||
|
|
||
|
|
||
| # Вывести количество гласных букв в слове | ||
| word = 'Архангельск' | ||
| vowel_letters = 'аеёиоуыэюя' | ||
| counter = 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. было бы отлично использовать чуть более конкретные имена вроде vowel_counter |
||
| for letter in word.lower(): | ||
| if letter in vowel_letters: | ||
| counter += 1 | ||
| print(counter) | ||
| # ??? | ||
|
|
||
|
|
||
| # Вывести количество слов в предложении | ||
| sentence = 'Мы приехали в гости' | ||
| print(len(sentence.split())) | ||
| # ??? | ||
|
|
||
|
|
||
| # Вывести первую букву каждого слова на отдельной строке | ||
| sentence = 'Мы приехали в гости' | ||
| for word in sentence.split(): | ||
| print(word[0]) | ||
| # ??? | ||
|
|
||
|
|
||
| # Вывести усреднённую длину слова в предложении | ||
| sentence = 'Мы приехали в гости' | ||
| numbers_of_letters = 0 | ||
| for word in sentence.split(): | ||
| numbers_of_letters += len(word) | ||
| print(numbers_of_letters / 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.
Тут можно чуть сократить код. Как минимум нам хотелось бы что бы осталась только одна f-строка, что бы избежать двойного редактирования.