pythonmax

Python - How to find the maximum number comparing to all its neighbors


I have a problem to solve with a Python code.

I try with this code but it doesn't return the correct T.

def findmaximun(M):
    # Write your code here
    r, c = len(M),len(M[0])
    T = [[1 for col in range(c)] for row in range(r)]
    for i in range(0,r):
        for j in range(0,c): 
            for k in [-1,0,1]:
                if i+k>=0 and i+k<r:
                    for l in [-1,0,1]:
                        if j+l>=0 and j+l<c and max(-i-k,0)!=max(-j-l,0):
                            if M[i][j] <= M[i+k][j+l]:
                                      T[i][j]=0                
    return(T)

Solution

  • my solution is very explicit. I'm sure there is a more elegant way of handling the edge cases, but it may not be as readable. Ideally one would use numpy for such a task. It's way faster and offers better indexing and array operations. Also instead of typing out idx explicitly, one could use itertools.

    I validated the code with matplotlibs imshow

    import random
    
    r = 10
    c = 15
    
    M = []
    for i in range(r):
        M.append([])
        for j in range(c):
            M[i].append(random.random())
    
    
    def find_max(M):
        # Setup array dimensions and output array
        r, c = len(M), len(M[0])
        T = [[0 for col in range(c)] for row in range(r)]
        # iterate over array
        for i, row in enumerate(M):
            for j, elem in enumerate(row):
                # handle edge cases (literally!)
                if i == 0:
                    if j==0:
                        idx = [(1,0), (1,1), (0,1)]
                    elif j==c-1:
                        idx = [(1,0), (1,-1), (0,-1)]
                    else:
                        idx = [(1,0), (1,1), (0,1), (1,-1), (0,-1)]
                elif i==r-1:
                    if j==0:
                        idx = [(-1,0), (-1,1), (0,1)]
                    elif j==c-1:
                        idx = [(-1,0), (-1,-1), (0,-1)]
                    else:
                        idx = [(-1,0), (-1,1), (0,1), (-1,-1), (0,-1)]
                else:
                    if j==0:
                        idx = [(-1,0), (-1,1), (0,1), (1,1), (1,0)]
                    elif j==c-1:
                        idx = [(-1,0), (-1,-1), (0,-1), (1,-1), (1,0)]
                    else:
                        idx = [(0,1), (1,1), (1,0), (1,-1), (0,-1), (-1,-1), (-1,0), (-1,1)]
                # get the neighbors
                neighbors = []
                for x, y in idx:
                    neighbors.append(M[i + x][j + y])
                # calculate t    
                if elem > max(neighbors):
                    T[i][j] = 1
        return T
    T = find_max(M)