1

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)

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

Matt
  • 11
  • 2
  • 1
    `name` is not a list. You need to be using a list. – Rafe Kettler May 22 '11 at 22:18
  • http://stackoverflow.com/questions/352670/weighted-random-selection-with-and-without-replacement and following a link there http://stackoverflow.com/questions/2140787/select-random-k-elements-from-a-list-whose-elements-have-weights – Yann Vernier May 23 '11 at 13:19

4 Answers4

2

For this example, I'd do this:

import random
name = ["alpha", "bravo", "charlie", "delta", "echo"]
name = "\n".join(random.sample(name, 3))
orbital
  • 139
  • 2
1

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)
Winston Ewert
  • 44,070
  • 10
  • 68
  • 83
1

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
Wern
  • 481
  • 1
  • 3
  • 6
0

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'
riza
  • 16,274
  • 7
  • 29
  • 29