我正在通过Project Euler编程,我遇到了一个奇怪的问题。我想找到所有可能的方法来从两个自然数中生成(自然)数字。我创建了一个简单的循环,我注意到了奇怪的结果。例如,从3和1产生1一些调查已经导致本:将值赋给python结果中的字典值为错误的键
#Importing stuff I often use in my solutions/tests
from math import sqrt, log, floor, pow, fabs, factorial
from sets import Set
from random import randint
from itertools import permutations
import sys
dub = dict()
c = 0 #Counting the number of elements in dub[18], use to track changes
for i in range (1,10):
if 18 in dub: #setting c = len(dub[18])
c = len(dub[18])
for j in range (i+1,10):
pair = [[i,j]]
v = i+j
if v in dub:
dub[v].append(pair[0])
else:
dub[v] = pair
v = i*j
if v in dub:
dub[v].append(pair[0])
else:
if i == 3 and j == 8: print 'here', v # The value that is added to dub[18] instead of dub[24]
dub[v] = pair
if 18 in dub and not c == len(dub[18]): #This is how I found that something is wrong.
c = len(dub[18])
print dub[18]
print v,i,j
raw_input()
与结果如下:
[[2, 9]]
18 2 9
[[2, 9], [3, 6]]
18 3 6
here 24
[[2, 9], [3, 6], [3, 8]]
24 3 8
我应该使用的关键是24,但该列表放置在关键之下18.为什么这样?
您的解决方案的工作,但我还是不明白。我使用不同的键,但我追加到同一个列表中? – Yotam
@Yam:我添加了一个有希望的解释性例子。 –
@SvenMarmach:谢谢。我现在知道了。 – Yotam