Bárbara - 7 months ago 43

Python Question

I am trying to run the following code. For those who know it, this is a try of the Ehrenfest Urn simulation.

`import numpy as np`

import random

C=5

L=2

# Here I create a matrix to be filled with zeros and after with numbers I want

b=np.zeros( (L,C) ) # line x column

A=[] # here I creat 2 lists to put random integer numbers on it

B=[]

i=1

while i<=10: # here I am filling list A (only) with 10 numbers

A.append(i)

i=i+1

for j in range(2):

for i in range(5): #here I want to choose random numbers between 1 and 10,

Sort=random.randint(1,10)

if i==0: # since there is no number on B, the first step, the number goes to B

B.append(Sort)

A.remove(Sort)

print(len(A))

if i>0: # now each list A and B have numbers on it, so I will choose one number and see in which list it is

if Sort in A:

B.append(Sort)

A.remove(Sort)

else:

A.append(Sort)

B.remove(Sort)

i=i+1

b[j,i]=len(A) # here I want to add the lenght of the list A in a matrix, but then I get the error.

j=j+1

print(b)

But I get the following error:

`Traceback (most recent call last):`

File "<ipython-input-26-4884a3da9648>", line 1, in <module>

runfile('C:/Users/Public/Documents/Python Scripts/33.py', wdir='C:/Users/Public/Documents/Python Scripts')

File "C:\Program Files\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 866, in runfile

execfile(filename, namespace)

File "C:\Program Files\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile

exec(compile(f.read(), filename, 'exec'), namespace)

File "C:/Users/Public/Documents/Python Scripts/33.py", line 42, in <module>

b[j,i]=len(A) # here I want to add the lenght of the list A in a matrix

IndexError: index 5 is out of bounds for axis 1 with size 5

What am I doing wrong with the arrays?

Is there anything to do with the identification of the numbers in the matrix?

Answer

The error implies that `b.shape[1]`

(axis 1) is 5; but `i`

is 5. Remember indexing starts at 0.

In the broader picture:

```
while i<5: #here I want to choose random numbers between 1 and 10,
...
i=i+1
b[j,i] ...
```

at the last iteration `i==4`

, you add one, and now it is 5, and gives the error.

Typically in Python we iterate with

```
for i in range(5):
b[j,i] ...
```

`range(5)`

produces `[0,1,2,3,4]`

. You may have good reasons to use the while instead, but it's subject to the same bounds.

Source (Stackoverflow)