1

I'm working in Python, and basically I have a list of integers:

[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 10]

with the variable total, and I'm trying to figure out how to produce random numbers from this list (without replacement) until the 10 is produced, and then stop. I'm thinking that this would use random.shuffle within a while loop, but I'm not sure. Any tips or advice?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
hayleyelisa
  • 359
  • 4
  • 5
  • 15
  • Sorry, what is the role of `total` in this scenario? You want to figure out how many loops it takes to produce `10`? – Martijn Pieters Feb 09 '13 at 21:49
  • Yes, total is just my set of integers, which have varying numbers of 1, 2, 3...10, and I want to pull numbers randomly out of this set of integers until I get the 10, and then stop. – hayleyelisa Feb 09 '13 at 22:17
  • standard library ``random.choice`` *Choose a random element from a non-empty sequence.* – sotapme Feb 09 '13 at 23:58

2 Answers2

2

You pop() a random element from total and then check if it's a 10. For example:

while total.pop(random.randrange(len(total))) != 10:
     ... # do your stuff until the 10 is chosen

total.pop(i) removes from total the element of index i, so this will work without replacement. Also, check out this answer.

EDIT:
Maybe what you're trying to achieve by having multiple times the same element is a weighted random selection; that would be a rather ugly solution. That being the case, see if this question (Weighted random selection with and without replacement) helps. Cheers.

Community
  • 1
  • 1
FRD
  • 2,254
  • 3
  • 19
  • 24
1

Using random.shuffle doesn't even require a loop.

random.shuffle(l)
random_selection = l[ :l.index(10) ]
chepner
  • 497,756
  • 71
  • 530
  • 681