dimanche 11 novembre 2018

Creating a list of random elements using recursion

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(int(lst[0]),valmax)] + random_list(lst[1:])

print(random_list(10,100))`

However, I'm getting an

IndexError: list out of range

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




Aucun commentaire:

Enregistrer un commentaire