Skip to content

Instantly share code, notes, and snippets.

@martasd
Created November 22, 2023 14:26
Show Gist options
  • Save martasd/387d367f5dd6fe01eb473744ea9723cd to your computer and use it in GitHub Desktop.
Save martasd/387d367f5dd6fe01eb473744ea9723cd to your computer and use it in GitHub Desktop.
Sum intervals
def sum_intervals(interval_list):
interval_list.sort(key=lambda lst: lst[0])
# sum numbers in the interval with the lowest begin number
begin, end = interval_list[0]
max = end
result = sum(range(begin, end + 1))
# sum numbers from the remaining intervals
for begin, end in interval_list[1:]:
if begin <= max:
result += sum(range(max + 1, end + 1))
if begin > max:
result += sum(range(begin, end + 1))
max = end
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment