这个程序有什么问题?

时间:2009-11-15 09:24:03

标签: python

def short_distance(origins,(x,y),gap):
for (i,j) in origins.spilt(“ ”):
 h=[]
   h.append(float(math.sqrt ((i-x)*(i-x)+(j-y)*(j-y))))
for n in h:
if not gap < n:
 print 0
if gap < n :
 print n 

5 个答案:

答案 0 :(得分:4)

我会更像这样编写代码。如果您运行代码,它将报告任何失败的测试(没有测试)。

import math

def short_distance(origins, point, gap):
    """
    Describe origins, point, and gap are and what the 
    expected outcome is.

    Then provide an example that tests the code
    >>> short_distance('1,2 3,4', (5,6), 1.5)
    5.65685424949
    2.82842712475
    """
    origins = parse_origins(origins)
    distance_to_point = lambda point2: point_distance(point, point2)
    # what's a better name for h?
    h = map(distance_to_point, origins)
    report(h, gap)

def report(h, gap):
    """
    Take the results of the distances and report on them
    """
    for distance in h:
        if not (gap < distance):
            print 0
        else:
            print distance

def point_distance(p1, p2):
    """
    Calculate the distance between two points

    >>> point_distance((0,0), (1,0))
    1.0

    more than one test here would be good
    """
    x1, y1 = p1
    x2, y2 = p2
    return math.sqrt((x1-x2)**2 + (y1-y2)**2)

def parse_origins(origin_string):
    """
    Parse an origins string.
    >>> parse_origins('1,2 3,4')
    ((1.0, 2.0), (3.0, 4.0))
    """
    points = origin_string.split(' ')
    return tuple(map(parse_point, points))

def parse_point(point_string):
    """
    Take a string like 1,2 and return a tuple of the numbers
    in that string.

    >>> parse_point('1,2.0')
    (1.0, 2.0)
    """
    return tuple(map(float, point_string.split(',')))

def test():
    import doctest
    doctest.testmod()

if __name__ == '__main__':
    test()

答案 1 :(得分:2)

  • 缩进是错误的; for循环应缩进多于def
  • 错字:origins.spilt(" ")应该是origins.split(" ")

答案 2 :(得分:2)

您的代码可能是为了从origins中找到接近(x, y)的点数。其中有很多错误:

  1. Indention是错误的。
  2. split()方法拼写错误。
  3. split()方法返回平面列表,而您期望列表对。
  4. 前两个很容易修复。如果不了解origins字符串格式,我不能确定你想要的是什么。有关如何将平面列表转换为对列表的解决方案,请参阅this question

    另请注意,if语句具有else子句,因此您可以写:

    if gap < n:
        print n
    else:
        print 0
    

答案 3 :(得分:0)

  1. 您需要导入数学
  2. 缩进错误
  3. 如果Origins是'1,1 2,2 3,3'之类的字符串,Origins.split(" ")会为您提供字符串列表["1,1", "2,2", "3,3"]。你需要做一些额外的工作才能将它与for循环一起使用for (i,j) in ...你需要一个像[(1,1),(2,2),(3,3)] <这样的元组列表/ LI>
  4. math.sqrt已经返回了一个浮点数,因此您可以将其保留

答案 4 :(得分:0)

以下是代码:

from math import sqrt
def short_distance(origins,(x,y),gap):
    def distance(i, j):
        ix, iy = i - x, j - y
        return sqrt (ix*ix + iy*iy)
    all_distances = (distance(float(i), float(j)) for (i,j) in origins)
    for n in all_distances:
        print (0 if gap >= n else n)

然后像这样使用它:

>>> origin = (0, 0)
>>> points = [(1, 1), (2, 1), (1, 2), (2, 2)]
>>> gap = 1.5
>>> short_distance(points, origin, gap)
0
2.2360679775
2.2360679775
2.82842712475

我最好的猜测就是这样做你想要的。