Problem overview
Version 6 ranks the top k brands by rating and breaks ties with the number of reviews. The data is three parallel lists, brands, ratings and reviews, plus k. This version builds on version 4's repeated search and has no filtering. Only the comparison changes: it now has a second criterion.
The rules, in order: the higher rating wins; if the ratings are equal, the brand with more reviews wins; if both are equal, the brand listed first wins. Each line is rank. Brand (rating, reviews), with ranks starting at 1, and the lines are joined with "\n" into output. The lesson guarantees that k is never larger than the number of brands.
For the starter data and k = 3:
1. NeoByte (5, 500)
2. MegaCorp (5, 150)
3. Zenith (4, 300)
MegaCorp and NeoByte tie on rating 5, and NeoByte has more reviews, so it comes first. TechPro and Zenith tie on 4, and Zenith's 300 reviews beat TechPro's 200.
Approach: the same search with a three-case comparison
The structure is that of version 4: a list used with one flag per brand, one round per rank, and a scan inside each round that looks only at brands not yet used. What changes is the test that decides whether brand i replaces the current best. It becomes a chain of three cases, tried in order:
- nothing has been found yet (
best_index == -1), so this brand is the best so far; - this brand's rating is higher than the best one's, so it wins, whatever the reviews;
- the ratings are equal and this brand has more reviews, so it wins the tie.
Because the cases are an if, elif, elif chain, only the first true one runs, and a later case is examined only when the earlier ones were false. A higher rating is settled in case 2 before reviews count at all. Case 3 needs both parts: the ratings must be equal and the reviews higher. If neither case 2 nor case 3 holds, the current best stays, which also settles the last rule: with equal rating and equal reviews, the brand found first remains.
Step by step
- Create
used = [False] * len(ratings), one flag per brand. - Create
lines = [], one finished line per rank will be added. - Loop over the ranks:
for rank in range(1, k + 1):. - Set
best_index = -1at the start of the round. - Add the inner loop over
range(len(ratings)), which visits every brand in each round. - Skip used brands:
if not used[i]:. - Case one: if
best_index == -1, setbest_index = i. The first unused brand has nobody to beat. - Case two:
elif ratings[i] > ratings[best_index]:setsbest_index = i. - Case three:
elif ratings[i] == ratings[best_index] and reviews[i] > reviews[best_index]:setsbest_index = i. - Mark the winner after the inner loop, with
used[best_index] = True, indented like the innerfor. - Append the line: the rank,
". ", the name, then the rating and the review count in parentheses, separated by a comma and a space. Every number goes throughstr(). - Build
outputwith"\n".join(lines)after the loop.
The solution in Python
brands = ["TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith"]
ratings = [4, 5, 5, 3, 4]
reviews = [200, 150, 500, 100, 300]
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:
best_index = i
elif ratings[i] > ratings[best_index]:
best_index = i
elif ratings[i] == ratings[best_index] and reviews[i] > reviews[best_index]:
best_index = i
used[best_index] = True
lines.append(str(rank) + ". " + brands[best_index] + " (" + str(ratings[best_index]) + ", " + str(reviews[best_index]) + ")")
output = "\n".join(lines)
Details about this code:
- The order of the cases protects the lookups. The check
best_index == -1comes first, soratings[best_index]in the later cases is only evaluated once a real brand is stored. With -1 Python would not raise an error, it would read the last element, which would hide the bug. ==compares,=assigns. The tie case uses==between the two ratings. Writing a single=there is a syntax error in Python.- Ratings and reviews are never added or combined. The comparison is lexicographic: first one number, then the other only if the first is equal. Python also lets you compare the pairs as tuples,
(ratings[i], reviews[i]) > (ratings[best_index], reviews[best_index]), but the lesson spells out the cases.
Tracing the example
In round 1 the scan accepts TechPro (4, 200) first. MegaCorp has rating 5, higher than 4, so case 2 makes it the best. NeoByte also has rating 5, so case 2 is false, and case 3 is true because 500 reviews beat 150: NeoByte takes over. Quantum (3) loses at both comparisons, and Zenith (4) does too. NeoByte is marked used. In round 2, MegaCorp (5, 150) wins, because no unused brand has rating 5 with more reviews. In round 3 the unused brands are TechPro (4, 200), Quantum (3, 100) and Zenith (4, 300). TechPro is accepted first, then Zenith ties the rating and has more reviews, so Zenith takes third place.
Complexity
There are k rounds over n brands, so the time is O(k * n). The flags and the lines need O(n + k) extra space. The second criterion costs only one more comparison per brand.
Edge cases and common mistakes
- Reviews compared first. If reviews were tested before ratings, NeoByte (5, 500) would still win, but a brand like (4, 9999) would beat (5, 1). Rating must decide first.
- Using
orin case three. Withratings[i] == ratings[best_index] or reviews[i] > reviews[best_index], a lower-rated brand with many reviews could take over. Both conditions must hold, so the word isand. - Full ties. With ratings 5, 5, 5 and reviews 10, 10, 10, no case fires after the first, so the brands appear in listed order. The test data has no such pair, but the rule holds because the comparisons are strict.
- Ties on rating only. With reviews 10, 30 and 20 for three brands rated 5, the order is by reviews descending: 30, 20, 10.
- Using
ifinstead ofelif. Separateifstatements would still give correct results here, because each only movesbest_indexto a better brand, but they would evaluate every case on every brand. The chain states the intent, one case at a time. - Forgetting to mark the winner. The same brand would be chosen in every round.
kbeyond the brand count. The lesson rules it out. With no guard, a round that finds nobody would use the index -1, and the last brand would silently repeat.
Testing
- With
k = 5, the starter data gives the three lines above, then4. TechPro (4, 200)and5. Quantum (3, 100). - With brands X and Y, ratings 5 and 4, and reviews 1 and 9999, the output is
1. X (5, 1)and2. Y (4, 9999): the rating decides even though Y has far more reviews. - With brands A, B and C, all rated 5, and reviews 10, 30 and 20, the output is B, then C, then A.
