Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python 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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

['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 return 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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading