转换为功能样式

时间:2015-03-24 14:25:40

标签: python functional-programming

我在python中编写了以下方法,在平面上找到2个段的交集(假设段与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'

这可以被认为是良好的功能形式吗?如果不是重写它的正确功能方式是什么?

2 个答案:

答案 0 :(得分:1)

我认为代码可以重构如下,但不一定是功能样式。

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))

答案 1 :(得分:-1)

你在滥用字符串。我会考虑返回整数而不是字符串并定义类似的东西:

class IntersectionType:
  NO_INTERSECTION = 1
  POINT_INTERSECTION = 2
  SEGMENT_INTERSECTION = 3

Python 3.4还包含枚举:How can I represent an 'Enum' in Python? ...所以,如果您使用的是Python 3.4,那么这将是枚举的一个用例。