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 @@
env/
27 changes: 21 additions & 6 deletions for_challenges.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
# Необходимо вывести имена всех учеников из списка с новой строки

names = ['Оля', 'Петя', 'Вася', 'Маша']
# ???
print('\nЗадание 1')
[print(name) for name in names]
Comment thread
Maksimous777 marked this conversation as resolved.


# Задание 2
Expand All @@ -12,7 +13,8 @@
# Петя: 4

names = ['Оля', 'Петя', 'Вася', 'Маша']
# ???
print('\nЗадание 2')
[print(f'{name}: {len(name)}') for name in names]
Comment thread
Maksimous777 marked this conversation as resolved.


# Задание 3
Expand All @@ -24,8 +26,16 @@
'Вася': True,
'Маша': False,
}
names = ['Оля', 'Петя', 'Вася', 'Маша']
# ???
names = ['Оля', 'Петя', 'Вася', 'Маша', 'Максим']
print('\nЗадание 3')
for name in names:
try:
if is_male[name]:
print(f'{name}: Мужской')
else:
print(f'{name}: Женский')
except KeyError:
print(f'Не знаю такого имени: {name}')
Comment on lines +32 to +38

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.

#42 (comment)
Добавил try...except



# Задание 4
Expand All @@ -40,7 +50,10 @@
['Вася', 'Маша', 'Саша', 'Женя'],
['Оля', 'Петя', 'Гриша'],
]
# ???
print('\nЗадание 4')
print(f'Всего {len(groups)} группы')
for index, group in enumerate(groups, start=1):
print(f"Группа {index}: {len(group)} ученика")


# Задание 5
Expand All @@ -54,4 +67,6 @@
['Оля', 'Петя', 'Гриша'],
['Вася', 'Маша', 'Саша', 'Женя'],
]
# ???
print('\nЗадание 5')
[print(f"Группа {index}: {', '.join(group)}")
for index, group in enumerate(groups, start=1)]
84 changes: 70 additions & 14 deletions for_dict_challenges.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from collections import Counter
# Задание 1
# Дан список учеников, нужно посчитать количество повторений каждого имени ученика
# Пример вывода:
Expand All @@ -12,7 +13,19 @@
{'first_name': 'Маша'},
{'first_name': 'Петя'},
]
# ???

print('Задание 1')
# qty_students = (Counter(student['first_name'] for student in students))
# for student in qty_students:
# print(f'{student}: {qty_students[student]}')
# print()
unique_students = []
for student in students:
if student['first_name'] not in unique_students:
unique_students.append(student['first_name'])
for student in unique_students:
print(f"{student}: {students.count({'first_name': student})}")

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.

#42 (comment)
Попробовал без Counter

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

А зачем тебе отдельный unique_students, если ты можешь проверять напрямую в словаре? проверка находится ли ключ в словаре работает ощутимо быстрее, чем проверка есть ли значение в словаре

print()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Fair enough.
работать будет. А можешь любое из этих заданий сделать напрямую через словари, без counter?



# Задание 2
Expand All @@ -26,7 +39,12 @@
{'first_name': 'Маша'},
{'first_name': 'Оля'},
]
# ???

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Хорошо!



# Задание 3
Expand All @@ -44,26 +62,35 @@
{'first_name': 'Маша'},
{'first_name': 'Маша'},
{'first_name': 'Оля'},
],[ # это – третий класс
], [ # это – третий класс
{'first_name': 'Женя'},
{'first_name': 'Петя'},
{'first_name': 'Женя'},
{'first_name': 'Саша'},
],
]
# ???

print('Задание 3')
for grade in range(len(school_students)):
max_students = Counter(student['first_name']
for student in school_students[grade]).most_common(1)
print(
f'Самое частое имя в классе {grade + 1}: {max_students[0][0]}')
print()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

👍


# Задание 4
# Для каждого класса нужно вывести количество девочек и мальчиков в нём.
# Пример вывода:
# Класс 2a: девочки 2, мальчики 0
# Класс 2a: девочки 2, мальчики 0
# Класс 2б: девочки 0, мальчики 2

