作為參考,您還可以看到這個問題: 我正在嘗試找到將字符添加到字串的所有可能組合
與另一個問題完全一樣,我正在嘗試獲取在字串中插入字符的每個可能的組合。
我不明白如何實作解決方案,特別是如何獲得位的每個組合。
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
有人能幫我嗎 ?
uj5u.com熱心網友回復:
這應該這樣做:
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/377842.html
上一篇:掃雷Python編碼挑戰
