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
3 changes: 3 additions & 0 deletions .idea/.gitignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 10 additions & 0 deletions .idea/basic_exercises.iml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions .idea/inspectionProfiles/profiles_settings.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions .idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions .idea/modules.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions .idea/vcs.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

18 changes: 11 additions & 7 deletions for_challenges.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

Choose a reason for hiding this comment

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

не нужно в репозиторий добавлять служебные файлы

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

print("\n".join(names))

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

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

for name in names:
print(name, ":", len(name))


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

for name in names:
print(f"{name}: {'Мужской' if is_male[name] else 'Женский'}")

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

print(f"{len(groups)} всего групп")
for index, group in enumerate(groups):

Choose a reason for hiding this comment

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

можно в enumerate через start указать номер с которого начинать

print(f"группа {index + 1}: {len(group)}")

# Задание 5
# Для каждой пары учеников нужно с новой строки перечислить учеников, которые в неё входят
Expand All @@ -54,4 +57,5 @@
['Оля', 'Петя', 'Гриша'],
['Вася', 'Маша', 'Саша', 'Женя'],
]
# ???
for index, group in enumerate(groups):
print(f'группа {index + 1}: {", ".join(group)}')
54 changes: 44 additions & 10 deletions for_dict_challenges.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from collections import Counter

# Задание 1
# Дан список учеников, нужно посчитать количество повторений каждого имени ученика
# Пример вывода:
Expand All @@ -12,8 +14,8 @@
{'first_name': 'Маша'},
{'first_name': 'Петя'},
]
# ???

for student in students:

Choose a reason for hiding this comment

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

Тут квадратичная сложность, потому что count будет весб список перебирать каждый раз. Лучше такого избегать

print(f"{student['first_name']} {students.count(student)}")

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

duplicates = [x for i, x in enumerate(students) if i != students.index(x)]

Choose a reason for hiding this comment

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

аналогично, index это как еще один цикл. Итого цикл в цикле

print(duplicates)

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

for j, s_class in enumerate(school_students, start=1):
count_list = []
for dic_student in s_class:
count_list.append(dic_student["first_name"])
count_dic = Counter(count_list)

Choose a reason for hiding this comment

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

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

print(f'Самое частое имя среди учеников {j} класса: {count_dic.most_common(1)[0][0]}')

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

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

# Задание 5
# По информации о учениках разных классов нужно найти класс, в котором больше всего девочек и больше всего мальчиков
Expand All @@ -91,5 +104,26 @@
'Олег': True,
'Миша': True,
}
# ???
count_list = []
list_class = []
for class_s in school:
list_class.append(class_s['students'])
class_g = 0
class_b = 0
for students in list_class:
for names in students:
name = names['first_name']
if is_male[name]:
class_b += 1
else:
class_g += 1
count_list.append({"class": class_s['class'], "boys": class_b, 'girls': class_g})

girls_max = max([g_count['girls'] for g_count in count_list])
boys_max = max([b_count['boys'] for b_count in count_list])

class_girls_max = [g_count['class'] for g_count in count_list if g_count['girls'] == girls_max][0]
class_boys_max = [b_count['class'] for b_count in count_list if b_count['boys'] == boys_max][0]

print(f'Больше всего мальчиков в классе {class_boys_max}')
print(f'Больше всего девочек в классе {class_girls_max}')
29 changes: 17 additions & 12 deletions string_challenges.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,33 @@
# Вывести последнюю букву в слове
word = 'Архангельск'
# ???

print(word[-1])

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

print(word.lower().count("а"))

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

word_one = 'Архангельск'
glasniye = ["а", "я", "у", "ю", "о", "е", "ё", "э", "и", "ы"]

Choose a reason for hiding this comment

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

можно просто написать буквы слитно

i = 0
for letter in word_one.lower():
if letter in glasniye:
i += 1
print(f'{i} "раз"')

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

print(len(sentence.split()))

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

for word in sentence.split():
print(word[0])

# Вывести усреднённую длину слова в предложении
sentence = 'Мы приехали в гости'
# ???
lenght = 0
for word in sentence.split():
lenght += len(word)
else:
print(f'Средняя длина слова в предложении {lenght // len(sentence.split())}')