首页 > 解决方案 > Python递归排列,固定第一个元素

问题描述

我正在对具有固定第一个元素的递归排列进行练习。在每个排列(Fruit1 Fruit2 Fruit3 Fruit4 Fruit5)之后,我需要一个具有特定格式的打印,并且第一个元素始终相同。我找不到这个特定排列问题的答案,因此,我提出了一个新问题。我尝试使用两种替代方法来解决,但是,第一种方法不断将元素添加到同一个结果列表中,另一种方法导致 typeError。出了什么问题以及修复代码需要什么。注意:我可以用 itertools.permutations 完成它;或与所有元素的排列;或者先使用四个元素,然后在打印时添加第一个元素;在这里我问这个特定的功能需要如何纠正?

fruits = ["Apple", "Banana", "Orange", "Peach", "Avocado"]

def permutation(menu, lst):

    if len(lst) == 0:
        
        #here prints of each permutation
            
        print(' '.join([fruits[i] for i in menu]))
        
        return []

    
      ##the first try which gives the permutations
       ##as ever expanding list
    for i in range(len(lst)):

       fruit = lst[i]
       
       menu.append(fruit)
       
       remLst = lst[:i] + lst[i+1:]
     
       permutation(menu, remLst)
       
       
       ##the second option which gives TypeError:
           ##can only concatenate list (not "int") to list
           ##this is alternative to the one above NOT in the same function
       
      
    for i in range(len(lst)):

        fruit = lst[i]
       
        remLst = lst[:i] + lst[i+1:]
        
  
        for p in permutation(menu, remLst):
            
            menu.append([fruit] + p)
           
    return menu


permutation([0], list(range(1, len(fruits))))

标签: pythonpermutation

解决方案


由于您希望第一个元素是固定的,比如说“Apple”,我将它从“fruit”中丢弃并找到其余水果的排列并将每个排列添加到 `["Apple"] 列表中。

fruits = ["Apple", "Banana", "Orange", "Peach", "Avocado"]
fixed=fruits[1:]
class Solution:
      def permute(self, fruits):
        result = []
        def dfs(fruits,path):
            if len(fruits) == 0:
                result.append(path)
                return
            for i in range(len(fruits)):
                dfs(fruits[:i] + fruits[i + 1:], path + [fruits[i]])

        dfs(fixed,['Apple'])
        return result
s=Solution()
s.permute(fixed)

在此处输入图像描述


推荐阅读