Erez Zinger
Erez Zinger

Reputation: 23

average of 2 neighbouring elements in array python

I'm trying to write a program to print if an element in an array is the average of its 2 neighbours. Say I have an array consisting of [1,3,5,7,12,21] -- 3 is the average of 1+5 and 5 is the average of 3+7. I'm using for i in arr: with if i>arr[0] and i<arr[-1] inside it and if i == (arr[i-1]+arr[i+1])/2: inside that. Except when i try to run it, it says index out of range... I'm assuming it's because i-1 goes under arr[0] and i+1 goes above arr[-1] but I thought if I put in the condition if i>arr[0] and i<arr[-1] it won't count both of them. How do I go about this code otherwise? my code:

arr = []
while True:
    x = input("Enter numbers, type ''STOP'' to stop.\n")
    if x.upper() == "STOP":
        break
    x=int(x)
    arr.append(x)
for i in range(len(arr)):
    if 0 < i < len(arr)-1:
        if arr[i] == (arr[i-1]+arr[i+1])//2:
            print(arr[i], "is the average of its neighbours")

Upvotes: 0

Views: 579

Answers (4)

Ade_1
Ade_1

Reputation: 1486

You can use the length of the array to create a check. Try this

size = len(arr)
for indx, i in enumerate(some):
    if indx >0:
        if indx < size-1:
            val = (arr[indx-1]+ arr[indx+1])//2
            print(f'{val} is the average of its neighbours' )
            
  

Upvotes: 1

balderman
balderman

Reputation: 23815

Something like the below

lst = [1, 3, 5, 7, 12, 21, 11, 12, 13]
for idx in range(1, len(lst) - 1):
    if lst[idx] == (lst[idx - 1] + lst[idx + 1]) / 2:
        print(f'{lst[idx]} is AVG of {lst[idx - 1]} and {lst[idx + 1]}')

output

3 is AVG of 1 and 5
5 is AVG of 3 and 7
12 is AVG of 11 and 13

Upvotes: 1

Roy
Roy

Reputation: 344

You have problem at this line if i == (arr[i-1]+arr[i+1])/2. Here you are checking if the item is the average of the items at the index of (current value -1) and the (current value + 1). So let's say when we are checking for 3, we are checking indices arr[3-1] and arr[3+1]. This should be safe for now. But in the next iteration for 7, you are checking arr[7-1] and arr[7+1], arr[8] does not exist. Thus it is throwing index out of range.

Thus instead of iterating through the list items you need to iterate through list indices and access list items using the index. The loop will look something like below code:

arr = [1,3,5,7,12,21]
for i in range(len(arr)):
    if 0 < i < len(arr)-1:
        if arr[i] == (arr[i-1]+arr[i+1])//2:
            print(arr[i], "is the average of its neighbours")

It prints

3 is the average of its neighbours
5 is the average of its neighbours

Upvotes: 1

Neeraj Sharma
Neeraj Sharma

Reputation: 73

In the condition if i == (arr[i-1]+arr[i+1])/2: i is value of an array item not index. So when i become 12 or 21 it gets out of the index range of arr. Instead you can use for i in range(len(arr)): to get the index.

Upvotes: 1

Related Questions