In: Computer Science
PYTHON: Write a function insertInOrder that takes in a list and
a number. This function should assume that the list is already in
ascending order. The function should insert the number into the
correct position of the list so that the list stays in ascending
order. It should modify the list,
not build a new list. It does not need to return
the list, because it is modifying it.
Hint: Use a whlie loop and list methods
lst = [1,3,5,7] insertInOrder(lst, 2) print(lst) # Should print [1, 2, 3, 5, 7] insertInOrder(lst, 4) print(lst) # Should print [1, 2, 3, 4, 5, 7] insertOnOrder(lst, 8) print(lst) # Should print [1, 2, 3, 4, 5, 7, 8] insertInOrder(lst, 0) print(lst) # Should print [0, 1, 2, 3, 4, 5, 7, 8]
Python code:
#defining insertInOrder function
def insertInOrder(lst,number):
#initializing i
i=0
#looping all elements in lst
while(i<len(lst)):
#checking if the number
is less than the current number in lst
if(number<lst[i]):
#inserting the number in the current position
lst.insert(i,number)
#exiting the loop
break
#incrementing i
i+=1
#checking if the entire loop is iterated
if(i==len(lst)):
#then add the number in
the last position
lst.append(number)
#initializing lst
lst=[1,3,5,7]
#calling insertInOrder and insrting 2
insertInOrder(lst,2)
#printing lst
print(lst)
#calling insertInOrder and insrting 4
insertInOrder(lst,4)
#printing lst
print(lst)
#calling insertInOrder and insrting 8
insertInOrder(lst,8)
#printing lst
print(lst)
#calling insertInOrder and insrting 0
insertInOrder(lst,0)
#printing lst
print(lst)
Screenshot:
Output: