Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Intersection of Line Segments. Here is a class for line segments that stores lin

ID: 3863060 • Letter: I

Question

Intersection of Line Segments. Here is a class for line segments that stores line segments by the coordinates of their end-points. class LineSegment(): def _____ init _____ (self, x1, y1, x2, y2): self.x1 = x1 self.x2 = x2 self.y1 = y1 self.y2 = y2 def intersect(self, other): # ... # returns the coordinates of the intersection point of self and other # returns None if there is no intersection point # can assume line segments are not parallel Implement the intersect function for the line segment class. You can assume that the line segments are not parallel. The function should return None if the line segments do not intersect.

Explanation / Answer

class LineSegment():
   def __init__(self, x1, y1, x2, y2):
       self.x1 = x1
       self.x2 = x2
       self.y1 = y1
       self.y2 = y2

   def intersect(self, other):
       slope1 = float(self.y2 - self.y1) / (self.x2 - self.x1)
       slope2 = float(other.y2 - other.y1) / (other.x2 - other.x1)

       x = (other.y1 - slope2 * other.x1 - self.y1 + slope1 * self.x1) / (slope1 - slope2);
       y = slope1 * (x - self.x1) + self.y1
       if (x - self.x1) * (x - self.x2) <= 0 and (x - other.x1) * (x - other.x2) <= 0 and (y - self.y1) * (y - self.y2) <= 0 and (y - other.y1) * (y - other.y2) <= 0:
           return [x, y]
       else:
           return None


x = LineSegment(0, 0, 5, 5)
y = LineSegment(3, 0, 0, 3)
print x.intersect(y)

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote