Pr.Germux
Pr.Germux

Reputation: 55

Two-Dimensional array (IndexError: list index out of range)

I'm trying to make an algorithm, which counts how many numbers are divided without a remainder.

d=[]
for i in range (0, 10001):
    for c in range (1, 16):
        if i % c == 0: d[c] += 1

I expect to have something like this

/1:  10000
/2:  5000
/3:  3334
/4:  2500
/5:  2000
/6:  1667
/7:  1429
/8:  1250
/9:  1112
/10:  1000
/11:  910
/12:  834
/13:  770
/14:  715
/15:  667

, but i get IndexError: list index out of range

Upvotes: 1

Views: 61

Answers (2)

NPE
NPE

Reputation: 500883

Just fill the list with zeros:

d = [0] * 17  # <== THIS
for i in range (0, 10001):
    for c in range (1, 16):
        if i % c == 0: d[c] += 1

Note that this has an extraneous zero at the start (i.e. d[0]). Very easy to ignore.

Also, your counts are off by one compared to what your code actually does (for example, there are 10001 even numbers in your range and not 10000).

Upvotes: 2

Scott Hunter
Scott Hunter

Reputation: 49920

You can't add to an element of a list that has never been created.

Upvotes: 2

Related Questions