jaqueline jaqueline - 18 days ago 6
Python Question

Inserting value into a list of int just before the rightmost item greater than the value?

def insert(lst, v):
""" (list of int, int) -> NoneType

Insert v into lst just before the rightmost item greater than v, or at
index 0 if no items are greater than v.

>>> my_list = [3, 10, 4, 2]
>>> insert(my_list, 5)
>>> my_list
[3, 5, 10, 4, 2]
>>> my_list = [5, 4, 2, 10]
>>> insert(my_list, 20)
>>> my_list
[20, 5, 4, 2, 10]
"""
for idx, val in enumerate(lst):
if val > v:
lst.insert(idx, v)
break
else:
lst.insert(0, v)


when ever i try testing the functions, it doesn't pass one of the hidden test cases which was having two items in the list that are bigger than the value. everything else in the example cases pass. how should i change my return statement in order to fix this issue?

Answer

Since the specification requires you to insert before the rightmost value greater than v, you can't break out early and have to traverse the entire list:

>>> def insert(lst, v):
...     rightmost = 0
...     for i, val in enumerate(lst):
...         if val > v:
...             rightmost = i
...     lst.insert(rightmost, v)
... 
>>> 

Some test cases:

>>> my_list = [3, 10, 4, 2]
>>> insert(my_list, 5)
>>> my_list
[3, 5, 10, 4, 2]
>>> my_list = [5, 4, 2, 10]
>>> insert(my_list, 20)
>>> my_list
[20, 5, 4, 2, 10]
>>> my_list = [3, 4 ,5, 6, 2]
>>> insert(my_list, 3)
>>> my_list
[3, 4, 5, 3, 6, 2]

Also note that no return statement is required, and you don't have one anyway so it cannot be changed...