【问题标题】:Nested loops slowing down program. How can I make it faster?嵌套循环减慢程序。我怎样才能让它更快?
【发布时间】:2015-07-04 04:55:36
【问题描述】:
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

^ 有程序、字典、加密和解密文件的链接。

【问题讨论】:

  • 要测试您是否怀疑嵌套循环会减慢速度,请使用cProfile
  • 在您对程序的瓶颈位置做出任何假设之前,您应该查看Python Profilers 并确认它。在优化之前进行分析总是一个好主意,因为问题通常不在您认为的位置。
  • 大部分循环看起来都没有必要。例如,设置highest_so_far(除了不必要地手动增加i)可以替换为单个函数调用highest_so_far = max(scores)

标签: python performance for-loop while-loop


【解决方案1】:

只需更改第 16 行:

dictionary_file=set(words_from_file("big_word_list.txt"))

所以if item in dictionary_file: 以恒定时间而不是线性时间执行。该程序现在在 4 秒内运行,禁用打印语句, 并在highest_so_far=i 中更改i=highest_so_far,并大写字典。

【讨论】:

  • 哇,非常感谢!如此简单的改变产生了巨大的变化!
猜你喜欢
  • 1970-01-01
  • 2020-12-27
  • 1970-01-01
  • 2021-02-17
  • 2023-02-21
  • 2012-03-23
  • 2021-06-19
  • 1970-01-01
  • 2019-07-13
相关资源
最近更新 更多