使用集合论找到 Python 中的形状区域

Using set theory to find the shape area in Python

所以我得到了下图:

我被要求找出给定 n 的每个多边形的面积。该面积基本上是所有蓝色方块的总和,因为每个方块的面积为 1。因此当 n = 1 时,面积为 1。当n = 2时,面积为5。由于每个多边形之间的关系,我知道我可以用集合论来解决这个问题。

n  Area(n)

1  1
2  A(n-1) + (4 * (n-1)) = 5
3  A(n-1) + (4 * (n-1)) = 13
4  A(n-1) + (4 * (n-1)) = 25
5  A(n-1) + (4 * (n-1)) = 41

但是,我没有那么幸运地尝试用代码表示它:

def shapeArea(n):
    prev_output = 0
    output = 0

    if n == 1:
        output = 1
    elif n > 1:
        for i in range(n):
            prev_output = n-1 + (4 * (n-1))

    output = prev_output + (4 * (n-1))

    return output

例如:对于 n = 2,我得到的输出是 9 而不是 5。

你很接近:-)

以下是小修正:

def shapeArea(n):
    output = 1
    for i in range(1, n):
        output += 4 * i
    return output

运行这个:

for n in range(1, 6):
    print(n, shapeArea(n))

给出此输出:

1 1
2 5
3 13
4 25
5 41

在递归解决方案中,从您的逻辑来看它要简单得多。

def shape_area(n):
    if n == 1:
        return 1
    return shape_area(n-1) + 4*(n-1)

你可以用高斯的技巧来做一个闭式公式:

2*Area(n) = 

    1   +   4    +    8    +   12   + ... + 4(n-1)
+
    1   + 4(n-1) +  4(n-2) + 4(n-3) + ... +   4 
--------------------------------------------------
    2   +  4n    +   4n    +   4n   + ... +  4n

= (n-1)4n + 2
= 4n^2 - 4n + 2

所以面积(n) = 2n2 - 2n + 1

当然,使用高斯定理,代码将如下所示:

def ShapeArea(n):
    return 2*(n**2) - (2*n)+1