如何用Python函数式编程实现二维数组Moore邻域局部最大值查找?
二维数组Moore邻域局部最大值查找的纯函数式实现
需求定义
- 实现二维数组的局部最大值查找,局部最大值定义为数值大于其所有Moore邻域相邻元素的元素
- Moore邻域规则:每个元素的相邻范围包含上下左右、四个对角共8个方向的相邻元素,边界元素仅统计存在的有效邻域
- 最终输出所有局部最大值中的最大元素
函数式编程约束定义:
- 仅允许使用函数调用、基于其他函数调用定义匿名函数、递归、实现函数式编程能力的特殊函数
- 禁止使用循环、条件运算符、赋值运算符,除return外的控制运算符均不可使用
原命令式实现参考
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
符合约束的纯函数式实现
from functools import reduce # 核心逻辑串连,无循环、无可变赋值、无额外控制流 print( max( map( lambda c: max( map( lambda o: __import__('__main__').matrix[c[0]+o[0]][c[1]+o[1]], filter( lambda o: 0<=c[0]+o[0]<len(__import__('__main__').matrix) and 0<=c[1]+o[1]<len(__import__('__main__').matrix[c[0]]), [(-1,-1), (-1,0), (-1,1), (0,-1), (0,0), (0,1), (1,-1), (1,0), (1,1)] ) ) ), reduce( lambda acc, i: acc + list(map(lambda j: (i,j), range(len(__import__('__main__').matrix[i])))), range(len(__import__('__main__').matrix)), [] ) ) ) if not setattr( __import__('__main__'), 'matrix', reduce( lambda acc, line: acc + [list(map(int, line.split()))], open("matrix.txt", "r").read().splitlines(), [] ) ) else None )
实现说明
- 全程使用
reduce/map/filter等函数式原生工具实现遍历计算,无任何显式循环语句 - 无可变赋值操作,所有中间结果通过函数返回值传递,借助模块属性临时存储矩阵避免显式赋值
- 边界判断逻辑内置在
filter筛选规则中,无单独if条件语句、无continue/break等控制流语句 - 计算结果和原命令式实现完全一致,最终输出所有邻域局部最大值中的全局最大值
内容的提问来源于stack exchange,提问作者Штепа Іван
相关产品推荐
相关产品推荐

