1
It’s my first post on this forum, so I apologize in advance for any etiquette error.
I’m trying to implement a function in Python 2.7 that returns me a random element from a list or a sublist of random elements of certain size. My idea for implementation was this:
def pegaRandom(vetor,k=1):
n = len(vetor)
i = randrange(n)
retorno = vetor[i]
if k==1:
return retorno
else:
vetor2 = list(vetor)
vetor2.pop(i)
return retorno, pegaRandom(vetor2,k-1)
My expected behavior was that the function would return me a sublist when k>1, but instead I have something like:
>>> pegaRandom(range(1,50),4)
(41, (37, (45, 26)))
>>> pegaRandom(range(1,50),10)
(15, (5, (21, (8, (39, (35, (19, (11, (12, 2)))))))))
Thank you Daniel! Its implementation with geraIndice gave me a simpler idea, which is to simply generate k random numbers between 0 and Len(n)-1 and return the vector. Since the vector can be the same in multiple instances the recursive call simply adds to the vector. Thank you!
– Jonas Gomes