Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 16 additions & 3 deletions for_challenges.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
# Необходимо вывести имена всех учеников из списка с новой строки

names = ['Оля', 'Петя', 'Вася', 'Маша']
# ???
for name in names:
print(name)


# Задание 2
Expand All @@ -12,7 +13,8 @@
# Петя: 4

names = ['Оля', 'Петя', 'Вася', 'Маша']
# ???
for name in names:
print(name, len(name))


# Задание 3
Expand All @@ -24,6 +26,11 @@
'Вася': True,
'Маша': False,
}
for name in is_male:
if is_male[name] == True:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Лучше не сравнивать с True, просто if is_male[name]:

print(f'{name}, мужской пол')
else:
print(f'{name}, женский пол')
names = ['Оля', 'Петя', 'Вася', 'Маша']
# ???

Expand All @@ -40,6 +47,9 @@
['Вася', 'Маша', 'Саша', 'Женя'],
['Оля', 'Петя', 'Гриша'],
]
print(f'Всего груп: {len(groups)}')

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

групп

for group in range(len(groups)):
print(f'Группа {group+1}: {len(groups[group])} ученика')
# ???


Expand All @@ -54,4 +64,7 @@
['Оля', 'Петя', 'Гриша'],
['Вася', 'Маша', 'Саша', 'Женя'],
]
# ???
# ???
for group in range(len(groups)):
print(f'Группа {group+1}:', end=' ')
print(*groups[group], sep=', ')
77 changes: 72 additions & 5 deletions for_dict_challenges.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,18 @@
{'first_name': 'Маша'},
{'first_name': 'Петя'},
]
# ???


names = {}
for student in students:
name = student['first_name']
if names.get(name) == None:
names[name] = 1

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Тут можно без if обойтись

Suggested change
names[name] = 1
names[name] = names.get(name, 0) + 1

else:
names[name] += 1
for i in names:
print(f'{i}: {names[i]}')

# Задание 2
# Дан список учеников, нужно вывести самое часто повторящееся имя
# Пример вывода:
Expand All @@ -26,7 +35,19 @@
{'first_name': 'Маша'},
{'first_name': 'Оля'},
]
# ???


names = {}
for student in students:
name = student['first_name']
if names.get(name) == None:
names[name] = 1

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Здесь можно использовать решение предыдущей задачи, если обернуть его в функцию.

else:
names[name] += 1
max_number_repetitions = max(names.values())
for i in names:
if names[i] == max_number_repetitions:
print(f'Самое частое имя среди учеников: {i}')


# Задание 3
Expand All @@ -51,7 +72,22 @@
{'first_name': 'Саша'},
],
]
# ???


class_counter = 1
for grade in school_students:
names = {}
for student in grade:
name = student['first_name']

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Аналогично, можно использовать решение первой задачи тут.

if names.get(name) == None:
names[name] = 1
else:
names[name] += 1
max_number_repetitions = max(names.values())
for i in names:
if names[i] == max_number_repetitions:
print(f'Самое частое имя в классе {class_counter}: {i}')
class_counter += 1


# Задание 4
Expand All @@ -72,9 +108,18 @@
'Миша': True,
'Даша': False,
}
# ???


for grade in school:
boys = girls = 0
name_grade = grade['class']
for student in grade['students']:
if is_male[student['first_name']] == True:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

можно использовать решение из третье задачи

boys += 1
else:
girls += 1
print(f'Класс {name_grade}: мальчики {boys}, девочки {girls}')

# Задание 5
# По информации о учениках разных классов нужно найти класс, в котором больше всего девочек и больше всего мальчиков
# Пример вывода:
Expand All @@ -91,5 +136,27 @@
'Олег': True,
'Миша': True,
}
# ???


boy = {}
girl = {}
for grade in school:
boys = girls = 0
name_grade = grade['class']
for student in grade['students']:
if is_male[student['first_name']] == True:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Тоже решение из третьей задачи можно использовать

boys += 1
else:
girls += 1
boy[name_grade] = boys
girl[name_grade] = girls


max_boy = max(boy.values())
max_girl = max(girl.values())
for i in boy:
if boy[i] == max_boy:
print(f'Больше всего мальчиков в классе {i}')
for i in girl:
if girl[i] == max_girl:
print(f'Больше всего девочек в классе {i}')
141 changes: 136 additions & 5 deletions for_dict_challenges_bonus.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,11 @@
Установите библиотеку lorem, чтобы она работала.

Нужно:
1. Вывести айди пользователя, который написал больше всех сообщений.
1. Вывести айди пользователя, который написал больше всех сообщений.
2. Вывести айди пользователя, на сообщения которого больше всего отвечали.
3. Вывести айди пользователей, сообщения которых видело больше всего уникальных пользователей.
4. Определить, когда в чате больше всего сообщений: утром (до 12 часов), днём (12-18 часов) или вечером (после 18 часов).
5. Вывести идентификаторы сообщений, который стали началом для самых длинных тредов (цепочек ответов).
3$. Вывести айди пользователей, сообщения которых видело больше всего уникальных пользователей.
4$. Определить, когда в чате больше всего сообщений: утром (до 12 часов), днём (12-18 часов) или вечером (после 18 часов).
5$. Вывести идентификаторы сообщений, который стали началом для самых длинных тредов (цепочек ответов).

