Python 转换为功能性风格

Python 转换为功能性风格,python,functional-programming,Python,Functional Programming,我用python编写了以下方法,该方法在一个平面上查找两个线段的交点(假设线段平行于x轴或y轴) 段_端点=[] def交叉口(s1、s2): 这能被认为是良好的功能形式吗?如果不是,那么重写它的正确功能方式是什么?您正在滥用字符串。我会考虑返回整数而不是字符串,并定义一些类似: class IntersectionType: NO_INTERSECTION = 1 POINT_INTERSECTION = 2 SEGMENT_INTERSECTION = 3 Python 3.4

我用python编写了以下方法,该方法在一个平面上查找两个线段的交点(假设线段平行于x轴或y轴)

段_端点=[]

def交叉口(s1、s2):


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

您正在滥用字符串。我会考虑返回整数而不是字符串,并定义一些类似:

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

Python 3.4还包含枚举:。。。因此,如果您使用的是Python3.4,那么这将是Enum的一个用例。

我认为代码可以按如下方式重构,但不一定是函数式的

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

这可以被认为是一个很好的函数形式吗?
-这是一个自以为是的问题。我同意。我是以过程的形式写的,因为我对编程的函数式不太了解。我很好奇是否有更“合适”的功能性风格谢谢,我喜欢它的简洁。
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))