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
- Create
filtered_brands = [], which will hold the brands that sell the target product. - Create
filtered_ratings = [], for the matching ratings. Both lists are filled in the same order, so they stay aligned. - Loop over the rows:
for i in range(len(products)):. Rowiis one product with its brand and its rating. - Test the product:
if products[i] == target:. Rows of other products are skipped. - Copy the brand with
filtered_brands.append(brands[i]). - Copy the rating with
filtered_ratings.append(ratings[i]). - Create
usedafter the loop, with no indent:[False] * len(filtered_ratings). It is as long as the filtered lists, not the original ones. - Create
lines = [], the list of finished lines. - Loop over the ranks:
for rank in range(1, k + 1):. - Set
best_index = -1at the start of each round. - Add the inner loop over
range(len(filtered_ratings)). - Skip used entries with
if not used[i]:. - Test for a new best:
best_index == -1or a strictly higher rating than the current best. - Remember it with
best_index = i. - Check that a brand was found after the inner loop:
if best_index != -1:. - Mark it used inside that check, so the next round skips it.
- Append the line inside the check: the rank,
". ", the brand's name and the rating in parentheses, withstr()on both numbers. - Build
outputafter 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,
iis a row of the catalog, from 0 to 5. In the search,iandbest_indexare positions in the filtered lists, from 0 to 2 here. The two never mix: the search only readsfiltered_brandsandfiltered_ratings. appendchanges the list in place. It returnsNone, sofiltered_brands = filtered_brands.append(...)would replace the list withNone.- Short-circuit evaluation. When
best_index == -1is true, Python doesn't evaluate the right side ofor, sofiltered_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. Withtarget = "Laptop"andk = 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 fork = 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, andoutputis an empty string. - A single match. With
target = "Tablet"andk = 2, the output is only1. 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 positionjin one is still positionjin the other.
Testing
target = "Phone"withk = 3gives1. MegaCorp (5)and2. Zenith (4).target = "Laptop"withk = 3gives the two lines above plus3. AlphaTech (4).k = 0gives an emptyoutput.
