Skip to content
Open
Show file tree
Hide file tree
Changes from 7 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
30 changes: 22 additions & 8 deletions for_challenges.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@
# Необходимо вывести имена всех учеников из списка с новой строки

names = ['Оля', 'Петя', 'Вася', 'Маша']
# ???

print(*names, sep='\n')

# Задание 2
# Необходимо вывести имена всех учеников из списка, рядом с именем показать количество букв в нём
Expand All @@ -12,8 +11,8 @@
# Петя: 4

names = ['Оля', 'Петя', 'Вася', 'Маша']
# ???

for name in names:
print(f'{name}: {len(name)}')

# Задание 3
# Необходимо вывести имена всех учеников из списка, рядом с именем вывести пол ученика
Expand All @@ -25,8 +24,8 @@
'Маша': False,
}
names = ['Оля', 'Петя', 'Вася', 'Маша']
# ???

for name in names:
print(f'{name}: {"мужской" if is_male[name] else "женский"}')

# Задание 4
# Даны группу учеников. Нужно вывести количество групп и для каждой группы – количество учеников в ней
Expand All @@ -40,8 +39,21 @@
['Вася', 'Маша', 'Саша', 'Женя'],
['Оля', 'Петя', 'Гриша'],
]
# ???

group_token = lambda group_to: (

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Не используй лямбда функции без острой необходимости
К тому же здесь ты даже ей имя даешь. Обычный def будет читаемее

https://towardsdatascience.com/the-python-lambda-function-has-become-a-devil-d0340404abcb

Переделай в обычные функции

(group_to in range(5, 20)) and 'групп' or
(1 in (group_to, (diglast := group_to % 10))) and 'группа' or
({group_to, diglast} & {2, 3, 4}) and 'группы' or 'групп')

student_token = lambda student_to: (
(student_to in range(5, 20)) and 'учеников' or
(1 in (student_to, (diglast := student_to % 10))) and 'ученик' or

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Классно что было интересно заняться этим, но это не подразумевалось в задании.
Доп. вопрос можно ли сделать это решение универсальнее, что бы не можно было использовать эту логику для почти любого существительного : "парта" "шкаф"?

({student_to, diglast} & {2, 3, 4}) and 'ученика' or 'учеников')

print(f'Всего {len(groups)} {group_token(len(groups))}.')

for key, value in dict(enumerate(groups, start=1)).items():
print(f'Группа {key}: {len(value)} {student_token(len(value))}.')

# Задание 5
# Для каждой пары учеников нужно с новой строки перечислить учеников, которые в неё входят
Expand All @@ -54,4 +66,6 @@
['Оля', 'Петя', 'Гриша'],
['Вася', 'Маша', 'Саша', 'Женя'],
]
# ???

for key, value in dict(enumerate(groups, start=1)).items():

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

вот тут не нужен dict().items()
просто for group, group_number in enumerate.
и постарайся запомнить порядок элементов в tuple от enumerate.

print(f'Группа {key}:', ", ".join(value))
43 changes: 36 additions & 7 deletions for_dict_challenges.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import pandas as pd
from collections import Counter

# Задание 1
# Дан список учеников, нужно посчитать количество повторений каждого имени ученика
# Пример вывода:
Expand All @@ -12,8 +15,12 @@
{'first_name': 'Маша'},
{'first_name': 'Петя'},
]
# ???
names = []
for student in students:
names.append(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.

Можно ли переделать с использование list comprehension?


for key, value in Counter(names).items():
print(f'{key}: {value}')

# Задание 2
# Дан список учеников, нужно вывести самое часто повторящееся имя
Expand All @@ -26,8 +33,16 @@
{'first_name': 'Маша'},
{'first_name': 'Оля'},
]
# ???
names = []
for student in students:
names.append(student['first_name'])

print('_' * 75)

# print(pd.DataFrame(names).mode()[0][0])
print(f'Самое частое имя среди учеников: {max(names, key=lambda x: names.count(x))}')

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Посчитай по честному, через числа в словаре


print('_' * 75)

# Задание 3
# Есть список учеников в нескольких классах, нужно вывести самое частое имя в каждом классе.
Expand All @@ -44,16 +59,18 @@
{'first_name': 'Маша'},
{'first_name': 'Маша'},
{'first_name': 'Оля'},
],[ # это – третий класс
], [ # это – третий класс
{'first_name': 'Женя'},
{'first_name': 'Петя'},
{'first_name': 'Женя'},
{'first_name': 'Саша'},
],
]
# ???

for key, value in dict(enumerate(school_students, start=1)).items():

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

dict().items не нужен

print(f'Самое частое имя в классе {key}: '
f'{(lambda x: max([x["first_name"] for x in value], key=lambda y: x.count(y)))(value)}')

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

используй решение предыдущей задачи как функцию


print('_' * 75)
# Задание 4
# Для каждого класса нужно вывести количество девочек и мальчиков в нём.
# Пример вывода:
Expand All @@ -72,8 +89,12 @@
'Миша': True,
'Даша': False,
}
# ???
for group in school:
print(f'Класс {group["class"]}: девочки '
f'{(lambda x: [is_male[x["first_name"]] for x in group["students"]])(group).count(False)}, мальчики '

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Переделай через обычные именованные функции.

f'{(lambda x: [is_male[x["first_name"]] for x in group["students"]])(group).count(True)}')

