Problem overview
Version 6 generalises the previous version from the top two employees to the top k, where k is a variable. The data is three parallel lists, names, productivities and salaries, where index i in all three describes the same employee. The most productive employee wins first place; a tie goes to whoever is listed first. Each winner's bonus is 15% of the salary, rounded down, and the program prints one line per winner, best first, as name: $bonus.
The lesson still forbids sorting. With k = 3 the output is:
Alice Chen: $37500
Mary Jane: $50250
Carlos Diaz: $27000
Alice Chen has the highest productivity (150), Mary Jane the next (133) and Carlos Diaz the next (120). If k is larger than the number of employees, everybody wins once and the extra rounds print nothing. The code has to keep working when k becomes 1, 2, 5 or 7.
Approach: search k times, and remember the winners
Version 5 ran a search for the best employee and then a second search that skipped the winner. Version 6 turns that into a loop: one search per round, repeated k times, where each round must ignore everyone who won earlier.
To remember the winners, the program keeps a list taken with one True or False per employee. A value at index i says whether employee i has already won. Marking winners by index, not by score, is what makes ties safe: two employees with the same productivity are still two different indexes.
Each round is one scan over all the employees. It keeps best_index, which starts at -1 to mean "nobody chosen yet in this round". An employee becomes the round's best when two things hold: they haven't won yet, and either nobody is chosen yet or their productivity is strictly higher than that of best_index. The strict comparison keeps the earlier employee when productivities are equal.
After the scan, a round that found someone marks the winner as taken, computes the bonus and prints the line. A round that found nobody, which happens only when k exceeds the number of employees, does nothing.
Step by step
- Create
taken = [False] * len(names). Multiplying a list repeats its contents, so this makes oneFalsefor every employee. - Write the round loop
for rank in range(k):. The counter only counts the rounds: 0, 1, 2 fork = 3. - Set
best_index = -1inside the round. It is created inside the loop so that every round starts over with nobody chosen. - Write the inner loop
for i in range(len(names)):, the search over all the employees. Every round looks at everyone again, and the next step skips earlier winners. - Write the combined condition. The employee must not be taken, and either
best_index == -1or the productivity atiis strictly greater than the one atbest_index. When it holds, setbest_index = i. - Check that someone was found with
if best_index != -1:, after the inner loop and level with it. Everything after this is indented inside the check. - Mark the winner with
taken[best_index] = True. It must change at once, because the next round reads it. - Compute the bonus as
salaries[best_index] * 15 // 100. Multiplying first and dividing second, with//, keeps the result a whole number rounded down. - Print the winner as the name,
": $"andstr(bonus). Python can't join text and a number with+, so the number goes throughstr().
The solution in Python
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))
Details worth knowing:
- The parentheses are needed. In Python
andbinds more tightly thanor. Without the parentheses, an employee who is already taken could still pass through the part afteror. orshort-circuits. Whenbest_index == -1is true, Python doesn't evaluate the right side. That protectsproductivities[best_index]whilebest_indexis still -1.- Negative indexes are legal.
productivities[-1]doesn't raise an error: it reads the last element. A missing guard would therefore not crash, it would quietly compare against the last employee. rankis unused inside the loop. The loop variable only counts rounds. Python doesn't mind a loop variable that the body never reads.
Tracing k = 3
Round 0 scans all five employees and ends with best_index = 3, Alice Chen with 150. Then taken is [False, False, False, True, False]. Round 1 skips index 3 and picks index 1, Mary Jane with 133, so taken becomes [False, True, False, True, False]. Round 2 picks index 4, Carlos Diaz with 120, leaving taken as [False, True, False, True, True]. The loop ends after three rounds. The bonuses are 250000 * 15 // 100 = 37500, 335000 * 15 // 100 = 50250 and 180000 * 15 // 100 = 27000.
Complexity
Each of the k rounds scans all n employees, so the work is O(k * n) time. The taken list adds O(n) space. For a small k this is cheap. If k grows toward n, the cost approaches O(n²), and sorting the employees by productivity would be faster, but the lesson sets that aside and keeps the parallel lists intact.
Edge cases and common mistakes
klarger than the number of employees. Withk = 7, five lines are printed, the same as fork = 5. In the last two rounds every slot oftakenis true, sobest_indexstays -1 and the check skips the round. Without the check,taken[-1] = Trueandnames[-1]would silently reuse the last employee.- Ties. With productivities 100, 100 and 50, the first listed employee wins first place and the second listed wins second place, because only a strictly higher score replaces
best_indexand the winner is marked by index. k = 0.range(0)is empty, so nothing is printed.- Creating
best_indexoutside the round loop. Then the second round would start from the previous winner instead of from nobody. - Forgetting to mark the winner. If the
takenupdate is missing, the same employee wins every round and the line repeatsktimes.
Testing
- For
k = 1the program prints onlyAlice Chen: $37500. - For
k = 5it prints the three lines above, thenBob Smith: $31500andJohn Doe: $20250. - With three employees named A, B and C, productivities 100, 100 and 50, salaries 1000, 2000 and 3000, and
k = 3, it printsA: $150,B: $300andC: $450.
