1

我真的需要代码方面的帮助。用户需要输入 10 个整数,程序必须显示最接近的对。我可以使用 itertools 来完成,但我的教授不会接受 .sort()、min()、enumerate() 等......我需要手动完成。这是我能够使用 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

对于手动最近配对程序,这是我到目前为止的代码:

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 

无论我多么努力和研究,我都无法完成它。我将不胜感激任何帮助......

谢谢,艾琳

4

3 回答 3

1

我认为您的教授拒绝使用itertools.combinations()不必要的低效答案并非不合理。您不需要查看所有组合,如果您对数组进行排序,那么您需要做的就是找到相邻项目之间的最小差异,并且这些项目是最接近的对。

所以问题归结为您是否被允许使用.sort()(如果不是,您将不得不实现自己的排序算法)以及您是否知道如何编写一个循环来找到相邻值之间的最小差异。我会把这两个作为练习留给你。

于 2012-12-10T14:45:57.337 回答
1

检查这个,我认为它对你有好处。

# 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
于 2012-12-10T15:20:59.853 回答
0

您可以通过查看每个数字,然后查看可以与之配对的每个(其他)数字来非常低效地做到这一点。在迭代每个可能的对后,您可以只返回最近的对。

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

我的错,我错过了不允许枚举:

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

由于这是家庭作业,因此我建议您在上交之前尝试了解为什么这样做会起作用以及为什么效率低下!

正如评论中所建议的,首先对列表进行排序可以为您提供更有效的解决方案。


但是,我认为您可能不应该使用 Python 来完成这项任务。在高级语言中使用低级结构没有太大的学习价值。

于 2012-12-10T14:43:08.407 回答