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
targetinto two new lists, keeping the order. - From the filtered lists pick the top
kby rating, highest first, with v4's repeated search. Ties go to the entry listed first. - If fewer than
kproducts 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 inoutput(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)
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
