蛮力最近对算法 - 用于循环

时间:2014-03-22 17:59:38

标签: python

Python新手。试图分析最近点对的算法。找到example

这些行有哪些:

return min( ((abs(point[i] - point[j]), (point[i], point[j]))
                 for i in range(numPoints-1)
                 for j in range(i+1,numPoints)),
                key=itemgetter(0))

我不清楚如何评估for循环。

for循环如何与points,key和itemgetter相关?

当我将此代码放入Ideone

我在times()函数中遇到运行时错误:

def times():
    ''' Time the different functions
    '''
    import timeit

    functions = [bruteForceClosestPair, closestPair]
    for f in functions:
        print 'Time for', f.__name__, timeit.Timer(
            '%s(pointList)' % f.__name__,
            'from closestpair import %s, pointList' % f.__name__).timeit(number=1)

谢谢。

1 个答案:

答案 0 :(得分:1)

您的min代码相当于使用generator,如下所示:

def getPoints(point, numPoints):
  for i in range(numPoints - 1):
    for j in range(i + 1, numPoints):
      yield (abs(point[i] - point[j]), (point[i], point[j]))

return min(getPoints(point, numPoints), key=itemgetter(0))

正如@DSM所指出的,代码中min的第一个参数是generator expression