From 63b4ce00407d11b0549a47ca84503f4376a70104 Mon Sep 17 00:00:00 2001 From: theyashmhatre <60573218+theyashmhatre@users.noreply.github.com> Date: Mon, 14 Dec 2020 13:38:53 +0530 Subject: [PATCH] Create points_and_segments.py Optimal python program for points and segments problem --- .../points_and_segments.py | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 Course 1 - Algorithmic Toolbox/week4_divide_and_conquer/5_organizing_a_lottery/points_and_segments.py diff --git a/Course 1 - Algorithmic Toolbox/week4_divide_and_conquer/5_organizing_a_lottery/points_and_segments.py b/Course 1 - Algorithmic Toolbox/week4_divide_and_conquer/5_organizing_a_lottery/points_and_segments.py new file mode 100644 index 0000000..eec0038 --- /dev/null +++ b/Course 1 - Algorithmic Toolbox/week4_divide_and_conquer/5_organizing_a_lottery/points_and_segments.py @@ -0,0 +1,49 @@ +import sys +from collections import defaultdict + + +def fast_count_segments(zippedList,points): + elements = [] + d = defaultdict(list) + + for i in zippedList: + elements.append([i[0],'l']) + for x in range(len(points)): + elements.append([points[x],'p']) + for j in zippedList: + elements.append([j[1],'r']) + + elements.sort(key=lambda x: x[1]) + elements.sort(key=lambda x: x[0]) + print(elements) + count = 0 + + for x in elements: + if x[1] == 'l': + count += 1 + if x[1] == 'r': + count -= 1 + if x[1] == 'p': + d[x[0]] = max(count,0) + return d + + +def naive_count_segments(starts, ends, points): + cnt = [0] * len(points) + for i in range(len(points)): + for j in range(len(starts)): + if starts[j] <= points[i] <= ends[j]: + cnt[i] += 1 + return cnt + +if __name__ == '__main__': + data = list(map(int, sys.stdin.read().split())) + n = data[0] + m = data[1] + starts = data[2:2 * n + 2:2] + ends = data[3:2 * n + 2:2] + points = data[2 * n + 2:] + zippedList = list(zip(starts,ends)) + cnt = fast_count_segments(zippedList, points) + for x in points: + print(cnt[x], end=' ')