-
Notifications
You must be signed in to change notification settings - Fork 260
Вторая домашка basic_exercises #59
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?
Changes from all 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,7 @@ | |
# Необходимо вывести имена всех учеников из списка с новой строки | ||
|
||
names = ['Оля', 'Петя', 'Вася', 'Маша'] | ||
print('\n'.join(names)) | ||
# ??? | ||
|
||
|
||
|
@@ -12,7 +13,8 @@ | |
# Петя: 4 | ||
|
||
names = ['Оля', 'Петя', 'Вася', 'Маша'] | ||
# ??? | ||
for name in names: | ||
print(f"{name}: {len(name)}") | ||
|
||
|
||
# Задание 3 | ||
|
@@ -25,6 +27,12 @@ | |
'Маша': False, | ||
} | ||
names = ['Оля', 'Петя', 'Вася', 'Маша'] | ||
for name in names: | ||
if name in is_male: | ||
# print(name) | ||
gender = "М" if is_male[name] else "Ж" | ||
print(f"{name}: {gender}") | ||
|
||
# ??? | ||
|
||
|
||
|
@@ -40,6 +48,13 @@ | |
['Вася', 'Маша', 'Саша', 'Женя'], | ||
['Оля', 'Петя', 'Гриша'], | ||
] | ||
|
||
count_groups = len(groups) | ||
print(f"Всего {count_groups} группы") | ||
|
||
for group_number,group in enumerate(groups, start = 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 |
||
count_students = len(group) | ||
print(f"Группа {group_number}: {count_students} ученика") | ||
# ??? | ||
|
||
|
||
|
@@ -54,4 +69,8 @@ | |
['Оля', 'Петя', 'Гриша'], | ||
['Вася', 'Маша', 'Саша', 'Женя'], | ||
] | ||
|
||
for group_number,group in enumerate(groups, start = 1): | ||
students = ', '.join(group) | ||
print(f"Группа {group_number}: {students}") | ||
# ??? |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -12,7 +12,18 @@ | |
{'first_name': 'Маша'}, | ||
{'first_name': 'Петя'}, | ||
] | ||
# ??? | ||
|
||
names = dict() | ||
|
||
for student in students: | ||
if student['first_name'] not in names.keys(): | ||
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. Так как мы работаем со словарем лучше сделать проверку Изменения по скорости на таком маленьком объеме мы не заметим, но общий подход запомнить полезно. Для словаря наличие ключа проверяем внутри словаря, а не внутри списка ключей словаря |
||
names[student['first_name']] = 1 | ||
else: | ||
names[student['first_name']] += 1 | ||
|
||
for name, count in names.items(): | ||
print(f"{name}:{count}") | ||
# ??? | ||
|
||
|
||
# Задание 2 | ||
|
@@ -26,6 +37,22 @@ | |
{'first_name': 'Маша'}, | ||
{'first_name': 'Оля'}, | ||
] | ||
names = dict() | ||
|
||
for student in students: | ||
if student['first_name'] not in names.keys(): | ||
names[student['first_name']] = 1 | ||
else: | ||
names[student['first_name']] += 1 | ||
|
||
frequent_name = None | ||
name_count = 0 | ||
|
||
for name, count in names.items(): | ||
if count > name_count: | ||
name_count = count | ||
frequent_name = name | ||
print(f"Самое частое имя: {frequent_name}") | ||
# ??? | ||
|
||
|
||
|
@@ -51,6 +78,16 @@ | |
{'first_name': 'Саша'}, | ||
], | ||
] | ||
|
||
from collections import Counter | ||
|
||
class_num = 1 | ||
for item in school_students: | ||
temp = [name['first_name'] for name in item] | ||
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. Здорово получилось собрать список имен из списка словарей! Горжусь тем, что ты нашла это решение |
||
count = Counter(temp) | ||
print(f'Самое частое имя в классе {class_num}: {count.most_common()[0][0]}') | ||
class_num += 1 | ||
|
||
# ??? | ||
|
||
|
||
|
@@ -72,6 +109,25 @@ | |
'Миша': True, | ||
'Даша': False, | ||
} | ||
|
||
print(school[0], type(school[0])) | ||
|
||
for class_info in school: | ||
class_name = class_info['class'] | ||
students = class_info['students'] | ||
|
||
boys = 0 | ||
girls = 0 | ||
|
||
for student in students: | ||
name = student['first_name'] | ||
if is_male.get(name): | ||
boys +=1 | ||
else: | ||
girls +=1 | ||
|
||
print(f'Класс {class_name}: девочки {girls}, мальчики {boys}') | ||
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. Да, как раз тот вопрос который задавала в тг. Тут получается мы выведем только для последнего класса. Потому что значения переменных пересчитываем в цикле, а выводим уже за пределами цикла |
||
|
||
# ??? | ||
|
||
|
||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,28 +1,51 @@ | ||
# Вывести последнюю букву в слове | ||
word = 'Архангельск' | ||
last = word[-1] | ||
print(last) | ||
# ??? | ||
|
||
|
||
# Вывести количество букв "а" в слове | ||
word = 'Архангельск' | ||
a= word.lower() | ||
print(a.count('а')) | ||
# ??? | ||
|
||
|
||
# Вывести количество гласных букв в слове | ||
word = 'Архангельск' | ||
vowels = "аеёиоуыэюяАЕЁОИУЫЭЮЯ" | ||
count_vow = 0 | ||
for letter in word.lower(): | ||
if letter in vowels: | ||
count_vow += 1 | ||
|
||
print(count_vow) | ||
|
||
# ??? | ||
|
||
|
||
# Вывести количество слов в предложении | ||
sentence = 'Мы приехали в гости' | ||
words = sentence.split() | ||
num_words = len(words) | ||
print(num_words) | ||
# ??? | ||
|
||
|
||
# Вывести первую букву каждого слова на отдельной строке | ||
sentence = 'Мы приехали в гости' | ||
words = sentence.split() | ||
for word in words: | ||
print(word[0]) | ||
# ??? | ||
|
||
|
||
# Вывести усреднённую длину слова в предложении | ||
sentence = 'Мы приехали в гости' | ||
words = sentence.split() | ||
num_words = len(words) | ||
for word in words: | ||
avg_word_len = len(sentence) / num_words | ||
print(f"Средняя длина слова в предложении {avg_word_len}") | ||
# ??? |
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.
Текущий код рабочий, но немного не ту задачу решает.
Нам надо пройтись по списку имен и для каждого из этих имен написать пол ученика
Можно предположить что в is_male сотни имен, а нам надо узнать только про те имена с которыми мы сталкиваемся в группе