# Re: how to insert random error in a programming

Discussion in 'Python' started by Chris Angelico, Oct 15, 2012.

1. ### Chris AngelicoGuest

On Tue, Oct 16, 2012 at 6:28 AM, Mark Lawrence <> 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

Chris Angelico, Oct 15, 2012

2. ### alex23Guest

On Oct 16, 5:52 am, Chris Angelico <> 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]
)
)

alex23, Oct 16, 2012

3. ### Steven D'ApranoGuest

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

> On Oct 16, 5:52Â am, Chris Angelico <> 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

Steven D'Aprano, Oct 16, 2012