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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With