Search code examples
pythongenerator

Generator - parse range of number using 2 generators


So I have string that represent numbers separate by '-' and and I need to write 2 generator the get this string and return the range of each numbers. For example the input string '1-2,4-4,8-10' need to return:

[1, 2, 4, 8, 9, 10]

So the first generator need to return list of numbers (could be list of string) for each iteration so this is what I have done:

def parse_ranges(ranges_string):
    range_splitter = (n for n in ranges_string.split(','))
    print(next(range_splitter).split('-'))
    print(next(range_splitter).split('-'))
    print(next(range_splitter).split('-')) 

This return:

['1', '2']
['4', '4']
['8', '10']

The second generator need to use this values and return each time all the numbers that exist in the range.

So currently this is what I have try:

numbers = [int(n) for n in list]

This returns list of numbers (minimum and maximum) and now I need to convert it to numbers inside this range.


Solution

  • As you speak of generators, you would at least need to use yield.

    Here are the two generators I think you need:

    def singlerange(s):
        start, stop = map(int, s.split('-'))
        yield from range(start, stop + 1)
    
    def multirange(s):
        for rng in s.split(','):
            yield from singlerange(rng)
    

    Example run:

    s = '1-2,4-4,8-10'
    print(*multirange(s))   # 1 2 4 8 9 10