【问题标题】:Couple of points that are closer to each other in a list列表中彼此靠近的几个点
【发布时间】:2015-01-28 17:41:05
【问题描述】:

我必须做一个算法,aprop,使用分而治之来计算列表中彼此更接近的几个点,而且我还必须计算复杂度。

def aprop(a):
    longitudlista = len(a)
    if longitudlista <= 2:
        return a
    else:
        mig = longitudlista / 2
        pivot = (a[mig])

a= [1.2,2.9,3.1,4.0,5.7]

aprop(a)

现在我希望算法使用枢轴返回列表中所有元素的所有差异的最小差异的几个点。我如何在代码中写出这个想法?

【问题讨论】:

  • 您所说的“使用枢轴”是什么意思?
  • 因为我必须划分算法或者我们也可以使用 a[:mig] 和 a[mig:]
  • 这是一道标准的算法作业题。我很确定你可以谷歌完整的答案
  • 但我不想看到解决方案,我想了解我该怎么做
  • 有人可以帮助我吗? :(

标签: python list divide-and-conquer


【解决方案1】:

以下代码是分治方案的一般实现:

def divide_and_conquer(S, divide, combine): 
  if len(S) == 1: return S
  L, R = divide(S)
  A = divide_and_conquer(L, divide, combine)
  B = divide_and_conquer(R, divide, combine)
  return combine(A, B)

所以基于上面的算法你可以使用这个:

from operator import sub

def divide_and_conquer(S, combine=[]):
    if len(S) == 2:
       combine.append(S)
    else :
       L, R = S[:(len(S)/2)+1],S[len(S)/2:]
       A = divide_and_conquer(L)
       B = divide_and_conquer(R)
       result=[abs(sub(i,j)) for i,j in combine]
       return combine[result.index(min(result))]

a= [1.2,2.9,3.1,4.0,5.7]

print divide_and_conquer(a)
[2.9, 3.1]

【讨论】:

  • 是的,我明白这一点,但我的结果必须显示 2.9 和 3.1 我该怎么做?
  • @Cristiano 我认为您对 StackOverflow 的理解有误,它不是一个可以为您完成所有作业的神奇地方,这里的人们想要学习和教书!所以最好自己做!此外,如果您觉得这个答案有帮助,您可以通过投票或接受答案告诉社区!
【解决方案2】:

对数组进行排序并成对检查最小距离。

可以使用分治算法完成排序,例如 O(nlog(n)) 时间的 merge_sort。

例如,您可以像这样捎带合并排序:

# For convenience of representation, assume pairs to be defined as 
# tuples of form ( no_1, no_2 )

def closest_pair(array):
    l = len(array)
    pivot = l/2

    if len(array) == 2:
        # Simply returns the pair
        return (array[0], array[1])

    if len(array) == 3:
        # Returns the pair which has the smallest distance amongst the 3C2 pairs
        return min(itertools.combinations(array, r = 2), key = lambda x : abs(x[1] - x[0]) )


    left_closest = closest_pair(array[:pivot])
    right_closest = closest_pair(array[pivot:])
    split_pair = (array[pivot-1], array[pivot]) # Just incase the split_pair is the closest

    return min(left_closest, right_closest, split_pair, key = lambda x : abs(x[1] - x[0]) )

为您的数组[1.2,2.9,3.1,4.0,5.7]

>>> closest_pair([1.2,2.9,3.1,4.0,5.7])
(2.9, 3.1)

旁注:

如果您不关心分而治之的实现,您可以简单地使用min 使用一个键和itertools.combinations(就像上面为组合步骤实现的那样/len(array) 的基本情况等于 3。 )

>>> a = [1.2,2.9,3.1,4.0,5.7]
>>> min(itertools.combinations(a, r = 2), key = lambda x : abs(x[1] - x[0])))
(2.9, 3.1)

点击此处了解更多信息:

希望这会有所帮助...

【讨论】:

    猜你喜欢
    • 2012-10-16
    • 2014-09-14
    • 1970-01-01
    • 2018-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多