I know that the best answer has already been chosen, but for educational purposes you can also consider mine.
I hope there are no typos:
def some_name(list_a, list_b): if len(list_a) != len(list_b): raise Exception("Too bad") result_list = [] for result in (list_a[i] + list_b[i] for i in range(len(list_a))): if len(result_list) >= 20: if result_list[0] > result: continue result_list = result_list[1:] result_list.append(result) result_list.sort()
And after some refactoring - it does almost what heapq.nlargest will do (here we must save the results, sorted by themselves):
def some_name(list_a, list_b): if len(list_a) != len(list_b): raise Exception("Too bad") result_list = [] for result in (list_a[i] + list_b[i] for i in range(len(list_a))): result_list.append(result) result_list.sort() result_list = result_list[-20:]
source share