I am trying to compute in Python the length of the path from a point A to a point B going through a list of intermediary points. I know how to do it but I do want to use the reduce Built-in function.
Why I tried so far, please note that it is completely wrong, is this:
reduce(lambda x,y: math.sqrt((y[1]-y[0])**2+(x[1]-x[0])**2) , ((1,2),(3,4),(1,8)))
Any idea?
Thanks.
You should map before you reduce.
points = [(1, 2), (3, 4), (1, 8)]
distances = (math.hypot(b[0]-a[0], b[1]-a[1])
for a, b in zip(points, points[1:]))
total_distance = sum(distances)
or, if you must use reduce()
, although sum()
is better for this purpose:
import operator
total_distance = reduce(operator.add, distances)
If you have a lot of points, you might find NumPy helpful in doing this all at once, quickly:
import numpy
total_distance = numpy.hypot(*numpy.diff(numpy.array(points), axis=0)).sum()
Edit: use math.hypot()
and add NumPy method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With