-
Notifications
You must be signed in to change notification settings - Fork 260
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
base: main
Are you sure you want to change the base?
Problem solution #30
Conversation
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.
У тебя в коммит попала служеблная папка .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К') |
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.
Тут и на предыдущей строке дублируешь цифру 100000, это не считается хорошей практикой.
Вынеси её в отдельную переменную и используй в двух местах, тогда будет хорошо.
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.
Тут в строке ты всё ещё дублируешь константу 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К') |
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.
Аналогично с 80000
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.
Аналогично.
company.py
Outdated
print(f'Отдел {department["title"]}: максимальная зарплата {max_salary}') | ||
print(f'Отдел {department["title"]}: cредняя зарплата {int(avg_salary)}') | ||
|
||
avg_salary = 0 # task 9 |
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.
Эту строку можно удалить.
for_challenges.py
Outdated
|
||
for group, names in enumerate(groups, start=1): | ||
print(f'Группа {group}: {", ".join(groups[names])}') |
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.
Чтобы гитхаб не ставил вот этих красных кружочкой, ставь в конце файла одну пустую строку. Так тоже принято.
max_names = [] | ||
max_count = 0 | ||
|
||
for name, count_of_name in names_counter.items(): |
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.
Почитай про функцию 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К') |
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.
Тут в строке ты всё ещё дублируешь константу 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К') |
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.
Аналогично.
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К') |
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.
Тут тоже.
for_dict_challenges.py
Outdated
print(f'{boys_predominate}{students["class"]}') if male_gender > female_gender else print(f'{girls_predominate}{students["class"]}') |
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.
Тут у тебя по сути выбирается только 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}К') |
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.
Теперь K из принта надо убрать, а то получается, что там теперь 100000к. Аналогично принтами ниже.
for_dict_challenges.py
Outdated
@@ -127,6 +126,11 @@ def max_name(students): | |||
'Миша': True, | |||
} | |||
|
|||
max_male_class = '' | |||
max_female_class = '' |
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.
Пока у тебя нет таких классов, в эти переменные стоит записывать None – его в пайтоне как раз для этого и придумали.
for_dict_challenges.py
Outdated
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: |
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.
Кажется, у этого ифа лишний отступ
for_dict_challenges.py
Outdated
max_female_class = '' | ||
max_male_gender = 0 | ||
max_female_gender = 0 | ||
|
||
for students in school: |
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.
Тут не students, тут класс типа.
for_dict_challenges.py
Outdated
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"]) |
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.
students["class"] и так строка, не надо её ещё раз превращать в строку.
company_add_tasks.py
Outdated
department_salary = [] | ||
for employer in department['employers']: | ||
department_salary.append(employer['salary_rub']) | ||
if department["title"] == 'IT department': |
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.
Тут ты в алгоритме решения используешь знание о том, какие есть налоги. Если добавить в список taxes пару строк, твой алгоритм перестанет работать. Давай перепишем так, чтобы было универсальнее.
company_add_tasks.py
Outdated
tax_departments["department"] = department["title"] | ||
tax_departments["tax"] = tax_sum | ||
else: | ||
tax_sum = sum(department_salary) * (taxes[0]["value_percents"] / 100) |
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.
Другая проблема в том, что в ветках ифа почти один и тот же код. От этого дублирования лучше бы избавиться.
company_add_tasks.py
Outdated
# task 14. Вывести список всех сотрудников с указанием зарплаты "на руки" и зарплаты с учётом налогов. | ||
|
||
tax_departments = {} | ||
for department in departments: |
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.
К этому заданию применимы оба коммента выше.
company_add_tasks.py
Outdated
tax_departments["department"] = department["title"] | ||
tax_departments["tax"] = tax_sum | ||
print(f'По {tax_departments["department"]} суммарный налог на сотрудников равен {tax_departments["tax"]}') | ||
def departments_salary(departments): |
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.
По названию функции непонятно, что функция делает тк в названии нет глагола.
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.
Это верно для всех функций ниже.
company_add_tasks.py
Outdated
|
||
for department in departments_lst: | ||
dep_tax = [] | ||
if True: |
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.
Этот иф всегда будет выполняться, а его ветка else – никогда. Удали ненужное.
company_add_tasks.py
Outdated
taxes_for_department["All"] = taxes_for_department.pop(None) | ||
|
||
department_taxes = {} | ||
departments_lst = [department["title"] for department in departments] |
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.
Во-первых, не используй сокращения в названиях переменных – никаких lst.
Во-вторых, в этой переменной не список департментов, а список названий департментов.
company_add_tasks.py
Outdated
for tax in taxes: | ||
taxes_for_department[tax["department"]] = tax["value_percents"] / 100 | ||
|
||
taxes_for_department["All"] = taxes_for_department.pop(None) |
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.
Такой подход не подойдёт тк если у нас появится департмент с названием All
, то всё сломается. Вытащи "общий" налог в отдельную переменную просто.
company_add_tasks.py
Outdated
if True: | ||
dep_tax.append(taxes_for_department.get(department)) | ||
dep_tax.append(taxes_for_department.get("All")) | ||
if None in dep_tax: |
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.
Вместо того чтобы добавлять нан, а потом его удалять, можно просто не добавлять нан :)
company_add_tasks.py
Outdated
|
||
if __name__ == "__main__": | ||
dep_sal = departments_salary(departments) | ||
dep_tax = departments_tax_rate(taxes, departments) |
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.
Опять сокращения, давай всё полностью называть.
company_add_tasks.py
Outdated
departments_salary = {} | ||
for department in departments: | ||
salary_lst = [] | ||
salary = [] |
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.
По названию я ожидаю, что в этой переменной живёт зарплата, а это не так: в ней список зарплат :)
company_add_tasks.py
Outdated
taxes_for_department[tax["department"]] = tax["value_percents"] / 100 | ||
|
||
taxes_for_department["All"] = taxes_for_department.pop(None) | ||
if tax["department"] != None: |
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.
С None принято сравнивать не с помощью ==
, а с помощью is
company_add_tasks.py
Outdated
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 |
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.
Тут ты используешь get, но если в словаре ключа не будет, всё сломается. Используй квадратные скобки.
for_dict_challenges_bonus.py
Outdated
@@ -55,5 +56,29 @@ def generate_chat_history(): | |||
return messages | |||
|
|||
|
|||
# 1. Вывести айди пользователя, который написал больше всех сообщений. | |||
def is_user_with_max_messages(messages): | |||
id_list = [] |
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.
Непонятное название.
for_dict_challenges_bonus.py
Outdated
uniq_id_list = list(set(id_list)) | ||
|
||
count_of_message_id = {} | ||
for id_uniq in uniq_id_list: |
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.
В этом блоке все переменные названы непонятно, поэтому понять, что тут происходит очень сложно.
А ещё ты выбрал не самую оптимальную логику с двумя вложенными циклами. Попробуй обойтись без двух вложенных циклов, для этого потребуется переделать сам алгоритм работы, но должно получиться проще.
for_dict_challenges_bonus.py
Outdated
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)) |
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.
Опять результат сортеда превращаешь в словарь и опять используешь сортед, когда надо использовать max
company_add_tasks.py
Outdated
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( |
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.
В list не надо превращать.
company_add_tasks.py
Outdated
|
||
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") |
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.
Тут 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 = [] |
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.
Тут было бы логично сделать не список из словарей, а просто словарь. Айди сообщения: количество ответов.
"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) |
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.
Эти принты хороши для дебага, но из финальной версии их надо удалять.
|
||
# 6. Выводим id пользователя на сообщения которого больше всего отвечали | ||
|
||
return messages_id_and_users_id_sent_by[message_id_with_max_sum_of_answers_var] |
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.
Тут получается, что ты выводишь айди пользователя, который написал сообщение, на которое ответило больше всего пользователей. Это неправильно.
Нам нужно найти пользователя, сообщения которого больше всего просматривали в сумме. То есть он мог написать оч много сообщений с небольшим количеством ответов. Это не обязательно автор самого отвечаемого сообщения.
Исправил замечания по company.py