How Can I Make This Program More Efficient
Solution 1:
import string
defencode(pattern, filename):
withopen(filename) as f:
contents = f.read()
s = string.maketrans(*[''.join(a) for a inzip(*pattern.split('|'))])
newMsg = contents.translate(s)
withopen(filename + 'encoded', 'rt') as f:
f.write(newMsg)
Solution 2:
Use str.translate()
instead of doing all the replacements the hard way, and do it line-by-line.
Solution 3:
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.
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.
Solution 4:
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:
import re
defencode(pattern, filename):
f = open(filename, "rt")
contents = f.read()
f.close()
printNow(contents)
change_dict = {}
matches = []
changes = pattern.split("|")
forstrin 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")
Post a Comment for "How Can I Make This Program More Efficient"