Skip to content

Problem solution #30

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

Open
wants to merge 25 commits into
base: main
Choose a base branch
from

Conversation

Chernykh-a-s
Copy link

Исправил замечания по company.py

Copy link
Contributor

@Melevir Melevir left a comment

Choose a reason for hiding this comment

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

У тебя в коммит попала служеблная папка .idea – удали её и добавь в гитигнор. В ней настройки твоей IDE, которым не место в репо.

company.py Outdated
for department in departments: # task 4
for employer in department['employers']:
if employer['salary_rub'] > 100000:
print(f'Заработная плата {employer["first_name"]} превышает 100К')
Copy link
Contributor

Choose a reason for hiding this comment

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

Тут и на предыдущей строке дублируешь цифру 100000, это не считается хорошей практикой.

Вынеси её в отдельную переменную и используй в двух местах, тогда будет хорошо.

Copy link
Contributor

Choose a reason for hiding this comment

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

Тут в строке ты всё ещё дублируешь константу 100000.

company.py Outdated
for department in departments: # task 5
for employer in department['employers']:
if employer['salary_rub'] < 80000:
print(f'Заработная плата {employer["position"]} ниже 80К')
Copy link
Contributor

Choose a reason for hiding this comment

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

Аналогично с 80000

Copy link
Contributor

Choose a reason for hiding this comment

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

Аналогично.

company.py Outdated
print(f'Отдел {department["title"]}: максимальная зарплата {max_salary}')
print(f'Отдел {department["title"]}: cредняя зарплата {int(avg_salary)}')

avg_salary = 0 # task 9
Copy link
Contributor

Choose a reason for hiding this comment

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

Эту строку можно удалить.


for group, names in enumerate(groups, start=1):
print(f'Группа {group}: {", ".join(groups[names])}')
Copy link
Contributor

Choose a reason for hiding this comment

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

Чтобы гитхаб не ставил вот этих красных кружочкой, ставь в конце файла одну пустую строку. Так тоже принято.

max_names = []
max_count = 0

for name, count_of_name in names_counter.items():
Copy link
Contributor

Choose a reason for hiding this comment

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

Почитай про функцию max и её аргументы, у тебя может получиться заменить весь этот цикл правильным её использованием.

company.py Outdated
for department in departments: # task 4
for employer in department['employers']:
if employer['salary_rub'] > 100000:
print(f'Заработная плата {employer["first_name"]} превышает 100К')
Copy link
Contributor

Choose a reason for hiding this comment

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

Тут в строке ты всё ещё дублируешь константу 100000.

company.py Outdated
for department in departments: # task 5
for employer in department['employers']:
if employer['salary_rub'] < 80000:
print(f'Заработная плата {employer["position"]} ниже 80К')
Copy link
Contributor

Choose a reason for hiding this comment

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

Аналогично.

company.py Outdated
for department in departments:
for employer in department['employers']:
if employer['salary_rub'] > 90000:
if employer['salary_rub'] > task_salary:
salary_cap.append(employer["position"])
print(f'{", ".join(salary_cap)} получают больше 90К')
Copy link
Contributor

Choose a reason for hiding this comment

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

Тут тоже.

print(f'{boys_predominate}{students["class"]}') if male_gender > female_gender else print(f'{girls_predominate}{students["class"]}')
Copy link
Contributor

Choose a reason for hiding this comment

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

Тут у тебя по сути выбирается только boys_predominate или girls_predominate, остальное одинаковое.

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

company.py Outdated
@@ -53,13 +53,13 @@
for department in departments:
for employer in department['employers']:
if employer['salary_rub'] > task_salary:
print(f'Заработная плата {employer["first_name"]} превышает 100К')
print(f'Заработная плата {employer["first_name"]} превышает {task_salary}К')
Copy link
Contributor

Choose a reason for hiding this comment

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

Теперь K из принта надо убрать, а то получается, что там теперь 100000к. Аналогично принтами ниже.

@@ -127,6 +126,11 @@ def max_name(students):
'Миша': True,
}

max_male_class = ''
max_female_class = ''
Copy link
Contributor

Choose a reason for hiding this comment

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

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

boys_predominate = 'Больше всего мальчиков в классе '
girls_predominate = 'Больше всего девочек в классе '
print(f'{boys_predominate}{students["class"]}') if male_gender > female_gender else print(f'{girls_predominate}{students["class"]}')
if male_gender > female_gender:
Copy link
Contributor

Choose a reason for hiding this comment

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

Кажется, у этого ифа лишний отступ

max_female_class = ''
max_male_gender = 0
max_female_gender = 0

for students in school:
Copy link
Contributor

Choose a reason for hiding this comment

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

Тут не students, тут класс типа.

print(f'{boys_predominate}{students["class"]}') if male_gender > female_gender else print(f'{girls_predominate}{students["class"]}')
if male_gender > female_gender:
max_male_gender = male_gender
max_male_class = str(students["class"])
Copy link
Contributor

Choose a reason for hiding this comment

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

students["class"] и так строка, не надо её ещё раз превращать в строку.

department_salary = []
for employer in department['employers']:
department_salary.append(employer['salary_rub'])
if department["title"] == 'IT department':
Copy link
Contributor

Choose a reason for hiding this comment

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

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

tax_departments["department"] = department["title"]
tax_departments["tax"] = tax_sum
else:
tax_sum = sum(department_salary) * (taxes[0]["value_percents"] / 100)
Copy link
Contributor

Choose a reason for hiding this comment

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

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

# task 14. Вывести список всех сотрудников с указанием зарплаты "на руки" и зарплаты с учётом налогов.

tax_departments = {}
for department in departments:
Copy link
Contributor

