2016-10-10 48 views
1

我試圖編寫一個數獨解算器(有一些部分引用到http://norvig.com/sudoku.html無法更新字典

這裏是我做了迄今參照上述網址的代碼面臨這樣的問題。

puzzle = '003198070890370600007004893030087009079000380508039040726940508905800000380756900' 
 
cell = '123456789' 
 
cell_break = ['123','456','789'] 
 

 

 
def generate_keys(A, B): 
 
    "Cross product of elements in A and elements in B." 
 
    return [a+b for a in A for b in B] 
 

 
#print generate_keys(cell,cell) 
 

 
def dict_puzzle(puzzle,cell): 
 
    'Making a dictionary to store the key and values of the puzzle' 
 
    trans_puzzle = {} 
 
    key_list = generate_keys(cell,cell) 
 
    i=0 
 
    for x in puzzle: 
 
    trans_puzzle[str(key_list[i])] = x 
 
    i = i + 1 
 
    return trans_puzzle 
 

 
dict_puzzle(puzzle,cell)['11'] = 'die' 
 
print dict_puzzle(puzzle,cell)['11']

最後2行的代碼,我試圖變異字典,但無濟於事。它只是返回我0,這是原始值。 (即突變wasnt成功)

我不知道爲什麼會這樣:(

+1

你每次運行'dict_puzzle()',創建了一個全新的解釋和以前的任何修改都扔掉了。我想,你只需要調用它__once__,保存產生一些名稱,並對該名稱執行所有進一步的操作。 –

回答

1

你再次調用該函數,所以它返回一個新的字典。你需要將第一個調用的結果一個變量和變異這一點。

result = dict_puzzle(puzzle,cell) 
result['11'] = 'die' 
print(result)