【问题标题】:How can I make this program more efficient我怎样才能使这个程序更有效率
【发布时间】:2012-06-01 07:14:14
【问题描述】:

这个程序是python中的基本编码器,我想看看是否可以在不更改定义变量名称的情况下使其更高效。有人可以给我一些建议吗?

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")

【问题讨论】:

  • 您可以先对其进行测量,然后告诉我们它在哪些方面表现不如您认为的那么好。
  • 效率更高是什么意思?你必须更具体。高效的定义因人而异,是执行时间,还是内存消耗,还是输出??

标签: python


【解决方案1】:
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)

【讨论】:

    【解决方案2】:

    使用str.translate(),而不是硬性地进行所有替换,并逐行进行。

    【讨论】:

      【解决方案3】:

      首先,您需要考虑您的算法已经足够好的选项。即使它可以被优化,如果你的代码是一个更大的程序的一部分并且它只在 0.1% 的时间内执行,那么优化代码很可能是无用的,因为程序的其余部分将主导总执行时间。

      如果你的代码真的有问题,那我先分析一下你算法的complexity

      最后,您可以尝试找出代码中的一些瓶颈。为此,我将使用 python 的timeit 之类的代码来分析代码。

      【讨论】:

        【解决方案4】:

        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")
        

        【讨论】:

          猜你喜欢
          • 2010-11-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-12-23
          • 2016-08-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多