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

Diez B. Roggisch deets at nospam.web.de
Thu Sep 20 18:53:40 EDT 2007


Python Maniac schrieb:
> 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

These might benefit from using a lookup-dictionary that maps ord(c) to 
the outcome of the operation. Actually, it becomes twice as fast:

import time

lt = {}
for i in xrange(255):
     lt[chr(i)] = chr(i | 0x80)

def scrambleLine(line):
     s = ''
     for c in line:
         s += chr(ord(c) | 0x80)
     return s

def scrambleLineLU(line):
     s = ''
     for c in line:
         s += lt[c]
     return s


if __name__ == "__main__":
     line = "abcdefghijklmnop" * 1000000
     start = time.time()
     scrambleLine(line)
     print time.time() - start

     start = time.time()
     scrambleLineLU(line)
     print time.time() - start



Diez




More information about the Python-list mailing list