1

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

cmh
  • 10,612
  • 5
  • 30
  • 40
Teacher Ai
  • 131
  • 1
  • 2
  • 9
  • *my prof won't accept* - does he allow you to use Python at all? – eumiro Dec 10 '12 at 14:29
  • not really, but he allows me with the swapping program.. he wants me to do it without using a built in functions.. I just can't get it right.. I guess, after sorting, I have to get all the possible combinations, minus it in each other and get the minimum. Then I would display those two combinations with the lowest answer.. – Teacher Ai Dec 10 '12 at 14:32
  • You don't have to get all possible combinations, only the size of difference between neighborging ones. – dgl Dec 10 '12 at 14:35
  • the neighboring, what if the closest pair is the second input and the ninth input? Sorry, I am just confuse... – Teacher Ai Dec 10 '12 at 14:36
  • If you sorted the list before finding the combinations, a closest pair can only consist of neighborging numbers. Because if the list is sorted and the numbers aren't neighbors, there is a number between that will form the shorter pair with one of them. – dgl Dec 10 '12 at 14:41
  • ahhh.. I see.. Thank you, I overlook that, too tired with this problem.. I'll try to solve it again... :D – Teacher Ai Dec 10 '12 at 14:44

3 Answers3

1

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.

Duncan
  • 92,073
  • 11
  • 122
  • 156
  • yes sir Duncan, I have done it as you have said.. I use while loop 8 times.. it's rather long but it's working :D I can't post it here because it is very long .. thank you all for the help :) – Teacher Ai Dec 10 '12 at 15:39
1

Check this, i think its good for you.

# fill the array with input
a = [int(num) for num in raw_input().split(" ")]

# REVERSE sorting the array
for j in range(len(a) - 1, -1, -1):
    for i in range(0, j):
        if (a[i] < a[i+1]):
            c = a[i]
            a[i] = a[i+1]
            a[i+1] = c

min = a[0] + a[1]

for i in range(0, len(a) - 1):    
    if min > a[i] - a[i + 1]:
        min = a[i] - a[i + 1]

print min
Laszlo Papp
  • 84
  • 1
  • 6
0

You can do that very in-efficiently by just looking at each number, and then looking at each (other) number you could pair with it. You can just return the closest pair after you iterated on each possible pair.

numbers = [7,15,0,4,3,12,76]


def pair_distance(pair):
    return abs(pair[0] - pair[1])

closest_pair = None

for i, number1 in enumerate(numbers):
    for j, number2 in enumerate(numbers):
        if i != j: #Otherwise we'd always have numbers[0], numbers[0] as pair!
            pair = number1, number2
            if closest_pair is None or pair_distance(pair) < pair_distance(closest_pair):
                closest_pair = pair


print "The closest pair is", closest_pair

My bad, I missed that enumerate wasn't allowed:

i = -1
j = -1
for number1 in numbers:
    i += 1
    for number2 in numbers:
        j += 1
        if i != j: #Otherwise we'd always have numbers[0], numbers[0] as pair!
            pair = number1, number2
            if closest_pair is None or pair_distance(pair) < pair_distance(closest_pair):
                closest_pair = pair

As this is homework, I suggest that you try to understand why this would work and why this is inefficient before turning it in!

As suggested in the comments, sorting the list first can give you a more efficient solution.


I, however, think you probably shouldn't be using Python for this task. There's not much learning value in using low-level constructs in an high-level language.

Thomas Orozco
  • 53,284
  • 11
  • 113
  • 116
  • Apparently `enumerate` is a no-no :) – Jon Clements Dec 10 '12 at 14:45
  • If `enumerate` is banned what about `range()` or even `len()`? There has to be *something* that's allowed. – Duncan Dec 10 '12 at 14:47
  • @JonClements Oh, I had missed this one. Well, proviced an answer without using it. But at some point, I'm not sure the OP should even be using Python! – Thomas Orozco Dec 10 '12 at 14:56
  • I think @Duncan has it right by mentioning that `itertools` is perhaps not what's being expected to be handed in (and in fact is not required - I believe most instructors would naturally be suspicious at the use of modules that aren't expected to be used at that point) - but I do find it difficult to accept `enumerate` and such aren't allowed... But oh well... – Jon Clements Dec 10 '12 at 15:02
  • I'm not sure but I create a program with a very long if code, I am still working on converting it to loop...I'm not really that familiar with for loop in python...I'll try the suggested code above... – Teacher Ai Dec 10 '12 at 15:11
  • Well, if the goal of the assignment is to learn combinatorics and/or understand what your code is doing, hiding the details behind a module is probably missing the point. Describing the assignment in some more detail probably wouldn't hurt ... – tripleee Dec 10 '12 at 15:18