print('_' * 75)

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

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 school:
girls_boys.append({
'class': group['class'],
'girls': (lambda x: [is_male[x["first_name"]] for x in group["students"]])(group).count(False),
'boys': (lambda x: [is_male[x["first_name"]] for x in group["students"]])(group).count(True)
})

print(f"Больше всего мальчиков в классе: {max(girls_boys, key=lambda x: x['boys'])['class']}")
print(f"Больше всего девочек в классе: {max(girls_boys, key=lambda x: x['girls'])['class']}")
81 changes: 76 additions & 5 deletions for_dict_challenges_bonus.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
import random
import uuid
import datetime
import lorem
from collections import Counter
from itertools import groupby


"""
Пожалуйста, приступайте к этой задаче после того, как вы сделали и получили ревью ко всем остальным задачам
в этом репозитории. Она значительно сложнее.
Expand Down Expand Up @@ -30,11 +38,7 @@

Весь код стоит разбить на логические части с помощью функций.
"""
import random
import uuid
import datetime

import lorem


def generate_chat_history():
Expand Down Expand Up @@ -66,5 +70,72 @@ def generate_chat_history():
return messages


def task1(messages):
users_list = [message['sent_by'] for message in messages]
return f'{max(users_list, key=lambda x: users_list.count(x))} - ' \

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

И не разрывай так строки. Используй (), если надо. Но лучше не разрывать вообще.

f'айди пользователя, который написал больше всех сообщений'

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Этот смысл должен быть передан в названии функции.



def task2(messages):
answers_list = [message['reply_for'] for message in messages if message['reply_for'] is not None]
for message in messages:
if message['id'] == max(answers_list, key=lambda x: answers_list.count(x)):
return f'{message["sent_by"]} - айди пользователя, на сообщения которого больше всего отвечали'

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Перенеси смысл этого пояснения в название функции.



def task3(messages):
id_unique = {}
for message in messages:
if message['sent_by'] not in id_unique:
id_unique[message['sent_by']] = message['seen_by']
else:
id_unique[message['sent_by']] = id_unique[message['sent_by']] + message['seen_by']

for key, value in id_unique.items():
print(f'Сообщения от пользователя под айди {key}, видело {len(set(value))} уникальных пользователей')

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Мы хотим возвращать значение а не печатать



def task4(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.

Название должно отражать что функция возвращает.

times = {
'утром (до 12 часов)': [],

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

ключи должны быть простыми вроде: morning, day, evening

'днём (12-18 часов)': [],
'вечером (после 18 часов)': []
}

for message in messages:
if float(message["sent_at"].strftime('%H.%M')) < 12:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Это очень непрямой способ проверять время.
Судя по всему sent_at это datetime, просто обратись к атрибуту .hour
и вытащи это в отдельную переменную, что бы message["sent_at"] использовался только один раз в этом цикле, а в if проверяй эту переменную.

times['утром (до 12 часов)'].append(float(message["sent_at"].strftime('%H.%M')))
elif 18 > float(message["sent_at"].strftime('%H.%M')) > 12:
times['днём (12-18 часов)'].append(float(message["sent_at"].strftime('%H.%M')))
else:
times['вечером (после 18 часов)'].append(float(message["sent_at"].strftime('%H.%M')))

return f'В чате больше всего сообщений: {max(times, key=lambda x: len(times[x]))}'

def task5(messages):
result = []

for k, g in groupby([message['reply_for'] for message 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.

k, g - плохие имена
Назови так что бы было понятно что там лежит.

length = len(list(g))
result.append((k, length))

lst = [(key, value) for key, value in sorted(result, key=lambda x: x[1], reverse=True) if
key is not None and value > 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?


if len(lst) > 0:
for key, value in lst:
print(f'Сообщение под айди: "{key}" стало началом для самых длинных тредов (цепочек ответов), а именно '

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

return instead of print

f'{value}.')
else:
print('Максимальная длина тредов (цепочек ответов) составляет 1.')

if __name__ == "__main__":
print(generate_chat_history())
print(task1(generate_chat_history()))
print('_' * 75)
print(task2(generate_chat_history()))
print('_' * 75)
task3(generate_chat_history())
print('_' * 75)
print(task4(generate_chat_history()))
print('_' * 75)
task5(generate_chat_history())
19 changes: 8 additions & 11 deletions string_challenges.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,25 @@
# Вывести последнюю букву в слове
word = 'Архангельск'
# ???

print(word[-1])

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

print(word.lower().count('а'))

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

vowels = 'аеиоуэюяыё'

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

👍

print(len([letter for letter in word.lower() if letter in vowels]))

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

print(len(sentence.split()))

# Вывести первую букву каждого слова на отдельной строке
sentence = 'Мы приехали в гости'
# ???

for word in sentence.split():
print(word[0])

# Вывести усреднённую длину слова в предложении
sentence = 'Мы приехали в гости'
# ???
print(int(sum([len(word) for word in sentence.split()]) / len(sentence.split())))