Generalize the previous version: give bonuses to the top K most productive employees, where k is given as a variable. Still no sorting: repeat the search for the best employee k times, and remember who already won so nobody wins twice.
You start with:
names = ["John Doe", "Mary Jane", "Bob Smith", "Alice Chen", "Carlos Diaz"]
productivities = [83, 133, 97, 150, 120]
salaries = [135000, 335000, 210000, 250000, 180000]
k = 3
Build:
Alice Chen: $37500 Mary Jane: $50250 Carlos Diaz: $27000
Rules:
- Index
iin all three lists refers to the same employee. - Round 1 finds the employee with the highest productivity, round 2 the best among the employees who have not won yet, and so on, for
krounds. - If two employees have the same productivity, the one listed first wins.
- Each bonus is 15% of the salary, rounded down (using
//). - Print one line per winner, best first:
name: $bonus. - If
kis larger than the number of employees, everybody wins once and you print one line per employee: when nobody is left, a round prints nothing. - Your code must keep working when
kchanges to 1, 2, 5 or 7.
Use a list of booleans:
taken = [False] * len(names). A round finds the best employee among those who are not taken yet, then marks that employee as taken.
The outer loop runs
k times and the inner loop is the search from v4 with one more condition: if not taken[i] and (best_index == -1 or productivities[i] > productivities[best_index]):. If nobody is found in a round, skip the rest of that round.
names = ["John Doe", "Mary Jane", "Bob Smith", "Alice Chen", "Carlos Diaz"]
productivities = [83, 133, 97, 150, 120]
salaries = [135000, 335000, 210000, 250000, 180000]
k = 3
taken = [False] * len(names)
for rank in range(k):
best_index = -1
for i in range(len(names)):
if not taken[i] and (best_index == -1 or productivities[i] > productivities[best_index]):
best_index = i
if best_index != -1:
taken[best_index] = True
bonus = salaries[best_index] * 15 // 100
print(names[best_index] + ": $" + str(bonus))
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
