Skip to content
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
20 changes: 15 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 @@ -11,8 +12,10 @@
# Оля: 3
# Петя: 4


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


# Задание 3
Expand All @@ -25,7 +28,11 @@
'Маша': False,
}
names = ['Оля', 'Петя', 'Вася', 'Маша']
# ???
for name in names:
if is_male[name]:
print(f'{name} мужской род')
else:
print(f'{name} женский род')

Choose a reason for hiding this comment

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

Можно одной строкой в данном случае:

print(name, 'мужской пол') if is_male[name] else print(name, 'женский пол')



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


# Задание 5
Expand All @@ -54,4 +63,5 @@
['Оля', 'Петя', 'Гриша'],
['Вася', 'Маша', 'Саша', 'Женя'],
]
# ???
for number, name in enumerate(groups, 1):
print(f"В группе {number}:{', '.join(name)}")
46 changes: 41 additions & 5 deletions for_dict_challenges.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
# Вася: 1
# Маша: 2
# Петя: 2
from collections import Counter


students = [
{'first_name': 'Вася'},
Expand All @@ -12,7 +14,14 @@
{'first_name': 'Маша'},
{'first_name': 'Петя'},
]
# ???
def count_name(students):
students_names = Counter([student['first_name'] for student in students])
return students_names


students_names = count_name(students)
for name, repeats in students_names.items():
print(f'{name}: {repeats}')

Choose a reason for hiding this comment

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

Решение без Counter для ознакомления:

count_students = {}
for student in students:
    if student['first_name'] not in count_students.keys():
        count_students[student['first_name']] = 1
    else:
        count_students[student['first_name']] += 1
print(count_students)
for name, count in count_students.items():
    print(f"{name}: {count}")



# Задание 2
Expand All @@ -26,7 +35,17 @@
{'first_name': 'Маша'},
{'first_name': 'Оля'},
]
# ???
def name_max_value(students):
name_max_value = Counter(names).most_common(1)
return name_max_value[0][0]


names = count_name(students)
most_common_name = name_max_value(names)
print(f'Самое частое имя в классе: {most_common_name}')

Choose a reason for hiding this comment

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

Решение без Counter, для ознакомления:

students_list = [student['first_name'] for student in students]
print("Самое частое имя среди учеников:", max(set(students_list), key=students_list.count))





# Задание 3
Expand All @@ -51,7 +70,10 @@
{'first_name': 'Саша'},
],
]
# ???
for i, school_class in enumerate(school_students):
names = count_name(school_class)
most_common_name = name_max_value(names)
print(f'Самое частое имя в классе {i+1}: {most_common_name}')

Choose a reason for hiding this comment

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

Переиспользование уже написанных функций хороший подход.
Публикую решение без использования Counter для ознакомления:

for num, students in enumerate(school_students, start=1):
    students_list = [student['first_name'] for student in students]
    print(f"Самое частое имя в классе {num}: {max(set(students_list), key=students_list.count)}")

Почитай, попробуй разобраться как это работает, если не получится, напиши мне.



# Задание 4
Expand All @@ -63,7 +85,7 @@
school = [
{'class': '2a', 'students': [{'first_name': 'Маша'}, {'first_name': 'Оля'}]},
{'class': '2б', 'students': [{'first_name': 'Олег'}, {'first_name': 'Миша'}]},
{'class': '', 'students': [{'first_name': 'Даша'}, {'first_name': 'Олег'}, {'first_name': 'Маша'}]},
{'class': '', 'students': [{'first_name': 'Даша'}, {'first_name': 'Олег'}, {'first_name': 'Маша'}]},
]
is_male = {
'Олег': True,
Expand All @@ -72,7 +94,21 @@
'Миша': True,
'Даша': False,
}
# ???
def students_gender(students):
gender = {'Male': 0, 'Female': 0}
for student in students:
name = student['first_name']
if is_male[name]:
gender['Male'] += 1
else:
gender['Female'] += 1
return gender


for school_class in school:
gender = students_gender(school_class['students'])
class_name = school_class['class']
print(f"Класс {class_name}: девочки {gender['Female']}, мальчики {gender['Male']}")

Choose a reason for hiding this comment

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

Ещё два способа решения для этой задачи для ознакомления:

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

print("альтернативный способ")  # альтернативный способ
for class_ in school:
    female = [name['first_name'] for name in class_['students'] if not is_male[name['first_name']]]
    male = [name['first_name'] for name in class_['students'] if is_male[name['first_name']]]
    print(f"Класс {class_['class']}: девочки {len(female)}, мальчики {len(male)}")

Choose a reason for hiding this comment

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

Когда разберёшь, выполни 5-е задание



# Задание 5
Expand Down
22 changes: 15 additions & 7 deletions string_challenges.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,36 @@
# Вывести последнюю букву в слове
word = 'Архангельск'
# ???
word = 'Архангельск'
print(word[-1])


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


# Вывести количество гласных букв в слове
word = 'Архангельск'
# ???
glas = set('аиеёоуыэюя')
word_set = set(word.lower())
print(f'{len(word_set.intersection(glas))} гласных слове')


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

sentence = sentence.split(' ')
print(len(sentence))

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



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