Parsing a list of single numbers and number ranges
$begingroup$
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")
python parsing python-3.x interval
$endgroup$
add a comment |
$begingroup$
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")
python parsing python-3.x interval
$endgroup$
add a comment |
$begingroup$
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")
python parsing python-3.x interval
$endgroup$
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")
python parsing python-3.x interval
python parsing python-3.x interval
edited Sep 5 '15 at 20:21
Jamal♦
30.3k11120227
30.3k11120227
asked Aug 20 '15 at 18:09
CarbonCarbon
1646
1646
add a comment |
add a comment |
3 Answers
3
active
oldest
votes
$begingroup$
Disclaimer: I'm not a Python programmer!
Your code isn't that bad. It's readable enough for me to understand it. B+ for readability!
Currently, you have this function:
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!")
Why don't you simply store the length in a variable?
Like this:
length=len(z)
if(length==1):
return [int(z[0])]
elif(length==2):
return list(range(int(z[0]),int(z[1])+1))
else:
raise IndexError("TOO MANY VALS!")
Now, you don't have to calculate the length twice, only once.
The name z
is a really bad name. Better names would be numbers
, pieces
or something similar.
Looking at the definition of chain()
, it seems to accept any iterable, which a range()
happens to be. So, you probably don't need that list()
, leaving this:
return range(int(z[0]),int(z[1])+1)
On your function unpackNums
instead of creating an empty set()
, you could use the a set comprehension:
def unpackNums(numString:str):
return {x for x in set(chain(*map(giveRange,numString.split(","))))}
If you notice any inaccuracies, please comment.
$endgroup$
add a comment |
$begingroup$
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
.
$endgroup$
add a comment |
$begingroup$
There's a python library called ifilters
built by me:
from ifilters import IntSeqPredicate as isp
print(list(filter(isp('1-5,3,15:16'), range(20))))
will output: [1, 2, 3, 4, 5, 15].
Note that in that library, 15:16
matches [15,16), whereas 15-16
matches [15,16].
New contributor
$endgroup$
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
return StackExchange.using("mathjaxEditing", function () {
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
});
});
}, "mathjax-editing");
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "196"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f101497%2fparsing-a-list-of-single-numbers-and-number-ranges%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
$begingroup$
Disclaimer: I'm not a Python programmer!
Your code isn't that bad. It's readable enough for me to understand it. B+ for readability!
Currently, you have this function:
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!")
Why don't you simply store the length in a variable?
Like this:
length=len(z)
if(length==1):
return [int(z[0])]
elif(length==2):
return list(range(int(z[0]),int(z[1])+1))
else:
raise IndexError("TOO MANY VALS!")
Now, you don't have to calculate the length twice, only once.
The name z
is a really bad name. Better names would be numbers
, pieces
or something similar.
Looking at the definition of chain()
, it seems to accept any iterable, which a range()
happens to be. So, you probably don't need that list()
, leaving this:
return range(int(z[0]),int(z[1])+1)
On your function unpackNums
instead of creating an empty set()
, you could use the a set comprehension:
def unpackNums(numString:str):
return {x for x in set(chain(*map(giveRange,numString.split(","))))}
If you notice any inaccuracies, please comment.
$endgroup$
add a comment |
$begingroup$
Disclaimer: I'm not a Python programmer!
Your code isn't that bad. It's readable enough for me to understand it. B+ for readability!
Currently, you have this function:
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!")
Why don't you simply store the length in a variable?
Like this:
length=len(z)
if(length==1):
return [int(z[0])]
elif(length==2):
return list(range(int(z[0]),int(z[1])+1))
else:
raise IndexError("TOO MANY VALS!")
Now, you don't have to calculate the length twice, only once.
The name z
is a really bad name. Better names would be numbers
, pieces
or something similar.
Looking at the definition of chain()
, it seems to accept any iterable, which a range()
happens to be. So, you probably don't need that list()
, leaving this:
return range(int(z[0]),int(z[1])+1)
On your function unpackNums
instead of creating an empty set()
, you could use the a set comprehension:
def unpackNums(numString:str):
return {x for x in set(chain(*map(giveRange,numString.split(","))))}
If you notice any inaccuracies, please comment.
$endgroup$
add a comment |
$begingroup$
Disclaimer: I'm not a Python programmer!
Your code isn't that bad. It's readable enough for me to understand it. B+ for readability!
Currently, you have this function:
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!")
Why don't you simply store the length in a variable?
Like this:
length=len(z)
if(length==1):
return [int(z[0])]
elif(length==2):
return list(range(int(z[0]),int(z[1])+1))
else:
raise IndexError("TOO MANY VALS!")
Now, you don't have to calculate the length twice, only once.
The name z
is a really bad name. Better names would be numbers
, pieces
or something similar.
Looking at the definition of chain()
, it seems to accept any iterable, which a range()
happens to be. So, you probably don't need that list()
, leaving this:
return range(int(z[0]),int(z[1])+1)
On your function unpackNums
instead of creating an empty set()
, you could use the a set comprehension:
def unpackNums(numString:str):
return {x for x in set(chain(*map(giveRange,numString.split(","))))}
If you notice any inaccuracies, please comment.
$endgroup$
Disclaimer: I'm not a Python programmer!
Your code isn't that bad. It's readable enough for me to understand it. B+ for readability!
Currently, you have this function:
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!")
Why don't you simply store the length in a variable?
Like this:
length=len(z)
if(length==1):
return [int(z[0])]
elif(length==2):
return list(range(int(z[0]),int(z[1])+1))
else:
raise IndexError("TOO MANY VALS!")
Now, you don't have to calculate the length twice, only once.
The name z
is a really bad name. Better names would be numbers
, pieces
or something similar.
Looking at the definition of chain()
, it seems to accept any iterable, which a range()
happens to be. So, you probably don't need that list()
, leaving this:
return range(int(z[0]),int(z[1])+1)
On your function unpackNums
instead of creating an empty set()
, you could use the a set comprehension:
def unpackNums(numString:str):
return {x for x in set(chain(*map(giveRange,numString.split(","))))}
If you notice any inaccuracies, please comment.
edited Aug 21 '15 at 0:49
Quill
10.4k53387
10.4k53387
answered Aug 20 '15 at 18:37
Ismael MiguelIsmael Miguel
4,31611453
4,31611453
add a comment |
add a comment |
$begingroup$
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
.
$endgroup$
add a comment |
$begingroup$
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
.
$endgroup$
add a comment |
$begingroup$
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
.
$endgroup$
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
.
answered Aug 20 '15 at 18:27
200_success200_success
130k16153417
130k16153417
add a comment |
add a comment |
$begingroup$
There's a python library called ifilters
built by me:
from ifilters import IntSeqPredicate as isp
print(list(filter(isp('1-5,3,15:16'), range(20))))
will output: [1, 2, 3, 4, 5, 15].
Note that in that library, 15:16
matches [15,16), whereas 15-16
matches [15,16].
New contributor
$endgroup$
add a comment |
$begingroup$
There's a python library called ifilters
built by me:
from ifilters import IntSeqPredicate as isp
print(list(filter(isp('1-5,3,15:16'), range(20))))
will output: [1, 2, 3, 4, 5, 15].
Note that in that library, 15:16
matches [15,16), whereas 15-16
matches [15,16].
New contributor
$endgroup$
add a comment |
$begingroup$
There's a python library called ifilters
built by me:
from ifilters import IntSeqPredicate as isp
print(list(filter(isp('1-5,3,15:16'), range(20))))
will output: [1, 2, 3, 4, 5, 15].
Note that in that library, 15:16
matches [15,16), whereas 15-16
matches [15,16].
New contributor
$endgroup$
There's a python library called ifilters
built by me:
from ifilters import IntSeqPredicate as isp
print(list(filter(isp('1-5,3,15:16'), range(20))))
will output: [1, 2, 3, 4, 5, 15].
Note that in that library, 15:16
matches [15,16), whereas 15-16
matches [15,16].
New contributor
New contributor
answered 27 mins ago
kkewkkew
1
1
New contributor
New contributor
add a comment |
add a comment |
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f101497%2fparsing-a-list-of-single-numbers-and-number-ranges%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown