【问题标题】:Get every combination of the insertion of a character in a string获取字符串中插入字符的每个组合
【发布时间】:2022-01-13 17:11:52
【问题描述】:

作为参考,您还可以看到这个问题: I am trying to finding every possible combination of adding a character to a string

就像另一个问题一样,我正在尝试获取在字符串中插入字符的每一个可能的组合。

我不明白如何实现该解决方案,特别是如何获得每个位组合。

string = 'abc'

def generate_string(string):
    number_of_combinations = 2**(len(string)-1)
    str = ''
    configurations = []
    for i in range(number_of_combinations):
        #somehow get a true/false configuration of dashes
        #with abc i should have 8 possible configurations
        #i would append every configuration to configurations list
        
        for char in string:
            str = str + char
            #if the first char of configuration is true then add a '-', if false do nothing and so on for every char in the string

有人可以帮我吗?

【问题讨论】:

  • 到目前为止您尝试过什么?如需指导,请参阅how to ask a question 上的本指南
  • @defladamouse 对我糟糕的问题设计感到抱歉,我编写的代码太基础了,我很惭愧地发布它。
  • 没有更好的学习方式
  • @defladamouse 我添加了我的尝试,我并不为此感到自豪,但至少是一些东西

标签: python algorithm


【解决方案1】:

应该这样做:

import itertools as itl

init = 'abcde' #Base str
inst = 'z' #Char to be inserted

for i in itl.combinations_with_replacement(init[:-1], len(init)-1):
    #Compute every combination of strs that can be computed from init
    instAfter = list(set(i)) #Remove duplicates
    newStr = '' #prepare result str
    for i in init: #loop over init str
        newStr = newStr + i #Add char to result str
        if i in instAfter: #If char in instAfter add the insert char
            newStr = newStr + inst
    print(newStr)

【讨论】:

  • 不错!感谢您的帮助。你也有它的算法版本吗?我很想了解它是如何在不使用 itertools 的情况下工作的
  • 没有,但是你可以在itertools documentation找到函数的解释,复制起来应该不会太难。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-23
  • 1970-01-01
  • 1970-01-01
  • 2017-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多