0

I wrote the following method in python that finds the intersection of 2 segments on a plane (assuming the segments are parallel to either the x or y axis)

segment_endpoints = []

def intersection(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'

Can this be considered in good functional form? If not what would be the proper functional way of rewriting it?

user35202
  • 389
  • 1
  • 10
  • `Can this be considered in good functional form?` - This is kind of opinionated question. – thefourtheye Mar 24 '15 at 14:26
  • I agree. I wrote it in procedural form as I dont know much about the functional style of programming. I was curious if there is a more "proper" functional style – user35202 Mar 24 '15 at 14:30

2 Answers2

1

I think the code can be refactored as follows, but not necessarily a functional style.

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))
Nizam Mohamed
  • 8,751
  • 24
  • 32
-1

You are abusing strings. I would consider returning integers instead of strings and defining something like:

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

Python 3.4 also contains enums: How can I represent an 'Enum' in Python? ... so if you're using Python 3.4 then this would be a use case for enums.

Community
  • 1
  • 1
juhist
  • 4,210
  • 16
  • 33