I could use some help making this Python code run faster using only Python code.

Michael Spencer mahs at telcopartners.com
Thu Sep 20 19:13:54 EDT 2007


Python Maniac wrote:
> I am new to Python however I would like some feedback from those who
> know more about Python than I do at this time.
> 
> def scrambleLine(line):
>     s = ''
>     for c in line:
>         s += chr(ord(c) | 0x80)
>     return s
> 
> def descrambleLine(line):
>     s = ''
>     for c in line:
>         s += chr(ord(c) & 0x7f)
>     return s
> 

Try using str.translate instead - it's usually much faster than a pure python loop:
  >>> scramble = "".join(chr(c | 0x80) for c in range(256))
  >>> "source text".translate(scramble)
  '\xf3\xef\xf5\xf2\xe3\xe5\xa0\xf4\xe5\xf8\xf4'
  >>> descramble = "".join(chr(c & 0x7F) for c in range(256))
  >>> '\xf3\xef\xf5\xf2\xe3\xe5\xa0\xf4\xe5\xf8\xf4'.translate(descramble)
  'source text'
  >>>

You might then do the translation inline e.g., untested:

 > def scrambleFile(fname,action=1):
     translators = {0: descramble, 1: scramble} # defined as above
     try:
         translation_action = translators[action]
     except KeyError:
         raise ValueError("action must be 0 or 1")

 >     if (path.exists(fname)):
...
...
                 for line in f:
                     ff.write(line.translate(translation_action))
...

HTH
Michael




More information about the Python-list mailing list