我正在尝试创建一个带partial_alphabetic
和字符串的函数。
此函数应该取字符串中的每个字符,并在partial_alphabetic
中找到它的第i个位置,并获取已知字母(a,b,c等)中的相应字符,如果字符未知它应该打印“!”取而代之。
这是我的代码:
def cipher_attack(partial_alphabetic,ciphertext):
var = ""
for i in xrange(len(ciphertext)):
letter = ciphertext[i]
for j in xrange(len(partial_alphabetic)):
if(partial_alphabetic[j] == letter):
c = partial_alphabetic.index(letter)
var += alphabet[c%26]
var += "!"
print var
cipher_attack("!wertyuiopasdfghjklzxcvbnm","rqr")
它会打印d!!d!
,但应该打印d!d
。
答案 0 :(得分:1)
找到匹配后突破for
循环,然后为循环提供else:
套件。该套件仅在循环不中断时才会执行:
def cipher_attack(partial_alphabetic, ciphertext):
var = ""
for letter in ciphertext:
for i, pa in enumerate(partial_alphabetic):
if pa == letter:
var += alphabet[i % 26]
break
else:
var += "!"
return var
请注意,您可以直接遍历ciphertext
和partial_alphabetic
,无需先创建索引。但是,拥有索引可以帮助匹配alphabet
,但使用enumerate()
可以更轻松地创建索引。
演示:
>>> import string
>>> alphabet = string.ascii_letters
>>> def cipher_attack(partial_alphabetic, ciphertext):
... var = ""
... for letter in ciphertext:
... for i, pa in enumerate(partial_alphabetic):
... if pa == letter:
... var += alphabet[i % 26]
... break
... else:
... var += "!"
... return var
...
>>> cipher_attack("!wertyuiopasdfghjklzxcvbnm", "rqr")
'd!d'
答案 1 :(得分:0)
使用:
def cipher_attack(partial_alphabetic,ciphertext):
var = ""
for c in chipertext:
if c in partial_alphabetic: var+=c
else: var+='!'
return var
cipher_attack("!wertyuiopasdfghjklzxcvbnm","rqr")
答案 2 :(得分:0)
这可以像这样改进
def cipher_attack(partial_alphabetic,ciphertext):
var = ""
for i in xrange(len(ciphertext)):
if ciphertext[i] in partial_alphabetic:
var += alphabet[partial_alphabetic.index(ciphertext[i]) % 26]
else:
var += "!"
print var
cipher_attack("!wertyuiopasdfghjklzxcvbnm","rqr")
<强>输出强>
d!d
答案 3 :(得分:0)
或使用str.translate:
import string
def cipher_attack(partial_alphabetic, ciphertext):
missing = ''.join(set(ciphertext).difference(partial_alphabetic))
table = string.maketrans(
partial_alphabetic+missing,
string.letters[:len(partial_alphabetic)]+'!'*len(missing))
return (ciphertext.translate(table))
print(cipher_attack('!wertyuiopasdfghjklzxcvbnm', 'rqr'))
打印
d!d
通常,str.translate
的执行速度比通过字符逐个字符循环的等效代码执行得更快。在您的示例中,ciphertext
非常短暂,几乎不重要,但对于较长的文本,它可能很重要。
使用循环解决方案cipher_attack2
进行比较:
In [43]: %timeit cipher_attack('!wertyuiopasdfghjklzxcvbnm', 'rqr'*10000)
1000 loops, best of 3: 696 µs per loop
In [44]: %timeit cipher_attack2('!wertyuiopasdfghjklzxcvbnm', 'rqr'*10000)
10 loops, best of 3: 32 ms per loop
In [45]: 32000/696.
Out[45]: 45.97701149425287