R. Leal - 1 year ago 61

Python Question

I'm trying to make an array with 30 integer elements between 0 and 2 randomly chosen. When some number is chosen 10 times, i can't append it anymore. In the end, I need an array with 30 elements with 10 numbers 0, 10 numbers 1 and 10 numbers 2. Here's what i'm trying:

`import random`

array_size = 30

number = 3

counter = [0, 0, 0]

solution = []

for i in range(array_size):

number = random.randrange(number) #generates numbers between 0 and 2

while counter[number] > 10:

number = random.randrange(number)

counter[number] += 1

solution.append(number)

As result, i have more than 10 elements of the same number. I believe the problem is in the random number that i put in the while is not changed even if i change it inside the loop. Someone know how to do this?

Thanks

Answer Source

Just change

```
while number[counter] > 10:
```

to

```
while number[counter] >= 10:
```

Originally your code would only stop appending a certain number only if there were more than 10 instances of it within your array. By changing it to a >=, the program will stop appending the number the moment it adds it for a tenth time.