 # pyFindOddTriangle

Aug 11th, 2022
721
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. # Given the coordinates of the points of a set of triangles, find the odd one out
2. # The triangles are of similar shapes, but different sizes and rotations
3. # One triangle is a mirror image
4. # Mike Kerry - August 2022
5. # acclivity2@gmail.com
6.
7. import math
8. rad2deg = 180/math.pi
9.
10.
11. def get_length_and_slope(t, w, v):
12.     # Compute the length of one side of a triangle
13.     # and the bearing of the end point from the start point
14.     # t points to a triangle. w and v refer to 2 points of the triangle
15.
16.     dx = t[v] - t[w]      # x-axis distance between points
17.     dy = t[v] - t[w]      # y-axis distance between points
18.
19.     # math.hypot calculates a hypotoneuse    sqrt(dx*dx + dy*dy)
20.     lgth = math.hypot(dx, dy)
21.
22.     # atan2 computes a bearing between 2 points, between -pi and +pi radians
23.     # given x and y axis distances dx and dy between the 2 points
24.     ang = rad2deg * math.atan2(dy, dx)
25.     return lgth, ang
26.
27.
28. a = [(3.0, 6.0), (3.0, 3.0), (7.0, 3.0)]
29. b = [(4.4, 3.2), (4.4, 5.0), (2.0, 5.0)]
30. c = [(3.0, 5.2), (5.4, 5.2), (5.4, 2.0)]
31. d = [(4.0, 1.0), (5.5, 1.0), (5.5, 3.0)]
32. arr = [a, b, c, d]
33.
34.
35. for j, tri in enumerate(arr):
36.     print("\nTRIANGLE: ", chr(ord('A') + j))       # TRIANGLE: A thru D
37.     # Assume the points of the triangle are labelled p, q and r
38.     # Hence the sides are pq, qr, and pr
39.     p, q, r = 0, 1, 2
40.     lenpq, slopepq = get_length_and_slope(tri, p, q)
41.     lenqr, slopeqr = get_length_and_slope(tri, q, r)
42.     lenpr, slopepr = get_length_and_slope(tri, p, r)
43.     circ = lenpq + lenqr + lenpr    # total circumference of triangle
44.     # for each side, compute its proportion of the overall circumference
45.     percentpq = lenpq * 100 / circ
46.     percentqr = lenqr * 100 / circ
47.     percentpr = lenpr * 100 / circ
48.     print(f"Percentages: {percentpq:.0f} {percentqr:.0f} {percentpr:.0f}")
49.
50.     # compute the directed angle at point q (between sides pq and qr)
51.     angleq = slopeqr - slopepq
52.     print(f"Angle q: {angleq:.1f}")
53.
54. # Results:
55. # TRIANGLE:  A
56. # Percentages: 25 33 42
57. # Angle q: 90.0
58. #
59. # TRIANGLE:  B
60. # Percentages: 25 33 42
61. # Angle q: 90.0
62. #
63. # TRIANGLE:  C
64. # Percentages: 25 33 42
65. # Angle q: -90.0
66. #
67. # TRIANGLE:  D
68. # Percentages: 25 33 42
69. # Angle q: 90.0
70.
71. # From the above, we can see that triangle C is the odd one.
72. # Its angle 'q' is reversed compared to the other three triangles
73.
74. print(math.pi)
75.
76.
77.
78.
79.