I'm creating a class where one of the methods inserts a new item into the sorted list. The item is inserted in the corrected (sorted) position in the sorted list. I'm not allowed to use any built-in list functions or methods other than []
, [:]
, +
, and len
though. This is the part that's really confusing to me.
What would be the best way in going about this?
You can add an item to a list with the append() method. A new item is added at the end. If you want to add to other positions, such as the beginning, use the insert() method described later. A list is also added as one item, not combined.
Insert Operation: In a sorted array, a search operation is performed for the possible position of the given element by using Binary search, and then an insert operation is performed followed by shifting the elements.
Use the insort function of the bisect module:
import bisect a = [1, 2, 4, 5] bisect.insort(a, 3) print(a)
Output
[1, 2, 3, 4, 5]
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