Skip to content
Open
Show file tree
Hide file tree
Changes from 9 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
24 changes: 19 additions & 5 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(f'{name}: {len(name)}')


# Задание 3
Expand All @@ -25,7 +27,12 @@
'Маша': False,
}
names = ['Оля', 'Петя', 'Вася', 'Маша']
# ???
for name in names:
if name == 'Петя' or 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.

здесь надо использовать is_male.
А что если мы хотим больше имен добавить в программу. Должно быть одно место в программе ответственное за вычисление пола по имени.

print(f'{name} пол мужской')
else:
print(f'{name} пол женский')



# Задание 4
Expand All @@ -40,7 +47,11 @@
['Вася', 'Маша', 'Саша', 'Женя'],
['Оля', 'Петя', 'Гриша'],
]
# ???
counter_1 = 0
for group in groups:
counter_1 += 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.

Используй enumerate, вместо того что бы считать индекс руками

print(f'Группа {counter_1}: {len(group)} ученика')



# Задание 5
Expand All @@ -54,4 +65,7 @@
['Оля', 'Петя', 'Гриша'],
['Вася', 'Маша', 'Саша', 'Женя'],
]
# ???
count_groups = 0
for group in 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.

enumerate

count_groups += 1
print(f'Группа {count_groups}: {", ".join(group)}')
35 changes: 26 additions & 9 deletions for_dict_challenges.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,12 @@
{'first_name': 'Маша'},
{'first_name': 'Петя'},
]
# ???
from collections import Counter

list_students = [name['first_name'] for name in students]
print(list_students)
for name, number in Counter(list_students).items():
print(f'{name}: {number}')

# Задание 2
# Дан список учеников, нужно вывести самое часто повторящееся имя
Expand All @@ -26,8 +30,11 @@
{'first_name': 'Маша'},
{'first_name': 'Оля'},
]
# ???
from collections import Counter

student_names = (name['first_name'] for name in students)
most_common_name = Counter(student_names).most_common(1)
print(f'Самое частое имя среди учеников: {most_common_name[0][0]}')

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

count = 0

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 безопаснее чем индексы, потому что точно не выйдет за пределы, и не пропустит ничего.

for klass in school_students:
most_common_name = Counter(name['first_name'] for name in school_students[count]).most_common(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.

school_students[count] это klass. Лучше использовать klass, и избавиться от count совсем.

print(f'Самое частое имя в классе {count + 1}: {most_common_name[0][0]}')
count += 1

# Задание 4
# Для каждого класса нужно вывести количество девочек и мальчиков в нём.
Expand All @@ -72,8 +84,10 @@
'Миша': True,
'Даша': False,
}
# ???

for klass in school:
print(
f"Класс {klass['class']}: мальчики {[is_male[men_person['first_name']] for men_person in klass['students']].count(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.

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

f"девочки {[is_male[women_person['first_name']] for women_person in klass['students']].count(False)}")

# Задание 5
# По информации о учениках разных классов нужно найти класс, в котором больше всего девочек и больше всего мальчиков
Expand All @@ -82,7 +96,7 @@
# Больше всего девочек в классе 2a

school = [
{'class': '2a', 'students': [{'first_name': 'Маша'}, {'first_name': 'Оля'}]},
{'class': '2a', 'students': [{'first_name': 'Маша'}, {'first_name': 'Оля'}, {'first_name': 'Оля'}]},
{'class': '3c', 'students': [{'first_name': 'Олег'}, {'first_name': 'Миша'}]},
]
is_male = {
Expand All @@ -91,5 +105,8 @@
'Олег': True,
'Миша': True,
}
# ???

for klass in school:
if [is_male[men_person['first_name']] for men_person in klass['students']].count(True) > [is_male[women_person['first_name']] for women_person in klass['students']].count(False):
print(f"Больше всего мальчиков в классе {klass['class']}")
else:
print(f"Больше всего девочек в классе {klass['class']}")
23 changes: 23 additions & 0 deletions for_dict_challenges_bonus.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,5 +66,28 @@ def generate_chat_history():
return messages


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

Разбей код на несколько максимально независимых функций, вынеси print наружу.

Назови переменные понятными именами: ab, ac, ac, i, j, k - плохие названия для переменных, потому что не показывают что в них лежит и как будут использоваться.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Код не разбит


from collections import Counter
sum_user = Counter(user['sent_by'] for user in messages).most_common(1)
print(f'Больше всего сообщений написал пользователь ID - {sum_user[0][0]}') # ответ на первый вопрос

sum_user = Counter(commentator['reply_for'] for commentator in messages).most_common(2)
print(f'Больше всего ответов - {sum_user[1][0]}')
for id in messages:
if id['id'] == sum_user[1][0]:
print(f"{id['sent_by']} айди пользователя, на сообщения которого больше всего отвечали") # ответ на второй вопрос
new_dict = {}
for message in messages:
if message['sent_by'] not in new_dict:
new_dict[message['sent_by']] = message['seen_by']
else:
new_dict[message['sent_by']] = new_dict[message['sent_by']] + message['seen_by']
print(new_dict)
for k, value in new_dict.items():
print(k, len(set(value))) # решение на 3 задачу


if __name__ == "__main__":
print(generate_chat_history())
zadacha(generate_chat_history())
18 changes: 12 additions & 6 deletions string_challenges.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,34 @@
# Вывести последнюю букву в слове
word = 'Архангельск'
# ???
print(word[-1])



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


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


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


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


# Вывести усреднённую длину слова в предложении
sentence = 'Мы приехали в гости'
# ???
spisok = []

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Suggested change
spisok = []
words = []

for letter in sentence.split():
spisok.append(len(letter))
print(int(sum(spisok)/len(sentence.split())))