python - 找到在列表中插入给定字符的所有方法
问题描述
我有以下列表["?","?","?,"?"]
,我想找到插入*
n 次的所有方法,其他索引将是"-"
例如 n = 3 我会得到[['*', '*', '*', '-'], ['*', '*', '-', '*'], ['*', '-', '*', '*'], ['-', '*', '*', '*']]
我写这个
def backtrack(lst, index_lst, res, number, index=0):
if index == len(index_lst):
if lst.count("*") == number:
lst_copy = lst.copy()
res.append(lst_copy)
return
lst[index] = "*"
backtrack(lst, index_lst, res, number, index + 1)
lst[index] = "-"
backtrack(lst, index_lst, res, number, index + 1)
lst[index] = "?"
res1 = []
backtrack(["?", "?", "?","?"], [0, 1, 2,3], res1, 3)
这是可行的,但是对于大型列表,它需要大量时间,有什么建议可以让它更有效吗?
顺便说一下,索引列表是必不可少的,因为我想在类似的列表上执行它["?","*","?"]
,["?","-","?"]
所以我需要在哪里有?
并且不使用任何模块
解决方案
您正在询问列表的排列。
L = ["-","*","*","*"]
print(list(itertools.permutations(L)))
推荐阅读
- asp.net - 使用 CQRS 模式在 API 中返回有意义的错误
- python - 为什么元组中允许连接和重复?由于元组是不可变的,因此不应在任何时候更改
- android - 我的右侧工具栏中缺少约束 GUI。如何取回
- java - 无法读取 URL 中有空格的 ASPX 页面
- php - PHP - 以 3 个一组打印数组的值
- jquery - 在堆栈溢出中制作类似“标签部分”的文本
- gstreamer - 如何继承插件提供的元素类型?
- amazon-web-services - 在 Amazon EC2 实例上启动 Selenium GRID - 节点注册到 http://172.17.42.1:4444/grid/register/
- c++ - 无法将 argv 传递给 main 内部调用的函数
- javascript - 访问给定索引的 Map 键/值的最快方法