Find list elements with higher values than the w elements on both sides

Viewed 61

This is what I was able to write for w = 2.

    A = [1,2,3,2,1,4,3,2,5,1,2,6,1,2,7]
    w = 2
    
    for i in range(w, len(A)- w):
        for j in range(w):
            if A[i] > A[j] and A[i] > A[i-1]:
                if A[i] > A[j+4] and A[i] > A[i+1]:
                    print(A[i])

Output: 3
        4
        5
        5
        6
        6

The first output is 3 (1,2,3,2,1) which is max out of it's left 'w' elements 1,2 and right 'w' elements 2,1. Similarly, the second output 4 derived from from (2,1,4,3,2) and so on.

How do I extend this for w = n, where n = 3, 4, 5 ?

3 Answers
import numpy as np

If you have:

A = np.array([1,2,3,2,1,4,3,2,5,1,2,6,1,2,7])

You can do:

result=[]
w=2
for i in range(w, len(A)-w):
    if all(A[i] > A[i-w:i]) and all(A[i] > A[i+1:i+w+1]):
        result.append(A[i])

result will be:

[3, 4, 5, 6]

If you change the definition of A to A = np.array([7,2,-3,9,1,4,3,2,10,11,2,6,1,2,7]), and w to 3, then result will be:

[9, 11]

as expected, I hope.

While I do like zabop's answer, there is a simpler way to achieve the same result, also without using numpy:

A = [1,2,3,2,1,4,3,2,5,1,2,6,1,2,7]
w = 2

for i in range(w, len(A)- w):
    greater = True
    for j in range(1,w+1):
        if A[i-j] >= A[i] or A[i+j] >= A[i]:
            greater = False
            break
    if greater:
        print(A[i])

The output is

3
4
5
6

Using just a for loop in Python:

for i in range(w, len(A)-w):
    s = []
    for j in range(1, w+1):
        s.append(A[i] >= A[i-j] and A[i] >= A[i+j])
    if sum(s)==w:
        print(A[i])

Mixing for loop with list comprehension:

for i in range(w, len(A)-w):
    if sum([A[i] >= A[i-j] and A[i] >= A[i+j] for j in range(1,w+1)]) == w:
        print(A[i])

Output (for both):

3
4
5
6

A crazy single-line list comprehension:

[A[i] for i in range(w, len(A)-w) if sum([A[i] >= A[i-j] and A[i] >= A[i+j] for j in range(1,w+1)]) == w]

Output:

[3, 4, 5, 6]
Related