Let’s say you have a collection of four points like this:
To draw lines between the points, you need to convert the four points to three lines like this:
Expressed in numbers, you convert these points:
(0, 0.5)
(1, 1)
(2, 0)
(3, .5)
to these lines:
(0, 0.5) -> (1, 1)
(1, 1) -> (2, 0)
(2, 0) -> (3, 0.5)
Here is a recursive Python function that converts the list of points to a list of lines.
def create_lines_from_points(points, lines = []):
if len(points) == 0:
# no more points, return collected lines
return lines
else:
if len(lines) == 0:
if len(points) == 1:
raise ValueError('Cannot create line from one point')
# starting situation, return create_lines_from_points with args:
# 1: remaining points after first two points
# 2: line created from first two points
return create_lines_from_points(points[2:], [(points[0], points[1])])
else:
# mid-list situation, return create_lines_from_points with args:
# 1: remaining points
# 2: collected lines plus a new line based on one point from
# the last line and a point from the list
return create_lines_from_points(points[1:], lines + [(lines[-1][1], points[0])])
Usage:
points = [(0, 0.5), (1, 1), (2, 0), (3, 0.5)]
print(create_lines_from_points(points))
Output:
[((0, 0.5), (1, 1)), ((1, 1), (2, 0)), ((2, 0), (3, 0.5))]
[Finished in 0.031s]