Start learning free

LESSON 250 OF 673 · NESTED LOOPS

Employee of the Year V6 in Python: Top K by Repeated Search

Practice Read the full explanation

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 i in 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 k rounds.
  • 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 k is 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 k changes 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))

STEP 1 OF 9
    Ctrl + Enter to check

    PYTHON · NESTED LOOPS

    Employee Of The Year V6 in Python, explained

    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

    1. Create taken = [False] * len(names). Multiplying a list repeats its contents, so this makes one False for every employee.
    2. Write the round loop for rank in range(k):. The counter only counts the rounds: 0, 1, 2 for k = 3.
    3. Set best_index = -1 inside the round. It is created inside the loop so that every round starts over with nobody chosen.
    4. 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.
    5. Write the combined condition. The employee must not be taken, and either best_index == -1 or the productivity at i is strictly greater than the one at best_index. When it holds, set best_index = i.
    6. 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.
    7. Mark the winner with taken[best_index] = True. It must change at once, because the next round reads it.
    8. Compute the bonus as salaries[best_index] * 15 // 100. Multiplying first and dividing second, with //, keeps the result a whole number rounded down.
    9. Print the winner as the name, ": $" and str(bonus). Python can't join text and a number with +, so the number goes through str().

    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 and binds more tightly than or. Without the parentheses, an employee who is already taken could still pass through the part after or.
    • or short-circuits. When best_index == -1 is true, Python doesn't evaluate the right side. That protects productivities[best_index] while best_index is 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.
    • rank is 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

    • k larger than the number of employees. With k = 7, five lines are printed, the same as for k = 5. In the last two rounds every slot of taken is true, so best_index stays -1 and the check skips the round. Without the check, taken[-1] = True and names[-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_index and the winner is marked by index.
    • k = 0. range(0) is empty, so nothing is printed.
    • Creating best_index outside the round loop. Then the second round would start from the previous winner instead of from nobody.
    • Forgetting to mark the winner. If the taken update is missing, the same employee wins every round and the line repeats k times.

    Testing

    • For k = 1 the program prints only Alice Chen: $37500.
    • For k = 5 it prints the three lines above, then Bob Smith: $31500 and John Doe: $20250.
    • With three employees named A, B and C, productivities 100, 100 and 50, salaries 1000, 2000 and 3000, and k = 3, it prints A: $150, B: $300 and C: $450.
    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free