Choose a reason for hiding this comment

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

К этому заданию применимы оба коммента выше.

tax_departments["department"] = department["title"]
tax_departments["tax"] = tax_sum
print(f'По {tax_departments["department"]} суммарный налог на сотрудников равен {tax_departments["tax"]}')
def departments_salary(departments):
Copy link
Contributor

Choose a reason for hiding this comment

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

По названию функции непонятно, что функция делает тк в названии нет глагола.

Copy link
Contributor

Choose a reason for hiding this comment

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

Это верно для всех функций ниже.


for department in departments_lst:
dep_tax = []
if True:
Copy link
Contributor

Choose a reason for hiding this comment

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

Этот иф всегда будет выполняться, а его ветка else – никогда. Удали ненужное.

taxes_for_department["All"] = taxes_for_department.pop(None)

department_taxes = {}
departments_lst = [department["title"] for department in departments]
Copy link
Contributor

Choose a reason for hiding this comment

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

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

for tax in taxes:
taxes_for_department[tax["department"]] = tax["value_percents"] / 100

taxes_for_department["All"] = taxes_for_department.pop(None)
Copy link
Contributor

Choose a reason for hiding this comment

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

Такой подход не подойдёт тк если у нас появится департмент с названием All, то всё сломается. Вытащи "общий" налог в отдельную переменную просто.

if True:
dep_tax.append(taxes_for_department.get(department))
dep_tax.append(taxes_for_department.get("All"))
if None in dep_tax:
Copy link
Contributor

Choose a reason for hiding this comment

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

Вместо того чтобы добавлять нан, а потом его удалять, можно просто не добавлять нан :)


if __name__ == "__main__":
dep_sal = departments_salary(departments)
dep_tax = departments_tax_rate(taxes, departments)
Copy link
Contributor

Choose a reason for hiding this comment

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

Опять сокращения, давай всё полностью называть.

departments_salary = {}
for department in departments:
salary_lst = []
salary = []
Copy link
Contributor

Choose a reason for hiding this comment

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

По названию я ожидаю, что в этой переменной живёт зарплата, а это не так: в ней список зарплат :)

taxes_for_department[tax["department"]] = tax["value_percents"] / 100

taxes_for_department["All"] = taxes_for_department.pop(None)
if tax["department"] != None:
Copy link
Contributor

Choose a reason for hiding this comment

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

С None принято сравнивать не с помощью ==, а с помощью is

tax_of_departments = get_departments_tax_rate(taxes, departments)
for department in departments:
for employer in department['employers']:
employer_tax = employer['salary_rub'] * (tax_of_departments.get(department["title"])) / 100
Copy link
Contributor

Choose a reason for hiding this comment

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

Тут ты используешь get, но если в словаре ключа не будет, всё сломается. Используй квадратные скобки.

@@ -55,5 +56,29 @@ def generate_chat_history():
return messages


# 1. Вывести айди пользователя, который написал больше всех сообщений.
def is_user_with_max_messages(messages):
id_list = []
Copy link
Contributor

Choose a reason for hiding this comment

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

Непонятное название.

uniq_id_list = list(set(id_list))

count_of_message_id = {}
for id_uniq in uniq_id_list:
Copy link
Contributor

Choose a reason for hiding this comment

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

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

А ещё ты выбрал не самую оптимальную логику с двумя вложенными циклами. Попробуй обойтись без двух вложенных циклов, для этого потребуется переделать сам алгоритм работы, но должно получиться проще.

counter += 1
count_of_message_id[id_uniq] = counter

count_of_message_id_sorted = dict(sorted(count_of_message_id.items(), key=lambda item: item[1], reverse=True))
Copy link
Contributor

Choose a reason for hiding this comment

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

Опять результат сортеда превращаешь в словарь и опять используешь сортед, когда надо использовать max

sorted_departments_total_taxes = dict(sorted(departments_total_taxes.items(), key=lambda item: item[1],
reverse=True))
departments_names_by_total_taxes = [department_name for department_name in sorted_departments_total_taxes]
departments_names_by_total_taxes = list(sorted(
Copy link
Contributor

Choose a reason for hiding this comment

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

В list не надо превращать.


return sorted_list_of_employers_tax[0]["first_name"], sorted_list_of_employers_tax[0]["last_name"]
return employer_with_max_tax.get("first_name"), employer_with_max_tax.get("last_name")
Copy link
Contributor

Choose a reason for hiding this comment

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

Тут get лишние: ты ж знаешь, что в employer_with_max_tax точно есть эти ключи, так что используй квадратные скобки.

unique_messages_id_that_were_replied = set(messages_id_that_were_replied)

# 2. Формируем список словарей: id сообщения, кол-во сообщений-ответов на это сообщение
messages_id_that_were_replied_with_sum_of_answers = []
Copy link
Contributor

Choose a reason for hiding this comment

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

Тут было бы логично сделать не список из словарей, а просто словарь. Айди сообщения: количество ответов.

"message_id": message_id,
"number_of_answers": messages_id_that_were_replied.count(message_id),
})
print(messages_id_that_were_replied_with_sum_of_answers)
Copy link
Contributor

Choose a reason for hiding this comment

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

Эти принты хороши для дебага, но из финальной версии их надо удалять.


# 6. Выводим id пользователя на сообщения которого больше всего отвечали

return messages_id_and_users_id_sent_by[message_id_with_max_sum_of_answers_var]
Copy link
Contributor

Choose a reason for hiding this comment

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

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

Нам нужно найти пользователя, сообщения которого больше всего просматривали в сумме. То есть он мог написать оч много сообщений с небольшим количеством ответов. Это не обязательно автор самого отвечаемого сообщения.

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
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy