Add optimized path to Points

This commit is contained in:
2024-06-11 17:39:17 +02:00
parent ac86f8588e
commit 9c215a5d24
4 changed files with 55 additions and 14 deletions

View File

@@ -34,6 +34,32 @@ class Point3D:
"""
return min(points, key=lambda point: self.distance(point))
def optimized_path(self, points: List["Point3D"]):
"""Get an optimized ordered path starting from the current point.
From: https://stackoverflow.com/questions/45829155/sort-points-in-order-to-have-a-continuous-curve-using-python
Args:
points (List[Point2D]): List of 3d-points. Could contain the current point.
Returns:
List[Point2D]: Ordered list of 3d-points starting from the current point.
>>> Point3D(-2, -5, 6).optimized_path([Point3D(0, 0, 7), Point3D(10, 5, 1), Point3D(1, 3, 3)])
[Point3D(x: -2, y: -5, z: 6), Point3D(x: 0, y: 0, z: 7), Point3D(x: 1, y: 3, z: 3), Point3D(x: 10, y: 5, z: 1)]
"""
start = self
if start not in points:
points.append(start)
pass_by = points
path = [start]
pass_by.remove(start)
while pass_by:
nearest = min(pass_by, key=lambda point: point.distance(path[-1]))
path.append(nearest)
pass_by.remove(nearest)
return path
def round(self, ndigits: int = None) -> "Point3D":
self.x = round(self.x, ndigits)
self.y = round(self.y, ndigits)