pythonalgorithmset-theory

Using set theory to find the shape area in Python


So I'm given the following diagram:

enter image description here

And I'm being asked to find the area of each polygon given n. The area is basically the sum of all blue squares since each square has an area of 1. So when n = 1, the area is one. When n = 2, the area is 5. Because of the relationship between each polygon, I know that I could knock this down using set theory.

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

However, I didn't have as much luck trying to represent this in code:

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

For example: For n = 2, I'm getting an output of 9 instead of 5.


Solution

  • You were close :-)

    Here are the small fix-ups:

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

    Running this:

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

    Gives this output:

    1 1
    2 5
    3 13
    4 25
    5 41