I wanted to know why my code is outputting the last tuple item in my tuple list [work hours] instead of the max hours/employee of the month, I am a noob in Python and I am stuck in this problem within my Python curriculum?
please advise:
work_hours1 = [('able',10067),('john',50000),('will',1000)]
work_hours2 = [('lebron',2000),('curry',5000),('richardson',1000)]
def employee_of_month(work_hours):
current_max = 0
employee_name = ''
for name, work_hours in work_hours:
if work_hours > current_max:
current_max = work_hours
employee_name = name
else:
pass
return(name, work_hours)
result_wkhr1 = employee_of_month(work_hours1)
result_wkhr2 = employee_of_month(work_hours2)
print(result_wkhr1)
print(result_wkhr2)
I am expecting the name "john" and 50000 in result_wkhr1, however, that is not the case.
>Solution :
All you need is the built-in max function with an appropriate key function:
def employee_of_month(work_hours):
return max(work_hours, key=lambda x: x[1])
