簡體   English   中英

更改字符串中的每個位置以查找所有可能的組合

[英]Change each place in a string to find all possible combinations

如果我們用某些特定字符更改字符串中的一個位置,目標是找到所有可能的組合。

這是我到目前為止的代碼:

from itertools import product

string = "abc123"

char = "def2346789"

for i in range(len(string)):
    for char1 in product(char):
        print(string[:i] + char1 + string[i+1:])

char表示將在每個地方使用的字符。

但我對它在第二部分的工作方式感到困惑,我會喜歡探索解決方案。

所以結果將是這樣的:

dbc123 adc123
ebc123 aec123
fbc123 afc123 
2bc123 a2c123 
3bc123 a3c123
4bc123 a4c123
6bc123 a5c123
7bc123 a6c123
8bc123 a7c123
9bc123 a8c123 etc...

您不需要(不應該)在此處使用itertools.product 這可能是讓你感到困惑的地方:

string = "abc123"

char = "def2346789"

for i in range(len(string)):
    for c in char:
        print(string[:i] + c + string[i+1:])

在第二部分中,我假設您的意思是 for 循環。

基本上是這樣的:

for every character position in string (called i):
    for every character in char (called char1):
        substitute the character at the current position with char1
        #This is done by printing all characters before the current position 
        #(string[:i]), then printing the new character (char1) then printing all 
        #charactrers after the current position (string[i+1:])

使用 function 和理解也使代碼更具可讀性

     string = "abc123"
     char = "def2346789"

     def fncCombinations(a):
           combination_list=[]
           for j in range(len(string)): 
                combination_list.append(string[:j] + a + string[j+1:])
     return combination_list 
     combination_list=[fncCombinations(a) for a in char]
     print(combination_list)

`

你可以使用堆棧和隊列

string="abc123"
char = "def2346789"
queue=[]
stack=[]
combination_list=[]
queue=[x for x in string]
    
for index in range(len(queue)):
    stack.append(queue.pop(0))
    front="".join(stack[:-1])
    back="".join(queue)
    combination_list.append([front+a+back for a in char])

 print(combination_list)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM