Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Strictly int math; no floats or Fractions solution in Clear category for Similar Triangles by rossras
from functools import reduce
from operator import mul
from typing import List, Tuple
Coords = List[Tuple[int, int]]
def sq_dist(p, q):
return (sum((px - qx)**2 for px, qx in zip(p, q)))
def sq_sides(coords):
a,b,c = coords
return sorted((sq_dist(a,b), sq_dist(b,c), sq_dist(a,c)))
def similar_triangles(coords1: Coords, coords2: Coords) -> bool:
# Determine whether two triangles are similar. Check ratios of sorted side
# lengths for a consistent ratio. To ensure integer results for integer
# inputs, use squared side lengths and scale up numerator lengths by the
# product of denominator lengths prior to division
sides1, sides2 = (sq_sides(c) for c in (coords1, coords2))
scale = reduce(mul, sides2)
ratios = (n*scale//d for n, d in zip(sides1, sides2))
if len(set(ratios)) == 1:
return True
return False
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!")
Feb. 15, 2020
Comments: