How to perform operations between arrays in python

Asked

Viewed 839 times

0

Hi, 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 dimension 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 square, then move to another array in which the product will have the same index I, and then add everything up, 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 someone shed some light on it? And I’d appreciate it if you had some good material on array operations to indicate. Thank you!

  • Why exactly do you need to do this without loops?

  • Recursiveness would be considered a loop in this case?

  • 1

    the module numpy has methods for arrays

  • @Claytontosatti clear. In any case in fact.

1 answer

1

Let’s go in pieces:

As I understand it, you have two lists (in Python, an array 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 make the difference of each "group" v[0]-v[1], squared and stored 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 go for 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 a little 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)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.