我正在解決一個 Hackerrank 問題,它只是最長公共子序列的簡單實作
tbl = [[0]*(len(s2) 1)] * (len(s1) 1)
# iterate the two strings and update the [i][j] location accordingly
for i in range(len(s1) 1):
for j in range(len(s2) 1):
if i == 0 or j == 0: continue # outer row/col indices
elif s1[i-1] == s2[j-1]:
tbl[i][j] = tbl[i-1][j-1] 1
else:
tbl[i][j] = max(tbl[i-1][j], tbl[i][j-1])
return tbl[len(s1)][len(s2)]
這一直給我錯誤的答案,即使我知道我正確地實作了演算法。
一時興起,我決定嘗試以不同的方式初始化我的表。我發現以下二維陣列初始化:
[[0]*(len(s2) 1) for i in range(len(s1) 1)]
唯一的區別是不是將外括號乘以 ,而是len(s) 1通過for回圈進行行擴展。
按提交,瞧,它接受了答案。
好奇,我把tblpython控制臺中的兩個初始化扔了。
>>> x = [[0]*(len(s2) 1)] * (len(s1) 1)
>>> y = [[0]*(len(s2) 1) for i in range(len(s1) 1)]
>>> x == y
True
這肯定是奇怪的行為。即使將表格內容列印到終端也證明了相同的結構。
>>> for row in x:
... print(row)
...
[None, None, None, None, None, None, None]
[None, None, None, None, None, None, None]
[None, None, None, None, None, None, None]
[None, None, None, None, None, None, None]
[None, None, None, None, None, None, None]
[None, None, None, None, None, None, None]
[None, None, None, None, None, None, None]
>>> for row in y:
... print(row)
...
[None, None, None, None, None, None, None]
[None, None, None, None, None, None, None]
[None, None, None, None, None, None, None]
[None, None, None, None, None, None, None]
[None, None, None, None, None, None, None]
[None, None, None, None, None, None, None]
[None, None, None, None, None, None, None]
>>>
有沒有人知道是什么導致了這種輸出差異?考慮到這可能與它的編譯方式有關,我使用 HR 給定的測驗用例輸入在本地測驗了該函式s1 = SHINCHAN; s2 = NOHARAAA,并使用我的(損壞的)表 init 產生了錯誤的 LCS 6 和我發現的正確 LCS 為 3在線的。
uj5u.com熱心網友回復:
這是典型的 Python 錯誤之一。您不能使用*運算子初始化二維陣列,例如x = [[0]*5]*5。原因是這為您提供了一個包含 5 個對 SAME[0,0,0,0,0]串列的參考的串列,它們不是 5 個獨立的串列。如果你改變x[0][3],你也會改變x[1][3]和x[2][3]。嘗試設定x[2][2] = 9并y[2][2] = 9注意差異。
>>> x[2][2] = 9
>>> y[2][2] = 9
>>> for row in x:
... print(row)
...
[0, 0, 9, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 9, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 9, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 9, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 9, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 9, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 9, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 9, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 9, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 9, 0, 0, 0, 0, 0, 0, 0]
>>> for row in y:
... print(row)
...
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 9, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/397236.html
