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
26 changes: 19 additions & 7 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,7 +12,8 @@
# Петя: 4

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


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

for name in names:
if is_male[name] is False:
print(f'{name}: Ж')
else:
print(f'{name}: М')

# Задание 4
# Даны группу учеников. Нужно вывести количество групп и для каждой группы – количество учеников в ней
Expand All @@ -40,18 +45,25 @@
['Вася', 'Маша', 'Саша', 'Женя'],
['Оля', 'Петя', 'Гриша'],
]
# ???
print(f'Всего {len(groups)} группы')
for index, name in enumerate(groups, start=1):
print(f'Группа {index}: {len(name)} ученика')



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

groups = [
['Вася', 'Маша'],
['Оля', 'Петя', 'Гриша'],
['Вася', 'Маша', 'Саша', 'Женя'],
]
# ???


for index, names in enumerate(groups, start=1):
names = ', '.join(names)
print(f'Группа {index}: {names}')
85 changes: 79 additions & 6 deletions for_dict_challenges.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,16 @@
{'first_name': 'Маша'},
{'first_name': 'Петя'},
]
# ???
count_student = {}
for student_dict in students:
for key, name in student_dict.items():

Choose a reason for hiding this comment

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

здесь не нужна итерация по словарю, можно же просто
name = student_dict['first_name']
остальное ок

if name in count_student:
count_student[name] += 1
else:
count_student[name] = 1
for name, count in count_student.items():
print(f'{name}: {count}')



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

counter_student_name_max = {}
for students_dict in students:
for key, name in students_dict.items():

Choose a reason for hiding this comment

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

видимо эта ошибка идёт через все задания :)
это кстати именно ошибка, потому что может привести к неожиданному поведению, например если структура student_dict расширится вот таким образом

{'first_name': 'Вася', 'mother_name': 'Галя', 'father_name': 'Вася', 'pet_name': 'Вася'}

if name in counter_student_name_max:
counter_student_name_max[name] += 1
else:
counter_student_name_max[name] = 1
name = sorted(counter_student_name_max.items(), key=lambda item: item[1], reverse=True)

Choose a reason for hiding this comment

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

как вариант, ещё можно использовать max(), он тоже умеет с аргументом key

print(f'Самое частое имя среди учеников: {name[0][0]}')

# Задание 3
# Есть список учеников в нескольких классах, нужно вывести самое частое имя в каждом классе.
Expand All @@ -51,7 +67,24 @@
{'first_name': 'Саша'},
],
]
# ???

def max_count_name(arg, arg2):

Choose a reason for hiding this comment

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

Suggested change
def max_count_name(arg, arg2):
def max_count_name(school_class, number_class):

counter_student_name_max = {}
for students_dict in arg:
for key, name in students_dict.items():
if name in counter_student_name_max:
counter_student_name_max[name] += 1
else:
counter_student_name_max[name] = 1
name_student = sorted(counter_student_name_max.items(), key=lambda item: item[1], reverse=True)

return f'Самое частое имя в классе {arg2}: {name_student[0][0]}'

Choose a reason for hiding this comment

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

Вообще это законно, но я бы предложил возвращать просто name_student[0][0], а весь пост-процессинг делать за пределами функции. Таким образом мы немножко улучшим чистоту кода.



number_class = 0
for school_class in school_students:

Choose a reason for hiding this comment

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

Suggested change
for school_class in school_students:
for number_class, school_class in enumerate(school_students):

number_class += 1
print(max_count_name(school_class, number_class))

Choose a reason for hiding this comment

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

Suggested change
print(max_count_name(school_class, number_class))
most_frequent_name = max_count_name(school_class)
print(f'Самое частое имя в классе {number_class}: {most_frequent_name }')



# Задание 4
Expand All @@ -72,7 +105,26 @@
'Миша': True,
'Даша': False,
}
# ???

def student_counting(val, numb):

Choose a reason for hiding this comment

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

Suggested change
def student_counting(val, numb):
def student_counting(students, class_num):

counter_gender_student = {'men': 0, 'female': 0}
for student_dict in val:
for key, name in student_dict.items():
if is_male[name] is True:
counter_gender_student['men'] += 1
else:
counter_gender_student['female'] += 1
return f'Класс {numb}: девочки {counter_gender_student["female"]}, мальчики {counter_gender_student["men"]}'



for classes in school:
for key, value in classes.items():

Choose a reason for hiding this comment

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

ага, здесь тоже просто по ключу берём из словаря то, что надо, цикл не нужен

if type(value) is type(list()):
value_list = value
else:
number_class = value
print(student_counting(value_list, number_class))


# Задание 5
Expand All @@ -91,5 +143,26 @@
'Олег': True,
'Миша': True,
}
# ???
def student_counting(val, numb):
counter_gender_student = {'men': 0, 'female': 0}
for student_dict in val:
for key, name in student_dict.items():
if is_male[name] is True:
counter_gender_student['men'] += 1
else:
counter_gender_student['female'] += 1
if counter_gender_student['men'] > counter_gender_student['female']:
return f'Больше всего мальчиков в классе {numb}'
else:
return f'Больше всего девочек в классе {numb}'



for classes in school:
for key, value in classes.items():
if type(value) is type(list()):
value_list = value
else:
number_class = value
print(student_counting(value_list, number_class))

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


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


# Вывести количество гласных букв в слове
word = 'Архангельск'
# ???
count = 0
for i in word.lower():
if i in 'ауоыяюёие':
count += 1
print(count)


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


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


# Вывести усреднённую длину слова в предложении
sentence = 'Мы приехали в гости'
# ???
count_word = len(sentence.split())
count_letter = 0
for i in sentence:
if i.isalpha():
count_letter += 1
print(count_letter / count_word)