Question9: Write a function called sumIntervals/sum_intervals() that accepts an array of intervals, and returns the sum of all the interval lengths. Overlapping intervals should only be counted once.
Intervals
Intervals are represented by a pair of integers in the form of an array. The first value of the interval will always be less than the second value. Interval example: [1, 5] is an interval from 1 to 5. The length of this interval is 4.
Overlapping Intervals
List containing overlapping intervals:
[
[1,4],
[7, 10],
[3, 5]
]
The sum of the lengths of these intervals is 7. Since [1, 4] and [3, 5] overlap, we can treat the interval as [1, 5], which has a length of 4.
Examples:
sumIntervals( [
[1,2],
[6, 10],
[11, 15]
] ); // => 9
sumIntervals( [
[1,4],
[7, 10],
[3, 5]
] ); // => 7
sumIntervals( [
[1,5],
[10, 20],
[1, 6],
[16, 19],
[5, 11]
] ); // => 19
def sum_of_intervals(intervals):
ReplyDeletea=[i for lists in intervals for i in range(int(lists[0]),int(lists[1]))]
return len(set(a))
print(sum_of_intervals([input().split(',') for i in range(int(input('enter total number of intervals')))]))
A very simple solution found in codewars website(https://www.codewars.com/kata/52b7ed099cdc285c300001cd/solutions/python/all/best_practice)
ReplyDeletesum_of_intervals=lambda a:len(set.union(*(set(range(*i))for i in a)))
def sumIntervals(input):
ReplyDeleteinterval = set()
if len(input) > 0:
for data in input:
if len(data) == 2 and data[0] < data[1]:
for i in range(data[0], data[1]):
interval.add(i)
else:
return 'Invalid input'
return len(interval)
else:
return 0
print(sumIntervals([[1,2], [6, 10], [11, 15]]))
You must indulge in a contest for one of the greatest blogs over the internet. Ill suggest this web site! https://python.engineering/game-dev-tycoon-best-combos/
ReplyDelete