0

I have a list

arr = [0, 1, 45, 2, 40, 3, 70, 4, 45, 5, 6, 7, 8, 9]

in which I'm trying to find the position/index of the maximum element from 3 consecutive elements using below code:

for i in range (0, len(arr)-3):
    print(arr.index(max(arr[i : i+3])))

When i goes to position 7, it gives incorrect result.

Result should be:

2 2 2 4 6 6 6 8 8 11 12

But is instead

2 2 2 4 6 6 6 2 2 11 12

Ted Klein Bergman
  • 9,146
  • 4
  • 29
  • 50
Mohiuddin
  • 9
  • 4
  • 2
    What does "maximum element from 3 consecutive elements" mean? Is the result you show there correct, or incorrect? If incorrect, what should the result be? Please read [ask]. – ChrisGPT was on strike Aug 15 '20 at 19:05
  • It's not really worth trying to do this in base Python. Pandas would be easier. See ^ – roganjosh Aug 15 '20 at 19:06
  • result should be 2 2 2 4 6 6 6 8 8 11 12 – Mohiuddin Aug 15 '20 at 19:10
  • @TedKleinBergman I'm kinda inclined to agree, but you've got a decent bit of rep from your answer :P I think the sliding window is easier to implement (and faster) using other tools, and the dupe status will prevent other answers that I _suspect_ will be sub-par – roganjosh Aug 15 '20 at 19:22

1 Answers1

7

That's because there's two 45's and index returns the first occurrence. You can pass a start and end argument to tell the index method from which indices to start looking from.

for i in range (0, len(arr)-3):
    print(arr.index(max(arr[i : i+3]), i, i+3))

Or alternatively:

for i in range (0, len(arr)-3):
    sliced_array = arr[i : i+3]
    print(i + sliced_array.index(max(sliced_array)))
Ted Klein Bergman
  • 9,146
  • 4
  • 29
  • 50