Alexandros Mylonas
Alexandros Mylonas

Reputation: 37

Error with matrix listing in python

I try to run this program but it has the following error:

Traceback (most recent call last):
  File "C:/Users/Αλέξανδρος/Desktop/1.py", line 12, in <module>
    k=k+C[s]
IndexError: list index out of range

The code is below

a=0
b=0
s=0
k=0
A = [0 for a in range(1000)]
B = [0 for b in range(1000)]
C = [0 for s in range(1000000)]
while a<=1000:
    C[s]=(A[a]**2+B[b]**2)**0.5
    a=a+1
    s=s+1
    k=k+C[s]
    if a==1000:
        b=b+1
        a=0
if a==1000 and b==1000:
    print (k/1000000)

I know that this question is probably duplicated, but I don't know how to solve it, because in the beggining I thought that the error is because C[-1] doesn't exist. But I don't think that is the problem.

Thank you in advance

Upvotes: 0

Views: 40

Answers (2)

FBergo
FBergo

Reputation: 1071

You are acessing past the array range, but just changing <= to < won't fix it as it will still execute

s=s+1
k=k+C[s]

in the iteration where s=999999 and it breaks when trying to access C[1000000].

You can easily debug the values on the iteration where it breaks by adding a print:

#!/usr/bin/python3

a=0
b=0
s=0
k=0
A = [0 for a in range(1000)]
B = [0 for b in range(1000)]
C = [0 for s in range(1000000)]
while a<=1000:
    print("a={:d} b={:d} s={:d}".format(a,b,s))
    C[s]=(A[a]**2+B[b]**2)**0.5
    a=a+1
    s=s+1
    k=k+C[s]
    if a==1000:
        b=b+1
        a=0
if a==1000 and b==1000:
    print (k/1000000)

And you will get your culprit:

(...)
a=997 b=999 s=999997
a=998 b=999 s=999998
a=999 b=999 s=999999
Traceback (most recent call last):
  File "./off.py", line 15, in <module>
    k=k+C[s]
IndexError: list index out of range

Regarding your algorithm, the s=s+1 / k=k+C[s] lines should probably be reversed (you want to accumulate in k the latest C[s] computed, C[s+1] is always 0 as it will only be computed by the next iteration.

Upvotes: 0

DYZ
DYZ

Reputation: 57033

Because of a<=1000 you code executes 1,000,001 iterations, but there are only 1,000,000 elements in the list. You made a classical "off by 1" mistake. Change <= to <.

Indeed, you should be using numpy for problems like this.

Upvotes: 2

Related Questions