Question

To learn python I am implementing Bulls and Cows. So I need to generate a 'random' number. I tried this:

possibilities = range(10)
number = "".join([str(possibilities.pop(random.choice(possibilities))) for i in range(4)])

Which I thought was a nice solution to the problem, but once in every couple of runs I get an IndexError on that line: IndexError: pop index out of range

So it looks like random.choice() gives me a non existent index. How come? Or am I making a wrong assumption and is the problem something else entirely? Come to think of it, I haven't got a clue how to debug a statement like this, any pointers on that?

Edit
My first solution was of the procedural kind:

for i in range(4):
    idx = random.choice(possibilities)
    number = number + str(possibilities[idx])
    del possibilities[idx]

This code seems to do the exact same thing as the one-liner above, but has no problems whatsoever.

Was it helpful?

Solution

You aren't randomly choosing indices, you're choosing values from the list. What if you pick 9 after a lower number or two has been popped from the list?

Instead, use random.sample:

number = "".join(map(str, random.sample(range(10), 4)))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top