Con*_*n7e 1 python string permutation python-2.7
虽然这似乎是一个已经回答的问题,但事实并非如此。
我正在尝试找到一种方法来执行以下操作:
预期输出的示例如下所述:
首先,程序将通过更改 ! 中的每个 i 来进行,具有:
"Th!s !s my str!ng"
Run Code Online (Sandbox Code Playgroud)
接下来,它将在 $ 中更改 s:
"Thi$ i$ my $tring"
Run Code Online (Sandbox Code Playgroud)
现在我完成了 1 个字符的排列,我需要开始 2 个字符的排列:
"Th!$ !s my $tr!ng"
Run Code Online (Sandbox Code Playgroud)
由于我只有一对,我这里只有一个可能的排列,因此程序结束。
我试图弄清楚如何在 python 中做到这一点,但我最终只得到了一个无限的“if .. then..”列表,并且必须有一种更有效的方法来做到这一点。
对于那些好奇的人,我对此很感兴趣,因为我“丢失”了我的密码。我的意思是,我的密码类似于“我喜欢冰淇淋”,但作为负责任的我,我用符号更改了一些字符,现在我不知道它是什么......
这并不完全符合您的要求,但可能会有所帮助:
from itertools import product
SUBSTITUTIONS = {
"i": "!1|",
"o": "0",
"s": "$5",
}
def sub(text):
possibilities = [c + SUBSTITUTIONS.get(c, "") for c in text]
# 'spoils' -> ['s$5', 'p', 'o0', 'i!1|', 'l', 's$5']
for subbed in product(*possibilities):
print("".join(subbed))
Run Code Online (Sandbox Code Playgroud)
它用于itertools.product()迭代SUBSTITUTIONSfor 的每个可能组合text:
>>> sub('spoils')
spoils spoil$ spoil5 spo!ls spo!l$ spo!l5 spo1ls spo1l$ spo1l5
spo|ls spo|l$ spo|l5 sp0ils sp0il$ sp0il5 sp0!ls sp0!l$ sp0!l5
sp01ls sp01l$ sp01l5 sp0|ls sp0|l$ sp0|l5 $poils $poil$ $poil5
$po!ls $po!l$ $po!l5 $po1ls $po1l$ $po1l5 $po|ls $po|l$ $po|l5
$p0ils $p0il$ $p0il5 $p0!ls $p0!l$ $p0!l5 $p01ls $p01l$ $p01l5
$p0|ls $p0|l$ $p0|l5 5poils 5poil$ 5poil5 5po!ls 5po!l$ 5po!l5
5po1ls 5po1l$ 5po1l5 5po|ls 5po|l$ 5po|l5 5p0ils 5p0il$ 5p0il5
5p0!ls 5p0!l$ 5p0!l5 5p01ls 5p01l$ 5p01l5 5p0|ls 5p0|l$ 5p0|l5
Run Code Online (Sandbox Code Playgroud)
我已重新格式化输出以使其紧凑,但您明白了。显然,候选密码的数量将随着替换的数量呈指数增长,但对此您无能为力。