Design

Saturday, December 4, 2010

Now on Github

HousewifeHacker is now on Github. To avoid further formatting problems with pasting my code on the blog, I will be using github to embed my code. For those who are unfamiliar with Github, the site allows programmers to follow open source contributions from different authors and contribute to full projects (Repositories) or small code snippets (Gists) by creating your own code or making changes to other user's work (forking). Users can determine whether their repositories and gists are public or private. The objective of Github is to serve as a social coding resource as well as a revision control. Because I want to be able to contribute to open source projects as I become more knowledgeable of Python, Github will become an increasingly valuable resource.

Thursday, December 2, 2010

maketrans Python and Improved Caesar's Shift

Maketrans is used to translate strings, character for character. The characters can be symbols, letters, or numbers. The following short example is a Caesar's Shift moving backwards by two letters.
#first we need to import maketrans
>>> from string import maketrans
#now define the translation
#parameters are strings, not lists
#first parameter defines what will be found in the string
#second parameter defines what each will be changed to
>>> trans = maketrans('cdefg','abcde')
#define our string and translate
>>> s = 'deg'
>>> s.translate(trans)
'bce'

Now using maketrans and a few other suggestions from the comments, I have written a newly improved Caesar's Shift. Encode and decode use the same code, because a shift of 4 in one direction of a 26 character alphabet is equivalent to a shift of 22 in the other direction. I also used ascii_letters to shift my translation, which is 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'. The letter w may be encoded to be a A by a shift of 4, but the decoding will return the lowercase w. There was an error in my exception handling, which is now corrected.