import numpy as np def simplify_coordinates(coordinates, tolerance): coordinates = np.array(coordinates) # Convert to NumPy array if len(coordinates) <= 2: return coordinates.tolist() # Convert back to list # Find the point with the maximum distance max_distance = 0 index = 0 end = len(coordinates) - 1 for i in range(1, end): distance = perpendicular_distance(coordinates[i], coordinates[0], coordinates[end]) if distance > max_distance: max_distance = distance index = i # If the maximum distance is greater than the tolerance, recursively simplify if max_distance > tolerance: simplified1 = simplify_coordinates(coordinates[:index+1], tolerance) simplified2 = simplify_coordinates(coordinates[index:], tolerance) return simplified1[:-1] + simplified2 # No need to convert back to list else: return [coordinates[0], coordinates[end]] # No need to convert back to list def perpendicular_distance(point, start, end): if np.all(start == end): return np.linalg.norm(np.array(point) - np.array(start)) line_length = np.linalg.norm(np.array(end) - np.array(start)) t = np.dot(np.array(point) - np.array(start), np.array(end) - np.array(start)) / (line_length * line_length) t = np.clip(t, 0, 1) closest_point = np.array(start) + t * (np.array(end) - np.array(start)) return np.linalg.norm(np.array(point) - closest_point)