问题描述
我写了一个简单的函数,可以将单词中的字母转换为"leet"数字对应物.
I wrote a straightforward function that converts letters in words to their 'leet' numerical counterparts.
def Leet(word):
letters = list(word.lower())
for n, letter, in enumerate(letters):
if letter == 'o':
letters[n]= '0'
elif letter == 'i':
letters[n]= '1'
elif letter == 'z':
letters[n]= '2'
elif letter == 'e':
letters[n]= '3'
elif letter == 'a':
letters[n]= '4'
elif letter == 's':
letters[n]= '5'
elif letter == 'g':
letters[n]= '6'
elif letter == 't':
letters[n]= '7'
elif letter == 'b':
letters[n]= '8'
return ''.join(letters)
因此,当我输入'zit'
时,程序将返回'217'
.
so when I input 'zit'
, the program will return '217'
.
我的问题是,如何更改它以提供所有可能的排列方式('217'
,'2it'
,'z1t'
,'zi7'
,'21t'
等)?我已经读过有关 itertools
的信息,但对于如何将其应用到我的函数中却感到困惑.
My question is, how can I change it to give me every possible permutation ('217'
, '2it'
, 'z1t'
, 'zi7'
, '21t'
, etc.)? I've read about itertools
but I am stumped as to how to apply it to my function.
推荐答案
第一个观察结果是您可以缩短查找,如下所示:
First observation is that you can shorten the lookup, like this:
REPLACE = { letter: str(index) for index, letter in enumerate('oizeasgtb') }
def Leet2(word):
letters = [ REPLACE.get(l, l) for l in word.lower() ]
return ''.join(letters)
REPLACE
如下:
{'a': '4', 'b': '8', 'e': '3', 'g': '6', 'i': '1',
'o': '0', 's': '5', 't': '7', 'z': '2'}
REPLACE.get(l,l)
会给您发回替换字母,或者如果没有替换字母,则返回原始字母.
And the REPLACE.get(l,l)
gives you back either the replacement letter, or the original letter if there is no replacement.
第二个观察结果是您并不真正想要排列,排列是在移动.'217'的排列是:
The second observation is that you don't really want permutations, which are shifts in ordering. The permutations of '217' are:
>>> [ ''.join(p) for p in permutations('217') ]
['217', '271', '127', '172', '721', '712']
您真正需要的是一个列表的产品,该列表对给定字符位置的所有可能选择进行编码:
What you really need is the product of a list that encodes all the possible choices for a given character position:
[('z', '2'), ('i', '1'), ('t', '7')]
如果我还显示带有某些字符的可能性列表,而这些字符没有有效替代,则可能会更清楚地了解其工作原理.例如,对于'red'
:
How this works might be clearer if I also show a possibility list with some characters for which there is no valid replacement. For 'red'
for example:
[('r',), ('e', '3'), ('d',)]
现在,我们需要这些选项的字符串连接产品.全部放在一起:
Now we need the string-joined product of those options. Putting it all together:
from itertools import product
def Leet2Combos(word):
possibles = []
for l in word.lower():
ll = REPLACE.get(l, l)
possibles.append( (l,) if ll == l else (l, ll) )
return [ ''.join(t) for t in product(*possibles) ]
print Leet2Combos('zit')
print Leet2Combos('red')
赠予:
['zit', 'zi7', 'z1t', 'z17', '2it', '2i7', '21t', '217']
['red', 'r3d']
这篇关于'leet'程序-获取所有排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!