Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find maximum with limited length in a list

Tags:

python

list

I'm looking for maximum absolute value out of chunked list.

For example, the list is:

[1, 2, 4, 5, 4, 5, 6, 7, 2, 6, -9, 6, 4, 2, 7, 8]

I want to find the maximum with lookahead = 4. For this case, it will return me:

[5, 7, 9, 8]

How can I do simply in Python?

for d in data[::4]:
    if count < LIMIT:
        count = count + 1

        if abs(d) > maximum_item:
            maximum_item = abs(d)
    else:
        max_array.append(maximum_item)

        if maximum_item > highest_line:
            highest_line = maximum_item

        maximum_item = 0
        count = 1

I know I can use for loop to check this. But I'm sure there is an easier way in python.

like image 843
moeseth Avatar asked Jan 06 '23 22:01

moeseth


1 Answers

Using standard Python:

[max(abs(x) for x in arr[i:i+4]) for i in range(0, len(arr), 4)]

This works also if the array cannot be evenly divided.

like image 178
eumiro Avatar answered Jan 14 '23 19:01

eumiro