首页 > 解决方案 > 我的排列列表需要在输出的最后一行有一个空格。如何在末尾添加额外的空格?

问题描述

我正在编写一个程序,输出字符串列表的所有可能排列。我需要在最后有一个带有额外空格的输出。如何在此处输入图像描述

这是我的代码:

def all_permutations(permList, nameList):
    # TODO: Implement method to create and output all permutations
    # of the list of names.
    res = []
    # if len = 0 stop executing (base condition)
    if len(nameList) == 0:
        return []
    # if there's only one item in nameList, return that item
    if len(nameList) == 1:
        return [nameList]
        
    for i in range(len(nameList)):
        word = nameList[i]
    # remove one item (word or nameList[i]) and
    # assign remaining list to "newlist"
        newlist = nameList[:i] + nameList[i + 1:]
    # generate all possible permutations
    # making "word" the first element
        for j in all_permutations([], newlist):
            res.append([word] + j)
    return res
    
    
if __name__ == "__main__": 
    nameList = input().split(" ")
    permList = []
    for p in all_permutations(permList, nameList):
        print(*p)

标签: pythonpermutation

解决方案


推荐阅读