Parsing a list of single numbers and number ranges












9












$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")









share|improve this question











$endgroup$

















    9












    $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")









    share|improve this question











    $endgroup$















      9












      9








      9





      $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")









      share|improve this question











      $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






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Sep 5 '15 at 20:21









      Jamal

      30.3k11120227




      30.3k11120227










      asked Aug 20 '15 at 18:09









      CarbonCarbon

      1646




      1646






















          3 Answers
          3






          active

          oldest

          votes


















          4












          $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.






          share|improve this answer











          $endgroup$





















            5












            $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.






            share|improve this answer









            $endgroup$





















              0












              $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].






              share|improve this answer








              New contributor




              kkew is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
              Check out our Code of Conduct.






              $endgroup$













                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
                });


                }
                });














                draft saved

                draft discarded


















                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









                4












                $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.






                share|improve this answer











                $endgroup$


















                  4












                  $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.






                  share|improve this answer











                  $endgroup$
















                    4












                    4








                    4





                    $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.






                    share|improve this answer











                    $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.







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    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

























                        5












                        $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.






                        share|improve this answer









                        $endgroup$


















                          5












                          $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.






                          share|improve this answer









                          $endgroup$
















                            5












                            5








                            5





                            $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.






                            share|improve this answer









                            $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.







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Aug 20 '15 at 18:27









                            200_success200_success

                            130k16153417




                            130k16153417























                                0












                                $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].






                                share|improve this answer








                                New contributor




                                kkew is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                Check out our Code of Conduct.






                                $endgroup$


















                                  0












                                  $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].






                                  share|improve this answer








                                  New contributor




                                  kkew is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                  Check out our Code of Conduct.






                                  $endgroup$
















                                    0












                                    0








                                    0





                                    $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].






                                    share|improve this answer








                                    New contributor




                                    kkew is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                    Check out our Code of Conduct.






                                    $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].







                                    share|improve this answer








                                    New contributor




                                    kkew is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                    Check out our Code of Conduct.









                                    share|improve this answer



                                    share|improve this answer






                                    New contributor




                                    kkew is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                    Check out our Code of Conduct.









                                    answered 27 mins ago









                                    kkewkkew

                                    1




                                    1




                                    New contributor




                                    kkew is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                    Check out our Code of Conduct.





                                    New contributor





                                    kkew is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                    Check out our Code of Conduct.






                                    kkew is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                    Check out our Code of Conduct.






























                                        draft saved

                                        draft discarded




















































                                        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.




                                        draft saved


                                        draft discarded














                                        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





















































                                        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







                                        Popular posts from this blog

                                        404 Error Contact Form 7 ajax form submitting

                                        How to know if a Active Directory user can login interactively

                                        Refactoring coordinates for Minecraft Pi buildings written in Python