找到在列表中插入给定字符的所有方法

问题描述 投票:0回答:1

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

这是可行的,但是列表很大,任何建议我都需要花费大量时间才能使它更有效?

顺便说一句,索引列表是必不可少的,因为我也想在["?","*","?"]["?","-","?"]之类的列表上执行索引,所以我需要到?所在的位置>

并且不使用amy模块

我有以下列表[“?”,“?”,“?”],我想找到所有插入* n次的方式,其他索引将是“-”,例如n = 3 i' ll get [['*','*','*','-'],['*','*','-','*'],...

python list recursion backtracking
1个回答
1
投票

您正在请求列表的排列。

© www.soinside.com 2019 - 2024. All rights reserved.