The input parameters are a list of tuples representing the intervals and a list of integers. The goal is to write a function that counts the number of intervals each integer is present in and return this result as a associative array. So for example:
Input intervals: [(1, 3), (5, 6), (6, 9)]
Input integers: [2, 4, 6, 8]
Output: {2: 1, 4: 0, 6: 2, 8: 1}
Other example:
Input intervals: [(3, 3), (22, 30), (17, 29), (7, 12), (12, 34), (18, 38), (30, 40), (5, 27), (19, 26), (27, 27), (1, 31), (17, 17), (22, 25), (6, 14), (5, 7), (9, 19), (24, 28), (19, 40), (9, 36), (2, 32)]
Input numbers: [16, 18, 39, 40, 27, 28, 4, 23, 15, 24, 2, 6, 32, 17, 21, 29, 31, 7, 20, 10]
Output: {2: 2, 4: 2, 6: 5, 7: 6, 10: 7, 15: 6, 16: 6, 17: 8, 18: 8, 20: 9, 21: 9, 23: 11, 24: 12, 27: 11, 28: 9, 29: 8, 31: 7, 32: 6, 39: 2, 40: 2}
How would I go about writing a function that does this efficiently? I already have the O(nm) implementation with n the number of intervals and m the number of integers but I'm looking for something more efficient.
What I have at the moment:
def intervals_per_number(numbers, intervals):
result_map = {i: 0 for i in numbers}
for i in result_map.keys():
for k in intervals:
if k[0] <= i <= k[1]:
result_map[i] += 1
return result_map
Hope I explained it well enough. Let me know if anything's still unclear.
Thanks in advance.