Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why KeyError: 0

I'm attempting to solve Project Euler 21 but I'm getting KeyError: 0 which normally occurs when you refer to a dictionary key that doesn't exist. However, I thought I had solved that problem with the < 10000 condition. The error refers to the first 'if' statement in the main() function.

sumsdivs = {}
for i in range(1, 10000):
    tmpls = []
    for j in range(1, i):
        if i % j == 0:
            tmpls.append(j)
    sumsdivs[i] = sum(tmpls)

amls = []
def main():
    for i in range(1, 10000):
        if sumsdivs[i] < 10000 and sumsdivs[i] == sumsdivs[sumsdivs[i]]:
            if sumsdivs[i] not in amls:
                amls.append(sumsdivs[i])
            if sumsdivs[sumsdivs[i]] not in amls:
                amls.append(sumsdivs[sumsdivs[i]])
    return sum(amls)

print(main())

Any ideas?

like image 484
mistermarko Avatar asked May 04 '26 01:05

mistermarko


1 Answers

You insert 0 for i = 1 here:

sumsdivs = {}
for i in range(1, 10000):
    tmpls = []
    for j in range(1, i):
        if i % j == 0:
            tmpls.append(j)
    sumsdivs[i] = sum(tmpls)

The inner loop never runs (range(1, 1) is empty), and sum([]) is 0.

Demo:

>>> sumsdivs = {}
>>> for i in range(1, 2):
...     tmpls = []
...     for j in range(1, i):
...         if i % j == 0:
...             tmpls.append(j)
...     sumsdivs[i] = sum(tmpls)
... 
>>> sumsdivs
{1: 0}
>>> sum([])
0    

So sumsdivs[1] is 0, and sumsdivs[sumsdivs[0]] throws a KeyError:

>>> sumsdivs[sumsdivs[1]]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 0
like image 193
Martijn Pieters Avatar answered May 05 '26 14:05

Martijn Pieters