HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Parsing a list of single numbers and number ranges

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
numbernumbersrangessingleparsingandlist

Problem

I have input of a string containing a single number (like: \$3\$) or a range (like: \$1-5\$). Sample input, all together, looks like: "1-5,3,15-16", and sample output for that input looks like "1,2,3,4,5,15". Output doesn't need to be sorted.

I built something to parse this, but it's ugly. How can I improve this?

from itertools import chain
def giveRange(numString:str):
    z=numString.split("-")
    if(len(z)==1):
        return [int(z[0])]
    elif(len(z)==2):
        return list(range(int(z[0]),int(z[1])+1))
    else:
        raise IndexError("TOO MANY VALS!")

def unpackNums(numString:str):
    rList=[]
    rList.extend(set(chain(*map(giveRange,numString.split(",")))))
    return rList
unpackNums("1-2,30-50,1-10")

Solution

Since the whole exercise is a string-transformation problem, I suggest performing it using a regex substitution.

import re

def expand_ranges(s):
    return re.sub(
        r'(\d+)-(\d+)',
        lambda match: ','.join(
            str(i) for i in range(
                int(match.group(1)),
                int(match.group(2)) + 1
            )   
        ),  
        s
    )


I think that expand_ranges would be a more descriptive name than unpackNums.

Code Snippets

import re

def expand_ranges(s):
    return re.sub(
        r'(\d+)-(\d+)',
        lambda match: ','.join(
            str(i) for i in range(
                int(match.group(1)),
                int(match.group(2)) + 1
            )   
        ),  
        s
    )

Context

StackExchange Code Review Q#101497, answer score: 8

Revisions (0)

No revisions yet.