Start learning free

LESSON 251 OF 673 · NESTED LOOPS

Top K Brands V4 in Python: Ranking with a Repeated Search

Practice Read the full explanation

Show the top k brands by rating. This is v3's search, repeated k times: find the best brand, mark it as taken, then search again among the brands that are not taken yet, until you have k brands in rank order.

You start with:

brands = ["TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"]
ratings = [4, 5, 3, 5, 4]
k = 3

Build:

1. MegaCorp (5)
2. NeoByte (5)
3. TechPro (4)

Rules:

  • Repeat v3's search k times. Each round looks only at brands that are not taken yet and picks the one with the highest rating, then marks it as taken (one true/false flag per brand).
  • Ties go to the brand listed first: keep the first brand you find and replace it only on a strictly higher rating.
  • k is never larger than the number of brands.
  • Each line is "rank. Brand (rating)", starting at rank 1.
  • Join the lines with "\n" and store the text in output (the site prints it for you).

Start with the two declarations used = [False] * len(ratings) and lines = []. A flag tells whether that position is already taken.

Each round is v3's search: nothing found yet, scan every position, skip taken ones, keep the first candidate and replace it only on a strictly higher rating. Then mark the winner as taken and add its line.

brands = ["TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"]
ratings = [4, 5, 3, 5, 4]
k = 3

used = [False] * len(ratings)
lines = []
for rank in range(1, k + 1):
    best_index = -1
    for i in range(len(ratings)):
        if not used[i]:
            if best_index == -1 or ratings[i] > ratings[best_index]:
                best_index = i
    used[best_index] = True
    lines.append(str(rank) + ". " + brands[best_index] + " (" + str(ratings[best_index]) + ")")
output = "\n".join(lines)

STEP 1 OF 11
    Ctrl + Enter to check

    PYTHON · NESTED LOOPS

    Top K Brands V4 in Python, explained

    Problem overview

    Version 4 shows the top k brands by rating, in rank order. The data is two parallel lists, brands and ratings, plus the number k. Each output line has the form rank. Brand (rating), with ranks starting at 1. When two brands have the same rating, the brand listed first ranks higher. The lesson guarantees that k is never larger than the number of brands.

    For brands = ["TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"], ratings = [4, 5, 3, 5, 4] and k = 3, the expected text is:

    1. MegaCorp (5)
    2. NeoByte (5)
    3. TechPro (4)

    MegaCorp and NeoByte both have 5, and MegaCorp is listed first. TechPro and Zenith both have 4, and TechPro is listed first, so it takes third place. The lines are joined with "\n" and stored in a variable named output.

    Approach: find the best, mark it, search again

    Version 3 found the single best brand with one scan. This version repeats that scan k times. The change that makes repetition work is a list of flags, used, with one False for each brand. After a round picks its winner, that brand's flag becomes True, and later rounds look only at brands whose flag is still False. A brand can't win twice, and no sorting is needed.

    Inside a round, best_index starts at -1, which is not a real position and so means "nothing found yet". The scan visits every position. A brand that is not used replaces the current best when nothing has been found yet, or when its rating is strictly higher than the best one's. The word "strictly" gives the tie rule: an equal rating never replaces the earlier brand.

    The result is built as text. Each round appends one finished line to a list called lines, and after the loop "\n".join(lines) glues them with a newline between each two.

    Step by step

    1. Create used = [False] * len(ratings). One flag per brand, all false, because nobody has been picked.
    2. Create lines = []. The lines arrive one per round, so the list starts empty.
    3. Loop over the ranks: for rank in range(1, k + 1):. The upper bound of range is excluded, so k + 1 makes the last rank equal to k. The number also gets printed in front of the brand.
    4. Set best_index = -1 inside the loop, so that each round starts a new search.
    5. Add the inner loop for i in range(len(ratings)):, nested in the first. For every round, it runs through all the brands from the start.
    6. Skip used brands with if not used[i]:. Only brands that haven't won are candidates.
    7. Test for a new best with if best_index == -1 or ratings[i] > ratings[best_index]:.
    8. Remember it: best_index = i. Only the position is stored, and the name and rating are looked up from it later.
    9. Mark the winner after the inner loop, with used[best_index] = True. Indent it like the inner for, so it runs once per round.
    10. Append the line: the rank, ". ", the brand's name, and the rating in parentheses. Both numbers pass through str().
    11. Build output after the loop with "\n".join(lines).

    The solution in Python

    brands = ["TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"]
    ratings = [4, 5, 3, 5, 4]
    k = 3
    
    used = [False] * len(ratings)
    lines = []
    for rank in range(1, k + 1):
        best_index = -1
        for i in range(len(ratings)):
            if not used[i]:
                if best_index == -1 or ratings[i] > ratings[best_index]:
                    best_index = i
        used[best_index] = True
        lines.append(str(rank) + ". " + brands[best_index] + " (" + str(ratings[best_index]) + ")")
    output = "\n".join(lines)
    

    Some details about this code:

    • str() is required. Python won't join text and a number with +. str(rank) + ". " works, and rank + ". " raises a TypeError.
    • join goes on the separator. "\n".join(lines) puts a newline between neighbours only, so there is no empty line at the end.
    • Short-circuit evaluation. When best_index == -1 is true, Python doesn't evaluate the right side of or. That protects ratings[best_index] while the index is still -1.

    Tracing the example

    Round 1 scans all five brands. The first, TechPro with 4, is accepted because nothing is found yet. MegaCorp's 5 beats it, Quantum's 3 doesn't, NeoByte's 5 doesn't beat 5, and Zenith's 4 doesn't. The winner is index 1, MegaCorp, and used becomes [False, True, False, False, False]. Round 2 skips index 1 and ends with index 3, NeoByte, so used is [False, True, False, True, False]. Round 3 skips both and picks index 0, TechPro, because Zenith's 4 doesn't strictly beat TechPro's 4.

    Complexity

    There are k rounds and each scans n brands, so the time is O(k * n). The used and lines lists take O(n) and O(k) space. When k is small, this beats sorting everything, and it never rearranges the parallel lists.

    Edge cases and common mistakes

    • Ties. Equal ratings keep the earlier brand because the comparison is >, not >=. With >=, the later brand would win every tie.
    • k = 1. One round runs and the output is the single line 1. MegaCorp (5).
    • k equal to the number of brands. With k = 5 every brand is listed, ending with 5. Quantum (3).
    • k larger than the brand count. The lesson rules this out, and this version has no guard for it. With k = 6, the sixth round finds nobody, so best_index stays -1, and Python's negative indexing quietly makes the last brand appear again: the sixth line would be 6. Zenith (4). No error is raised.
    • Forgetting to mark the winner. If used[best_index] = True is missing, every round picks MegaCorp again.
    • Marking inside the inner loop. The winner is only known after the whole scan, so the marking belongs after it.
    • Starting rank at 0. range(k) would number the lines from 0, and the lesson wants 1.

    Testing

    • With k = 1, the output is 1. MegaCorp (5).
    • With k = 5, the output is the three lines above followed by 4. Zenith (4) and 5. Quantum (3).
    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free