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

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

for name in names:
print(name)

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

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

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

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

for name in names:
if is_male[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.

Научу плохому. Можно так сделать:

Suggested change
if is_male[name]:
gender = "жм"[is_male[name]]

Работает потому что False это 0, и мы берем элемент строки с нулевым индексом.
Можно даже:

Suggested change
if is_male[name]:
gender = ("woman", "man")[is_male[name]]

Copy link
Copy Markdown
Author

@AlexandraPoturaeva AlexandraPoturaeva May 23, 2023

Choose a reason for hiding this comment

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

Офигенно!!) спасибо

gender = 'м'
else:
gender = 'ж'
print(f'{name}: {gender}')

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

print(f'Всего {len(groups)} группы.')
for n in range(1, len(groups) + 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.

У enoumerate есть start.
Всегда когда тебе нужен и объект и номер используй enoumerate

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

да, точно, забыла про это, спасибо!

print(f'Группа {n}: {len(groups[n - 1])} ученика.')

# Задание 5
# Для каждой пары учеников нужно с новой строки перечислить учеников, которые в неё входят
# Пример вывода:
# Группа 1: Вася, Маша
# Группа 2: Оля, Петя, Гриша
# Группа 2: Оля, Петя, Гри

groups = [
['Вася', 'Маша'],
['Оля', 'Петя', 'Гриша'],
['Вася', 'Маша', 'Саша', 'Женя'],
]
# ???
for n in range(1, len(groups) + 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.

аналогично

print(f'Группа {n}:', end=' ')
print(*groups[n - 1], sep=", ")
91 changes: 85 additions & 6 deletions for_dict_challenges.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,14 @@
{'first_name': 'Маша'},
{'first_name': 'Петя'},
]
# ???
names = set([x['first_name'] for x in students])

for name in names:
name_count = 0
for student in students:
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

слишком много раз проходишь по names - students.
Можно всего раз пройти по students
Используй словарь из str -> int, каждый элемент это то сколько раз встречалось имя.

if name == student['first_name']:
name_count += 1
print(f'{name}: {name_count}')

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

names = set([x['first_name'] for x in students])
names_freq_dict = dict()

for name in names:
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

name_count = 0
for student in students:
if name == student['first_name']:
name_count += 1
names_freq_dict[name] = name_count

max_freq = max(names_freq_dict.values())
max_freq_names_positions = [index for index, value in enumerate(list(names_freq_dict.values()))
if value == max_freq]
max_freq_names = [list(names_freq_dict.keys())[pos] for pos in max_freq_names_positions]
max_freq_names_str = ', '.join(max_freq_names)

print(f'Чаще всего встречаются имена: {max_freq_names_str} ({max_freq} раз(a))')

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

print('Самые частые имена по классам / число повторений:')
for num, group in enumerate(school_students):
# формирую частотный словарь имён в классе {имя: частота}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

каждое решение - отдельная функция

students = [student['first_name'] for student in group]
student_unique_names = set(students)
student_names_freq_dict = {name: students.count(name) for name in student_unique_names}

# считаю, какое имя чаще всего встречается
max_freq = max(student_names_freq_dict.values()) # нахожу максимальное значение частоты

# создаю список позиций (индексов) элементов с максимальной частотой в частотном словаре имён
max_freq_names_positions = [
index
for index, value in enumerate(list(student_names_freq_dict.values()))
if value == max_freq
]

# формирую список самых частых имён
max_freq_names = [list(student_names_freq_dict.keys())[pos] for pos in max_freq_names_positions]
max_freq_names_str = ', '.join(max_freq_names)

print(f'\t№{num + 1}: {max_freq_names_str} / {max_freq}')

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

for group in school:
group_name = group['class']
gender_composition = {
'ж': 0,
'м': 0
}
for student in group['students']:
if is_male[student['first_name']]:
gender_composition['м'] += 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 not is_male[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.

just else

gender_composition['ж'] += 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 только выбор ключа, а инкремент вынести наружу.


print(f'Класс {group_name}: девочки {gender_composition["ж"]}, мальчики {gender_composition["м"]}')

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

school_gender_by_class = dict()
girls_by_class = dict()
boys_by_class = dict()

for group in school:
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Author

@AlexandraPoturaeva AlexandraPoturaeva May 23, 2023

Choose a reason for hiding this comment

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

Смогла добавить только одну функцию, а вторую взяла из предыдущих упражнений по именам (find_items_with_max_values). Норм?

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Отлично!

class_name = group['class']
boys = 0
girls = 0
for student in group['students']:
if is_male[student['first_name']]:
boys += 1
if not is_male[student['first_name']]:
girls += 1
girls_by_class[class_name] = girls
boys_by_class[class_name] = boys

school_gender_by_class['девочек'] = girls_by_class
school_gender_by_class['мальчиков'] = boys_by_class

for gender, breakdown in school_gender_by_class.items():
max_gender_cnt = max(breakdown.values())
classes_with_max_gender_cnt = [key for key, value in breakdown.items() if value == max_gender_cnt]
result = ', '.join(classes_with_max_gender_cnt)
print(f'Больше всего {gender} в классах: {result}')
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 = 'Архангельск'
# ???
word = word.lower()
print(word.count('а'))


# Вывести количество гласных букв в слове
rus_vowels = 'аоуэыяёеюи'
word = 'Архангельск'
# ???
word_vowels_cnt = 0
for letter in word.lower():
if letter in rus_vowels:
word_vowels_cnt += 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.

Слегка спорное решение, но мне нравится. Можно добавлять bool в инкременте, True=1, False=0
На твое усмотрение

Suggested change
word_vowels_cnt += 1
word_vowels_cnt += letter in rus_vowels

print(f'Количество гласных букв в слове "{word}": {word_vowels_cnt}')



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


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


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