XORing long strings opimization?
not.available at na.no
Tue Nov 4 23:33:52 CET 2003
> Tim Peters wrote:
>>> # Xoring
>>> for c1 in s1:
>>> for c2 in s2:
>>> output += chr(ord(c1) ^ ord(c2))
>>> return output
>>> This way is very slow for large strings.
>>> Anyone know of a better and faster way to do it?
>> First do an ord() only once per character:
>> ord1 = map(ord, s1)
>> ord2 = map(ord, s2)
>> Now loop over that and accumulate the individual results in a list:
>> alist = [chr(x ^ y) for x in ord1 for y in ord2]
>> Now paste those all together:
>> return ''.join(alist)
>> The major inefficiency in the original is that "output += ..." copies
>> all of
>> output each time it's executed (strings in Python are immutable -- you
>> cannot append to a Python string in-place).
> alist = [chr(x ^ y) for x in ord1 for y in ord2]
> This creates a way too big list... Im not familiar with two for loops in
> one, so I cant see whats wrong :(
Oh, my debugger says that it works like:
for x in range ord1:
for y in range ord2:
which does it x*y times...
wonder how the line really should look like...
More information about the Python-list