Reputation: 21
I'm trying to loop through a list of values I got from database
I tried using a while loop to go through it while less than a number of times given by the user.
def winner(x):
winner = random.choice(x)
return winner_list(x, winner)
winner_lists = []
def winner_list(y, x):
if x not in winner_lists:
winner_lists.append(x)
else:
winner(y)
i = 0
competitors = User.query.all() #gotten from database
main_competitors = []
for competitor in competitors:
competitor_raffles = competitor.raffles.split(',')
if uuid in competitor_raffles:
main_competitors.append(competitor.uuid.strip(' '))
while (i < form.number.data) and (main_competitors != []):
winner(main_competitors)
i+=1
I expect to see randomly chosen names from the list competitors
Upvotes: 0
Views: 1043
Reputation: 53623
winner_list
doesn't return a value to the caller. There's a bit to unpack here including the fact that you're using variable names that shadow your function names, among other things I'd change, but ultimately this is not a problem that requires recursion.
Why not? You know how many times to maximally choose a winner (from form.number.data
), and you have a list of competitors of certain length.
This example chooses only unique winners. If a competitor can "win" more than once, then just remove the last line.
results = []
how_many_winners = form.number_data
contestants = main_competitors[:]
while main_competitors and len(results) < how_many_winners:
this_winner = random.choice(contestants)
results.append(this_winner)
contestants.remove(this_winner) # Remove this line if a contestant can 'win' more than once
Upvotes: 0
Reputation: 81
It looks like the problem is in the while loop. When winner_lists
has all of the main_competitors
in it, then the functions winner
and winner_lists
keep calling each other since it is impossible to choose a new winner.
Maybe you forgot to remove a competitor from main_competitors
each time winner
is run.
Upvotes: 1