Welcome, guest | Sign In | My Account | Store | Cart

This function takes a range in form of "a-b" and generate a list of numbers between a and b inclusive. Also accepts comma separated ranges like "a-b,c-d,f" will build a list which will include numbers from a to b, a to d and f Example: hyphen_range('54-78') hyphen_range('57-78,454,45,1-10') hyphen_range('94-100,1052,2-50')

Python, 13 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
def hyphen_range(s):
    """ Takes a range in form of "a-b" and generate a list of numbers between a and b inclusive.
    Also accepts comma separated ranges like "a-b,c-d,f" will build a list which will include
    Numbers from a to b, a to d and f"""
    s="".join(s.split())#removes white space
    r=set()
    for x in s.split(','):
        t=x.split('-')
        if len(t) not in [1,2]: raise SyntaxError("hash_range is given its arguement as "+s+" which seems not correctly formated.")
        r.add(int(t[0])) if len(t)==1 else r.update(set(range(int(t[0]),int(t[1])+1)))
    l=list(r)
    l.sort()
    return l

1 comment

zongzhi liu 13 years, 9 months ago  # | flag

a version using generator.

def hyphen_range(s):
    """ yield each integer from a complex range string like "1-9,12, 15-20,23"

    >>> list(hyphen_range('1-9,12, 15-20,23'))
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 15, 16, 17, 18, 19, 20, 23]

    >>> list(hyphen_range('1-9,12, 15-20,2-3-4'))
    Traceback (most recent call last):
        ...
    ValueError: format error in 2-3-4
    """
    for x in s.split(','):
        elem = x.split('-')
        if len(elem) == 1: # a number
            yield int(elem[0])
        elif len(elem) == 2: # a range inclusive
            start, end = map(int, elem)
            for i in xrange(start, end+1):
                yield i
        else: # more than one hyphen
            raise ValueError('format error in %s' % x)

if __name__ == '__main__':
    import doctest
    doctest.testmod()
Created by Siddhant Sanyam on Thu, 1 Jul 2010 (MIT)
Python recipes (4591)
Siddhant Sanyam's recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks