misc corrections/optimizations in top() and similarity()
This commit is contained in:
parent
42b49c7ecc
commit
6f4444f67e
|
@ -825,7 +825,7 @@ def copy_recursive(src, dest):
|
|||
memoized_similarities = {}
|
||||
|
||||
def similarity(a, b):
|
||||
if len(a) < len(b):
|
||||
if len(a) < len(b) or (len(a) == len(b) and a < b):
|
||||
shorter = a
|
||||
longer = b
|
||||
else:
|
||||
|
@ -849,18 +849,17 @@ def similarity(a, b):
|
|||
return result
|
||||
|
||||
def top(items, n, key):
|
||||
if len(items) == 0:
|
||||
return []
|
||||
winners = items[:1]
|
||||
for item in items[1:]:
|
||||
if len(winners) < n or key(item) > key(winners[-1]):
|
||||
for i in range(len(winners)):
|
||||
if key(item) > key(winners[i]):
|
||||
winners.insert(i, item)
|
||||
winners = []
|
||||
for item in items:
|
||||
score = key(item)
|
||||
if len(winners) < n or score > winners[-1][1]:
|
||||
for i in range(len(winners) + 1):
|
||||
if i == len(winners) or score > winners[i][1]:
|
||||
winners.insert(i, (item, score))
|
||||
break
|
||||
if len(winners) > n:
|
||||
while len(winners) > n:
|
||||
winners.pop()
|
||||
return winners
|
||||
return [item for (item, score) in winners]
|
||||
|
||||
def generate(args):
|
||||
jenv = Environment(
|
||||
|
|
Loading…
Reference in a new issue