So I'm creating a matchup generator for my friends since 2k is launching soon but I can't figure out how to stop the repeating of the names of my list when the matchups are generated. I've only been learning python for a few days. I've tried random.sample, and random.choice(my original code, which I now realize is not right.) The code works but it generates repeated values, i.e. 'red vs red', 'blue vs blue.' How do I stop this?
import random
print("Matchup Generator")
bracket_one = ["sub", "gc", "ron", "tame", "clak", "moe", "matic", "kapp"]
bracket_two = ["red", "blue", "yellow", "green"]
lineup = int(input("Press '1' for bracket one or press '2' for bracket two: "))
if lineup == 1:
print("You chose a bracket of 8 competitors. \n The matchups are: \n")
x = range(4)
#print(x)
for x in x:
matchups_one = random.sample(bracket_one, 1) " vs " random.sample(bracket_one, 1)
print(matchups_one)
elif lineup == 2:
print("You chose a bracket of 4 competitors. \n The matchups are: \n")
y = range(2)
#print(y)
for y in y:
matchups_two = matchups_two = random.choice(bracket_two) " vs " random.choice(bracket_two)
print(matchups_two)
else:
print("You did not press '1' or '2'")
CodePudding user response:
Check https://numpy.org/doc/stable/reference/random/generated/numpy.random.choice.html, quote - replace - Whether the sample is with or without replacement. Default is True, meaning that a value of a can be selected multiple times.
CodePudding user response:
The main issue is that you're not removing the elements you randomly sample from the bracket. Therefore, you always have a chance of getting elements you already saw when you sample the bracket again.
Another note - while it doesn't really change the result, you can sample 2 competitors at each matchup, instead of sampling 1 competitor twice for each matchup.
Then for each matchup, you will randomly draw 2 competitors and remove them from the list. Then the next matchup will pick 2 new competitors from the remaining competitors in the list.
With a few other adjustments, the code might look something like this:
import random
print("Matchup Generator")
bracket_one = ["sub", "gc", "ron", "tame", "clak", "moe", "matic", "kapp"]
bracket_two = ["red", "blue", "yellow", "green"]
lineup = int(input("Press '1' for bracket one or press '2' for bracket two: "))
if lineup != 1 and lineup != 2:
print("You did not press '1' or '2'")
quit()
bracket = bracket_one if lineup == 1 else bracket_two
num_competitors = len(bracket)
print(f"You chose a bracket of {num_competitors} competitors. \n The matchups are: \n")
num_matchups = num_competitors // 2
for i in range(num_matchups):
competitor1, competitor2 = random.sample(bracket, 2)
bracket.remove(competitor1)
bracket.remove(competitor2)
matchup = f"{competitor1} vs. {competitor2}"
print(matchup)