Весь код стоит разбить на логические части с помощью функций.
"""
Expand Down Expand Up @@ -55,5 +55,136 @@ def generate_chat_history():
return messages


def user_messages(messages): # 'id пользователя: список с id всех его сообщений
user_messages = {}
for _ in messages:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

имя "_" используют только если к нему не обращаются. Используй тут message (используй функцию refactor, из меню по правому щелчку мышкой в ide)

sender_id = _['sent_by']
message_id = _['id']

if user_messages.get(sender_id) == None:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is None
Только так сравнивам на None

user_messages[sender_id] = [message_id]
else:
user_messages[sender_id].append(message_id)
return user_messages # 'id пользователя: список с id всех его сообщений
def first_issue(user_messages):
Comment thread
mxlZUBENKO marked this conversation as resolved.
Outdated
wrote_the_most = max(user_messages.values(), key=len)
for _ in user_messages:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

не используем имя _ если обращаемся к этой переменной.

if user_messages[_] == wrote_the_most:
wrote_the_most = _
return wrote_the_most


def number_answers(messages):
number_answers = {}
for _ in messages:
if _['reply_for'] != None and _['reply_for'] != []:
if _['reply_for'] in number_answers:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Попробуй без if сделать, как было в предыдущем упражнении.

number_answers[_['reply_for']] += 1
else:
number_answers[_['reply_for']] = 1
return number_answers
def second_issue(number_answers):
number_responses_per_user = {}
for _ in chat_history:
message_id = _['id']
for i in number_answers:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what is i?

if i == message_id:
if number_responses_per_user.get(_['sent_by']) == None:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Если избавимся от if так же как раньше, код значительно упростится.

number_responses_per_user[_['sent_by']] = number_answers[i]
else:
number_responses_per_user[_['sent_by']] += number_answers[i]
most_cited = max(number_responses_per_user.values())
for _ in number_responses_per_user:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

избавляемся от _

if number_responses_per_user[_] == most_cited:
most_cited = _
return most_cited


def how_many_views(user_messages):
how_many_views = {}
reply = []
for _ in user_messages:
who_saw = []
message_list = user_messages[_]
for i in message_list:
for j in chat_history:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

что такое i, j? переименуй на что-то более понятное плиз

if j['id'] == i:
who_saw += j['seen_by']
how_many_views[_] = len(who_saw)
most_viewed = max(how_many_views.values())
for _ in how_many_views:
if how_many_views[_] == most_viewed:
reply.append(_)
return reply


def sending_time(messages):
sending_time = {
'morning': 0,
'day': 0,
'evening': 0,
'night': 0
}
for _ in messages:
time = int(_['sent_at'].strftime('%H'))
if 6 <= time < 12:
sending_time['morning'] += 1
elif 12 <= time < 18:
sending_time['day'] += 1
elif 18 <= time < 23:
sending_time['evening'] += 1
else:
sending_time['night'] += 1
busiest_time = max(sending_time.values())
for _ in sending_time:
if sending_time[_] == busiest_time:
return _


def is_there_answer(id):
for _ in chat_history:
if _['reply_for'] == id:
return True
return False
def reply_for_from_id(id):
for _ in chat_history:
if _['id'] == id:
return _['reply_for']
def message_threads(messages):
message_threads = {}
reply = []
for _ in messages:
answer = is_there_answer(_['id'])
count = 0
by = _['id']
beginning = _['reply_for']
if answer == False:
while beginning != None and beginning != []:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is not None
любой не пустой словарь будет true, можно сделать

Suggested change
while beginning != None and beginning != []:
while beginning is not None and beginning:

by = beginning
beginning = reply_for_from_id(beginning)
count += 1
if count > 0:
message_threads[by] = count

max_branch_length = max(message_threads.values())

for _ in message_threads:
if message_threads[_] == max_branch_length:
reply.append(_)
return reply


if __name__ == "__main__":
print(generate_chat_history())
chat_history = generate_chat_history()

print(f'ID пользователя, который написал больше всех сообщений: {first_issue(user_messages(chat_history))}', end='\n\n')

print(f'ID пользователя, на которого больше всего отвечали: {second_issue(number_answers(chat_history))}', end='\n\n') #2

print('ID пользователя с наибольшим кол-ом просмотров:', end=' ') #3
print(*how_many_views(user_messages(chat_history)), end='\n\n')

print(f'Больше всего сообщений: {sending_time(chat_history)}', end='\n\n') #4

print('Начало для самых длинных тредов:', end='\n') #5
print(*message_threads(chat_history), sep='\n')
23 changes: 17 additions & 6 deletions string_challenges.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,39 @@
# Вывести последнюю букву в слове
word = 'Архангельск'
# ???
print(word[-1])


# Вывести количество букв "а" в слове
word = 'Архангельск'
# ???
print(len(word))


# Вывести количество гласных букв в слове
word = 'Архангельск'
# ???
vowels = ['а', 'о', 'у', 'ы', 'э', 'е', 'ё', 'и', 'ю', 'я']
count = 0
for letter in word:
if letter.lower() in vowels:
count += 1
print(count)


# Вывести количество слов в предложении
sentence = 'Мы приехали в гости'
# ???
print(len(sentence.split()))


# Вывести первую букву каждого слова на отдельной строке
sentence = 'Мы приехали в гости'
# ???
for word in sentence.split():
print(word[0])


# Вывести усреднённую длину слова в предложении
sentence = 'Мы приехали в гости'
# ???
count_words = len(sentence.split())
count_letters = 0
for word in sentence.split():
count_letters += len(word)
average_length = count_letters / count_words
print(average_length)