Skip to content

Conversation

@dimamushalapugin
Copy link

No description provided.

Copy link

@krepysh krepysh left a comment

Choose a reason for hiding this comment

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

Обрати внимание на то как ты называешь переменные и функции. Имена должны быть понятными и объяснять что в переменной лежит или что функция делает.
По списком лучше итерироваться сразу по объектем, а не по индексу по длине.
Не используй i,j,k, etc как имена переменных в циклах, кроме как для индексов.

names = ['Оля', 'Петя', 'Вася', 'Маша']
# ???
for i in is_male:
if is_male[i] == True:
Copy link

Choose a reason for hiding this comment

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

c True никогда не нужно сравнивать. просто if something:

}
names = ['Оля', 'Петя', 'Вася', 'Маша']
# ???
for i in is_male:
Copy link

Choose a reason for hiding this comment

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

Позапускай код, он кажется не делает то что нужно. Я бы ожидал здесь увидеть другой for.

# ???
a = 0
print(f'Всего {len(groups)} группы.')
for i in groups:
Copy link

Choose a reason for hiding this comment

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

for group in groups:

# ???
a = 0
print(f'Всего {len(groups)} группы.')
for i in groups:
Copy link

Choose a reason for hiding this comment

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

Suggested change
for i in groups:
for group in groups:

a = 0
print(f'Всего {len(groups)} группы.')
for i in groups:
a += 1
Copy link

Choose a reason for hiding this comment

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

В питоне при итерировании списка принято использовать сразу элементы списка, а не индексы. Не используй индексы без острой необходимости.

return messages


def zadacha(messages):
Copy link

Choose a reason for hiding this comment

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

Разбей код на несколько максимально независимых функций, вынеси print наружу.

Назови переменные понятными именами: ab, ac, ac, i, j, k - плохие названия для переменных, потому что не показывают что в них лежит и как будут использоваться.

Copy link

Choose a reason for hiding this comment

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

Код не разбит

# Вывести количество букв "а" в слове
word = 'Архангельск'
# ???
print(len([j for j in ''.join(word) if j.lower() == 'а']))
Copy link

Choose a reason for hiding this comment

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

переусложнено - join тут вообще не нужен.
используй методы lower и count у str

# Вывести количество гласных букв в слове
word = 'Архангельск'
# ???
print(len([j for j in ''.join(word) if j.lower() not in ['а', 'е', 'у', 'ы', 'о', 'э', 'я', 'и', 'ю']]))
Copy link

Choose a reason for hiding this comment

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

вынеси список в перменную vowels
join не нужен

sentence = 'Мы приехали в гости'
# ???
for i in ''.join(sentence).split():
print(i[0])
Copy link

Choose a reason for hiding this comment

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

join не нужен
вместо i подошло бы имя переменной word

# Вывести усреднённую длину слова в предложении
sentence = 'Мы приехали в гости'
# ???
q = []
Copy link

Choose a reason for hiding this comment

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

q?

Copy link

@krepysh krepysh left a comment

Choose a reason for hiding this comment

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

Much better!
Есть только замечание про поразбивать функции на функции попроще. Можешь потренироваться использовать в пайчарм рефакторинг:
Выдели курсором код который хочешь вынести в отдельную функцию, нажми правой кнопкой мыши - выбери Refactoring, используй Extract method функцию, Должна хорошо тут сработать.

names = ['Оля', 'Петя', 'Вася', 'Маша']
# ???
for name in names:
if name == 'Петя' or name == 'Вася':
Copy link

Choose a reason for hiding this comment

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

здесь надо использовать is_male.
А что если мы хотим больше имен добавить в программу. Должно быть одно место в программе ответственное за вычисление пола по имени.

# ???
counter_1 = 0
for group in groups:
counter_1 += 1
Copy link

Choose a reason for hiding this comment

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

Используй enumerate, вместо того что бы считать индекс руками

]
# ???
count_groups = 0
for group in groups:
Copy link

Choose a reason for hiding this comment

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

enumerate


for klass in school:
print(
f"Класс {klass['class']}: мальчики {[is_male[men_person['first_name']] for men_person in klass['students']].count(True)} "
Copy link

Choose a reason for hiding this comment

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

Вынеси функцию расчета числа мальчиков и девочек в отдельную функцию, так что бы можно было ее переиспользовать в следующих задачах.

return messages


def zadacha(messages):
Copy link

Choose a reason for hiding this comment

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

Код не разбит

# Вывести усреднённую длину слова в предложении
sentence = 'Мы приехали в гости'
# ???
spisok = []
Copy link

Choose a reason for hiding this comment

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

Suggested change
spisok = []
words = []

Copy link

@krepysh krepysh left a comment

Choose a reason for hiding this comment

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

Почти отлично.
Поправь эту штуку, что бы у тебя klass передавался аргументом явно. Очень плохая практика лазить неявно к чему-то вне твоей локальной области видимости.

]
# ???

for group in enumerate(groups, start=1):
Copy link

Choose a reason for hiding this comment

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

распакуй же сразу:

Suggested change
for group in enumerate(groups, start=1):
for group_number, group in enumerate(groups, start=1):

И в остальных местах тоже. Эта техника называется list unpacking, кода ты паре переменных присваиваешь значение листа.


count = 0
for klass in school_students:
most_common_name = Counter(name['first_name'] for name in school_students[count]).most_common(1)
Copy link

Choose a reason for hiding this comment

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

school_students[count] это klass. Лучше использовать klass, и избавиться от count совсем.

return [is_male[men_person['first_name']] for men_person in klass['students']].count(True)


def womens_count():
Copy link

Choose a reason for hiding this comment

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

klass должен передаваться явно как аргумент (можно еще и назвать его по другому, что бы точно не было сомнений.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants