Python

Нужна программа на питоне

Напишите класс отрезков на прямой Segment. Класс должен иметь два поля (две переменных класса):
start_point: float
end_point: float
При инициализации объекта класса Segment в качестве аргументов конструктора должны передаваться два вещественных значения (float), при этом значение поля класса start_point должно оказаться меньше либо равно значению end_point.
Класс должен иметь несколько методов:
Метод, возвращающий длину отрезка length();
Метод, возвращающий новый отрезок, являющийся пересечением двух intersection(other_segment); если отрезки не пересекаются, следует вернуть None;
Метод, возвращающий новый отрезок, являющийся объединением двух union(other_segment); если отрезки не пересекаются, условимся, что следует вернуть None.

 class Segment: 
def __init__(self, start_point: float, end_point: float):
self.start_point = start_point
self.end_point = end_point

# Return the length of the segment
def length(self):
return abs(self.start_point - self.end_point)

# Return the intersection of two segments
def intersection(self, other_segment):
# Check if the segments intersect
if self.end_point < other_segment.start_point or other_segment.end_point < self.start_point:
return None
else:
# Calculate the intersection
start_point = max(self.start_point, other_segment.start_point)
end_point = min(self.end_point, other_segment.end_point)
return Segment(start_point, end_point)

# Return the union of two segments
def union(self, other_segment):
# Check if the segments are disjoint
if self.end_point < other_segment.start_point or other_segment.end_point < self.start_point:
return None
else:
# Calculate the union
start_point = min(self.start_point, other_segment.start_point)
end_point = max(self.end_point, other_segment.end_point)
return Segment(start_point, end_point)
Евгений Евстафьев
Евгений Евстафьев
13 649
Лучший ответ
 from math import sqrt  



class Vector:



x_coor: float

y_coor: float



def __init__(self, _x_coor, _y_coor):

self.x_coor = _x_coor

self.y_coor = _y_coor



def length(self):

return sqrt(self.x_coor ** 2 + self.y_coor ** 2)



def get_unit_vector(self):

this_length = self.length()

return Vector(self.x_coor / this_length, self.y_coor / this_length)



def __add__(self, other):

new_x = self.x_coor + other.x_coor

new_y = self.y_coor + other.y_coor

return Vector(new_x, new_y)



def __sub__(self, other):

new_x = self.x_coor - other.x_coor

new_y = self.y_coor - other.y_coor

return Vector(new_x, new_y)



def __radd__(self, other):

self.x_coor += other.x_coor

self.y_coor += other.y_coor

return self



def __rsub__(self, other):

self.x_coor -= other.x_coor

self.y_coor -= other.y_coor

return self



def __mul__(self, other):

return self.x_coor * other.x_coor + self.y_coor * other.y_coor



def __str__(self):

return f'Vector({self.x_coor}, {self.y_coor})'