Skip to content

Вторая домашка 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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
21 changes: 20 additions & 1 deletion for_challenges.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
# Необходимо вывести имена всех учеников из списка с новой строки

names = ['Оля', 'Петя', 'Вася', 'Маша']
print('\n'.join(names))
# ???


Expand All @@ -12,7 +13,8 @@
# Петя: 4

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


# Задание 3
Expand All @@ -25,6 +27,12 @@
'Маша': False,
}
names = ['Оля', 'Петя', 'Вася', 'Маша']

Choose a reason for hiding this comment

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

Текущий код рабочий, но немного не ту задачу решает.
Нам надо пройтись по списку имен и для каждого из этих имен написать пол ученика
Можно предположить что в is_male сотни имен, а нам надо узнать только про те имена с которыми мы сталкиваемся в группе

for name in names:
if name in is_male:
# print(name)
gender = "М" if is_male[name] else "Ж"
print(f"{name}: {gender}")

# ???


Expand All @@ -40,6 +48,13 @@
['Вася', 'Маша', 'Саша', 'Женя'],
['Оля', 'Петя', 'Гриша'],
]

count_groups = len(groups)
print(f"Всего {count_groups} группы")

for group_number,group in enumerate(groups, start = 1):

Choose a reason for hiding this comment

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

отлично! Отдельно хвалю за выбор имен переменных и использование enumerate

count_students = len(group)
print(f"Группа {group_number}: {count_students} ученика")
# ???


Expand All @@ -54,4 +69,8 @@
['Оля', 'Петя', 'Гриша'],
['Вася', 'Маша', 'Саша', 'Женя'],
]

for group_number,group in enumerate(groups, start = 1):
students = ', '.join(group)
print(f"Группа {group_number}: {students}")
# ???
58 changes: 57 additions & 1 deletion for_dict_challenges.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,18 @@
{'first_name': 'Маша'},
{'first_name': 'Петя'},
]
# ???

names = dict()

for student in students:
if student['first_name'] not in names.keys():

Choose a reason for hiding this comment

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

Так как мы работаем со словарем лучше сделать проверку
if student['first_name'] not in names:
Она будет работать быстрее чем
if student['first_name'] not in names.keys():

Изменения по скорости на таком маленьком объеме мы не заметим, но общий подход запомнить полезно. Для словаря наличие ключа проверяем внутри словаря, а не внутри списка ключей словаря

names[student['first_name']] = 1
else:
names[student['first_name']] += 1

for name, count in names.items():
print(f"{name}:{count}")
# ???


# Задание 2
Expand All @@ -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}")
# ???


Expand All @@ -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]

Choose a reason for hiding this comment

The 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

# ???


Expand All @@ -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}')

Choose a reason for hiding this comment

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

Да, как раз тот вопрос который задавала в тг. Тут получается мы выведем только для последнего класса. Потому что значения переменных пересчитываем в цикле, а выводим уже за пределами цикла


# ???


Expand Down
23 changes: 23 additions & 0 deletions string_challenges.py
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}")
# ???
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy