Creating a list of random elements using recursion










3














I was asked to define a recursive function that takes in two parameters:



  • n



  • valmax



    and returns a list of n numbers picked randomly from the interval [0 , valmax]



`



import random

def random_list(n, valmax, lst = ):
"""
parameters : n of type int;
valmax of type int;
returns : a list of n numbers picked randomly from the interval
[0, valmax]
"""
if len(lst) == n:
return lst
return [random.randint(0, valmax)] + random_list(n, valmax)

print(random_list(10,100))`


However, I'm getting an




RecursionError




How can I fix my code so that it returns a list with n random numbers in the interval [0, valmax] ?










share|improve this question























  • you are trying to slice lst in your recursive step, but the list is empty at first. you may want to rethink if you'd want to slice it in the first place.
    – Paritosh Singh
    Nov 11 '18 at 19:17










  • Do you want to allow repetitions?
    – schwobaseggl
    Nov 11 '18 at 19:20















3














I was asked to define a recursive function that takes in two parameters:



  • n



  • valmax



    and returns a list of n numbers picked randomly from the interval [0 , valmax]



`



import random

def random_list(n, valmax, lst = ):
"""
parameters : n of type int;
valmax of type int;
returns : a list of n numbers picked randomly from the interval
[0, valmax]
"""
if len(lst) == n:
return lst
return [random.randint(0, valmax)] + random_list(n, valmax)

print(random_list(10,100))`


However, I'm getting an




RecursionError




How can I fix my code so that it returns a list with n random numbers in the interval [0, valmax] ?










share|improve this question























  • you are trying to slice lst in your recursive step, but the list is empty at first. you may want to rethink if you'd want to slice it in the first place.
    – Paritosh Singh
    Nov 11 '18 at 19:17










  • Do you want to allow repetitions?
    – schwobaseggl
    Nov 11 '18 at 19:20













3












3








3


1





I was asked to define a recursive function that takes in two parameters:



  • n



  • valmax



    and returns a list of n numbers picked randomly from the interval [0 , valmax]



`



import random

def random_list(n, valmax, lst = ):
"""
parameters : n of type int;
valmax of type int;
returns : a list of n numbers picked randomly from the interval
[0, valmax]
"""
if len(lst) == n:
return lst
return [random.randint(0, valmax)] + random_list(n, valmax)

print(random_list(10,100))`


However, I'm getting an




RecursionError




How can I fix my code so that it returns a list with n random numbers in the interval [0, valmax] ?










share|improve this question















I was asked to define a recursive function that takes in two parameters:



  • n



  • valmax



    and returns a list of n numbers picked randomly from the interval [0 , valmax]



`



import random

def random_list(n, valmax, lst = ):
"""
parameters : n of type int;
valmax of type int;
returns : a list of n numbers picked randomly from the interval
[0, valmax]
"""
if len(lst) == n:
return lst
return [random.randint(0, valmax)] + random_list(n, valmax)

print(random_list(10,100))`


However, I'm getting an




RecursionError




How can I fix my code so that it returns a list with n random numbers in the interval [0, valmax] ?







python recursion random






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 11 '18 at 19:19

























asked Nov 11 '18 at 19:13







user10158754


















  • you are trying to slice lst in your recursive step, but the list is empty at first. you may want to rethink if you'd want to slice it in the first place.
    – Paritosh Singh
    Nov 11 '18 at 19:17










  • Do you want to allow repetitions?
    – schwobaseggl
    Nov 11 '18 at 19:20
















  • you are trying to slice lst in your recursive step, but the list is empty at first. you may want to rethink if you'd want to slice it in the first place.
    – Paritosh Singh
    Nov 11 '18 at 19:17










  • Do you want to allow repetitions?
    – schwobaseggl
    Nov 11 '18 at 19:20















you are trying to slice lst in your recursive step, but the list is empty at first. you may want to rethink if you'd want to slice it in the first place.
– Paritosh Singh
Nov 11 '18 at 19:17




you are trying to slice lst in your recursive step, but the list is empty at first. you may want to rethink if you'd want to slice it in the first place.
– Paritosh Singh
Nov 11 '18 at 19:17












Do you want to allow repetitions?
– schwobaseggl
Nov 11 '18 at 19:20




Do you want to allow repetitions?
– schwobaseggl
Nov 11 '18 at 19:20












3 Answers
3






active

oldest

votes


















3














Your logic is wrong. You need each function call to return n random integers, so you do not need to pass it in a list.



Each function generates a single random number in the range [0, valmax] and concatenates it to the random list of integers which is of length one less (n-1) which it gets from calling itself recursively.



The base case is when n == 1, in which case we return an empty list.



import random
def random_list(n, valmax):
if n == 0:
return
return [random.randint(0, valmax)] + random_list(n-1, valmax)


and a test:



random_list(10, 20)
#[20, 9, 4, 7, 3, 4, 3, 18, 19, 9]





