vushalina
vushalina

Reputation: 31

How do I get the difference of each number in the list from other numbers?

For example, in a situation where I have 100 different locations, I want to find the farthest location from the others. so I thought of a for loop that would take the difference of each position from the other 99 and add it to a list. the same locations in the loop should not meet.

I thought of making a condition for it. it works but I'm not sure if it's the right approach. What approach should I take in such a situation?

def getDifferenceCoord(t1, t2):
    expDist = (t1[0] - t2[0]) ** 2 + (t2[1] - t1[1]) ** 2
    dist = expDist ** 0.5
    return dist


allDistance = []
for i in range(len(locationList)): 
    for j in range(len(locationList) - 1):
        if i == j:
            j = 99
        allDistance.append(getDifferenceCoord(locationList[i], locationList[j]))

Upvotes: 0

Views: 128

Answers (3)

Nk03
Nk03

Reputation: 14949

Try - >

import math
from itertools import combinations

for item in  combinations(locationList,2):
    print(f'distance for locations {item} = {math.dist(item[0], item[1])}')

You can use math.dist to evaluate the distance more cleanly -

import math
from itertools import combinations

result = [math.dist(item[0],item[1]) for item in  combinations(locationList,2)]

Upvotes: 1

Moon President
Moon President

Reputation: 98

I think you have the right approach. There are minor optimisations that can be made for memory or processing complexity but it remains and O(N^2) problem either way.

One minor adjustment, if i == j, you should let the calculation equal 0, instead of putting j to the 99 to exit the loop. Unless you do want to break out of the loop in which case you should use the break command instead.

A fun addition: this is a possible solution using list comprehension.

alldistance = [ 
    sum([getDifferenceCoord(locationList[i], locationList[j]) for j in range(0,99)]) 
    for i in range(0, 99)
]

Upvotes: 1

Jamie Deith
Jamie Deith

Reputation: 714

This will give you all the distances:

from itertools import permutations
allDistance = [getDifferenceCoord(i, j) for (i, j) in permutations(locationList, 2)]

If the return distances are the same (which they normally would be) a more efficient method is:

from itertools import combinations
allDistance = [getDifferenceCoord(i, j) for (i, j) in combinations(locationList, 2)]

permutations: all i,j where i!=j

combinations: all i,j where j>i (half of the permutations)

Upvotes: 1

Related Questions