我正在練習遞回,我想回傳串列中每個元素的深度(從 1 開始)(我已經完成了),還想回傳嵌套串列深度的加權和 * 值。
例如,[1, [4]] -> (1 * 1) (4 * 2) = 1 8 = 9
我正在使用變數res來存盤總和,但是每次它更改為新的串列串列時都會重新啟動它的計數器。有沒有辦法像我對串列一樣跟蹤總和?
nestedList = [[1,1],2,[1,1]]
def depth_checker(nested_list, depth=1, output=[], res=0):
for i in nested_list:
if not isinstance(i, list):
output.append(depth)
print(i, depth)
res = res (i * depth)
print(res)
elif isinstance(i, list):
depth_checker(i, depth 1, output, res)
return (res, output)
輸出
depth_checker(nestedList)
OUTPUT >>
1 2
2
1 2
4
2 1
2
1 2
4
1 2
6
(2, [2, 2, 1, 2, 2]])
預期輸出:
(10, [2, 2, 1, 2, 2])
uj5u.com熱心網友回復:
你可以這樣做:
def depth_checker(nested_list, depth=1):
res = 0
for obj in nested_list:
if isinstance(obj, list):
res = depth_checker(obj, depth 1)
else:
res = obj * depth
return res
print(depth_checker([2, 2, 1, 2, 2])) # 9
uj5u.com熱心網友回復:
問題是串列和整數的實作之間的區別。當您對 進行遞回呼叫時depth_checker
,對 的任何更改output
都將反映在原始變數中。但是,對 的更改res
不會修改傳入的變數。串列是可變的,整數不是。
您最簡單的選擇是更改代碼以res
在所有情況下都回傳值。然后修改最后一行以res = depth_checker(....)
使其更新
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/507836.html