I want the location to appear when I ask for results. Why can't I display the employee of the month's location?
Code:
work_hours = [("Jao", "Ville", 800), ("Billy", "Jackson St", 400), ("Kevin", "Westside", 500)]
def employee_check(work_hours):
current_max = 0
employee_of_month = ""
for employee, location, hours in work_hours:
if hours > current_max:
current_max = hours
employee_of_month = employee
else:
pass
# return the statement
return (employee_of_month, location, current_max)
result = employee_check(work_hours)
print(result)
-
4Please don't post pictures of your code - post your actual code!gvee– gvee2021年05月21日 07:28:39 +00:00Commented May 21, 2021 at 7:28
-
Unrelated to the question, but looking at the picture, it is recommended to use a monospace font for programmingAurèle– Aurèle2021年05月21日 07:31:29 +00:00Commented May 21, 2021 at 7:31
3 Answers 3
current_max = 0
employee_of_month = ''
employee_of_month_location = ''
for employee,location,hours in work_hours:
if hours > current_max:
current_max = hours
employee_of_month = employee
employee_of_month_location = location
else:
pass
return (employee_of_month, employee_of_month_location, current_max)
6 Comments
In this case more convenient is using built-in function max, not reinventing its functionality:
max(work_hours, key=lambda x: x[2])
Since your list consists of items with the same structure and you want to get only the tuple where the third element (the working hours) is maximum, you can use the key argument of the max function. You can pass a function there, in this case an anonymous lambda function. It changes the behavior of the max function, i.e. changing where exactly to look at the maximum value (here: the third position of each element in work_hours).
This reduces your code a lot as you can see how to use it:
work_hours = [("Jao", "Ville", 800), ("Billy", "Jackson St", 400), ("Kevin", "Westside", 500)]
result = max(work_hours, key=lambda x: x[2])
4 Comments
def employee_check(work_hours):
current_max = 0
employee_of_month = ''
employee_of_month_location = ''
for employee,location,hours in work_hours:
if hours > current_max:
current_max = hours
employee_of_month = employee
employee_of_month_location = location
else:
pass
return employee_of_month, employee_of_month_location, current_max
1 Comment
else block, just remove it. Also parentheses is redundant in your return statement.