-
Notifications
You must be signed in to change notification settings - Fork 259
Alexandra Poturaeva #34
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from 6 commits
eca0cf1
c1ffe74
68476ce
096794d
8d1b34c
008c088
1bd56e8
889660f
c7718d3
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| .idea/ |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -2,8 +2,8 @@ | |
| # Необходимо вывести имена всех учеников из списка с новой строки | ||
|
|
||
| names = ['Оля', 'Петя', 'Вася', 'Маша'] | ||
| # ??? | ||
|
|
||
| for name in names: | ||
| print(name) | ||
|
|
||
| # Задание 2 | ||
| # Необходимо вывести имена всех учеников из списка, рядом с именем показать количество букв в нём | ||
|
|
@@ -12,8 +12,8 @@ | |
| # Петя: 4 | ||
|
|
||
| names = ['Оля', 'Петя', 'Вася', 'Маша'] | ||
| # ??? | ||
|
|
||
| for name in names: | ||
| print(f'{name}: {len(name)}') | ||
|
|
||
| # Задание 3 | ||
| # Необходимо вывести имена всех учеников из списка, рядом с именем вывести пол ученика | ||
|
|
@@ -25,8 +25,12 @@ | |
| 'Маша': False, | ||
| } | ||
| names = ['Оля', 'Петя', 'Вася', 'Маша'] | ||
| # ??? | ||
|
|
||
| for name in names: | ||
| if is_male[name]: | ||
| gender = 'м' | ||
| else: | ||
| gender = 'ж' | ||
| print(f'{name}: {gender}') | ||
|
|
||
| # Задание 4 | ||
| # Даны группу учеников. Нужно вывести количество групп и для каждой группы – количество учеников в ней | ||
|
|
@@ -40,18 +44,21 @@ | |
| ['Вася', 'Маша', 'Саша', 'Женя'], | ||
| ['Оля', 'Петя', 'Гриша'], | ||
| ] | ||
| # ??? | ||
|
|
||
| print(f'Всего {len(groups)} группы.') | ||
| for n in range(1, len(groups) + 1): | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. У enoumerate есть start.
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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): | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. аналогично |
||
| print(f'Группа {n}:', end=' ') | ||
| print(*groups[n - 1], sep=", ") | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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: | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. слишком много раз проходишь по names - students. |
||
| if name == student['first_name']: | ||
| name_count += 1 | ||
| print(f'{name}: {name_count}') | ||
|
|
||
| # Задание 2 | ||
| # Дан список учеников, нужно вывести самое часто повторящееся имя | ||
|
|
@@ -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: | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 | ||
| # Есть список учеников в нескольких классах, нужно вывести самое частое имя в каждом классе. | ||
|
|
@@ -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): | ||
| # формирую частотный словарь имён в классе {имя: частота} | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 | ||
| # Для каждого класса нужно вывести количество девочек и мальчиков в нём. | ||
|
|
@@ -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 | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Нет ни одной причины использовать кирилические ключи в этом словаре. |
||
| if not is_male[student['first_name']]: | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. just else |
||
| gender_composition['ж'] += 1 | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. попробуй оставить в блоках if только выбор ключа, а инкремент вынести наружу. |
||
|
|
||
| print(f'Класс {group_name}: девочки {gender_composition["ж"]}, мальчики {gender_composition["м"]}') | ||
|
|
||
| # Задание 5 | ||
| # По информации о учениках разных классов нужно найти класс, в котором больше всего девочек и больше всего мальчиков | ||
|
|
@@ -91,5 +147,28 @@ | |
| 'Олег': True, | ||
| 'Миша': True, | ||
| } | ||
| # ??? | ||
|
|
||
| school_gender_by_class = dict() | ||
| girls_by_class = dict() | ||
| boys_by_class = dict() | ||
|
|
||
| for group in school: | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Разбить на отдельные функции, переиспользовать код по возможности.
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Смогла добавить только одну функцию, а вторую взяла из предыдущих упражнений по именам (find_items_with_max_values). Норм? There was a problem hiding this comment. Choose a reason for hiding this commentThe 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}') | ||
| 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 | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Слегка спорное решение, но мне нравится. Можно добавлять bool в инкременте, True=1, False=0
Suggested change
|
||||||
| 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) | ||||||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Научу плохому. Можно так сделать:
Работает потому что False это 0, и мы берем элемент строки с нулевым индексом.
Можно даже:
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Офигенно!!) спасибо