我想创建一个递归函数,它要么生成不同的置换,要么在列表中存储并返回它们和
我在https://www.geeksforgeeks.org/distinct-permutations-string-set-2/上找到了以下代码:
def shouldSwap(string, start, curr):
for i in range(start, curr):
if string[i] == string[curr]:
return False
return True
# Prints all distinct permutations
# in str[0..n-1]
def findPermutations(string, index, n):
if index >= n:
print(''.join(string))
return
for i in range(index, n):
# Proceed further for str[i] only
# if it doesn't match with any of
# the characters after str[index]
check = shouldSwap(string, index, i)
if check:
string[index], string[i] = string[i], string[index]
findPermutations(string, index + 1, n)
string[index], string[i] = string[i], string[index]
但我需要以某种方式编辑它,它将返回排列列表。 多谢各位
您可以将函数更改为生成器,并将结果转换为列表。这只需要两个变化:
将
print(''.join(string))
更改为yield ''.join(string)
并在
findPermutations(string, index + 1, n)
前面插入yield from
然后可以将其用作列表构造函数的参数:
然而,该功能过于复杂和繁琐。您可以使用更简单的方法获得相同的结果,从而避免将输入转换为列表并提供额外的参数
相关问题 更多 >
编程相关推荐