用指定的字符集替换字符串中的两个字符以创建所有可能的组合

2024-09-28 22:30:43 发布

您现在位置:Python中文网/ 问答频道 /正文

目标是通过更改两个字符来生成具有字符串0a1b2c3d4e5的所有可能组合

到目前为止,我掌握的代码是:

import itertools

pattern_index_zero = "xa1b2c3d4e5"

a = [['0','1', '2', '3', '4', '5', 'a', 'b', 'c', 'd', 'e'] if (c == 'x') else c for c in pattern_index_zero]
b = [''.join(lst) for lst in list(itertools.product(*a))]
for s in b:
    print(s)

输出:

0a1b2c3d4e5
1a1b2c3d4e5
2a1b2c3d4e5
3a1b2c3d4e5
4a1b2c3d4e5
5a1b2c3d4e5
aa1b2c3d4e5
ba1b2c3d4e5
ca1b2c3d4e5
da1b2c3d4e5
ea1b2c3d4e5

它改变了第一个字符,这是可以的,但问题是我想改变第二个,第三个字符,并继续到最后一个

最终目标是生成所有可能的组合来更改字符串中的两个字符,例如:

xx1b2c3d4e5
xaxb2c3d4e5
xa1x2c3d4e5
xa1bxc3d4e5
....
xx1b2c3d4e5
0xxb2c3d4e5
0x1x2c3d4e5
0x1bxc3d4e5

如果x可以是0,1,2,3,4,5,a,b,c,d,e,那么在代码方面,将x的数量增加到3甚至4有多难

EDIT用户Timus有答案。我会尽我所能去探索所有的答案,谢谢大家


Tags: 字符串答案代码inimport目标forindex
3条回答

您可以使用itertools.compositions来实现这一点: 因为您想交换/更改两个字符,所以我在参数中传递了2

from itertools import combinations 
a = '0a1b2c3d4e5'
for i, j in combinations(a, 2):
    # rest of the code swaps the characters
    dummy = a.replace(i, '_')
    first_repalcement = dummy.replace(j, i)
    second_replacement= first_repalcement.replace('_', j)
    print(second_replacement)

输出 a01b2c3d4e5
1a0b2c3d4e5
ba102c3d4e5
2a1b0c3d4e5
ca1b203d4e5
3a1b2c0d4e5
da1b2c304e5
4a1b2c3d0e5
ea1b2c3d405
5a1b2c3d4e0
01ab2c3d4e5
0b1a2c3d4e5
021bac3d4e5
0c1b2a3d4e5
031b2cad4e5
0d1b2c3a4e5
041b2c3dae5
0e1b2c3d4a5
051b2c3d4ea
...

pattern_index_zero = "xa1b2c3d4e5"
pattern = [letter for letter in pattern_index_zero]
possible_options = ['0', '1', '2', '3', '4', '5', 'a', 'b', 'c', 'd', 'e']

indices_values = []
for i0 in range(0, len(pattern)):
    for i1 in range(0, len(pattern)):
        if i0 != i1 and (i1, i0) not in indices_values:
            indices_values.append((i0, i1))

current_indices_index = 0

possibilities = []

for index0, index1 in indices_values:
    for new_option0 in possible_options:
        if new_option0 != pattern[index0]:
            for new_option1 in possible_options:
                if new_option1 != pattern[index1]:
                    pattern_copy = pattern.copy()
                    pattern_copy[index0] = new_option0
                    pattern_copy[index1] = new_option1
                    possibilities.append(''.join(pattern_copy))

这是使用for循环的基本结构来解决问题。我们首先创建一个列表,其中两个索引的值将发生变化。此列表看起来有点像:[(0, 1), (0, 2), ..., (1, 0), (1, 2), ...],包含所有选项

然后,我们迭代每一个可能的索引,我们可以更改其值

for index0, index1 in indices_values:

在本文中,我们还迭代了字符串的索引也可以更改为的所有值

for new_option0 in possible_options:

然后检查new_option0是否不等于当前值,以确保没有重复项。如果没有,我们将再次迭代可能的选项-这次是为了更改第二个索引。我们再次检查new_option1是否不等于当前值

最后,我们附加编辑后的值

为了确认确实没有重复项,以下代码输出True

len(possibilities) == len(set(possibilities))

如果您想增加编辑的索引数量,我想您可以增加for循环和if语句的数量。这是一个非常模块化的结构

您可以从itertools尝试其他工具:

from itertools import combinations

s = "0a1b2c3d4e5"
positions = tuple(range(len(s)))
for i, j in combinations(positions, 2):
    print(s[:i] + s[j] + s[i+1:j] + s[i] + s[j+1:])

编辑:好的,再试一次:)。这就是你想要的吗:

from itertools import combinations, product

s = "0a1b2c3d4e5"
r = "012345abcde"
for i, j in combinations(tuple(range(len(s))), 2):
    for r1, r2 in product(r, r):
        print(s[:i] + r1 + s[i+1:j] + r2 + s[j+1:])

编辑2:如果要排除倍数,可以通过^{统一:

from itertools import combinations, product

s = "0a1b2c3d4e5"
r = "012345abcde"
output = []
for i, j in combinations(tuple(range(len(s))), 2):
    for r1, r2 in product(r, r):
        output.append(s[:i] + r1 + s[i+1:j] + r2 + s[j+1:])
output = set(output)
print(output)

编辑3:我想不出你的问题,这是如何扩展到更高数量的替换。我希望你不介意我添加一个概括。这有点复杂。而且产量增长很快。因此,我没有将其打印到控制台,而是使用了一个文件(带有详细的输出)。也许你感兴趣。没问题,如果不是的话,我玩得很开心。一个问题:你需要这些东西来解决现实世界的问题吗

from itertools import combinations, product

# Base string
base = "0a1b2c3d4e5"
# Length of the base string
len_of_base = len(base)
# String with replacement characters
replacements = "012345abcde"
# Number of replacements
num_of_replacements = 3
output = {}
for istart, *imiddle, iend in combinations(range(len_of_base),
                                           num_of_replacements):
    for rstart, *rrest in product(replacements,
                                  repeat=num_of_replacements):
        new = base[:istart] + rstart
        for i, j, r in zip([istart] + imiddle,
                           imiddle + [iend],
                           rrest):
            new += base[i+1:j] + r
        new += base[iend+1:]
        if new not in output:
            output[new] = {}
            output[new]['positions'] = tuple([istart] + imiddle + [iend])
            output[new]['replacements'] = tuple([rstart] + rrest)

with open('data.txt', 'w') as file:
    for key in output:
        file.write(f"{key} - "
                   f"Positions {output[key]['positions']} "
                   f"replaced with {output[key]['replacements']}\n")

输出:

000b2c3d4e5 - Positions (0, 1, 2) replaced with ('0', '0', '0')
001b2c3d4e5 - Positions (0, 1, 2) replaced with ('0', '0', '1')
002b2c3d4e5 - Positions (0, 1, 2) replaced with ('0', '0', '2')
003b2c3d4e5 - Positions (0, 1, 2) replaced with ('0', '0', '3')
004b2c3d4e5 - Positions (0, 1, 2) replaced with ('0', '0', '4')
005b2c3d4e5 - Positions (0, 1, 2) replaced with ('0', '0', '5')
00ab2c3d4e5 - Positions (0, 1, 2) replaced with ('0', '0', 'a')
00bb2c3d4e5 - Positions (0, 1, 2) replaced with ('0', '0', 'b')
00cb2c3d4e5 - Positions (0, 1, 2) replaced with ('0', '0', 'c')
...

相关问题 更多 >