XORing long strings opimization?

Noen not.available at na.no
Tue Nov 4 23:30:46 CET 2003


Tim Peters wrote:

> [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).
> 
> 
  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 :(





More information about the Python-list mailing list