Start learning free

LESSON 183 OF 287 · LOOPING OVER LIST INDICES

Employee of the Year V5 in Python: Top 2 Without Sorting

Practice Read the full explanation

Hand out bonuses to the top 2 most productive employees: the best one first, then the second best. You don't need any sorting. Find the best employee with the loop from v4, then find the best of the other employees with a second loop.

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]

Build:

Alice Chen: $37500
Mary Jane: $50250

Rules:

  • Index i in all three lists refers to the same employee.
  • The best employee is the one with the highest productivity; the second best is the one with the highest productivity among all the other employees.
  • If two employees have the same productivity, the one listed first wins.
  • Each bonus is 15% of the salary, rounded down (using //).
  • Print two lines, the best employee first: name: $bonus.

Find the best employee first, exactly as in v4. Remember: strictly greater, so the first listed wins a tie.

For the second place, loop over all the indices and ignore the best one. The whole condition is if i != best_index and (second_index == -1 or productivities[i] > productivities[second_index]):. "Nobody chosen yet" must also let an employee in.

names = ["John Doe", "Mary Jane", "Bob Smith", "Alice Chen", "Carlos Diaz"]
productivities = [83, 133, 97, 150, 120]
salaries = [135000, 335000, 210000, 250000, 180000]

best_index = 0
for i in range(1, len(names)):
    if productivities[i] > productivities[best_index]:
        best_index = i
second_index = -1
for i in range(len(names)):
    if i != best_index and (second_index == -1 or productivities[i] > productivities[second_index]):
        second_index = i
best_bonus = salaries[best_index] * 15 // 100
second_bonus = salaries[second_index] * 15 // 100
print(names[best_index] + ": $" + str(best_bonus))
print(names[second_index] + ": $" + str(second_bonus))

STEP 1 OF 10
    Ctrl + Enter to check

    PYTHON · LOOPING OVER LIST INDICES

    Employee Of The Year V5 in Python, explained

    Problem overview

    Version 5 hands out bonuses to the two most productive employees, best first. The data is the same three parallel lists as before: names, productivities and salaries. The best employee has the highest productivity. The second best has the highest productivity among all the others. Ties go to whoever is listed first. Each bonus is 15% of the salary, rounded down, and the program prints two lines in the form name: $bonus.

    With scores 83, 133, 97, 150 and 120, Alice Chen is first with 150 and Mary Jane is second with 133:

    Alice Chen: $37500
    Mary Jane: $50250

    Notice that second place earns a bigger bonus here, because Mary Jane's salary is higher. The ranking depends on productivity only.

    Approach: two scans, the second one skips the winner

    Sorting the employees would be one way to get the top two, but the lists are parallel, and sorting one of them would break the link between names, scores and salaries. The lesson avoids sorting and runs the scan from version 4 twice.

    The first scan is unchanged: best_index starts at 0, and a strictly higher score replaces it. The second scan looks for the best of everyone except best_index. It keeps second_index, which starts at -1, meaning nobody has been picked yet. No employee has the index -1, so it works as a "nothing yet" marker. Every employee except the best one is a candidate, and each is accepted in one of two cases: nobody has been picked yet, or this employee's score is strictly higher than that of the current second_index.

    The second loop starts at 0 rather than 1. The best employee may be anywhere in the list, including position 0, so the loop cannot assume that the first position is already taken. It visits every index and skips best_index inside the loop.

    Step by step

    1. Create best_index = 0. Employee 0 is the best until someone beats them.
    2. Loop for i in range(1, len(names)). Visit every other employee.
    3. Update on a strictly higher score. If productivities[i] > productivities[best_index], set best_index = i. The strict comparison keeps the earlier employee on ties.
    4. Create second_index = -1. This is the "nobody yet" marker.
    5. Start a second loop over range(len(names)). This one begins at 0.
    6. Write the combined condition. The employee must not be the best (i != best_index), and either second_index == -1 or this score beats the one at second_index. When it all holds, set second_index = i. The first part of the or must come first, so that productivities[second_index] is never read while second_index is -1.
    7. Compute best_bonus from salaries[best_index], with * 15 // 100.
    8. Compute second_bonus the same way from second_index.
    9. Print the best employee as the name, ": $" and the bonus converted with str().
    10. Print the second best in the same form on the next line.

    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]
    
    best_index = 0
    for i in range(1, len(names)):
        if productivities[i] > productivities[best_index]:
            best_index = i
    second_index = -1
    for i in range(len(names)):
        if i != best_index and (second_index == -1 or productivities[i] > productivities[second_index]):
            second_index = i
    best_bonus = salaries[best_index] * 15 // 100
    second_bonus = salaries[second_index] * 15 // 100
    print(names[best_index] + ": $" + str(best_bonus))
    print(names[second_index] + ": $" + str(second_bonus))
    

    Some details worth knowing:

    • Parentheses matter. In Python, and binds more tightly than or. Without the parentheses, the condition would read as "not the best, and nobody chosen" or "this score is higher", and the best employee could slip in through the second part.
    • or short-circuits. When second_index == -1 is true, Python does not evaluate the right side. That is what protects the lookup productivities[second_index].
    • Negative indexes are legal in Python. productivities[-1] does not raise an error: it returns the last element. So forgetting the -1 guard would not crash. It would silently compare against the last employee, which is a harder bug to notice.
    • String joining. names[best_index] + ": $" + str(best_bonus) joins the name, a colon with a space and a dollar sign, and the bonus as text.

    Tracing the example

    The first scan ends with best_index = 3 (score 150). In the second scan, i = 0 is accepted because nobody is chosen yet, so second_index = 0 (score 83). At i = 1, 133 beats 83, so it moves to 1. At i = 2, 97 does not beat 133. At i = 3, the employee is the best, so the condition's first part fails and the index is skipped. At i = 4, 120 does not beat 133. The second best is index 1, Mary Jane, with a bonus of 335000 * 15 // 100 = 50250.

    Edge cases and common mistakes

    • Ties for first. With scores 90, 150, 150 and 80, the first 150 is the best, and the second 150 becomes the second best, because the best employee is skipped by index, not by score.
    • Ties for second. With scores 100, 100, 50 and 10, employee 0 is first and employee 1 is second.
    • Skipping by score instead of index. Excluding "the employees with the top score" would drop a tied runner-up. The index is the right test.
    • Fewer than two employees. With a single employee, second_index stays -1, and names[-1] is that same employee, so the same line is printed twice. The lesson's data has five, so the case does not arise, but real code should check the length first.
    • Starting the second loop at 1. That would never consider employee 0 for second place.
    • Reusing one loop. Tracking both the best and the runner-up in a single pass is possible but needs more cases. Two simple scans are easier to get right.

    Testing

    • Scores [50, 60, 70, 80, 90] give Carlos Diaz first and Alice Chen second.
    • Scores [200, 100, 100, 100, 100] give John Doe first and Mary Jane second, the first of the tied runners-up.

    Both scans cost one pass each, so the total work grows in direct proportion to the number of employees.

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free