Trying to make this section of python code repeat until it gets three different results. This isn't the actual code, just a simplified version that does the same thing.
roll = random.randint(1,100)
if roll < 10:
name += "alpha"
elif roll < 37:
name += "bravo"
elif roll < 50:
name += "charlie"
elif roll < 89:
name += "delta"
else:
name += "echo"
print(name)
Basic开发者_如何学编程ally, I want this segment of code to continuously repeat until [name] has three different values, and then I want the output to list all three values, each on a new line. I'm not sure what the best way to do this would be. Thanks for any helpn
edit: in my actual code, the ranges for each number aren't evenly distributed. I edited the above to reflect this. Since the chance at getting each of the five possible results is different, random.sample won't work (unless it can be formatted for different odds on each result)
For this example, I'd do this:
import random
name = ["alpha", "bravo", "charlie", "delta", "echo"]
name = "\n".join(random.sample(name, 3))
Make a list and then loop until you have three unique items in it.
values = []
while len(values) != 3:
index = random.randrange(100)
value = determine_value_for_index(index)
if value not in values:
values.append(value)
If you need unique values, perhaps the set
type is what you're after.
name = set()
while len(name)<3:
roll = random.randint(1,100)
if roll < 10: name.add("alpha")
elif roll < 37: name.add("bravo")
elif roll < 50: name.add("charlie")
elif roll < 89: name.add("delta")
else: name.add("echo")
for n in name: print n
What is wrong with random.sample?
names = ["alpha", "bravo", "charlie", "delta", "echo"]
random.sample(names, 3) # ['delta', 'echo', 'bravo']
random.sample(names, 3) # ['echo', 'charlie', 'delta']
random.sample(names, 3) # ['bravo', 'charlie', 'delta']
EDIT:
name = ''.join(random.sample(names, 3)) # 'deltabravocharlie'
精彩评论