I feel like the title is a bit wordy. What I have defined here is a function that takes two parameters:
- a list that contains valued sorted from smallest to biggest
- a number to insert at the right index so that the returned list print its values from smallest to biggest
NOTE: Recursion is mandatory
def insert(lst, to_insert):
"""
parameters : lst of type list, that contains values sorted from smallest to largest;
to_insert : represents a value
returns : same list with the to_insert value positioned at the right index
in order for the list to remain sorted from smallest to largest;
"""
if len(lst) == 1:
return []
if lst[0] < to_insert and to_insert < lst[1]:
lst[3] = to_insert
return [lst[0]] + [lst[3]] + insert(lst[1:], to_insert)
else:
return [lst[0]] + insert(lst[1:], to_insert)
print(insert([1,2,3,4,5,7,8,9], 6))
The list outputs the following :
[1,2,3,4,5,6,7,8] #not sure where 9 got left
How do I optimize this function, using only simple functions.