如何在递归函数的列表中存储所有不同的排列?

2024-09-30 20:26:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建一个递归函数,它要么生成不同的置换,要么在列表中存储并返回它们和

我在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]

但我需要以某种方式编辑它,它将返回排列列表。 多谢各位


Tags: in列表forstringindexreturnifdef
1条回答
网友
1楼 · 发布于 2024-09-30 20:26:21

您可以将函数更改为生成器,并将结果转换为列表。这只需要两个变化:

print(''.join(string))更改为yield ''.join(string)

并在findPermutations(string, index + 1, n)前面插入yield from

然后可以将其用作列表构造函数的参数:

result = list(findPermutations(list("abc"),0,3)

然而,该功能过于复杂和繁琐。您可以使用更简单的方法获得相同的结果,从而避免将输入转换为列表并提供额外的参数

def permute(string):
    if len(string)==1: yield string;return
    for i,c in enumerate(string):
        yield from (c+rest for rest in permute(string[:i]+string[i+1:]))

result = list(permute("abc"))

# ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']

相关问题 更多 >