MCPcopy Create free account
hub / github.com/codemistic/Data-Structures-and-Algorithms / merge_sky

Method merge_sky

Python/skyline.py:16–71  ·  view source on GitHub ↗
(self, left_skyline, right_skyline)

Source from the content-addressed store, hash-verified

14 return self.merge_sky(left_skyline, right_skyline)
15
16 def merge_sky(self, left_skyline, right_skyline):
17 # Initalize left_pos=0, right_pos=0 as the pointer of left_skyline and right_skyline.
18 # Since we start from the left ground, thus the previous height from
19 # left_skyline and right_skyline are 0.
20 answer = []
21 left_pos, right_pos = 0, 0
22 left_prev_height, right_prev_height = 0, 0
23
24 # Now we start to iterate over both skylines.
25 while left_pos < len(left_skyline) and right_pos < len(right_skyline):
26 next_left_x = left_skyline[left_pos][0]
27 next_right_x = right_skyline[right_pos][0]
28
29 # If we meet left_skyline key point first, our current height changes to the
30 # larger one between height on left skyline and the previous height on right
31 # skyline. Update the previous height from left_skyline and increment left_pos by 1.
32 if next_left_x < next_right_x:
33 left_prev_height = left_skyline[left_pos][1]
34 cur_x = next_left_x
35 cur_y = max(left_prev_height, right_prev_height)
36 left_pos += 1
37
38
39 # If we meet right_skyline key point first, our current height changes to the
40 # larger one between height on right skyline and the previous height on left
41 # skyline. Update the previous height from right_skyline and increment right_pos by 1.
42 elif next_left_x > next_right_x:
43 right_prev_height = right_skyline[right_pos][1]
44 cur_x = next_right_x
45 cur_y = max(left_prev_height, right_prev_height)
46 right_pos += 1
47
48 # If both skyline key points has same x:
49 # Our current height is the larger one, update the previous height
50 # from left_skyline and right_skyline. Increment both left_pos and right_pos by 1.
51 else:
52 left_prev_height = left_skyline[left_pos][1]
53 right_prev_height = right_skyline[right_pos][1]
54 cur_x = next_left_x
55 cur_y = max(left_prev_height, right_prev_height)
56 left_pos += 1
57 right_pos += 1
58
59 # Discard those key points that has the same height as the previous one.
60 if not answer or answer[-1][1] != cur_y:
61 answer.append([cur_x, cur_y])
62
63 # If we finish iterating over any skyline, just append the rest of the other
64 # skyline to the merged skyline.
65 while left_pos < len(left_skyline):
66 answer.append(left_skyline[left_pos])
67 left_pos += 1
68 while right_pos < len(right_skyline):
69 answer.append(right_skyline[right_pos])
70 right_pos += 1
71 return answer

Callers 1

getSkylineMethod · 0.95

Calls 1

maxFunction · 0.50

Tested by

no test coverage detected