How to do operations between arrays in python

0

Hello, I'm learning python, I saw the basics and I'm in a problem where I need to do operations between arrays. I have, for example, two arrays of equal size D. For each index I in the array, I want to make the difference between the two i-th elements (one of each array) and raise it to the square, then move to another array in which the product will have the same index I, then add all, take the square root and get the Euclidean distance between the coordinates indicated by the array. The challenge is to do this without using loops. Can anyone give me a light? And thanks if you have good material on operations with arrays to indicate. Thanks!

    
asked by anonymous 11.05.2018 / 00:49

1 answer

0

Let's break it down:

So I understand, you have two lists (in Python, a vector is called a list):

x = [1, 5, 7]
y = [3, 6, 2]

The first part of your problem can be solved as follows:

z = [(v[0] - v[1]) ** 2 for v in zip(x, y)]

What this does is create an iterator containing the elements of each vector grouped by index ((1,3), (5,6), (7,2)) , then we make the difference of each "group" v[0]-v[1] , we squared and store in a list.

In this case, since they are vectors with the same number of elements, the new list will obviously have the same number of elements.

Now let's get to the rest:

distancia = sum(z) ** (1 / 2.0)

I believe this part is self-explanatory.

Of course, this can all be reduced to one line, but I find it particularly unreadable:

distancia = sum((v[0] - v[1]) ** 2 for v in zip(x, y)) ** (1 / 2.0)

Or using lambda:

distancia = sum(map(lambda v: (v[0] - v[1]) ** 2, zip(x, y))) ** (1 / 2.0)
    
12.05.2018 / 05:08