-2

Write a function called dist that takes in two points (so two lists of two elements each), and computes the distance between them. Make sure this works on the example below before proceeding to the next step.
Use dist in a nested loop inside shortestDist to compare each element of the list of points with every element in the list after it. So, basically, find the shortest distance between points in a list.

Here's what I have so far:

        sample= [[45, -99], [24, 83], [-48, -68], [-97, 99], [-8, -77], [-2, 50], [44, 41], [-48, -58], [-1, 53], [14, 86], [31, 94], [12, -91], [33, 50], [82, 72], [83, -90], [10, 78], [7, -22], [90, -88], [-21, 5], [6, 23]]

        def dist(p0, p1):
            return (((p0[0] - p1[0])**2) + ((p0[1] - p1[1])**2))**.5


        def shortestDist(sample):
            distances = []
            for i in range(len(sample)-1):
                for j in range(i+1, len(sample)):
                    distances += [dist(sample[i],sample[j])]
            return(min(distances))

That finds the distance alright between two points. I just need some help figuring out how to start writing shortestDist to compare all points and keep track of the shortest distance. UPDATE: The error was resolved and I'm good to go now. Thank you to everyone for their assistance!

Joe
  • 121
  • 3
  • 3
  • 10
  • Just apply this function to all pairs of points? You can do this with two nested for loops and a variable, or in a single line with [`min`](https://docs.python.org/3/library/functions.html#min) and [`itertools.product`](https://docs.python.org/3/library/itertools.html#itertools.product). – tobias_k Feb 25 '16 at 16:34
  • I just dont know what the syntax for shortestDist should look like. Like, what exactly does the loop look like? We can't use min/itertools and stuff either. Appreicate your help! – Joe Feb 25 '16 at 16:37
  • Possible duplicate of [How do I find the distance between two points?](http://stackoverflow.com/questions/5228383/how-do-i-find-the-distance-between-two-points) – Vorsprung Feb 25 '16 at 16:38
  • @Vorsprung Nope, that's about the part that OP already has solved. – tobias_k Feb 25 '16 at 16:39
  • ah ok http://codereview.stackexchange.com/questions/81865/travelling-salesman-using-brute-force-and-heuristics – Vorsprung Feb 25 '16 at 16:41
  • Which pair of points do you believe are only 3.1 apart? – David Zemens Feb 25 '16 at 17:01

5 Answers5

1

This should do the job

def shortestDist(points):
        sh = float("inf")
        for i in range(1, len(points)):
                d = dist(points[i-1], points[i])
                if d < sh:
                        sh = d
        return sh
pltrdy
  • 2,069
  • 1
  • 11
  • 29
  • Edited: sh = -1 was to find the maximum :p Infinity will be better here – pltrdy Feb 25 '16 at 16:43
  • You're right in your own way. But see I need the def shortestDist and inside that I need def dist inside a loop. I think you guys are usin gubilt-in functions, which we cant – Joe Feb 25 '16 at 16:45
  • I don't get your point. I'm only using your function dist in a loop. – pltrdy Feb 25 '16 at 16:48
  • Never mind, I see what you mean. Can yo ucheck my updated code now and tell me what I'm messing up. ShortestDist(sample) gives me 18.7 not 3.12 – Joe Feb 25 '16 at 16:55
  • 1
    Well, in your sample I don't get where you could get 3.12. I guess the code is ok but the sample is not. Still, validate anwsers that must be – pltrdy Feb 25 '16 at 17:03
  • Are you sure about the distance function? You use the Euclidian Distance, maybe the 3.12 corresponds to another – pltrdy Feb 25 '16 at 17:05
  • 18.7 is the shortest distance based on the `sample` provided. @Joe do some `print` statements in your `dist` function and you will see there is no such distance of 3.12... – David Zemens Feb 25 '16 at 17:07
1

This is a fully functioning example based on a list of points.

points = [(1,5), (5,8), (8,1), (9,5)]

def euclideanDistance(coordinate1, coordinate2):
    return pow(pow(coordinate1[0] - coordinate2[0], 2) + pow(coordinate1[1] - coordinate2[1], 2), .5)

distances = []
for i in range(len(points)-1):
    for j in range(i+1, len(points)):
        distances += [euclideanDistance(points[i],points[j])]
print min(distances)
Coline Do
  • 96
  • 2
0

I think code below would move you into right direction:

def shortestDist(points):
    min_dist = None
    while points:
        p1, p2 = points.pop()
        dist = dist(p1, p2)
        if min_dist is None:
            min_dist = dist
        else:
            min_dist = dist  if dist < min_dist else min_dist

Let me know if you don't understand some parts of code and i will give more explanations to it.

Good luck!

Andriy Ivaneyko
  • 20,639
  • 6
  • 60
  • 82
0

First, you might want to use tuples rather than lists. Either way will work, but given the values "x" and "y" are different, albeit both "numbers" (doubles,int...), a tuple is typically used.

You can pass in the points like:

dist((0,1), (2,3))

And they can be accessed like you would access a list:

p0[0] # access "x" in point 0
p0[1] # access "y" in point 0

As for writing shortestDistance, you'll want to take in a list of the tuples from above: e.g. [(0,1),(2,4),(3,2),(1,3)]

So something like this for the def:

def shortestDist(listOfPoints)

Then for each point you can compare it to each point after it using the following, which stores it in a dictionary.

 currentIndex = 0
 pointDict = {}
 for point in listOfPoints:
    currentPoint = point
    for i in range(currentIndex,len(listOfPoints)):
        pointDict[currentPoint] = dist(currentPoint,listOfPoints[i])

That should get you started. It assumes that the points are not duplicated.

rye
  • 487
  • 1
  • 5
  • 15
0
def solve(self, coordinates):
    m = float('inf')
    for i in range(len(coordinates)-1):
        for j in range(i+1,len(coordinates)):
            z = ((coordinates[i][0]-coordinates[j][0])**2)+((coordinates[i][1]-coordinates[j][1])**2)
            m = min(m,z)
    return m

Iterate through all the possible coordinates and find the distances then compare the with minimum counter in this case variable m.

We can also sort the coordinates according to the the x coordinates and y coordinates the find distances separately and then finally compare the min of x and min of y, so as to reduce the time complexity.

  1. To sort with respect to x:

    coordinates.sort(key = lambda x:x[0])

  2. To sort with respect to y:

    coordinates.sort(key = lambda x:x[1])