【问题标题】:How to take the output of permutation into a list如何将排列的输出放入列表中
【发布时间】:2021-10-10 15:30:12
【问题描述】:

我有这段代码可以输出给定单词的所有排列:

def get_permutation(word, base = ""):
    
    if len(word) == 0:
        print(base)
    
    for i in range(len(word)):
        
        newBase = base + word[i]
        newWord = word[0:i] + word[i + 1:]
        
        get_permutation(newWord, newBase)

我希望将输出保存到此函数结束后返回的列表中。 这可能很容易,但我是 python 的初学者,所以我不知道如何

【问题讨论】:

  • 我假设您正在为此寻找通用技术,并且您在这里解决的实际问题并不重要?因为如果你只想要排列,你应该使用标准库中的itertools.permutations
  • 是的,我想要技术
  • 您知道附加到列表吗?并从函数返回值?如果没有,这些都是 Python 非常基础的方面,所以我建议您阅读一本 Python 基础书籍并学习一些初学者教程,这样您就可以掌握对您未来的所有程序有所帮​​助的基础知识。
  • 你明白return 是干什么用的吗?您能否将结果收集到一个递归算法的列表中?

标签: python list recursion permutation


【解决方案1】:

我已经找到答案了:

answer = [ ]

def get_permutation(word, base = ""):
    
    if len(word) == 0:
        answer.append(base)
    
    for i in range(len(word)):
        
        newBase = base + word[i]
        newWord = word[0:i] + word[i + 1:]
        
        get_permutation(newWord, newBase)
    
    return answer

唯一的问题是列表是垂直打印的?

【讨论】:

    【解决方案2】:

    如果您想要一个返回整个列表的函数,并且包含所有内容,可以按以下方式完成。

    def get_permutations_list(word, base = ""):    
    
        lst = [] #Create a list to hold permutations.
    
        def get_permutation(word, base):
    
            if len(word) == 0:
                lst.append(base) #Add current permutation to end of list.
    
            for i in range(len(word)):
    
                newBase = base + word[i]
                newWord = word[0:i] + word[i + 1:]
    
                get_permutation(newWord, newBase)
    
        get_permutation(word, base) #Run the recursive function.
        
        return lst #Return the completed list.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-03
      • 2023-02-06
      • 2022-11-21
      • 1970-01-01
      • 2015-09-17
      • 2017-01-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多