Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why does my python tuple unpacking output the last item in my tuple list instead of the max condition?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

>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])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading