Reputation: 9
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
Upvotes: 0
Views: 100
Reputation: 9766
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)))
Upvotes: 7