Skip to content

Instantly share code, notes, and snippets.

@rich-hart
Last active December 3, 2016 00:25
Show Gist options
  • Save rich-hart/fb85b200907812dbe8cff65753f3de2c to your computer and use it in GitHub Desktop.
Save rich-hart/fb85b200907812dbe8cff65753f3de2c to your computer and use it in GitHub Desktop.
AH-HA!
import unittest
def find_slope(x1,y1,x2,y2):
slope = (y2 - y1) / (x2 - x1)
return slope
def find_intercept(x,y,slope):
intercept = y - slope * x
return intercept
# NOTE: runs in O(N^2) time
def solution(point_list):
point_list = [ (float(x),float(y)) for (x,y) in point_list ]
point_list = list(set(point_list)) # remove duplicates
line_list = []
collinear_list = []
for i in range(0, len(point_list)):
for j in range(0, len(point_list)):
if i < j:
(x1 , y1 ) = point_list[i]
(x2 , y2 ) = point_list[j]
try:
vector = find_slope(x1,y1,x2,y2)
point = (0.0,find_intercept(x1,y1,vector))
except ZeroDivisionError:
vector = "UND"
point = (x1, 0.0)
line = {'vector':vector, 'point':point}
line_list.append(line)
line_list=sorted(line_list, key=lambda line: line['vector'])
for i in range(0,len(line_list)-1):
if line_list[i]==line_list[i+1]:
collinear_list.append(line_list[i])
#remove duplicates
collinear_list=[dict(t) for t in set([tuple(d.items()) for d in collinear_list])]
return collinear_list
class Test(unittest.TestCase):
def test_solution_2(self):
problem_instance = [(0, 0), (1, 1), (3, 4), (2, 2)]
expected = [
{'point': (0.0, 0.0), 'vector': 1.0}
]
returned = solution(problem_instance)
self.assertEqual(expected,returned)
def test_solution_a(self):
problem_instance = [(0, 0), (1, 1), (3, 4), (2, 2),(4,5),(5,6)]
expected = [
{'point': (0.0, 0.0), 'vector': 1.0},
{'point': (0.0, 1.0), 'vector': 1.0}
]
returned = solution(problem_instance)
self.assertEqual(expected,returned)
def test_solution_2_empty_sol(self):
problem_instance = [(0, 0), (0, 0), (0,0)]
expected = []
returned = solution(problem_instance)
self.assertEqual(expected,returned)
problem_instance = [(0, 0), (1,1), (1,1)]
expected = []
returned = solution(problem_instance)
self.assertEqual(expected,returned)
def test_solution_2_undefined(self):
problem_instance = [(0, 0), (0, 1), (0,2)]
expected = [{'point': (0.0, 0.0), 'vector': 'UND'}]
returned = solution(problem_instance)
self.assertEqual(expected,returned)
if __name__ == "__main__":
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment