我正在通过Project Euler进行编程,但遇到了一个奇怪的问题。我想找到从两个自然数生成(自然)数的所有可能方法。我创建了一个简单的循环,我注意到奇怪的结果。例如,1 是从 3 和 1 生成的。一些调查结果如下:
#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 下。为什么会这样?