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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With