share|improve this answer




























    2














    Instead of keeping a default parameter (which can also cause unexpected behavior on consecutive calls), use yield for a cleaner solution. Also, simply use random.randint(0, valmax) to generate a single random integer between 0 and valmax:



    import random
    def random_list(n, valmax):
    if n:
    yield random.randint(0, valmax)
    yield from random_list(n-1, valmax)

    print(list(random_list(10, 10))) #create a list of length ten with random values between 0 and 10, inclusive.


    Output:



    [4, 6, 9, 1, 10, 2, 2, 8, 2, 10]





    share|improve this answer




























      1














      You could write a generic build_list function -



      import random

      def identity (x):
      return x

      def build_list (size, proc = identity):
      if size == 0:
      return
      else:
      return build_list (size - 1, proc) + [ proc (size - 1) ]

      print (build_list (5))
      # [ 0, 1, 2, 3, 4 ]

      print (build_list (5, lambda _: random.randint (0, 10)))
      # [ 4, 7, 7, 3, 6 ]


      random_list could be a specialization of build_list -



      def random_list (size, valmax):
      return build_list (size, lambda _: random.randint (0, valmax))

      print (random_list (5, 10))
      # [ 1, 7, 4, 7, 0 ]





      share|improve this answer




















        Your Answer






        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: "1"
        ;
        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: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        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%2fstackoverflow.com%2fquestions%2f53252243%2fcreating-a-list-of-random-elements-using-recursion%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









        3














        Your logic is wrong. You need each function call to return n random integers, so you do not need to pass it in a list.



        Each function generates a single random number in the range [0, valmax] and concatenates it to the random list of integers which is of length one less (n-1) which it gets from calling itself recursively.



        The base case is when n == 1, in which case we return an empty list.



        import random
        def random_list(n, valmax):
        if n == 0:
        return
        return [random.randint(0, valmax)] + random_list(n-1, valmax)


        and a test:



        random_list(10, 20)
        #[20, 9, 4, 7, 3, 4, 3, 18, 19, 9]





        share|improve this answer

























          3














          Your logic is wrong. You need each function call to return n random integers, so you do not need to pass it in a list.



          Each function generates a single random number in the range [0, valmax] and concatenates it to the random list of integers which is of length one less (n-1) which it gets from calling itself recursively.



          The base case is when n == 1, in which case we return an empty list.



          import random
          def random_list(n, valmax):
          if n == 0:
          return
          return [random.randint(0, valmax)] + random_list(n-1, valmax)


          and a test:



          random_list(10, 20)
          #[20, 9, 4, 7, 3, 4, 3, 18, 19, 9]





          share|improve this answer























            3












            3








            3






            Your logic is wrong. You need each function call to return n random integers, so you do not need to pass it in a list.



            Each function generates a single random number in the range [0, valmax] and concatenates it to the random list of integers which is of length one less (n-1) which it gets from calling itself recursively.



            The base case is when n == 1, in which case we return an empty list.



            import random
            def random_list(n, valmax):
            if n == 0:
            return
            return [random.randint(0, valmax)] + random_list(n-1, valmax)


            and a test:



            random_list(10, 20)
            #[20, 9, 4, 7, 3, 4, 3, 18, 19, 9]





            share|improve this answer












            Your logic is wrong. You need each function call to return n random integers, so you do not need to pass it in a list.



            Each function generates a single random number in the range [0, valmax] and concatenates it to the random list of integers which is of length one less (n-1) which it gets from calling itself recursively.



            The base case is when n == 1, in which case we return an empty list.



            import random
            def random_list(n, valmax):
            if n == 0:
            return
            return [random.randint(0, valmax)] + random_list(n-1, valmax)


            and a test:



            random_list(10, 20)
            #[20, 9, 4, 7, 3, 4, 3, 18, 19, 9]






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 11 '18 at 19:19









            Joe Iddon

            14.8k31538




            14.8k31538























                2














                Instead of keeping a default parameter (which can also cause unexpected behavior on consecutive calls), use yield for a cleaner solution. Also, simply use random.randint(0, valmax) to generate a single random integer between 0 and valmax:



                import random
                def random_list(n, valmax):
                if n:
                yield random.randint(0, valmax)
                yield from random_list(n-1, valmax)

                print(list(random_list(10, 10))) #create a list of length ten with random values between 0 and 10, inclusive.


                Output:



                [4, 6, 9, 1, 10, 2, 2, 8, 2, 10]





                share|improve this answer

























                  2














                  Instead of keeping a default parameter (which can also cause unexpected behavior on consecutive calls), use yield for a cleaner solution. Also, simply use random.randint(0, valmax) to generate a single random integer between 0 and valmax:



                  import random
                  def random_list(n, valmax):
                  if n:
                  yield random.randint(0, valmax)
                  yield from random_list(n-1, valmax)

                  print(list(random_list(10, 10))) #create a list of length ten with random values between 0 and 10, inclusive.


                  Output:



                  [4, 6, 9, 1, 10, 2, 2, 8, 2, 10]





                  share|improve this answer























                    2












                    2








                    2






                    Instead of keeping a default parameter (which can also cause unexpected behavior on consecutive calls), use yield for a cleaner solution. Also, simply use random.randint(0, valmax) to generate a single random integer between 0 and valmax:



                    import random
                    def random_list(n, valmax):
                    if n:
                    yield random.randint(0, valmax)
                    yield from random_list(n-1, valmax)

                    print(list(random_list(10, 10))) #create a list of length ten with random values between 0 and 10, inclusive.


                    Output:



                    [4, 6, 9, 1, 10, 2, 2, 8, 2, 10]





                    share|improve this answer












                    Instead of keeping a default parameter (which can also cause unexpected behavior on consecutive calls), use yield for a cleaner solution. Also, simply use random.randint(0, valmax) to generate a single random integer between 0 and valmax:



                    import random
                    def random_list(n, valmax):
                    if n:
                    yield random.randint(0, valmax)
                    yield from random_list(n-1, valmax)

                    print(list(random_list(10, 10))) #create a list of length ten with random values between 0 and 10, inclusive.


                    Output:



                    [4, 6, 9, 1, 10, 2, 2, 8, 2, 10]






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 11 '18 at 19:21









                    Ajax1234

                    40.4k42653




                    40.4k42653





















                        1














                        You could write a generic build_list function -



                        import random

                        def identity (x):
                        return x

                        def build_list (size, proc = identity):
                        if size == 0:
                        return
                        else:
                        return build_list (size - 1, proc) + [ proc (size - 1) ]

                        print (build_list (5))
                        # [ 0, 1, 2, 3, 4 ]

                        print (build_list (5, lambda _: random.randint (0, 10)))
                        # [ 4, 7, 7, 3, 6 ]


                        random_list could be a specialization of build_list -



                        def random_list (size, valmax):
                        return build_list (size, lambda _: random.randint (0, valmax))

                        print (random_list (5, 10))
                        # [ 1, 7, 4, 7, 0 ]





                        share|improve this answer

























                          1














                          You could write a generic build_list function -



                          import random

                          def identity (x):
                          return x

                          def build_list (size, proc = identity):
                          if size == 0:
                          return
                          else:
                          return build_list (size - 1, proc) + [ proc (size - 1) ]

                          print (build_list (5))
                          # [ 0, 1, 2, 3, 4 ]

                          print (build_list (5, lambda _: random.randint (0, 10)))
                          # [ 4, 7, 7, 3, 6 ]


                          random_list could be a specialization of build_list -



                          def random_list (size, valmax):
                          return build_list (size, lambda _: random.randint (0, valmax))

                          print (random_list (5, 10))
                          # [ 1, 7, 4, 7, 0 ]





                          share|improve this answer























                            1












                            1








                            1






                            You could write a generic build_list function -



                            import random

                            def identity (x):
                            return x

                            def build_list (size, proc = identity):
                            if size == 0:
                            return
                            else:
                            return build_list (size - 1, proc) + [ proc (size - 1) ]

                            print (build_list (5))
                            # [ 0, 1, 2, 3, 4 ]

                            print (build_list (5, lambda _: random.randint (0, 10)))
                            # [ 4, 7, 7, 3, 6 ]


                            random_list could be a specialization of build_list -



                            def random_list (size, valmax):
                            return build_list (size, lambda _: random.randint (0, valmax))

                            print (random_list (5, 10))
                            # [ 1, 7, 4, 7, 0 ]





                            share|improve this answer












                            You could write a generic build_list function -



                            import random

                            def identity (x):
                            return x

                            def build_list (size, proc = identity):
                            if size == 0:
                            return
                            else:
                            return build_list (size - 1, proc) + [ proc (size - 1) ]

                            print (build_list (5))
                            # [ 0, 1, 2, 3, 4 ]

                            print (build_list (5, lambda _: random.randint (0, 10)))
                            # [ 4, 7, 7, 3, 6 ]


                            random_list could be a specialization of build_list -



                            def random_list (size, valmax):
                            return build_list (size, lambda _: random.randint (0, valmax))

                            print (random_list (5, 10))
                            # [ 1, 7, 4, 7, 0 ]






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 11 '18 at 20:14









                            user633183

                            67.9k21135175




                            67.9k21135175



























                                draft saved

                                draft discarded
















































                                Thanks for contributing an answer to Stack Overflow!


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

                                To learn more, see our tips on writing great answers.





                                Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                Please pay close attention to the following guidance:


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

                                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%2fstackoverflow.com%2fquestions%2f53252243%2fcreating-a-list-of-random-elements-using-recursion%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

                                Kleinkühnau

                                Makov (Slowakei)

                                Deutsches Schauspielhaus