Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
yield all values solution in Clear category for Expand Intervals by mu_py
from typing import Iterable
def expand_intervals(items: Iterable) -> Iterable:
"""
Given:
an an iterable with intervals, guaranteed not to overlap and to be in a sorted ascending order
Return:
all numbers in those intervalls
"""
for start, stop in items: # the two elements of the tupels in items
for i in range(start, stop+1): # range "excludes" the end, thus stop+1
yield i # yield instead of return: we don't need to build up a list
if __name__ == '__main__':
print("Example:")
print(list(expand_intervals([(1, 3), (5, 7)])))
# These "asserts" are used for self-checking and not for an auto-testing
assert list(expand_intervals([(1, 3), (5, 7)])) == [1, 2, 3, 5, 6, 7]
assert list(expand_intervals([(1, 3)])) == [1, 2, 3]
assert list(expand_intervals([])) == []
assert list(expand_intervals([(1, 2), (4, 4)])) == [1, 2, 4]
print("Coding complete? Click 'Check' to earn cool rewards!")
Oct. 12, 2022
Comments: