python - 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))))
解决方案
由于您希望第一个元素是固定的,比如说“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)
推荐阅读
- sql-server - 如果有人可以在服务器上进行物理访问,他们可以获得数据库的当前密码吗?
- javascript - 在前端 HTML 文件中显示 fs.readdirSync() 的输出
- java - 获取“VM初始化期间发生错误”
- firebase - 用于设置外键的 Firestore 引用数据类型
- python-3.x - 将方法移动到另一个 Python 文件
- python - Django Celery autoretry_for 和 retry_policy
- mysql - 无法创建 PoolableConnectionFactory 并打开 JDBC 连接
- java - 将双精度值显式转换为浮点数并将其存储在双精度变量中
- sql - 从表格中的逗号分隔值中获取单个值
- sql - spark sql中的广播连接(Spark 1.6.2)