該函式接受一個字串 (str) s 和一個整數 (int) n 。
- 該函式回傳一個長度為 n 的 s 的所有笛卡爾積的串列(串列)
- 運算式 product(s,n) 可以通過將 s 中的每個字符添加到 product(s,n-1) 的結果中來計算。
>>> product('ab',3)
'aaa', 'aab', 'aba', 'abb', 'baa', 'bab', 'bba', 'bbb']
我的嘗試:
def product(s, n):
if n == 0:
return ""
string = ''
for i in range(len(s)):
string = s[i] product(s, n - 1)
return string
免責宣告:它不起作用^
uj5u.com熱心網友回復:
您的代碼正在構建一個字串。這與函式應該做的不匹配,即回傳字串串列。您需要添加串列構建邏輯,并處理遞回呼叫也將生成串列的事實。
我會做這樣的事情:
def product(s, n):
if n == 0:
return ['']
result = []
for prefix in s: # pick a first character
for suffix in product(s, n-1): # recurse to get the rest
result.append(prefix suffix) # combine and add to our results
return result
這會以所需的順序產生輸出,但它的遞回頻率比必要的要高得多。您可以交換回圈的順序,但為了避免以不同的順序獲得結果,您需要更改邏輯以便直接從中選擇最后一個字符,s同時讓遞回產生前綴。
def product(s, n):
if n == 0:
return ['']
result = []
for prefix in product(s, n-1): # recurse to get the start of each string
for suffix in s: # pick a final character
result.append(prefix suffix) # combine and add to our results
return result
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/527153.html
