Using recursion to generate a list of X random numbers between 0 and 100, sorted from low to high in Python? -
i'm trying write program uses recursion generate list of x random numbers within range of 0 100, sorts them low high. code have written far:
import random def multicaller(x): if x == 0: return "enter valid number" else: return random.randint(0, 100) + multicaller(x) multicaller.sort() return multicaller(x)
this crashes, , i'm not sure go here. ideal output this. let's enter multicaller(4)
: program ideally generate [3, 35, 45, 82]
. if entered, multicaller(5)
, [1, 2, 45, 56, 99]
, , on. @ appreciated!
to recursively achieve have said, need honor base case first i.e need return empty list when asked random number list length zero. if x not 0 need create list single random number , recursively call same function x-1 , concatenate them both, result in list x number of random numbers
import random def multicaller(x): if x == 0: return [] else: return [random.randint(0, 100)] + multicaller(x-1) def get_list(x): res = multicaller(x) res.sort() return res print get_list(5)
Comments
Post a Comment