school = [
{'class': '2a', 'students': [{'first_name': 'Маша'}, {'first_name': 'Оля'}]},
{'class': '2б', 'students': [{'first_name': 'Олег'}, {'first_name': 'Миша'}]},
{'class': '2б', 'students': [{'first_name': 'Даша'}, {'first_name': 'Олег'}, {'first_name': 'Маша'}]},
{'class': '2a', 'students': [
{'first_name': 'Маша'}, {'first_name': 'Оля'}]},
{'class': '2б', 'students': [
{'first_name': 'Олег'}, {'first_name': 'Миша'}]},
{'class': '2б', 'students': [{'first_name': 'Даша'}, {
'first_name': 'Олег'}, {'first_name': 'Маша'}]},
]
is_male = {
'Олег': True,
Expand All @@ -72,24 +99,53 @@
'Миша': True,
'Даша': False,
}
# ???


print('Задание 4')
for grade in school:
male = 0
female = 0
for student in grade['students']:
if is_male[student['first_name']]:
male += 1
else:
female += 1
print(
f"Класс {grade['class']}: девочки {female}, мальчики {male}")
print()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

👍

# Задание 5
# По информации о учениках разных классов нужно найти класс, в котором больше всего девочек и больше всего мальчиков
# Пример вывода:
# Больше всего мальчиков в классе 3c
# Больше всего девочек в классе 2a

school = [
{'class': '2a', 'students': [{'first_name': 'Маша'}, {'first_name': 'Оля'}]},
{'class': '3c', 'students': [{'first_name': 'Олег'}, {'first_name': 'Миша'}]},
{'class': '2a', 'students': [
{'first_name': 'Маша'}, {'first_name': 'Оля'}]},
{'class': '3c', 'students': [
{'first_name': 'Олег'}, {'first_name': 'Миша'}]},
]
is_male = {
'Маша': False,
'Оля': False,
'Олег': True,
'Миша': True,
}
# ???
print('Задание 5')
male = []
female = []
for grade in range(len(school)):
male.append(0)
female.append(0)
for student in school[grade]['students']:
if is_male[student['first_name']]:
male[grade] += 1
else:
female[grade] += 1

most_male_index = male.index(max(male))
most_male_class = school[most_male_index]['class']
most_female_index = female.index(max(female))
most_female_class = school[most_female_index]['class']
print(
f"Больше всего мальчиков в классе {most_male_class}")
print(
f"Больше всего девочек в классе {most_female_class}")
29 changes: 23 additions & 6 deletions string_challenges.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,45 @@
# Вывести последнюю букву в слове
word = 'Архангельск'
# ???
print(f"В слове {word} последняя буква: {word[-1:]}\n")


# Вывести количество букв "а" в слове
word = 'Архангельск'
# ???
cymbol_to_count = 'а'
cymbols_in_word = word.lower().count(cymbol_to_count)
print(
f'Количество букв "{cymbol_to_count}" в слове {word}: {cymbols_in_word}\n')


# Вывести количество гласных букв в слове
word = 'Архангельск'
# ???
vowels = 'аеёиоуыэюя'
vowels_sum = 0
for symbol in word:
if symbol.lower() in vowels:
vowels_sum += 1
print(
f'Количество гласных букв в слове {word}: {vowels_sum}\n')


# Вывести количество слов в предложении
sentence = 'Мы приехали в гости'
# ???
words_quantity = sentence.count(' ') + 1
print(
f"Количество слов в тексте: '{sentence}' - {words_quantity}\n")


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


# Вывести усреднённую длину слова в предложении
sentence = 'Мы приехали в гости'
# ???
words_num = len(sentence.split())
symbols_sum = sum([len(word) for word in sentence.split()])
avg_cymbols_in_sentence = symbols_sum // words_num
print(
f"Средняя длина слова в предложении: '{sentence}' - {avg_cymbols_in_sentence}")