Search code examples
pythonclosest-points

Closest pair of ten integers with only primitive data type in python


I really need help with the code. The user need to input 10 integers and the program must display the closest pair. I was able to do it using itertools but my prof won't accept the .sort (), min(), enumerate(), etc... I need to do it manually. Here's the code I was able to make using itertools:

import itertools

a = [0,1,2,3,4,5,6,7,8,9]

a[0]=input()
a[1]=input()
a[2]=input()
a[3]=input()
a[4]=input()
a[5]=input()
a[6]=input()
a[7]=input()
a[8]=input()
a[9]=input()


a.sort()

for item in enumerate(a):             
c = min(itertools.combinations(b, 2),
                   key=lambda item: abs(item[0]-item[1]))

print 'The closest pair/One of the closest pair is: ', c

For the Manual closest pair program, Here is my code so far:

a=[0,1,2,3,4,5,6,7,8,9]
a[0]=input()
a[1]=input()
a[2]=input()
a[3]=input()
a[4]=input()
a[5]=input()
a[6]=input()
a[7]=input()
a[8]=input()
a[9]=input()

#Sorting the Array
b = True             #para sa swapping
while b==True:
b= False
for i in range(0,len(a)-1):
    if (a[i]>a[i+1]):
        c=a[i]
        a[i]=a[i+1]
        a[i+1]=c
        b=True

#Generate all the posible combinations of 

I can't finish it no matter how hard I tried and research.. I would appreciate any help...

Thanks, Ailen


Solution

  • I think it's not unreasonable for your professor to reject an answer that uses itertools.combinations() as being needlessly inefficient. You don't need to look at all combinations, if you sort the array then all you need to do is find the smallest difference between adjacent items and those items are the closest pair.

    So the question comes down to whether you are allowed to use .sort() (if not you'll have to implement your own sort algorithm) and whether you know how to write a loop that finds the smallest difference between adjacent values. I'll leave both of those as exercises for you.