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
16 changes: 16 additions & 0 deletions .vscode/launch.json
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"
}
]
}
28 changes: 22 additions & 6 deletions for_challenges.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,12 @@
# Необходимо вывести имена всех учеников из списка с новой строки

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

Choose a reason for hiding this comment

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

👍

print()
name2 = '\n'.join(names)
print(name2)
print()


# Задание 2
Expand All @@ -12,8 +17,9 @@
# Петя: 4

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

for name3 in names:

Choose a reason for hiding this comment

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

💡 можно не менять названия переменным и использовать тот же name

print(f'{name3}: {len(name3)}')
print()

# Задание 3
# Необходимо вывести имена всех учеников из списка, рядом с именем вывести пол ученика
Expand All @@ -25,7 +31,13 @@
'Маша': False,
}
names = ['Оля', 'Петя', 'Вася', 'Маша']
# ???
for name in names:
if is_male[name] == False:

Choose a reason for hiding this comment

The 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
Expand All @@ -40,7 +52,9 @@
['Вася', 'Маша', 'Саша', 'Женя'],
['Оля', 'Петя', 'Гриша'],
]
# ???
for group in range(1,len(groups)+1):

Choose a reason for hiding this comment

The 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
Expand All @@ -54,4 +68,6 @@
['Оля', 'Петя', 'Гриша'],
['Вася', 'Маша', 'Саша', 'Женя'],
]
# ???
for name in range(len(groups)):
names = ', '.join(groups[name])

Choose a reason for hiding this comment

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

👍

print(f'Группа{name+1}: {names}')
85 changes: 80 additions & 5 deletions for_dict_challenges.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,19 @@
{'first_name': 'Маша'},
{'first_name': 'Петя'},
]
# ???
def diction_name_count(lis):

Choose a reason for hiding this comment

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

💡 чтобы было попроще писать и читать функцию старайся называть переменными с чуть большей инфой о ее содержимом - тут у нас кажется students вместо lis

repeat = {}
for key_name in range(len(lis)):

Choose a reason for hiding this comment

The 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:

Choose a reason for hiding this comment

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

👍 хорошее решении, чтобы было полегче сделать подобное есть еще такая конструкция как defauldict:

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
# Дан список учеников, нужно вывести самое часто повторящееся имя
Expand All @@ -26,7 +37,18 @@
{'first_name': 'Маша'},
{'first_name': 'Оля'},
]
# ???
repeat = diction_name_count(students)

Choose a reason for hiding this comment

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

👍 классно, что переиспользуешь написанную ранее функцию

def max_name(diction):

Choose a reason for hiding this comment

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

💡 Непонятно без контекста, что там в этом diction

max_count = 0
for name,count in diction.items():

Choose a reason for hiding this comment

The 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
Expand All @@ -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]))} ')

Choose a reason for hiding this comment

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

👍 очень здорово, что пользуешься переиспользованием функций
💡 тут лучше бы зашел str.format, а не f-strings

print()

# Задание 4
# Для каждого класса нужно вывести количество девочек и мальчиков в нём.
Expand All @@ -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)

Choose a reason for hiding this comment

The 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
Expand All @@ -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:

Choose a reason for hiding this comment

The 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()
32 changes: 25 additions & 7 deletions string_challenges.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,46 @@
# Вывести последнюю букву в слове
word = 'Архангельск'
# ???
print(word[-1])

Choose a reason for hiding this comment

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

👍

print()


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

Choose a reason for hiding this comment

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

🔴 нет, это выведет кол-во букв в целом, а нам нужны только буквы 'a'

print()


# Вывести количество гласных букв в слове
word = 'Архангельск'
# ???
vowels ='аоуыэеёиюя'
vowels_list = []
for letter in word.lower():

Choose a reason for hiding this comment

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

👍 здорово, что преобразовал в lower()

if letter in vowels:

Choose a reason for hiding this comment

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

👍 проверяем наличие буквы в списке гласных

vowels_list.append(letter)

Choose a reason for hiding this comment

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

💡 добавляем в свой список результирующий, от которого нам нужна только длина. Довольно затратное решение, ведь формировать массив тоже не просто, он еще и место в памяти занимает прилично, в случае если текст очень большой.

можно завести себе переменную для кол-во и увеличивать ее на 1, когда у нас гласная. Это решение и быстрое и место занимает только под одно число.

print(len(vowels_list))
print()


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

sentence = sentence.split()

Choose a reason for hiding this comment

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

👍 разделили предложение на слова
🔴 нехорошо, что сменили и тип и содержимое исходной переменной - у нас было предложение sentence, а ведь стал список слов - тут лучше заходит переменная words, по названию будет понятно, что внутри список слов

print(len(sentence))
print()

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

Choose a reason for hiding this comment

The 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)

Choose a reason for hiding this comment

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

👍

print()