|
| 1 | +""" |
| 2 | +InterviewCake Problem 4 |
| 3 | +
|
| 4 | +Let's work with two tuples at a time, e.g. (3,5) and (4,8). |
| 5 | +There is overlap (i.e. they should merge if |
| 6 | +(1) tuple_one[0] <= tuple_two[0] and tuple_one[1] >= tuple_two[0] |
| 7 | + or the other way round (switch tuples 1,2) |
| 8 | +Can take a greedy approach -> merge as we go. |
| 9 | +
|
| 10 | +... |
| 11 | +Insight: if you don't merge with any tuples the first run through, you will NEVER merge with any of the tuples. |
| 12 | +So we should compare the first tuple with every other tuple. And then we can throw it away. |
| 13 | +
|
| 14 | +>>> condense_meeting_times_alt([(0, 1), (3, 5), (4, 8), (10, 12), (9, 10)]) |
| 15 | +[(0, 1), (3, 8), (9, 12)] |
| 16 | +
|
| 17 | +
|
| 18 | +""" |
| 19 | +import unittest |
| 20 | + |
| 21 | + |
| 22 | +def condense_meeting_times_alt(meeting_times): |
| 23 | + sorted_meeting_times = sorted(meeting_times) |
| 24 | + merged_meetings = [meeting_times[0]] |
| 25 | + |
| 26 | + for current_meeting_start, current_meeting_end in sorted_meeting_times[1:]: |
| 27 | + last_merged_meeting_start, last_merged_meeting_end = merged_meetings[-1] |
| 28 | + # If current and last_merged_meeting overlap: |
| 29 | + if current_meeting_start <= last_merged_meeting_end: |
| 30 | + merged_meetings[-1] = (last_merged_meeting_start, max(last_merged_meeting_end, current_meeting_end)) |
| 31 | + |
| 32 | + # Else add current meeting since it doesn't overlap |
| 33 | + else: |
| 34 | + merged_meetings.append((current_meeting_start, current_meeting_end)) |
| 35 | + return merged_meetings |
| 36 | + |
| 37 | + |
| 38 | +def merge(first, second): |
| 39 | + return first[0], second[1] |
| 40 | + |
| 41 | + |
| 42 | +def condense_meeting_times(list_of_tuples): |
| 43 | + """Rubbish.""" |
| 44 | + new_list_of_tuples = [] |
| 45 | + index = 0 |
| 46 | + list_len = len(list_of_tuples) |
| 47 | + action_two_tuples(list_of_tuples[0], list_of_tuples[1], list_of_tuples) |
| 48 | + while index + 1 < list_len: |
| 49 | + for j in range(index + 1, list_len): |
| 50 | + action_two_tuples(list_of_tuples[index], list_of_tuples[j], new_list_of_tuples) |
| 51 | + |
| 52 | + |
| 53 | +def action_two_tuples(first_index, second_index, tuples_list): |
| 54 | + """Also rubbish.""" |
| 55 | + first = tuples_list[first_index] |
| 56 | + second = tuples_list[second_index] |
| 57 | + if first[0] <= second[0]: |
| 58 | + if first[1] >= second[0]: |
| 59 | + # TODO: list append merged times properly |
| 60 | + tuples_list.append(merge(first_index, second_index)) |
| 61 | + # TODO: delete(first, second) |
| 62 | + else: |
| 63 | + # i.e. we know first[0] > second[0] |
| 64 | + if second[1] >= first[0]: |
| 65 | + # TODO: list append merged, delete prev |
| 66 | + merge(second_index, first_index) |
| 67 | + |
| 68 | +if __name__ == '__main__': |
| 69 | + unittest.main() |
0 commit comments