Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Similar Triangles by ___1981
from typing import List, Tuple
Coords = List[Tuple[int, int]]
# Check similay of two triangles using : "All the corresponding sides have lengths in the same ratio."
def similar_triangles(coords_1: Coords, coords_2: Coords) -> bool:
# Function of distance between two points, no need to do square root.
dis = lambda x,y: ((x[0]-y[0])**2 + (x[1]-y[1])**2)
# For convenience
l1 = coords_1 + [coords_1[0]]
l2 = coords_2 + [coords_2[0]]
# List of sides of triangles.
# Sorted so they're corresponding.
ld1 = sorted([dis(l1[i],l1[i+1]) for i in range(3)])
ld2 = sorted([dis(l2[i],l2[i+1]) for i in range(3)])
# Check ratio.
# I'd use Fraction(x,y) but it's stated in line 2 the coords are int,
# and in precondition it said -10 ≤ (x, y) coordinate ≤ 10.
# Figured / wouldn't make much difference.
return ld1[0]/ld2[0] == ld1[1]/ld2[1] == ld1[2]/ld2[2]
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 22, 2021