[英]How can I make this program more efficient
This program is a basic encoder in python and I want to see if I can make it more efficient without changing the names of the defined variables. 该程序是python中的基本编码器,我想看看是否可以在不更改定义变量名称的情况下使其更加高效。 Can someone give me some suggestions?
有人可以给我一些建议吗?
def encode(pattern, filename):
f = open(filename, "rt")
contents = f.read()
f.close()
printNow(contents)
changes = pattern.split("|")
for str in changes:
printNow("Change "+ str[0] + " to " + str[1])
newMsg = ""
for char in contents:
for change in changes:
if char == change [0]:
char = change[1]
newMsg += char
f = open(filename + "encoded", "wt")
f.write(newMsg)
f.close()
f = open(filename + "encoded", "rt")
printNow(f.read())
f.close()
encode("ae|ga|s3", "C:\\Users\\Shaun\\Desktop\\Test.txt")
import string
def encode(pattern, filename):
with open(filename) as f:
contents = f.read()
s = string.maketrans(*[''.join(a) for a in zip(*pattern.split('|'))])
newMsg = contents.translate(s)
with open(filename + 'encoded', 'rt') as f:
f.write(newMsg)
使用str.translate()
而不是艰难地进行所有替换,然后逐行进行。
First of all you need to consider the option that your algorithm is already good enough. 首先,您需要考虑您的算法已经足够好的选择。 Even if it can be optimized, if your code is part of a bigger program and it only executes during 0.1% of time, for instance, then it will be most probably useless to optimize the code, since the rest of the program will dominate the total execution time.
即使可以对其进行优化,例如,如果您的代码是较大程序的一部分,并且仅在0.1%的时间内执行,那么对代码进行优化就很可能没有用,因为该程序的其余部分将占据主导地位。总执行时间。
If you really have a problem in your code, then I would start by analyzing the complexity of your algorithm. 如果您的代码中确实存在问题,那么我将从分析算法的复杂性开始。
And finally, you could try to find some bottlenecks in your code. 最后,您可以尝试在代码中找到一些瓶颈。 For that, I would profile the code with something like python's timeit .
为此,我将使用python的timeit之类的代码来分析代码。
The str.translate() method works well for character substitutions, but here's another fast way I've used that also works for multi-character substitutions: str.translate()方法适用于字符替换,但这是我使用的另一种快速方法,该方法也适用于多字符替换:
import re
def encode(pattern, filename):
f = open(filename, "rt")
contents = f.read()
f.close()
printNow(contents)
change_dict = {}
matches = []
changes = pattern.split("|")
for str in changes:
printNow("Change "+ str[0] + " to " + str[1])
change_dict[str[0]] = str[1]
matches.append(str[0])
change_re = re.compile("|".join(re.escape(x) for x in matches))
newMsg = change_re.sub(lambda m: change_dict[m.group(0)], contents)
f = open(filename + "encoded", "wt")
f.write(newMsg)
f.close()
f = open(filename + "encoded", "rt")
printNow(f.read())
f.close()
encode("ae|ga|s3", "C:\\Users\\Shaun\\Desktop\\Test.txt")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.