如何使用递归从各种输入量进行排列以在 Python 中工作?

How do I make permutations with recursion from various amount of input to work in Python?

我快要完成这个程序了,但是我遇到了一个问题,如果我将超过 2 个项目输入到列表中,比如 3 个项目或 4 个项目,它只会在每行中生成 2 个项目的输出直到置换完成。我希望它输出对应于每行输入项目的数量,直到排列完成。

(我还不能嵌入图片。这是下图中的示例。)

https://imgur.com/XP7RLp0

def all_permutations(permList, nameList):

    if len(permList) == 2 or len(permList) == 3 or len(permList) == 4:
        for i in range(len(permList)):
            print(permList[i], end=" ")
        print()

    else:
        for indx, itm in enumerate(nameList):
            permList.append(itm)
            nameList.pop(indx)
            all_permutations(permList, nameList)
            nameList.insert(indx, itm)
            permList.pop()

if __name__ == "__main__": 
    nameList = input().split(' ')
    permList = []
    all_permutations(permList, nameList)

这里;我只更改了 3 或 4 行,这有效:

def all_permutations(n, permList, nameList):

    if len(permList) == n:
        for i in range(len(permList)):
            print(permList[i], end=" ")
        print()

    else:
        for indx, itm in enumerate(nameList):
            permList.append(itm)
            nameList.pop(indx)
            all_permutations(n, permList, nameList)
            nameList.insert(indx, itm)
            permList.pop()

if __name__ == "__main__": 
    nameList = input().split(' ')
    permList = []
    all_permutations(len(nameList), permList, nameList)

更好的循环方式是:

    if len(permList) == n:
        print(' '.join(permList))