Start learning free

LESSON 251 OF 287 · NESTED LOOPS

Top K Brands V5 in Python: Filter by Product, Then Rank

Practice Read the full explanation

The full catalog covers many products. Filter to one product first, then rank the top k brands that sell it, using v4's repeated search on the filtered lists.

You start with:

products = ["Laptop", "Phone", "Laptop", "Tablet", "Phone", "Laptop"]
brands = ["TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith", "AlphaTech"]
ratings = [4, 5, 5, 3, 4, 4]
target = "Laptop"
k = 2

Build:

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

Rules:

  • Filter: copy the brand and the rating of every row whose product equals target into two new lists, keeping the order.
  • From the filtered lists pick the top k by rating, highest first, with v4's repeated search. Ties go to the entry listed first.
  • If fewer than k products match, list only those that exist: when no brand is left, add no more lines (no extra lines, no error).
  • 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).

Build filtered_brands and filtered_ratings first: a loop over the catalog that copies the row when products[i] == target.

Then run v4's repeated search over the filtered lists (same code, new names).

If fewer than k products match, some round finds nobody (best_index stays -1): add a line only when a brand was found.

products = ["Laptop", "Phone", "Laptop", "Tablet", "Phone", "Laptop"]
brands = ["TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith", "AlphaTech"]
ratings = [4, 5, 5, 3, 4, 4]
target = "Laptop"
k = 2

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

STEP 1 OF 18
    Ctrl + Enter to check

    PYTHON · NESTED LOOPS

    Top K Brands V5 in Python, explained

    Problem overview

    The catalog in version 5 lists many products, one row per brand and product. Three parallel lists describe it: products, brands and ratings, and row i in each is one entry. Two more variables set the question: target, the product of interest, and k, how many brands to show.

    The task has two parts: keep only the rows whose product equals target, then rank the top k of those by rating, highest first, with version 4's repeated search. Ties go to the entry listed first. With target = "Laptop" and k = 2 in the starter data, three rows are laptops: TechPro (4), NeoByte (5) and AlphaTech (4). The expected text is:

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

    If fewer than k rows match, only the existing ones are listed, with no extra lines and no error. The lines are joined with "\n" and stored in output.

    Approach: copy the matching rows, then reuse the search

    Instead of changing the search to skip non-matching rows, the lesson separates the two jobs. A first loop builds two new lists, filtered_brands and filtered_ratings, holding the brand and the rating of every matching row, in the original order. A brand and its rating always sit at the same position in the new lists, as they do in the originals.

    After that, version 4's search runs on the filtered lists alone. It uses a used flag per entry and a best_index that starts at -1, and it runs once per rank. The only new rule is that a round can now find nobody, which happens when the product has fewer than k brands. In that case the round must add no line.

    Step by step

    1. Create filtered_brands = [], which will hold the brands that sell the target product.
    2. Create filtered_ratings = [], for the matching ratings. Both lists are filled in the same order, so they stay aligned.
    3. Loop over the rows: for i in range(len(products)):. Row i is one product with its brand and its rating.
    4. Test the product: if products[i] == target:. Rows of other products are skipped.
    5. Copy the brand with filtered_brands.append(brands[i]).
    6. Copy the rating with filtered_ratings.append(ratings[i]).
    7. Create used after the loop, with no indent: [False] * len(filtered_ratings). It is as long as the filtered lists, not the original ones.
    8. Create lines = [], the list of finished lines.
    9. Loop over the ranks: for rank in range(1, k + 1):.
    10. Set best_index = -1 at the start of each round.
    11. Add the inner loop over range(len(filtered_ratings)).
    12. Skip used entries with if not used[i]:.
    13. Test for a new best: best_index == -1 or a strictly higher rating than the current best.
    14. Remember it with best_index = i.
    15. Check that a brand was found after the inner loop: if best_index != -1:.
    16. Mark it used inside that check, so the next round skips it.
    17. Append the line inside the check: the rank, ". ", the brand's name and the rating in parentheses, with str() on both numbers.
    18. Build output after the loops with "\n".join(lines).

    The solution in Python

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

    Details worth knowing:

    • Indexes mean different things in the two parts. In the first loop, i is a row of the catalog, from 0 to 5. In the search, i and best_index are positions in the filtered lists, from 0 to 2 here. The two never mix: the search only reads filtered_brands and filtered_ratings.
    • append changes the list in place. It returns None, so filtered_brands = filtered_brands.append(...) would replace the list with None.
    • Short-circuit evaluation. When best_index == -1 is true, Python doesn't evaluate the right side of or, so filtered_ratings[best_index] is not read while the index is -1.

    Tracing the example

    The filter keeps rows 0, 2 and 5, so filtered_brands is ['TechPro', 'NeoByte', 'AlphaTech'] and filtered_ratings is [4, 5, 4]. Round 1 accepts TechPro (4), replaces it with NeoByte (5), and keeps NeoByte against AlphaTech (4). NeoByte becomes 1. NeoByte (5). Round 2 skips NeoByte, accepts TechPro (4), and AlphaTech's 4 doesn't strictly beat it, so TechPro takes second place.

    Complexity

    The filter is one pass over n rows. If m rows match, the ranking is k rounds over m entries, which is O(k * m). The total is O(n + k * m) time and O(n) extra space for the filtered lists and flags.

    Edge cases and common mistakes

    • Fewer matches than k. With target = "Laptop" and k = 5, three lines are printed: after the third round, every flag is true, so the later rounds find nobody and the check skips them. The first three lines are the same as for k = 3.
    • Without the check. If if best_index != -1: were missing, a round with nobody left would use -1 as an index. Python's negative indexing would pick the last filtered brand again, and a duplicate line would appear without any error.
    • No matching product. With target = "Watch" both filtered lists are empty, no round finds anyone, and output is an empty string.
    • A single match. With target = "Tablet" and k = 2, the output is only 1. Quantum (3).
    • Ranking the unfiltered lists. Searching the original lists, and checking the product inside the search, is possible, but the result would be harder to reason about. Filtering first keeps the search identical to the previous version.
    • Misaligned lists. The brand and the rating must be appended in the same if, so that position j in one is still position j in the other.

    Testing

    • target = "Phone" with k = 3 gives 1. MegaCorp (5) and 2. Zenith (4).
    • target = "Laptop" with k = 3 gives the two lines above plus 3. AlphaTech (4).
    • k = 0 gives an empty output.
    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free