[Tutor] Masking operation
Rich Lovely
roadierich at googlemail.com
Thu Oct 15 17:58:34 CEST 2009
2009/10/15 Kent Johnson <kent37 at tds.net>:
> On Wed, Oct 14, 2009 at 10:48 PM, Wayne <srilyk at gmail.com> wrote:
>
>> Using zip is redundant for me, this is what my function looks like now:
>> def crypt(msg, mask):
>> m = itertools.cycle(mask)
>> word = ''
>> for l in msg:
>> word += chr(ord(l) ^ ord(m.next()))
>> return word
>
> With zip() and a generator expression you can write it as
> def crypt(msg, mask):
> mask = itertools.cycle(mask)
> chars = zip(msg, mask)
> return ''.join(chr(ord(l) ^ ord(m)) for l, m in chars)
>
> which could be reduced to a one-liner if you like.
>
> Kent
>
And that's why itertools is probably my favourite module.
For extra jollies, you can define it as a lambda:
crypt = lambda msg, mask: "".join(chr(ord(l)^ord(m)) for l,m in
zip(msg, itertools.cycle(mask)))
But that's maybe going a little over the top, unless we're entering an
obfuscated code contest.
--
Rich "Roadie Rich" Lovely
There are 10 types of people in the world: those who know binary,
those who do not, and those who are off by one.
More information about the Tutor
mailing list