Skip to content Skip to sidebar Skip to footer

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

Solution 1:

If you are uncertain about how your loops work I recommend adding in some print statements. That way you can see what your loop is actually doing, especially in more complicated problems this is useful.

Something like this would solve your problem.

a = [1,2,3,2,4]
for k in range(0,len(a)-2): #-2 so that one don't go past the loops length
    #print(k)
    y = a
    if(a[k]>a[k+1]):
        del y[k+1] #delete the k+1 element if it is 

Solution 2:

>>> s =  [5, 20, 10, 15, 30]
>>> max_so_far = s[0]
>>> result = []
>>> for x in s:
        if x >= max_so_far:
            result.append(x)
            max_so_far = x

>>> result
[5, 20, 30]

Solution 3:

Depending whether you need to do some calculation later with the list you can use a generator

s = [1, 20, 10, 30]

def find_smaller_generator(l: list):
    last_item = None
    for item in l:
        if last_item is None or item >= last_item: 
            last_item = item
            yield item
def find_smaller_list(l: list):
    return list(find_smaller_generator(l))



print(find_smaller_list(s))

for i in find_smaller_generator(s):
    print(i)

print([i**2 for i in find_smaller_generator(s)])

this returns:

[1, 20, 30]

1
20
30

[1, 400, 900]

Solution 4:

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.


Post a Comment for "Finding If The Next Element Is Smaller Than The One Before It And Deleting It From The List Python"