Start learning free

LESSON 252 OF 287 · NESTED LOOPS

Top K Brands V6 in Python: Rating First, Reviews as Tie-Break

Practice Read the full explanation

Rank the top k brands by rating, breaking ties with the review count. This builds on v4's repeated search (not on v5: there is no filtering here); only the comparison gets a second criterion.

You start with:

brands = ["TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith"]
ratings = [4, 5, 5, 3, 4]
reviews = [200, 150, 500, 100, 300]
k = 3

Build:

1. NeoByte (5, 500)
2. MegaCorp (5, 150)
3. Zenith (4, 300)

Rules:

  • Rating decides first: the higher rating wins.
  • If two brands have the same rating, the one with more reviews wins.
  • If rating and reviews are both equal, the one listed first wins (the test data has no such pair, but your code must follow the rule).
  • k is never larger than the number of brands.
  • Each line is "rank. Brand (rating, reviews)", starting at rank 1.
  • Join the lines with "\n" and store the text in output (the site prints it for you).

Start from v4: the same used = [False] * len(ratings) and lines = [], the same two loops. Only the comparison inside the inner loop changes.

Use a chain (if / elif / elif): no candidate yet, take this one; else a higher rating, take this one; else the same rating and more reviews, take this one.

brands = ["TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith"]
ratings = [4, 5, 5, 3, 4]
reviews = [200, 150, 500, 100, 300]
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:
                best_index = i
            elif ratings[i] > ratings[best_index]:
                best_index = i
            elif ratings[i] == ratings[best_index] and reviews[i] > reviews[best_index]:
                best_index = i
    used[best_index] = True
    lines.append(str(rank) + ". " + brands[best_index] + " (" + str(ratings[best_index]) + ", " + str(reviews[best_index]) + ")")
output = "\n".join(lines)

