"""
Ex 6.9 from "A primer on..."
Modify code from ex. 3.16 (or 4.4 in the Exercises booklet)
to make the argument a dict instead of a list.
Steps:
1. Start with the function and test function from exercise 4.4 in the
exercise booklet.
2. Modify the test function to give the vertices as a dictionary
on the format given in the question text. This makes the code fail, since
the function triangle_area still expects a list
3. Modify how the argument is treated inside triangle_area, to look up a dictionary
rather than index a list.
"""
def triangle_area(v):
# v is a dictionary with keys 1,2,3, and coordinates as values
[x1,y1] = v[1]
[x2,y2] = v[2]
[x3,y3] = v[3]
# or more verbose code:
# x1 = v[0][0]; y1 = v[0][1] etc
A = abs(0.5*( (x2*y3)-(x3*y2)-(x1*y3)+(x3*y1)+(x1*y2)-(x2*y1) ))
return A
# From book
def test_triangle_area():
"""
Verify the area of a triangle with vertex coordinates
(0,0), (1,0), and (0,2).
"""
v1 = (0,0); v2 = (1,0); v3 = (0,2)
vertices = {1:v1,2:v2,3:v3} #[v1, v2, v3]
expected = 1
computed = triangle_area(vertices)
tol = 1E-14
success = abs(expected - computed) < tol
msg = f"computed area={computed} != {expected}(expected)"
assert success, msg
test_triangle_area()
"""
Terminal> python area_triangle_dict.py
"""