Guest User

Untitled

a guest
Jan 23rd, 2018
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.13 KB | None | 0 0
  1. class Triangle(object):
  2. def __init__(self, line):
  3. split_line = line.split(',')
  4. self.vertices = (Point(int(split_line[0]), int(split_line[1])),
  5. Point(int(split_line[2]), int(split_line[3])),
  6. Point(int(split_line[4]), int(split_line[5])))
  7.  
  8. def edge_lines(self):
  9. for i in range(len(self.vertices)):
  10. yield EdgeLine(self.vertices[i], self.vertices[(i + 1) % len(self.vertices)])
  11.  
  12. class Point(object):
  13. def __init__(self, x, y):
  14. self.x = x
  15. self.y = y
  16.  
  17. def __eq__(self, other):
  18. return self.x == other.x and self.y == other.y
  19.  
  20. class EdgeLine(object):
  21. def __init__(self, start, end):
  22. self.start = start
  23. self.end = end
  24.  
  25. def slope(self):
  26. if self.start.x == self.end.x:
  27. return 1e10
  28.  
  29. return (float(self.start.y) - self.end.y) / (self.start.x - self.end.x)
  30.  
  31. def y_intercept(self):
  32. return self.start.y - self.slope() * self.start.x
  33.  
  34. def __eq__(self, other):
  35. return self.start == other.start and self.end == other.end \
  36. or self.end == other.start and self.start == other.end
  37.  
  38. class TriangleFile(object):
  39. def __init__(self, file):
  40. self.file = file
  41.  
  42. def triangles(self):
  43. for line in self.file:
  44. yield Triangle(line)
  45.  
  46. def y_intercept_is_on_segment(edge_line):
  47. y_intercept = edge_line.y_intercept()
  48. return y_intercept >= edge_line.start.y and y_intercept <= edge_line.end.y \
  49. or y_intercept <= edge_line.start.y and y_intercept >= edge_line.end.y
  50.  
  51. def contains_origin(triangle):
  52. edge_lines = list(triangle.edge_lines())
  53. return any(edge_line.y_intercept() > 0 and y_intercept_is_on_segment(edge_line) for edge_line in edge_lines) \
  54. and any(edge_line.y_intercept() < 0 and y_intercept_is_on_segment(edge_line) for edge_line in edge_lines)
  55.  
  56. if __name__ == "__main__":
  57. with open("triangles.txt") as file:
  58. triangle_file = TriangleFile(file)
  59. count = 0
  60. for triangle in triangle_file.triangles():
  61. if contains_origin(triangle):
  62. count += 1
  63. print count
Add Comment
Please, Sign In to add comment