import re
file=input("What is the name of your file? ")
def words_from_file(filename):
try:
f = open(filename, "r")
words = re.split(r"[,.;:?\s]+", f.read())
f.close()
return [word for word in words if word]
except IOError:
print("Error opening %s for reading. Quitting" % (filename))
exit()
dictionary_file=words_from_file("big_word_list.txt")
newfile=words_from_file(file)
def dictionary_check(scores, dictionary_file, full_text):
count=0
for item in full_text:
if item in dictionary_file:
count+=1
scores.append(count)
def decoder(item,shiftval):
decoded = ""
for c in item:
c=c.upper()
if c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
num = ord(c)
num += shiftval
if num > ord("Z"):
num=num-26
elif num < ord("A"):
num=num+26
decoded+=chr(num)
else:
decoded = decoded + c
return decoded
shiftval=0
scores=[]
while shiftval<=26:
full_text=[]
for item in newfile:
result=decoder(item,shiftval)
full_text.append(result)
shiftval+=1
print(full_text)
dictionary_check(scores, dictionary_file, full_text)
highest_so_far=0
for i in range(len(scores)):
if scores[i]>highest_so_far:
i=highest_so_far
i+=1
else:
i+=1
fully_decoded=""
for item in newfile:
test=decoder(item,highest_so_far)
fully_decoded+=test
print(fully_decoded)
大家好。在
我有一个任务,我必须做一个程序,解码一个移位密码。现在它可以工作,但速度非常慢。我怀疑这可能是因为嵌套的循环。我真的不知道从这一点该怎么办。在
对代码的一些解释:程序读取一个加密文件,其中每个字母都会移位一定量(即,如果移位5,那么现在每个a都是F。这将针对每个字母进行)。程序也会读入字典文件。只有26个可能的移位,所以每一个移位都会解码文件。程序将获取每个可能的移位的文件,并将其与字典文件进行比较。与字典文件最相似的文件将作为最终解密文件重新打印。在
谢谢大家!在
https://drive.google.com/file/d/0B3bXyam-ubR2U2Z6dU1Ed3oxN1k/view?usp=sharing
^有指向程序、词典、加密和解密文件的链接。在
只需更改第16行:
因此
if item in dictionary_file:
是在恒定时间内执行的,而不是线性时间。程序现在只需4秒就可以运行,禁用print语句, 改变highest_so_far=i
中的i=highest_so_far
,并将字典大写。在相关问题 更多 >
编程相关推荐