0

Given points on a plane, find the smallest distance between a pair of two (different) points. Recall that the distance between points (1, 1) and (2, 2) is equal to sqrt((x1-x2)**2 + (y1-y2)**2).

I've written below Python code(Divide & Conquer) but it's given wrong answer on some hidden test case and I can't figure out what's going wrong. Any Help in code correction will be heartily appriciated. PS: I've checked other answers available on web but where is this code doing wrong?

from math import sqrt
import heapq as hp

def dist(a,b): # 'a' and 'b' are tuples of two points (x1,y1) and (x2,y2)
    (p,q),(x,y)=a,b
    return sqrt((p-x)**2+(q-y)**2)

def solve(a,l,r): #Logic used is of Divide and Conquer
    if r-l<=2:
        if a[l][1]>a[r][1]: #sorting according to 'y' coordinate
            a[l],a[r]=a[r],a[l]
        return dist(a[l],a[r])
    mid=(l+r)//2
    d1=solve(a,l,mid)
    d2=solve(a,mid+1,r)
    d=min(d1,d2)
    z=l
    for i in hp.merge(a[l:mid+1],a[mid+1:r+1],key=lambda x:x[1]):
        a[z]=i
        z+=1
    for i in range(l,r+1):
        if abs(a[i][0]-a[mid][0])<d:
            for j in range(i+1,r+1):
                d=min(d,dist(a[i],a[j]))
    return d

if __name__=='__main__':
    n=int(input()) #number of points 
    l=[]
    for i in range(n): # appending tuples of point in form (x,y)
        l.append(tuple(map(int,input().split())))
    print(solve(l,0,n-1))

# example:
# 4  <- this is n. Below are 'n' points (x,y) 
# 0 0
# 5 6
# 3 4
# 7 2
py guy
  • 1
  • 1
  • One problem is a call like "solve(a, 0, 2)" (directly or during recursion). Your code will then not even look at "a[1]". – Michael Butscher May 23 '20 at 13:05
  • https://docs.scipy.org/doc/scipy/reference/spatial.distance.html – Joe May 23 '20 at 13:59
  • https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.pdist.html#scipy.spatial.distance.pdist – Joe May 23 '20 at 14:00

0 Answers0