0

I will like to find out the numbers in an array which is equal to the arithmetic mean of their immediate neighbors.The twist here is to use 0 if a[i-1] or a[i+1] does not exist.

For example:

a =  [2,4,6,8,2,5]
a[0] = (0 + 4)/2 = 2 ----count 1
a[1] = (2 + 6)/2 = 4---- count 2
a[5] = (2 + 0)/2 != 5 ----no count

If it is not, it should be a count of 0. I have written the below code but it won't work for all the arrays, like this one. How can I do it?

a = [100, 110, 120, 130, 140, 150, 160, 170, 180, 190]

My code:

def countMeans(a):
    count = 0
    for i in range(1, len(a)-1):
        if a[i-1]+ a[i+1] is 2 * a[i]:
            count += 1
    return count
  • See [is operator behaves unexpectedly with integers](https://stackoverflow.com/questions/306313/is-operator-behaves-unexpectedly-with-integers) – Tomerikoo Nov 23 '20 at 08:19

3 Answers3

1

As per your new update, use the following code:

def countMeans(a):
    count = 0
    if len(a) > 1:
        for i in range(0, len(a)):
            val1 = 0 if i == 0 else a[i-1]
            try:
                val2 = a[i+1]
            except:
                val2 = 0
            if val1 + val2 == 2 * a[i]:
                count += 1
    else:
        count = 1 if a[0] == 0 else 0
    return count
theashwanisingla
  • 417
  • 3
  • 12
1

Let me know if I got this right.

def countMeans(a):
    count = 0
    if (a[1]/2) == a[0]:
        count +=1
    for i in range(1, len(a)-1):
        if (a[i-1] + a[i+1])/2 == a[i]:
            count += 1
    if (a[-2]/2) == a[-1]:
        count +=1
    return count

a =  [2,4,6,8,2,5]
print (countMeans(a))

a = [100, 110, 120, 130, 140, 150, 160, 170, 180, 190]
print (countMeans(a))

The output for this is:

3
8
Joe Ferndz
  • 8,163
  • 2
  • 11
  • 32
0

Use == instead of is while comparing the values. Use the following snippet:

def countMeans(a):
    count = 0
    for i in range(1, len(a)-1):
        if a[i-1]+ a[i+1] == 2 * a[i]:
            count += 1
    return count

Remember is operator defines if both the variables point to the same object whereas the == sign checks if the values for the two variables are the same.

theashwanisingla
  • 417
  • 3
  • 12