首页 > 解决方案 > 找到在列表中插入给定字符的所有方法

问题描述

我有以下列表["?","?","?,"?"],我想找到插入*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)

这是可行的,但是对于大型列表,它需要大量时间,有什么建议可以让它更有效吗?

顺便说一下,索引列表是必不可少的,因为我想在类似的列表上执行它["?","*","?"]["?","-","?"] 所以我需要在哪里有?

并且不使用任何模块

标签: pythonlistrecursionbacktracking

解决方案


您正在询问列表的排列。

L = ["-","*","*","*"]
print(list(itertools.permutations(L)))

推荐阅读