-
Notifications
You must be signed in to change notification settings - Fork 0
For challenges #1
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 all commits
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,16 @@ | ||
| { | ||
| // Use IntelliSense to learn about possible attributes. | ||
| // Hover to view descriptions of existing attributes. | ||
| // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 | ||
| "version": "0.2.0", | ||
| "configurations": [ | ||
| { | ||
| "name": "Python: Module", | ||
| "type": "python", | ||
| "request": "launch", | ||
| "module": "for_dict_challenges", | ||
| "justMyCode": true, | ||
| "console": "internalConsole" | ||
| } | ||
| ] | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -2,7 +2,12 @@ | |
| # Необходимо вывести имена всех учеников из списка с новой строки | ||
|
|
||
| names = ['Оля', 'Петя', 'Вася', 'Маша'] | ||
| # ??? | ||
| for name1 in names: | ||
| print(name1) | ||
| print() | ||
| name2 = '\n'.join(names) | ||
| print(name2) | ||
| print() | ||
|
|
||
|
|
||
| # Задание 2 | ||
|
|
@@ -12,8 +17,9 @@ | |
| # Петя: 4 | ||
|
|
||
| names = ['Оля', 'Петя', 'Вася', 'Маша'] | ||
| # ??? | ||
|
|
||
| for name3 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. 💡 можно не менять названия переменным и использовать тот же |
||
| print(f'{name3}: {len(name3)}') | ||
| print() | ||
|
|
||
| # Задание 3 | ||
| # Необходимо вывести имена всех учеников из списка, рядом с именем вывести пол ученика | ||
|
|
@@ -25,7 +31,13 @@ | |
| 'Маша': False, | ||
| } | ||
| names = ['Оля', 'Петя', 'Вася', 'Маша'] | ||
| # ??? | ||
| for name in names: | ||
| if is_male[name] == False: | ||
|
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. 💡 еще можешь использовать тернарный оператор: gender = 'мужской' if is_male[name] else 'женский' |
||
| print(f'{name}, женский') | ||
| else: | ||
| print(f'{name}, мужской') | ||
| print() | ||
|
|
||
|
|
||
|
|
||
| # Задание 4 | ||
|
|
@@ -40,7 +52,9 @@ | |
| ['Вася', 'Маша', 'Саша', 'Женя'], | ||
| ['Оля', 'Петя', 'Гриша'], | ||
| ] | ||
| # ??? | ||
| for group 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. 👍 хорошее решение, есть еще попроще метод (а мы такие любим): for idx, group in enumerate(groups, start=1): |
||
| print(f'Группа {group}: {len(groups[group-1])} ученика.') | ||
| print() | ||
|
|
||
|
|
||
| # Задание 5 | ||
|
|
@@ -54,4 +68,6 @@ | |
| ['Оля', 'Петя', 'Гриша'], | ||
| ['Вася', 'Маша', 'Саша', 'Женя'], | ||
| ] | ||
| # ??? | ||
| for name in range(len(groups)): | ||
| names = ', '.join(groups[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. 👍 |
||
| print(f'Группа{name+1}: {names}') | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -12,8 +12,19 @@ | |
| {'first_name': 'Маша'}, | ||
| {'first_name': 'Петя'}, | ||
| ] | ||
| # ??? | ||
| def diction_name_count(lis): | ||
|
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 вместо lis |
||
| repeat = {} | ||
| for key_name in range(len(lis)): | ||
|
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. 🔴 старайся вместо такой конструкции использовать ее более читаемый вариант: for student in students:
... |
||
| name = lis[key_name]['first_name'] | ||
| if name not in repeat: | ||
|
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. 👍 хорошее решении, чтобы было полегче сделать подобное есть еще такая конструкция как repeat = defaultdict(int)
repeat[name] += 1Если ключ отсутствует, ошибки не будет при обращении к нему а создастся новый элемент со значением int() - то есть 0 |
||
| repeat[name] = 1 | ||
| else: | ||
| repeat[name] += 1 | ||
| return repeat | ||
|
|
||
| for name,count in diction_name_count(students).items(): | ||
| print(f'{name}: {count}') | ||
| print() | ||
|
|
||
| # Задание 2 | ||
| # Дан список учеников, нужно вывести самое часто повторящееся имя | ||
|
|
@@ -26,7 +37,18 @@ | |
| {'first_name': 'Маша'}, | ||
| {'first_name': 'Оля'}, | ||
| ] | ||
| # ??? | ||
| repeat = diction_name_count(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. 👍 классно, что переиспользуешь написанную ранее функцию |
||
| def max_name(diction): | ||
|
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. 💡 Непонятно без контекста, что там в этом diction |
||
| max_count = 0 | ||
| for name,count in diction.items(): | ||
|
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 count > max_count: | ||
| max_count = count | ||
| max_n = name | ||
| return max_n | ||
|
|
||
|
|
||
| print(f'самое частое имя среди учеников: {max_name(repeat)}') | ||
| print() | ||
|
|
||
|
|
||
| # Задание 3 | ||
|
|
@@ -51,8 +73,10 @@ | |
| {'first_name': 'Саша'}, | ||
| ], | ||
| ] | ||
| # ??? | ||
|
|
||
| for classes in range(len(school_students)): | ||
| print(f'Самое частое имя в классе {classes+1}: {max_name(diction_name_count(school_students[classes]))} ') | ||
|
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() | ||
|
|
||
| # Задание 4 | ||
| # Для каждого класса нужно вывести количество девочек и мальчиков в нём. | ||
|
|
@@ -72,7 +96,27 @@ | |
| 'Миша': True, | ||
| 'Даша': False, | ||
| } | ||
| # ??? | ||
|
|
||
| for classy in range(len(school)): | ||
| clas = school[classy] | ||
| nomer_classa = clas['class'] | ||
| boys = [] | ||
| girls = [] | ||
| student = clas['students'] | ||
| for n in student: | ||
| name = n['first_name'] | ||
| if is_male[name] == True: | ||
| boys.append(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. 💡 в целом верно, но тот же коммент, что вместо списка можно было бы просто использовать переменную число мальчиков и такую же для девочек и увеличивать его на 1 |
||
| else: | ||
| girls.append(name) | ||
| count_boys = len(boys) | ||
| count_girls = len(girls) | ||
| print(f'Класс {nomer_classa}: девочки {count_girls}, мальчики {count_boys}') | ||
| print() | ||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
||
| # Задание 5 | ||
|
|
@@ -91,5 +135,36 @@ | |
| 'Олег': True, | ||
| 'Миша': True, | ||
| } | ||
| # ??? | ||
| clas_count_boys = 0 | ||
| clas_count_girls = 0 | ||
| clas_max_boys = '' | ||
| clas_max_girls = '' | ||
|
|
||
| for classy in range(len(school)): | ||
| clas = school[classy] | ||
| nomer_classa = clas['class'] | ||
| boys = [] | ||
| girls = [] | ||
| student = clas['students'] | ||
|
|
||
| for elem in student: | ||
| name = elem['first_name'] | ||
|
|
||
| if is_male[name] == True: | ||
| boys.append(name) | ||
| else: | ||
| girls.append(name) | ||
|
|
||
| count_boys = len(boys) | ||
| count_girls = len(girls) | ||
|
|
||
| if count_boys > clas_count_boys: | ||
|
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. 👍 это задание тут самое сложное и сделано верно |
||
| clas_count_boys = count_boys | ||
| clas_max_boys = nomer_classa | ||
|
|
||
| if count_girls > clas_count_girls: | ||
| clas_count_girls = count_girls | ||
| clas_max_girls = nomer_classa | ||
| print(f'Больше всего мальчиков в классе {clas_max_boys}') | ||
| print(f'Больше всего девочек в классе {clas_max_girls}') | ||
| print() | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,28 +1,46 @@ | ||
| # Вывести последнюю букву в слове | ||
| word = 'Архангельск' | ||
| # ??? | ||
| print(word[-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() | ||
|
|
||
|
|
||
| # Вывести количество букв "а" в слове | ||
| word = 'Архангельск' | ||
| # ??? | ||
| print(len(word)) | ||
|
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. 🔴 нет, это выведет кол-во букв в целом, а нам нужны только буквы 'a' |
||
| print() | ||
|
|
||
|
|
||
| # Вывести количество гласных букв в слове | ||
| word = 'Архангельск' | ||
| # ??? | ||
| vowels ='аоуыэеёиюя' | ||
| vowels_list = [] | ||
| for letter in word.lower(): | ||
|
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. 👍 здорово, что преобразовал в lower() |
||
| if letter in vowels: | ||
|
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. 👍 проверяем наличие буквы в списке гласных |
||
| vowels_list.append(letter) | ||
|
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. 💡 добавляем в свой список результирующий, от которого нам нужна только длина. Довольно затратное решение, ведь формировать массив тоже не просто, он еще и место в памяти занимает прилично, в случае если текст очень большой. можно завести себе переменную для кол-во и увеличивать ее на 1, когда у нас гласная. Это решение и быстрое и место занимает только под одно число. |
||
| print(len(vowels_list)) | ||
| print() | ||
|
|
||
|
|
||
| # Вывести количество слов в предложении | ||
| sentence = 'Мы приехали в гости' | ||
| # ??? | ||
|
|
||
| sentence = sentence.split() | ||
|
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(len(sentence)) | ||
| print() | ||
|
|
||
| # Вывести первую букву каждого слова на отдельной строке | ||
| sentence = 'Мы приехали в гости' | ||
| # ??? | ||
| sentence = sentence.split() | ||
| for word in sentence: | ||
| print(word) | ||
|
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() | ||
|
|
||
|
|
||
| # Вывести усреднённую длину слова в предложении | ||
| sentence = 'Мы приехали в гости' | ||
| # ??? | ||
| sentence = sentence.split() | ||
| sum = 0 | ||
| for word in sentence: | ||
| sum += len(word) | ||
| average = sum//len(sentence) | ||
| print(average) | ||
|
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() | ||
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.
👍