Python: Find the coordinates of a triangle with the given side lengths
Python Programming Puzzles: Exercise-31 with Solution
Triangle Coordinates Finder
Write a Python program to find the coordinates of a triangle with given side lengths.
Input: [3, 4, 5] Output: [[0.0, 0.0], [3, 0.0], [3.0, 4.0]] Input: [5, 6, 7] Output: [[0.0, 0.0], [5, 0.0], [3.8, 5.878775382679628]]
Visual Presentation:
Sample Solution:
Python Code:
# License: https://bit.ly/3oLErEI
# Define a function named 'test' that takes a list 'sides' representing the side lengths of a triangle
def test(sides):
# Sort the side lengths in ascending order and assign them to variables a, b, and c
a, b, c = sorted(sides)
# Calculate the semi-perimeter of the triangle
s = sum(sides) / 2
# Use Heron's formula to calculate the area of the triangle
area = (s * (s - a) * (s - b) * (s - c)) ** 0.5
# Calculate the height of the triangle
y = 2 * area / a
# Calculate the x-coordinate of the third vertex using the Pythagorean theorem
x = (c ** 2 - y ** 2) ** 0.5
# Return the coordinates of the vertices of the triangle as a list of lists
return [[0.0, 0.0], [a, 0.0], [x, y]]
# Assign a specific list of side lengths 'sides' to the variable
sides = [3, 4, 5]
# Print the side lengths of the triangle
print("Sides of the triangle:", sides)
# Print a message indicating the operation to be performed
print("Coordinates of a triangle with the said side lengths:")
# Print the result of the test function applied to the 'sides' list
print(test(sides))
# Assign another specific list of side lengths 'sides' to the variable
sides = [5, 6, 7]
# Print the side lengths of the triangle
print("\nSides of the triangle:", sides)
# Print a message indicating the operation to be performed
print("Coordinates of a triangle with the said side lengths:")
# Print the result of the test function applied to the 'sides' list
print(test(sides))
Sample Output:
Sides of the triangle: [3, 4, 5] Coordinates of a triangle with the said side lengths: [[0.0, 0.0], [3, 0.0], [3.0, 4.0]] Sides of the triangle: [5, 6, 7] Coordinates of a triangle with the said side lengths: [[0.0, 0.0], [5, 0.0], [3.8, 5.878775382679628]]
Flowchart:
Python Code Editor :
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Find the list that has fewer total characters (including repetitions).
Next: Rescale and shift numbers so that they cover the range [0, 1].
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/python-exercises/puzzles/python-programming-puzzles-31.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics