-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy path194_Facebook_Count_Pairs_Of_Line_Segments.py
More file actions
executable file
·85 lines (39 loc) · 1.52 KB
/
194_Facebook_Count_Pairs_Of_Line_Segments.py
File metadata and controls
executable file
·85 lines (39 loc) · 1.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
"""
This problem was asked by Facebook.
Suppose you are given two lists of n points,
one list p1, p2, ..., pn on the line y = 0 and
the other list q1, q2, ..., qn on the line y = 1.
Imagine a set of n line segments connecting each point pi to qi.
Write an algorithm to determine how many pairs of the line segments intersect.
"""
def number_of_intersecting_line_segments(P, Q):
points = []
for p,q in zip(P, Q):
points.append((p,q))
points.sort(key=lambda x: x[0]) # Sort by p
count_intersecting_line_segments = 0
for i,(p_1, q_1) in enumerate(points):
for p_2,q_2 in points[i+1:]:
# we have an intersection if q1 bigger than q2
if q_1 > q_2:
count_intersecting_line_segments += 1
return count_intersecting_line_segments
if __name__ == '__main__':
print(number_of_intersecting_line_segments(P=[6, 2, 4, 3, 5, 1], Q=[1, 6, 5, 2, 3, 4]))
print(number_of_intersecting_line_segments(P=[1, 2, 3], Q=[2, 3, 1]))
print(number_of_intersecting_line_segments(P=[1, 2, 3], Q=[2, 1, 3]))
print(number_of_intersecting_line_segments([1, 2, 3, 4], [4, 3, 2, 1]))
# def number_of_intersecting_line_segments(P, Q):
# PQ = []
# for p, q in zip(P, Q):
# PQ.append((p, q))
#
# PQ = sorted(PQ, key= lambda t:t[0])
# print(PQ)
#
# intersections = 0
# for i, (p1, q1) in enumerate(PQ):
# for p2, q2 in PQ[i:]:
# if q2 < q1:
# intersections += 1
# return intersections