STEP 1 OF 12
    Ctrl + Enter to check

    PYTHON · NESTED LOOPS

    Top K Brands V6 in Python, explained

    Problem overview

    Version 6 ranks the top k brands by rating and breaks ties with the number of reviews. The data is three parallel lists, brands, ratings and reviews, plus k. This version builds on version 4's repeated search and has no filtering. Only the comparison changes: it now has a second criterion.

    The rules, in order: the higher rating wins; if the ratings are equal, the brand with more reviews wins; if both are equal, the brand listed first wins. Each line is rank. Brand (rating, reviews), with ranks starting at 1, and the lines are joined with "\n" into output. The lesson guarantees that k is never larger than the number of brands.

    For the starter data and k = 3:

    1. NeoByte (5, 500)
    2. MegaCorp (5, 150)
    3. Zenith (4, 300)

    MegaCorp and NeoByte tie on rating 5, and NeoByte has more reviews, so it comes first. TechPro and Zenith tie on 4, and Zenith's 300 reviews beat TechPro's 200.

    Approach: the same search with a three-case comparison

    The structure is that of version 4: a list used with one flag per brand, one round per rank, and a scan inside each round that looks only at brands not yet used. What changes is the test that decides whether brand i replaces the current best. It becomes a chain of three cases, tried in order:

    1. nothing has been found yet (best_index == -1), so this brand is the best so far;
    2. this brand's rating is higher than the best one's, so it wins, whatever the reviews;
    3. the ratings are equal and this brand has more reviews, so it wins the tie.

    Because the cases are an if, elif, elif chain, only the first true one runs, and a later case is examined only when the earlier ones were false. A higher rating is settled in case 2 before reviews count at all. Case 3 needs both parts: the ratings must be equal and the reviews higher. If neither case 2 nor case 3 holds, the current best stays, which also settles the last rule: with equal rating and equal reviews, the brand found first remains.

    Step by step

    1. Create used = [False] * len(ratings), one flag per brand.
    2. Create lines = [], one finished line per rank will be added.
    3. Loop over the ranks: for rank in range(1, k + 1):.
    4. Set best_index = -1 at the start of the round.
    5. Add the inner loop over range(len(ratings)), which visits every brand in each round.
    6. Skip used brands: if not used[i]:.
    7. Case one: if best_index == -1, set best_index = i. The first unused brand has nobody to beat.
    8. Case two: elif ratings[i] > ratings[best_index]: sets best_index = i.
    9. Case three: elif ratings[i] == ratings[best_index] and reviews[i] > reviews[best_index]: sets best_index = i.
    10. Mark the winner after the inner loop, with used[best_index] = True, indented like the inner for.
    11. Append the line: the rank, ". ", the name, then the rating and the review count in parentheses, separated by a comma and a space. Every number goes through str().
    12. Build output with "\n".join(lines) after the loop.

    The solution in Python

    brands = ["TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith"]
    ratings = [4, 5, 5, 3, 4]
    reviews = [200, 150, 500, 100, 300]
    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:
                    best_index = i
                elif ratings[i] > ratings[best_index]:
                    best_index = i
                elif ratings[i] == ratings[best_index] and reviews[i] > reviews[best_index]:
                    best_index = i
        used[best_index] = True
        lines.append(str(rank) + ". " + brands[best_index] + " (" + str(ratings[best_index]) + ", " + str(reviews[best_index]) + ")")
    output = "\n".join(lines)
    

    Details about this code:

    • The order of the cases protects the lookups. The check best_index == -1 comes first, so ratings[best_index] in the later cases is only evaluated once a real brand is stored. With -1 Python would not raise an error, it would read the last element, which would hide the bug.
    • == compares, = assigns. The tie case uses == between the two ratings. Writing a single = there is a syntax error in Python.
    • Ratings and reviews are never added or combined. The comparison is lexicographic: first one number, then the other only if the first is equal. Python also lets you compare the pairs as tuples, (ratings[i], reviews[i]) > (ratings[best_index], reviews[best_index]), but the lesson spells out the cases.

    Tracing the example

    In round 1 the scan accepts TechPro (4, 200) first. MegaCorp has rating 5, higher than 4, so case 2 makes it the best. NeoByte also has rating 5, so case 2 is false, and case 3 is true because 500 reviews beat 150: NeoByte takes over. Quantum (3) loses at both comparisons, and Zenith (4) does too. NeoByte is marked used. In round 2, MegaCorp (5, 150) wins, because no unused brand has rating 5 with more reviews. In round 3 the unused brands are TechPro (4, 200), Quantum (3, 100) and Zenith (4, 300). TechPro is accepted first, then Zenith ties the rating and has more reviews, so Zenith takes third place.

    Complexity

    There are k rounds over n brands, so the time is O(k * n). The flags and the lines need O(n + k) extra space. The second criterion costs only one more comparison per brand.

    Edge cases and common mistakes

    • Reviews compared first. If reviews were tested before ratings, NeoByte (5, 500) would still win, but a brand like (4, 9999) would beat (5, 1). Rating must decide first.
    • Using or in case three. With ratings[i] == ratings[best_index] or reviews[i] > reviews[best_index], a lower-rated brand with many reviews could take over. Both conditions must hold, so the word is and.
    • Full ties. With ratings 5, 5, 5 and reviews 10, 10, 10, no case fires after the first, so the brands appear in listed order. The test data has no such pair, but the rule holds because the comparisons are strict.
    • Ties on rating only. With reviews 10, 30 and 20 for three brands rated 5, the order is by reviews descending: 30, 20, 10.
    • Using if instead of elif. Separate if statements would still give correct results here, because each only moves best_index to a better brand, but they would evaluate every case on every brand. The chain states the intent, one case at a time.
    • Forgetting to mark the winner. The same brand would be chosen in every round.
    • k beyond the brand count. The lesson rules it out. With no guard, a round that finds nobody would use the index -1, and the last brand would silently repeat.

    Testing

    • With k = 5, the starter data gives the three lines above, then 4. TechPro (4, 200) and 5. Quantum (3, 100).
    • With brands X and Y, ratings 5 and 4, and reviews 1 and 9999, the output is 1. X (5, 1) and 2. Y (4, 9999): the rating decides even though Y has far more reviews.
    • With brands A, B and C, all rated 5, and reviews 10, 30 and 20, the output is B, then C, then A.
    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free