Top K Longest Words ในลิสต์
กำหนดลิสต์คำ และจำนวน K หา K คำที่ยาวที่สุด (ถ้ายาวเท่ากัน เรียงตามลำดับเดิม)
วิธีที่ 1: ใช้ sorted() กับ key=len และ itertools.count()
from itertools import count
def top_k_longest(words, k):
c = count()
return sorted(words, key=lambda w: (len(w), next(c)), reverse=True)[:k]
print(top_k_longest(['Earth','Moonshine','Aurora','Snowflakes','Sunshine'], 2))
# ['Snowflakes', 'Moonshine']
วิธีที่ 2: ใช้ enumerate + zip + sorted
def top_k_longest(words, k):
idx, ws = zip(*sorted(enumerate(words), key=lambda x: (-len(x[1]), -x[0]))[:k])
return list(ws)
print(top_k_longest(['Earth','Moonshine','Aurora','Snowflakes','Sunshine'], 2))
# ['Snowflakes', 'Moonshine']