Search code examples
pythonfunctiongenerator

Hardest python generator interview question - python generator object of ranges of numbers


got this one in a python course, still can't figure it out:

Input - a string of start and end points a of a desired range.

Output - a generator of numbers containing all the numbers in all of the ranges.

The problem: making a function, using only two generators expressions (no for loops).

Example:

Input:

list(parse_ranges("1-2,4-4,8-10"))

Desired output:

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

what I've come to so far:

def parse_ranges(ranges_string):
    first_generator = ([int(i[0]),int(i[-1])] for i in ranges_string.split(','))
    second_generator = (range(j[0],j[1]) for j in first_generator)
    return second_generator

my output:

[range(1, 2), range(4, 4), range(8, 0)]

Solution

  • Well, that does it, but I wouldn't recommend to write such unreadable code...

    def parse_ranges(string):
        ranges = (tuple(map(int, (s.split('-')))) for s in string.split(','))
        return (x for r in ranges for x in range(r[0], r[1]+1) )
    
    
    list(parse_ranges("1-2,4-4,8-10"))
    # [1, 2, 4, 8, 9, 10]