XORing long strings opimization?

Terry Reedy tjreedy at udel.edu
Tue Nov 4 15:43:12 EST 2003


"Noen" <not.available at na.no> wrote in message
news:i8Tpb.24451$BD3.4567242 at juliett.dax.net...
> def XOR(s1,s2):
>      """ XOR string s1 with s2 """
>      output = ""
>      # Argument check
>      if (type(s1) and type(s2)) != type(""):
>          raise TypeError, "Arguments are not strings"
>      if len(s1) != len(s2):
>          raise ValueError, "Size differs in strings"
>      # Xoring
>      for i in range(len(s1)):
>          output += chr(ord(s1[i]) ^ ord(s2[i]))
>      return output

You fell into the O(n**2) immutable sequence repeated addition trap.
For O(n) behavior, try output = [] and return ''.join(output).
Replacing output+=stuff with output.append(stuff) might be faster
still.

Terry J. Reedy






More information about the Python-list mailing list