At My Fingertips
Rapid Playground
Have a look at these geometric figures:
A | B | C | D | E |
---|---|---|---|---|
Here are some similarities:
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:
corners
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.
How would you decompose a regular polygon, given that you have functions to create a rectangle, triangle, ellipse, and circular_sector?
Yes, you can decompose the polygon into triangles, one triangle per side.
Hint: You may want to use empty_graphic, compose, and a for-loop.
Let's try different numbers of corners:
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 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
PyTamaro is a project created by the Lugano Computing Education Research Lab at the Software Institute of USI
Privacy Policy • Platform Version 79aacf0 (Fri, 08 Nov 2024 13:24:29 GMT)