Blue Monday Blue Monday - 1 month ago 9
Python Question

Finding if the next element is smaller than the one before it and deleting it from the list python

I am having trouble with my code, I am writing a method that will check if the next element is smaller than the previous element and if it is, it will delete it.

Example:

Input:

[1, 20, 10, 30]


Desired output:
[1,20,30]


Actual output:
[30]


def findSmaller(s):
i = -1
y = []
while i <= len(s):
for j in range(len(s)):
if s[i+1] <= s[i]:
del s[i + 1]
y.append(s[i])
i += 1
return y

Answer

You can try something like this

def findSmaller(s):
    # sets p (previous) as the first value in s
    p = s[0]
    # initializes y to be an array and sets the first value to p
    y = [p]
    # iterates over s, starting with the second element
    for i in s[1::]:
        # checks if i is greater than or equal to the previous element
        if i >= p:
            # if it is, i is appended to the list y
            y.append(i)
            # also set the previous value to i, so the next iteration can check against p
            p = i
    #returns the list
    return y

What this does is iterate over s and checks if the current item in the list is greater than or equal to the previous element in the list. If it is then it appends it to y, and y is returned.

Try out the code here.