我使用python創建字典,但隨着數據變大,我開始出現內存錯誤,所以我想我會節省內存,只是將數據寫入數據庫,但結果並不相同。我認爲這與defaultdict的行爲有關(但我不確定)。python和mysql之間的結果類似,命令不一樣
這裏的工作Python代碼(它基本上建立數值表):
from collections import defaultdict
data = [2,5,10]
target_sum = 100
# T[x, i] is True if 'x' can be solved
# by a linear combination of data[:i+1]
T = defaultdict(bool) # all values are False by default
T[0, 0] = True # base case
for i, x in enumerate(data): # i is index, x is data[i]
for s in range(target_sum + 1): #set the range of one higher than sum to include sum itself
for c in range(s/x + 1):
if T[s - c * x, i]:
T[s, i+1] = True
#check the python dict results
count = 0
for x in T:
if T[x] == True:
print x, ':', T[x]
count = count +1
print 'total count is ', count
#False is 152 and True is 250. Total is: 402
結果是值的大表(你可以看到在評論擊穿這是正確的結果我想要),但是當我將第一條語句的最後一行更改爲添加到數據庫而不是本地字典時,結果會有所不同。
這裏是我修改後的代碼是有問題的:
cursor = conn.cursor()
cursor = conn.cursor()
cursor.execute ("DROP TABLE IF EXISTS data_table")
cursor.execute ("""
CREATE TABLE data_table
(
value CHAR(80),
state BOOL
)
""")
#with database
for i, x in enumerate(data): # i is index, x is data[i]
for s in range(target_sum + 1): #set the range of one higher than sum to include sum itself
for c in range(s/x + 1):
cursor.execute(""" SELECT value, state FROM data_table WHERE value='%s' """ % ([s - c * x, i]))
if cursor.rowcount == 0:
#print 'nothing found, adding'
cursor.execute (""" INSERT INTO data_table (value, state) VALUES ('%s', False)""" % ([s - c * x, i]))
elif cursor.rowcount == 1:
cursor.execute (""" UPDATE data_table SET state=True WHERE value = '%s'""" % ([s - c * x, i]))
#print 'record updated'
conn.commit()
#False is 17 and True is 286. Total is: 303
只是總結一下(如果你不想運行的代碼),defaultdict創建時的東西被查詢的虛假條目(在此case if T[s - c * x, i]:
)所以要複製這個特性,我做了一個mysql查找值,如果它不存在,那麼我創建它,如果它確實存在,那麼我將它設置爲true。我高度懷疑我沒有正確地複製功能
我唯一想到的其他事情是python顯示結果爲(222, 0) : False
但mysql正在做[222,0]不知道這是否有所作爲。
謝謝你指出這一點..我剛剛解決這個問題。現在一切都是錯誤的。但算法通過查看過去的請求,然後改變之前的價值。 – Lostsoul 2012-02-17 23:39:09
@Lostsoul檢查我的更新答案,那個錯誤不是唯一的。 – mgibsonbr 2012-02-17 23:51:01
@Lostsoul我也發佈了一個替代解決方案,只存儲True值 – mgibsonbr 2012-02-18 00:13:40