Show the top k brands by rating. This is v3's search, repeated k times: find the best brand, mark it as taken, then search again among the brands that are not taken yet, until you have k brands in rank order.
You start with:
brands = ["TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"]
ratings = [4, 5, 3, 5, 4]
k = 3
Build:
1. MegaCorp (5) 2. NeoByte (5) 3. TechPro (4)
Rules:
- Repeat v3's search
ktimes. Each round looks only at brands that are not taken yet and picks the one with the highest rating, then marks it as taken (one true/false flag per brand). - Ties go to the brand listed first: keep the first brand you find and replace it only on a strictly higher rating.
kis never larger than the number of brands.- 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).
Start with the two declarations
used = [False] * len(ratings) and lines = []. A flag tells whether that position is already taken.
Each round is v3's search: nothing found yet, scan every position, skip taken ones, keep the first candidate and replace it only on a strictly higher rating. Then mark the winner as taken and add its line.
brands = ["TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"]
ratings = [4, 5, 3, 5, 4]
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 or ratings[i] > ratings[best_index]:
best_index = i
used[best_index] = True
lines.append(str(rank) + ". " + brands[best_index] + " (" + str(ratings[best_index]) + ")")
output = "\n".join(lines)
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
