Pythonic最近对天真

时间:2018-04-01 06:32:11

标签: python

我正在尝试编写最接近的对算法的暴力版本,而不使用嵌套的for循环。这是我写的代码,但代码给了我0.0因为我正在计算点与自己的距离。如何更改代码以给我正确的最小距离?

import math

x = [4, -2, -3, -1, 2, -4, 1, -1, 3, -4, -2]  
y = [4, -2, -4,  3, 3,  0, 1, -1, -1, 2,  4] 

def _ClosestPair(x,y):  
    Px = sorted(list(zip(x,y)), key = lambda elem: elem[0])  
    return ClosestPairNaive(Px)

def ClosestPairNaive(points):
    dis = lambda p, q: math.sqrt((p[0]-q[0])**2 +  (p[1] - q[1])**2)
    return  min([dis(p,q) for p in points[:len(points)-1] for q in points[1:]])

print(_ClosestPair(x, y))

2 个答案:

答案 0 :(得分:1)

循环遍历列表中每个位置唯一对的惯用方法是从内循环中的In [4]: data = 'abc' In [5]: [(data[i], data[j]) for i in range(len(data)) for j in range(i+1, len(data))] Out[5]: [('a', 'b'), ('a', 'c'), ('b', 'c')] In [6]: data = 'abcd' In [7]: [(data[i], data[j]) for i in range(len(data)) for j in range(i+1, len(data))] Out[7]: [('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')] 开始:

math

使用序列类型时,这是一种简单有效的算法。

另请注意,hypot有一个方便的In [8]: ps = list(zip( ...: [4, -2, -3, -1, 2, -4, 1, -1, 3, -4, -2], ...: [4, -2, -4, 3, 3, 0, 1, -1, -1, 2, 4] ...: )) In [9]: import math ...: def dis(p1, p2): ...: (x0, y0), (x1, y1) = p1, p2 ...: return math.hypot(x1 - x0, y1 - y0) ...: In [10]: min(dis(ps[i], ps[j]) for i in range(len(ps)) for j in range(i + 1, len(ps))) Out[10]: 1.4142135623730951 功能,这只是欧几里德规范。所以你可以简单地实现这个:

snake_case

注意,将lambda表达式的结果分配给名称是明确针对PEP8的。就此而言,您应该使用CapitalCase而不是Scenario: Trigger a job when commit is pushed and the pusher is not named "build". Given the following generic variables are configured: | variable | expression | expressionType | defaultValue | regexpFilter | | user | $.pusher.name | JSONPath | | | Given filter is configured with: | text | expression | | $user | ^((?!build)) | Given received post content is: """ { "pusher": { "name": "baxterthehacker", } } """ Then the job is triggered Given received post content is: """ { "pusher": { "name": "build", } } """ Then the job is not triggered 作为函数名称。

答案 1 :(得分:0)

单一陈述

int count=0;
@Override
protected void reduce(IntWritable1 key, Iterable<Text> values,Context context) throws IOException, InterruptedException {

    int count=0;
    String key1 = "";
    for(Text value:values) {
        key1+=value;
    }
    if(count<5) {
        count++;
        context.write(new Text(key1), key);

    }
}