我需要將串列的深層副本(不是參考)以遞回方式附加到其自身 n 次,例如
n=0 -> []
n = 1 -> [[]]
n=2 -> [[], [[]]]
and so forth.
這是我到目前為止寫的:
def magic_list(n: int) -> List[Any]:
#take only positive numbers
assert(n>=0)
if n == 0:
return []
else:
return magic_list_helper(0, n, [])
主要功能,我必須保持這個def簽名完全相同(只需要n:int)。這是我寫的輔助函式:
def magic_list_helper(index: int,threshold:int ,lst:List[Any]) -> List[Any]:
if index >= threshold:
return lst
else:
# temp_lst = deepcopy(lst)
# lst.append(temp_lst)
return magic_list_helper(index 1, threshold, lst)
對于這個問題,我無法使用copy.deepcopy
或任何其他外部庫(這就是為什么它帶有#,沒有它就可以作業)并且我無法在沒有深拷貝的情況下在線找到解決方案。我也不能對串列使用串列理解、切片或任何 O(n) 操作(我可以使用追加)。希望你能幫助我,在此先感謝。
uj5u.com熱心網友回復:
你可以試試這個。不確定它是否正確。
l=[]
n=2
for i in range(n):
l.append(l.copy())
print(l)
uj5u.com熱心網友回復:
你不需要復印。每個呼叫都可以使用執行n
時間的串列推導,遞回呼叫自身。串列推導式創建適當長度的新串列。
您甚至不需要檢查基本情況,因為當n == 0
串列推導將回傳一個空串列時。
def magic_list(n: int) -> List[Any]:
return [magic_list(x) for x in range(n)]
for i in range(5): print(magic_list(i))
[]
[[]]
[[], [[]]]
[[], [[]], [[], [[]]]]
[[], [[]], [[], [[]]], [[], [[]], [[], [[]]]]]
uj5u.com熱心網友回復:
使用歸納推理是遞回問題解決的基礎——
- 如果
n
小于或等于零,則作業完成。回傳空結果,[]
- (感應)
n
至少為 1(正)。找到子問題的結果,magic_list(n - 1)
并將其連接到相同子問題的單例串列中,[magic_list(n - 1)]
# write
def magic_list(n):
if n <= 0: return []
return magic_list(n - 1) [magic_list(n - 1)]
遞回是一種函式式遺產,因此將其與函式式風格一起使用會產生最佳結果。這意味著要避免諸如突變 ( .append
)、變數重新分配和其他副作用之類的事情。
# test
for n in range(5):
print(magic_list(n))
# output
[]
[[]]
[[], [[]]]
[[], [[]], [[], [[]]]]
[[], [[]], [[], [[]]], [[], [[]], [[], [[]]]]]
在上面的程式中,可以看到子問題magic_list(n - 1)
被計算了兩次。我們通過將結果分配給一個變數來將作業減半 -
# optimize
def magic_list(n):
if n == 0: return []
m = magic_list(n - 1) # ??
return m [m] # ??
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/470935.html
下一篇:匿名遞回函式