XORing long strings opimization?

Tim Peters tim.one at comcast.net
Tue Nov 4 14:16:20 EST 2003


[Noen]
> ...
> 	# 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).






More information about the Python-list mailing list