python怎么来算面积_如何在Python中计算一个总面积表?

博主在实现Python中的Summed Area Table算法时遇到了问题,代码在更新二维数组时出现了错误,导致结果不正确。问题在于就地更新列表时的逻辑错误。尽管尝试了两种迭代方法,但结果始终不匹配手动计算。博客寻求对问题原因的解答,以及可能的就地更新替代方案。
摘要由CSDN通过智能技术生成

我在Python中计算求和面积表(https://en.wikipedia.org/wiki/Summed_area_table)时遇到问题。最明显的算法是在引用已经编写好的元素的同时就地更新列表元素……但是关于就地更新的一些内容似乎让Python感到困惑。在

下面是一些示例代码:def compute_summed_area_table(image):

# image is a 2-dimensional array containing ints or floats, with at least 1 element.

height = len(image)

width = len(image[0])

new_image = [([0.0] * width)] * height # Create an empty summed area table

for row in range(0, height):

for col in range(0, width):

if (row > 0) and (col > 0):

new_image[row][col] = image[row][col] + \

new_image[row][col - 1] + new_image[row - 1][col] - \

new_image[row - 1][col - 1]

elif row > 0:

new_image[row][col] = image[row][col] + new_image[row - 1][col]

elif col > 0:

new_image[row][col] = image[row][col] + new_image[row][col - 1]

else:

new_image[row][col] = image[row][col]

# Note that two-pass code gives the same kind of results, e.g.:

# for row in range(0, height):

# for col in range(0, width):

# if col > 0:

# new_image[row][col] = image[row][col] + new_image[row][col - 1]

# else:

# new_image[row][col] = image[row][col]

# for row in range(0, height):

# for col in range(0, height):

# if row > 0:

# new_image[row][col] += new_image[row - 1][col]

return new_image

small_image = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25]]

small_sat = compute_summed_area_table(small_image)

print(small_sat)

根据我自己的手动计算(可能出错),此测试代码应给出如下内容:

[[1,3,6,10,15],[7,16,27,40,55],[18,39,63,90,120],[34,72,114,160,210],[55,115,180,250,325]]

相反,它给出了:

[[55,61,68,76,85],[55,61,68,76,85],[55,61,68,76,85],[55,61,68,76,85],[55,61,68,76,85]]

很明显,在每一行迭代中更新每一行,但我不确定确切的原因或方式。有人知道到底出了什么问题吗?有没有其他方法可以进行就地更新?如果没有,你会如何处理?在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值