我是 python 和一般编程的新手。我编写了一个函数,它将搜索数组中的相邻元素并查找值彼此相差在 0.05 以内的元素,就像 floodfill 算法一样。唯一的区别是我在计算函数运行次数时做了一些愚蠢的事情(我想这也会告诉我找到了多少元素),所以我的计数器值是错误的。该代码在查找彼此相距 0.05 以内的相邻元素时有效,只是计数很有趣。
def floodcount (x,y,array,value,count=0): #akin to a bucket fill in paint, finds the area instead
nrows = len(array)-1 #rows of the image
ncols = len(array[0])-1 #columns of the image
diff = array[x][y] - value
if (diff < 0.00) or (diff > 0.05): # the base case, finding a diff more than 0.05 or less than 0 is like finding a boundary
return 0
count = count +1
print 'count1 ',count
array[x][y] = -5 # so we do no calculate this pixel again
#print "[",x,",",y,"]"
if x > 0:
#print '1'# if not the first elemnet then can go back, this makes sure that x is within the array all the time
floodcount (x-1,y,array,value,count)
if y > 0:
#print '2'
floodcount (x,y-1,array,value,count)
if x < nrows:
#print '3'
floodcount (x+1,y,array,value,count)
if y < ncols:
#print '4'
floodcount (x,y+1,array,value,count)
if x > 0 and y > 0:
#print '5'
floodcount (x-1,y-1,array,value,count)
if x < nrows and y < ncols:
#print '6'
floodcount (x+1,y+1,array,value,count)
if x <nrows and y > 0:
#print '7'
floodcount (x+1,y-1,array,value,count)
if x > 0 and y < ncols:
#print '8'
floodcount (x-1,y+1,array,value,count)
print 'count2 ',count
return count
所以对于一个测试用例
数组 = [[5,1,1,3,4],[4,5,6,2,5],[5,8,5,5,9]] x=0 和 y=0
输出
count1 1 计数 1 2 计数 1 3 计数 1 4 计数 1 5 计数 2 5 计数 2 4 计数 2 3 计数 1 3 计数 2 3 计数 2 count2 1
如你所见,有些东西是可疑的 :P 谁能指出我做错了什么?任何帮助将不胜感激。
最佳答案
所以 floodcount()
返回新的 count
值。但是你永远不会存储/使用它:)
像这样替换行:
floodcount(x+1, y-1, array, value, count)
与:
count = floodcount(x+1, y-1, array, value, count)
关于python - 递归函数中的计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8500627/