Created
November 12, 2010 07:06
-
-
Save amjith/673824 to your computer and use it in GitHub Desktop.
Python script to parse user input to a list of numbers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
def convert(inp): | |
""" | |
* Get the input from user. | |
* Parse the input to extract numbers | |
** Split by comma | |
*** Each item in the list will then be split by '-' | |
**** Populate the number between a-b using range(a,b) | |
>>> convert("") | |
[] | |
>>> convert("1") | |
[1] | |
>>> convert("1,2") | |
[1, 2] | |
>>> convert("1,2-5") | |
[1, 2, 3, 4, 5] | |
>>> convert("1-3,2-5,8,10,15-20") | |
[1, 2, 3, 2, 3, 4, 5, 8, 10, 15, 16, 17, 18, 19, 20] | |
""" | |
if not inp: # empty string must return an empty list | |
return [] | |
pages = [] | |
comma_separated = [] | |
comma_separated = inp.split(",") # split the input string based on comma delimitation | |
for item in comma_separated: | |
if "-" in item: | |
a = item.split("-") | |
pages.extend(range(int(a[0]),int(a[1])+1)) | |
else: | |
pages.append(int(item)) | |
return pages | |
if __name__ == '__main__' : | |
import doctest | |
doctest.testmod() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment