首页 > 解决方案 > 在二维数组中查找局部最大值。Python

问题描述

不知道函数式编程怎么写?我在编程范例中制作了这段代码。我用过摩尔社区。

需要在给定的二维数组局部最大值中找到最大值。局部最大值是一个元素,一个比所有邻居都重要的值。

我如何理解函数式编程:

仅使用函数调用、基于其他函数调用的匿名函数定义、递归、实现函数式编程可能性的特殊函数;禁止使用循环、条件运算符、赋值运算符、控制运算符(返回除外)。

编程范式。

with open("matrix.txt", "r") as file:
    txtMatrix = file.read()
    txtMatrix += "\0"
# matrix =1 3 9 3
#         2 3 2 1
#         2 5 1 7
#         1 2 3 4

counterColumn = 0
counterRow = 0
txtNumber = ""

matrix = [[]]
for i in range(len(txtMatrix)):
    if txtMatrix[i] == " " or txtMatrix[i] == "\0":
        matrix[counterRow].append(int(txtNumber))
        counterColumn += 1
        txtNumber = ""
    elif txtMatrix[i] == "\n":
        matrix[counterRow].append(int(txtNumber))
        matrix.append([])
        counterRow += 1
        counterColumn = 0
        txtNumber = ""
    else:
        txtNumber += txtMatrix[i]

print(matrix)

localMax = []
maxInLocalMax = matrix[0][0]
print("Local maxes:")
for i in range(0, len(matrix)):
    for j in range(0, len(matrix[i])):
        localMax.append(matrix[i][j])
        #RU Соседство определяется по окрестности Мура
        #ENG Neighborhood is determined by the neighborhood of Moore
        for k in range(-1, 2):
            if (i == 0 and k == -1) or (i == len(matrix) - 1 and k == 1): continue
            for l in range(-1, 2):
                if (j == 0 and l == -1) or (j == len(matrix[i]) - 1 and l == 1): continue
                if localMax[len(localMax) - 1] < matrix[i + k][j + l]:
                    localMax[len(localMax) - 1] = matrix[i + k][j + l]

        print(localMax[len(localMax) - 1], end=' ')
        if maxInLocalMax < localMax[len(localMax) - 1]: maxInLocalMax = localMax[len(localMax) -1]
    print()

# print("Max in localMax: " )#, end=''
# print(maxInLocalMax)

#Output:
#Local maxes:
#3 9 9 9 
#5 9 9 9 
#5 5 7 7 
#5 5 7 7 

我试图在函数式编程中编写代码,但它不是那么正确。

# Function to find minimum and maximum position in list
def maxminposition(A, n):
   # inbuilt function to find the position of minimum 
   minposition = A.index(min(A))
   # inbuilt function to find the position of maximum 
   maxposition = A.index(max(A)) 
   print ("The maximum is at position::", maxposition + 1) 
   print ("The minimum is at position::", minposition + 1)
# Driver code
A=list()
n=int(input("Enter the size of the List ::"))
print("Enter the Element ::")
for i in range(int(n)):
   k=int(input(""))
   A.append(k)
maxminposition(A,n)

标签: pythonarrayslocalmaxima

解决方案


推荐阅读