Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: reduce on tuple of tuples

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.

like image 357
lc2817 Avatar asked Dec 07 '22 18:12

lc2817


1 Answers

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.

like image 110
Michael Hoffman Avatar answered Dec 27 '22 11:12

Michael Hoffman