[英]Converting nested for-loops into a recursive function in Python
我試圖創建一個代碼來顯示字符串的所有可能的排列而不使用itertools,所以我想出了如何使用這些丑陋的嵌套for循環來實現它的基本思路,但現在我想將其轉換為對於長度為'n'的任何字符串的函數,我對遞歸有點新意,所以我需要一些幫助來解決這個問題。
wrdinp=input("Enter a word: ")
d=[]
#Works for string with length 4
for a in wrdinp:
for b in wrdinp:
if b!=a:
for c in wrdinp:
if c!=a and c!=b:
for d in wrdinp:
if d!=a and d!=b and d!=c:
d.append(a+b+c+d)
print("Permutations:",d)
我需要一個函數,它接受任意長度的字符串並返回一個包含字符串的各種排列的列表。
這是一種在遞歸中執行此操作的方法:
def permutations(wrdinp):
if len(wrdinp) <= 1:
return [wrdinp]
else:
d = []
for e in permutations(wrdinp[:-1]):
for i in range(len(e)+1):
d.append(e[:i] + wrdinp[-1] + e[i:])
return d
wrdinp=input("Enter a word: ")
result = permutations(wrdinp)
print(result)
希望能幫助到你 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.