Function Returning Multiple Values in Python 2.7

Asked

Viewed 125 times

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)))))))))

1 answer

1


Jonah,

This is happening because when there are two or more returns in a function, Python returns all the data in a tuple (tuple) format, see this example:

def multiploRetorno():
  return 1,2

multiplo = multiploRetorno()

print(type(multiplo), multiplo)

https://repl.it/repls/ElderlySimultaneousOutcomes


There is the possibility of receiving this return in several variables, when done in this way, the return ceases to be the tuple:

def multiploRetorno():
  return 1,2

primeiro, segundo = multiploRetorno()

print(primeiro)
print(segundo)

https://repl.it/repls/JoyfulRosyCharacters


Therefore, as its function has two recursion returns, these tuples are generated, one inside the other.


So that your function returns a list when k > 1, you can do as follows:

from random import randrange

def geraIndiceAleatorio(vetor):
  return randrange(len(vetor))

def pegaRandom(vetor,k=1):
  if k==1:
    return vetor[geraIndiceAleatorio(vetor)]
  else:
    retorno = []
    vetor2 = vetor[:]

    for j in range(k):
      indice = geraIndiceAleatorio(vetor2)
      retorno.append(vetor2[indice])
      vetor2.pop(indice)

    return retorno

print(pegaRandom(range(1,50)))

print(pegaRandom(range(1,50),1))

print(pegaRandom(range(1,50),4))

print(pegaRandom(range(1,50),10))

https://repl.it/repls/IdenticalGrippingExperiment

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.