Sorting and Ranking
Sort by Key
Order a list of names by a paired numeric score using a repeated selection-of-minimum. Each step picks the index of the lowest remaining score, appends the corresponding name to the result, then removes that index so it cannot be chosen again.
By hand
The Pythonic way
zip(names, scores) pairs each name with its score; sorted(..., key=lambda x: x[1]) orders by the score field; the comprehension strips the score back
out, leaving the sorted names.
naive.py
names = ['eve', 'bob', 'dan', 'amy', 'cal', 'fay']
scores = [72, 45, 88, 31, 63, 57]
remain = list(range(len(names)))
result = []
while remain:
best = min(remain, key=lambda i: scores[i])
result.append(names[best])
remain.remove(best)
print('RESULT:', result)
library.py
names = ['eve', 'bob', 'dan', 'amy', 'cal', 'fay']
scores = [72, 45, 88, 31, 63, 57]
result = [n for n, s in sorted(zip(names, scores), key=lambda x: x[1])]
print('RESULT:', result)
RESULT: ['amy', 'bob', 'fay', 'cal', 'eve', 'dan']
Implementation notes
- Data is stored in parallel lists because a list of record dicts would exceed
the 80-character repr limit after two elements;
tupleis also not in the tracer's tracked types, so index integers are used instead. remainshrinks by one per step andresultgrows by one — both are visible in the replay. Thewhile remain:condition events are zero-delta (condition evaluation changes no variables).- The selection-of-minimum approach makes O(n²) comparisons;
sorteduses Timsort at O(n log n). For six elements the difference is negligible.