Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Second (used helper methods, thx to drednout) solution in Clear category for Similar Triangles by Ali.Pxl
from typing import List, Tuple
import math
Coords = List[Tuple[int, int]]
def tri_sides(coords):
sides = []
sides.append(math.sqrt((coords[1][0] - coords[0][0])**2 + (coords[1][1] - coords[0][1])**2))
sides.append(math.sqrt((coords[2][0] - coords[1][0])**2 + (coords[2][1] - coords[1][1])**2))
sides.append(math.sqrt((coords[2][0] - coords[0][0])**2 + (coords[2][1] - coords[0][1])**2))
return sides
def tri_angles(sides):
angles = []
angles.append(math.acos((sides[1]**2 + sides[2]**2 - sides[0]**2) / (2*sides[1]*sides[2])))
angles.append(math.acos((sides[0]**2 + sides[2]**2 - sides[1]**2) / (2*sides[0]*sides[2])))
angles.append(math.acos((sides[0]**2 + sides[1]**2 - sides[2]**2) / (2*sides[0]*sides[1])))
return angles
def similar_triangles(coords_1: Coords, coords_2: Coords) -> bool:
# Goal: get angles of each triangle then compare them
# (procedure)
# getting the lengths of each side
# using sides' lengths to get the angles
# compare: if equal return true, otherwise return false
sides1 = tri_sides(coords_1)
angles1 = tri_angles(sides1)
sides2 = tri_sides(coords_2)
angles2 = tri_angles(sides2)
return set(angles1) == set(angles2)
if __name__ == '__main__':
print("Example:")
print(similar_triangles([(0, 0), (1, 2), (2, 0)], [(3, 0), (4, 2), (5, 0)]))
# These "asserts" are used for self-checking and not for an auto-testing
assert similar_triangles([(0, 0), (1, 2), (2, 0)], [(3, 0), (4, 2), (5, 0)]) is True, 'basic'
assert similar_triangles([(0, 0), (1, 2), (2, 0)], [(3, 0), (4, 3), (5, 0)]) is False, 'different #1'
assert similar_triangles([(0, 0), (1, 2), (2, 0)], [(2, 0), (4, 4), (6, 0)]) is True, 'scaling'
assert similar_triangles([(0, 0), (0, 3), (2, 0)], [(3, 0), (5, 3), (5, 0)]) is True, 'reflection'
assert similar_triangles([(1, 0), (1, 2), (2, 0)], [(3, 0), (5, 4), (5, 0)]) is True, 'scaling and reflection'
assert similar_triangles([(1, 0), (1, 3), (2, 0)], [(3, 0), (5, 5), (5, 0)]) is False, 'different #2'
print("Coding complete? Click 'Check' to earn cool rewards!")
July 28, 2023
Comments: