At My Fingertips

Documentation

Abstraction

Have a look at these geometric figures:

ABCDE
TriangleSquarePentagonOctagon11-gon

Here are some similarities:

  • In a given figure, all sides have the same length
  • In a given figure, all angles are the same

Figures like that are called regular polygon.

You may also notice that they are rotated such that their bottom side is always horizontal, which means that for polygons with an odd number of corners, the top corner is nicely centered.

def regular_polygon(...) -> Graphic:

We can see that the color differs, so we want to have a parameter to specify the color.

There are different approaches to unambiguously specify the shape. Here is one possible way:

  • the number of corners
  • the radius (radius of the circumscribed circle, distance from center to corner)

There would be other ways (e.g, to specify angles, the side lengths), but let's go with corners and radius. The following function signature reflects this choice:

def regular_polygon(radius: float, corners: int, color: Color) -> Graphic:

Note that the parameter corners has type int: the number of corners has to be an integer number. We can't have a polygon with, say, 2.5 corners.

Decomposition

How would you decompose a regular polygon, given that you have functions to create a rectangle, triangle, ellipse, and circular_sector?

Pentagon

Yes, you can decompose the polygon into triangles, one triangle per side.

Implementation

Hint: You may want to use empty_graphic, compose, and a for-loop.

Loading...

Play With Parameters

Let's try different numbers of corners:

Loading...

We see that a polygon with 4 corners is a square.

Your function should be able to create a triangle.

If you tried to create a degenerate polygon with two corners (a "digon"), the two triangles your function would create (with an angle of 180 degrees and two angles of 0 degrees) would have 0 area, and thus would become invisible. Even more degenerate would be a "monogon", a one-sided polygon, which most people would not consider to be a polygon. If you tried to construct a monogon with your function, and your function composes it from triangles, it would try to create a triangle with an angle of 360 degrees, which is impossible (and leads to a ValueError in the triangle function).

Save in Toolbox

Save the regular_polygon function in your toolbox. It can be useful in the future.


This activity has been created by LuCE Research Lab and is licensed under CC BY-SA 4.0.

Regular Polygon

Logo of PyTamaro

PyTamaro is a project created by the Lugano Computing Education Research Lab at the Software Institute of USI

Privacy PolicyPlatform Version 0d7866a (Fri, 20 Dec 2024 07:46:38 GMT)