我在python中编写了以下方法,该方法可以找到平面上两个线段的交点(假设线段平行于x或y轴)
segment_endpoints=[]
def交叉点(s1,s2):
segment_endpoints = [] left = max(min(s1[0], s1[2]), min(s2[0], s2[2])) right = min(max(s1[0], s1[2]), max(s2[0], s2[2])) top = max(min(s1[1], s1[3]), min(s2[1], s2[3])) bottom = min(max(s1[1], s1[3]), max(s2[1], s2[3])) if top > bottom or left > right: segment_endpoints = [] return 'NO INTERSECTION' elif top == bottom and left == right: segment_endpoints.append(left) segment_endpoints.append(top) return 'POINT INTERSECTION' else: segment_endpoints.append(left) segment_endpoints.append(bottom) segment_endpoints.append(right) segment_endpoints.append(top) return 'SEGMENT INTERSECTION'
这可以被认为是一种良好的功能形式吗?如果没有,重写它的正确功能方式是什么?
我认为代码可以如下重构,但不一定是函数式的。
def intersection(s1, s2):
left = max(min(s1[0], s1[2]), min(s2[0], s2[2]))
right = min(max(s1[0], s1[2]), max(s2[0], s2[2]))
top = max(min(s1[1], s1[3]), min(s2[1], s2[3]))
bottom = min(max(s1[1], s1[3]), max(s2[1], s2[3]))
if top > bottom or left > right:
return ('NO INTERSECTION',dict())
if (top,left) == (bottom,right):
return ('POINT INTERSECTION',dict(left=left,top=top))
return ('SEGMENT INTERSECTION',dict(left=left,bottom=bottom,right=right,top=top))
您正在滥用字符串。我会考虑返回整数而不是字符串,并定义如下内容:
class IntersectionType:
NO_INTERSECTION = 1
POINT_INTERSECTION = 2
SEGMENT_INTERSECTION = 3
Python 3.4还包含枚举:我如何表示一个';枚举';在Python中。。。因此,如果您使用的是Python 3.4,那么这将是枚举的一个用例。