Start learning free

LESSON 191 OF 410 · NESTED LOOPS

Top K Brands V6 - Tie-Break by Review Count in Python

Practice

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

    Top K Brands V6 in Python

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