Problem overview
Version 4 shows the top k brands by rating, in rank order. The data is two parallel lists, brands and ratings, plus the number k. Each output line has the form rank. Brand (rating), with ranks starting at 1. When two brands have the same rating, the brand listed first ranks higher. The lesson guarantees that k is never larger than the number of brands.
For brands = ["TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"], ratings = [4, 5, 3, 5, 4] and k = 3, the expected text is:
1. MegaCorp (5)
2. NeoByte (5)
3. TechPro (4)
MegaCorp and NeoByte both have 5, and MegaCorp is listed first. TechPro and Zenith both have 4, and TechPro is listed first, so it takes third place. The lines are joined with "\n" and stored in a variable named output.
Approach: find the best, mark it, search again
Version 3 found the single best brand with one scan. This version repeats that scan k times. The change that makes repetition work is a list of flags, used, with one False for each brand. After a round picks its winner, that brand's flag becomes True, and later rounds look only at brands whose flag is still False. A brand can't win twice, and no sorting is needed.
Inside a round, best_index starts at -1, which is not a real position and so means "nothing found yet". The scan visits every position. A brand that is not used replaces the current best when nothing has been found yet, or when its rating is strictly higher than the best one's. The word "strictly" gives the tie rule: an equal rating never replaces the earlier brand.
The result is built as text. Each round appends one finished line to a list called lines, and after the loop "\n".join(lines) glues them with a newline between each two.
Step by step
- Create
used = [False] * len(ratings). One flag per brand, all false, because nobody has been picked. - Create
lines = []. The lines arrive one per round, so the list starts empty. - Loop over the ranks:
for rank in range(1, k + 1):. The upper bound ofrangeis excluded, sok + 1makes the last rank equal tok. The number also gets printed in front of the brand. - Set
best_index = -1inside the loop, so that each round starts a new search. - Add the inner loop
for i in range(len(ratings)):, nested in the first. For every round, it runs through all the brands from the start. - Skip used brands with
if not used[i]:. Only brands that haven't won are candidates. - Test for a new best with
if best_index == -1 or ratings[i] > ratings[best_index]:. - Remember it:
best_index = i. Only the position is stored, and the name and rating are looked up from it later. - Mark the winner after the inner loop, with
used[best_index] = True. Indent it like the innerfor, so it runs once per round. - Append the line: the rank,
". ", the brand's name, and the rating in parentheses. Both numbers pass throughstr(). - Build
outputafter the loop with"\n".join(lines).
The solution in Python
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)
Some details about this code:
str()is required. Python won't join text and a number with+.str(rank) + ". "works, andrank + ". "raises aTypeError.joingoes on the separator."\n".join(lines)puts a newline between neighbours only, so there is no empty line at the end.- Short-circuit evaluation. When
best_index == -1is true, Python doesn't evaluate the right side ofor. That protectsratings[best_index]while the index is still -1.
Tracing the example
Round 1 scans all five brands. The first, TechPro with 4, is accepted because nothing is found yet. MegaCorp's 5 beats it, Quantum's 3 doesn't, NeoByte's 5 doesn't beat 5, and Zenith's 4 doesn't. The winner is index 1, MegaCorp, and used becomes [False, True, False, False, False]. Round 2 skips index 1 and ends with index 3, NeoByte, so used is [False, True, False, True, False]. Round 3 skips both and picks index 0, TechPro, because Zenith's 4 doesn't strictly beat TechPro's 4.
Complexity
There are k rounds and each scans n brands, so the time is O(k * n). The used and lines lists take O(n) and O(k) space. When k is small, this beats sorting everything, and it never rearranges the parallel lists.
Edge cases and common mistakes
- Ties. Equal ratings keep the earlier brand because the comparison is
>, not>=. With>=, the later brand would win every tie. k = 1. One round runs and the output is the single line1. MegaCorp (5).kequal to the number of brands. Withk = 5every brand is listed, ending with5. Quantum (3).klarger than the brand count. The lesson rules this out, and this version has no guard for it. Withk = 6, the sixth round finds nobody, sobest_indexstays -1, and Python's negative indexing quietly makes the last brand appear again: the sixth line would be6. Zenith (4). No error is raised.- Forgetting to mark the winner. If
used[best_index] = Trueis missing, every round picks MegaCorp again. - Marking inside the inner loop. The winner is only known after the whole scan, so the marking belongs after it.
- Starting
rankat 0.range(k)would number the lines from 0, and the lesson wants 1.
Testing
- With
k = 1, the output is1. MegaCorp (5). - With
k = 5, the output is the three lines above followed by4. Zenith (4)and5. Quantum (3).
