Reputation: 47
To sort a series of numbers from the console, it is first appended into an myList
and this myList
is sorted using myList.sort()
n = int(input())
count = 0
myList = []
while count < n:
i = int(input())
myList.append(i)
count += 1
myList.sort()
print(myList)
Is there a way in which as it gets added to the list it is directly and automatically placed in the correct order/index? I want to get rid of the sort()
function and the unsorted myList
, if possible.
Upvotes: 3
Views: 132
Reputation: 3833
The heapq
module is yet another option:
from heapq import heappush, nsmallest
def myheap():
heap=[]
n=int(input())
for i in range(n):
heappush(heap, int(input()))
return nsmallest(n, heap)
Upvotes: 1
Reputation: 61910
Use SortedList from SortedContainers:
from sortedcontainers import SortedList
n = int(input())
count = 0
myList = SortedList()
while count < n:
i = int(input())
myList.add(i)
count += 1
print(myList)
Output (example of a dummy run)
4
5
3
2
1
SortedList([1, 2, 3, 5])
It keeps the list sorted and the insertion time is O(logn) (see the documentation on .add
)
Note
SortedContainers is a third-party library, needs to be install by doing:
pip install sortedcontainers
Upvotes: 2
Reputation: 78700
You can use bisect.insort
to insert into an already sorted list.
>>> from bisect import insort
>>> l = []
>>> insort(l, 5)
>>> l
[5]
>>> insort(l, 1)
>>> l
[1, 5]
>>> insort(l, 2)
>>> l
[1, 2, 5]
edit: If you don't require the list to be sorted after every insertion I'd just sort it once after the loop, though.
Upvotes: 4