EDIT:
I'm curious as to why I'm being downvoted. The solution by @wim
willingly ignores the restriction in the original question about "without making a new list". The only response was to temporarily change it to a deque in an odd attempt to get around that restriction. Currently, this is the only answer which adheres to all of OPs requirements (listed below as two separate comments).
Print largest values of a list in the same order without making a new list
I need to print the top 3 in this list like
This answer assumes that the number is always three for how many of the top numbers you need to extract, in their original order. If that is the case, this answer seems to be O(n)
time and O(1)
space.
def top_three(nums):
if len(nums) <= 3:
return nums
a = b = c = float('-inf')
dex_a = dex_b = dex_c = None
for i, num in enumerate(nums):
if num > a and num > b and num > c:
a, b, c = num, a, b
dex_a, dex_b, dex_c = i, dex_a, dex_b
elif num > b and num > c:
b, c = num, b
dex_b, dex_c = i, dex_b
elif num > c:
c = num
dex_c = i
if dex_a < dex_b < dex_c:
print(a, b, c)
elif dex_a < dex_c < dex_b:
print(a, c, b)
elif dex_b < dex_a < dex_c:
print(b, a, c)
elif dex_b < dex_c < dex_a:
print(b, c, a)
elif dex_c < dex_a < dex_b:
print(c, a, b)
elif dex_c < dex_b < dex_a:
print(c, b, a)
Tests:
In[3]: top_three([9, 1, 2, 11, 8])
9 11 8
In[4]: top_three([9, 1, 2, 11, 8, 9])
9 11 9
In[5]: top_three([3, 3, 1, 0, 4, 3, 2, 5])
3 4 5