I have a list of number of work hours of some employees in a month in the form of tuples and I would like to choose the employee of the month based on the highest number of work hours in the month. But what if we have some tuples with ties between them? How will the function change as I want to include both the employees who had tie between them.
Here’s what I’ve got too far.
”’python
work_hours = [("Abby",400),("Billy",500),("Cassie",700),("David",700)]
def employee_check(work_hours):
current_max_hours = 0
employee_of_the_month = ""
for a,b in work_hours:
if b >= current_max_hours:
employee_of_the_month = a
current_max_hours = b
else:
pass
return (employee_of_the_month,current_max_hours)
employee_check(work_hours)
”’
Then I’m getting the last one as my output.
”’python
(‘David’, 700)
”’
>Solution :
You are only storing one employee as the employee of the month, even when there is a tie. You need to modify your code to store multiple employees in case of a tie.
def employee_check(work_hours: list[tuple[str, int]]) -> tuple[list[str], int]:
"""
Determines the employee(s) with the highest number of work hours in a month.
:param work_hours: List of tuples containing employee names and their corresponding work hours.
:return: A tuple containing a list of employee(s) of the month and the highest number of work hours.
"""
current_max_hours = 0
employees_of_the_month = []
for employee, hours in work_hours:
if hours > current_max_hours:
employees_of_the_month = [employee]
current_max_hours = hours
elif hours == current_max_hours:
employees_of_the_month.append(employee)
return (employees_of_the_month, current_max_hours)
work_hours = [("Abby", 400), ("Billy", 500), ("Cassie", 700), ("David", 700)]
print(employee_check(work_hours))
Output:
(['Cassie', 'David'], 700)
As you can see from the above output, the function will now return a list of employees of the month along with the highest number of work hours.