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

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 How to Ask. Commented Aug 15, 2020 at 19:05
  • It's not really worth trying to do this in base Python. Pandas would be easier. See ^ Commented Aug 15, 2020 at 19:06
  • result should be 2 2 2 4 6 6 6 8 8 11 12 Commented Aug 15, 2020 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 Commented Aug 15, 2020 at 19:22

1 Answer 1

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)))
Sign up to request clarification or add additional context in comments.

6 Comments

Nice. The alternative, which I won't bother to post as a separate answer, is to save the slice (arr[i:i+3]) in a separate variable and do i + the_slice.index(max(the_slice))
@alaniwi True. I'll add that. Thanks!
Incidentally, it shouldn't need that end argument. (Not that it does any harm.)
@alaniwi True, but having the end argument will reduce the amount of elements the index method have to compare
@TedKleinBergman It will tell it when to give up if it hasn't yet found a match, but it is already constrained to find a match before it gets to the point where it could give up.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.