user3624406 user3624406 - 3 months ago 9
Python Question

Program error for this solution

This is what is available right now

l = [list[0]]
list.pop(0)
x = len(list)

for i in range(x+1):
n = len(l)
j = 0

if list[j] > l[n-1]:
l.append(list[j])
list.pop(j)
j = j+1

elif i == len(list):
l.append(list[j])
list.pop(j)
print(list)
print(l)


`

Some pointers would be really helpful!

Answer

Make a copy of the list. Iterate through the copy in successions and check for monotonically increasing entries to be added to result in the current iteration of the while loop. Delete the entries as they are added to the result.

Repeat the check-append-delete cycle in the next iteration of the while loop; until the copy of the list is empty:

lst = [1, 2, 2, 2, 11, 5, 9, 8, 19]

lst_cp = lst.copy()
result = []

while lst_cp: # keep iterating until list is empty
    result.append(lst_cp.pop(0))
    for v in lst_cp[:]:
        if v > result[-1]:
            result.append(v)
            lst_cp.remove(v)

print(result)
# [1, 2, 11, 19, 2, 5, 9, 2, 8]
Comments