Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Triangle(object):
- def __init__(self, line):
- split_line = line.split(',')
- self.vertices = (Point(int(split_line[0]), int(split_line[1])),
- Point(int(split_line[2]), int(split_line[3])),
- Point(int(split_line[4]), int(split_line[5])))
- def edge_lines(self):
- for i in range(len(self.vertices)):
- yield EdgeLine(self.vertices[i], self.vertices[(i + 1) % len(self.vertices)])
- class Point(object):
- def __init__(self, x, y):
- self.x = x
- self.y = y
- def __eq__(self, other):
- return self.x == other.x and self.y == other.y
- class EdgeLine(object):
- def __init__(self, start, end):
- self.start = start
- self.end = end
- def slope(self):
- if self.start.x == self.end.x:
- return 1e10
- return (float(self.start.y) - self.end.y) / (self.start.x - self.end.x)
- def y_intercept(self):
- return self.start.y - self.slope() * self.start.x
- def __eq__(self, other):
- return self.start == other.start and self.end == other.end \
- or self.end == other.start and self.start == other.end
- class TriangleFile(object):
- def __init__(self, file):
- self.file = file
- def triangles(self):
- for line in self.file:
- yield Triangle(line)
- def y_intercept_is_on_segment(edge_line):
- y_intercept = edge_line.y_intercept()
- return y_intercept >= edge_line.start.y and y_intercept <= edge_line.end.y \
- or y_intercept <= edge_line.start.y and y_intercept >= edge_line.end.y
- def contains_origin(triangle):
- edge_lines = list(triangle.edge_lines())
- return any(edge_line.y_intercept() > 0 and y_intercept_is_on_segment(edge_line) for edge_line in edge_lines) \
- and any(edge_line.y_intercept() < 0 and y_intercept_is_on_segment(edge_line) for edge_line in edge_lines)
- if __name__ == "__main__":
- with open("triangles.txt") as file:
- triangle_file = TriangleFile(file)
- count = 0
- for triangle in triangle_file.triangles():
- if contains_origin(triangle):
- count += 1
- print count
Add Comment
Please, Sign In to add comment