Velocity Reviews > Re: how to insert random error in a programming

# Re: how to insert random error in a programming

Chris Angelico
Guest
Posts: n/a

 10-15-2012
On Tue, Oct 16, 2012 at 6:28 AM, Mark Lawrence <(E-Mail Removed)> wrote:
> I like clearly written code like this
>
> "
> d = {}
> for c in (65, 97):
> for i in range(26):
> d[chr(i+c)] = chr((i+13) % 26 + c)
>
> print "".join([d.get(c, c) for c in s])

Surely there's a shorter way to rot13 a piece of text? CODE GOLF!

At very least, a single cryptic expression in place of your nice clear
loops MUST be an improvement.

d = dict((chr(i+c),chr((i+13)%26+c))for i in range(26)for c in(65,97))

And with superfluous spaces removed like that, it takes 0.02
jiggawatts less power in DeLorean Python.

ChrisA

alex23
Guest
Posts: n/a

 10-16-2012
On Oct 16, 5:52*am, Chris Angelico <(E-Mail Removed)> wrote:
> Surely there's a shorter way to rot13 a piece of text? CODE GOLF!

In Python2: "a piece of string".encode('rot13')

> At very least, a single cryptic expression in place of your nice clear
> loops MUST be an improvement.
>
> d = dict((chr(i+c),chr((i+13)%26+c))for i in range(26)for c in(65,97))

Do I get points for explicitness?

import string as s
print "a piece of text".translate(
s.maketrans(
s.letters,
s.letters[:26][13:]+s.letters[:26][:13]+s.letters[26:]
[13:]+s.letters[26:][:13]
)
)

Steven D'Aprano
Guest
Posts: n/a

 10-16-2012
On Mon, 15 Oct 2012 18:21:55 -0700, alex23 wrote:

> On Oct 16, 5:52Â*am, Chris Angelico <(E-Mail Removed)> wrote:
>> Surely there's a shorter way to rot13 a piece of text? CODE GOLF!

>
> In Python2: "a piece of string".encode('rot13')

And in Python 3, unfortunately there has been a right-royal mess made of
the codecs system:

http://bugs.python.org/issue7475

So I expect that in Python 3.4 this will work:

"a piece of string".transform('rot13')

or this:

import codecs
codecs.encode('a piece of string', 'rot13')

but who knows really?

--
Steven