from bisect import insort_left K = 5 top = [] while 1: x = input() if len(top) < K: insort_left(top, x) elif x > top[0]: del top[0] insort_left(top, x) print top will be enough