gol*_*ean 6 string iteration permutation python-2.7
我阅读了这个简单而优雅的python解决方案,用于查找给定字符串的所有排列.它是递归的.基于此,我尝试在python中实现迭代解决方案.
以下是我的代码.但它只适用于3个字符串:(试图看看递归基本情况条件和递归条件如何转换为迭代(非递归)任何指针都有助于使迭代解决方案有效.(基于此算法或任何其他)
def permutations_iter(word):
while True:
perms = []
result = []
char = word[0]
new_word = word[1:]
if len(new_word)==2:
perms = [new_word,''.join(reversed(new_word))]
for perm in perms:
#insert the character into every possible location
for i in range(len(perm)+1):
result.append(perm[:i] + char + perm[i:])
return result
if len(new_word)==2:
break;
#example code to call this iterative function
print permutations_iter("LSE")
Run Code Online (Sandbox Code Playgroud)
Vik*_*kez 17
您可以使用堆栈将每个递归转换为迭代.但在这种情况下,由于算法非常简单,因此更简单.
def perms(word):
stack = list(word)
results = [stack.pop()]
while len(stack) != 0:
c = stack.pop()
new_results = []
for w in results:
for i in range(len(w)+1):
new_results.append(w[:i] + c + w[i:])
results = new_results
return results
Run Code Online (Sandbox Code Playgroud)
对于递归到迭代的更一般转换,使用堆栈读取此内容