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] ?

Community
  • 1
  • 1

3 Answers3

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]
Joe Iddon
  • 20,101
  • 7
  • 33
  • 54
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]
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
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 ]
Mulan
  • 129,518
  • 31
  • 228
  • 259