I was doing a python challenge and this one stumped me. This is the input matrix (numpy format):
# [[1, 7, 2, 2, 1],
# [7, 7, 9, 3, 2],
# [2, 9, 4, 4, 2],
# [2, 3, 4, 3, 2],
# [1, 2, 2, 7, 1]]
and the function would output this matrix
# [[False, True, False, False, False],
# [True, False, True, False, False],
# [False, True, False, True, False],
# [False, False, False, False, False],
# [False, False, False, True, False]]
And you can see the value will be 'true' if any (up/down/left/right) neighbor is 2 smaller than itself. We've been learning numpy, but this doesn't feel like it's too much of a numpy thing).
I tried to do simple if comparison=true checks, but I kept stumbling into out-of-index errors and I couldnt find any way to circumvent/ignore those.
Thanks in advance.
This is the essence of what I've tried so far. I've simplified the task here to simply check the first row horizontally. If I could get this to work, I would extend it to check the next row horizontally until the end, and then I would do the same thing but vertically.
import numpy as np
ex=np.array([[7, 2, 3, 4, 3, 4, 7]])
def count_peaks(A):
matrixHeight=A.shape[0]
matrixWidth=A.shape[1]
peakTable=np.zeros(shape=(matrixHeight,matrixWidth))
for i in range(matrixWidth):
if A[i]-A[i+1]>=2 or A[i]-A[i-1]>=2:
peakTable[0,i]=1
return peakTable
... which of course outputs:
IndexError: index 1 is out of bounds for axis 0 with size 1
as I'm trying to find the value of A[-1] which doesn't exist.