1.
The Pythagorean theorem lets us find the hypotenuse of a right triangle if we know the length of the two legs of the triangle. In this program, you will have a nested list that contains pairs of leg lengths (for example,
[3.0, 4.0]
is a sublist describing a triangle whose legs are 3.0 and 4.0 units long).Your job is to take this nested list and create a new list of the corresponding hypotenuse lengths.
Solution.
This solution does not use any functions
triangle_list = [[3.0, 4.0], [12.0, 5.0], [7.6, 3.2], [8.5, 10.4]]
hypotenuse_list = []
for sublist in triangle_list:
hypotenuse = (sublist[0] ** 2 + sublist[1] ** 2) ** 0.5
hypotenuse_list.append(hypotenuse)
print(f"Hypotenuses are {hypotenuse_list}.")
This solution uses a function for calculating the Pythagorean theorem.
def hypotenuse(first_leg, second_leg):
"""Return length of hypotenuse given leg lengths."""
result = (first_leg ** 2 + second_leg ** 2) ** 0.5
return result
triangle_list = [[3.0, 4.0], [12.0, 5.0], [7.6, 3.2], [8.5, 10.4]]
hypotenuse_list = []
for sublist in triangle_list:
hypotenuse_list.append(hypotenuse(sublist[0], sublist[1]))
print(f"Hypotenuses are {hypotenuse_list}.")