On Sun, Feb 8, 2009 at 12:57 PM, Paul McGuire <pt...@austin.rr.com> wrote: > On Feb 8, 12:42 pm, J <seaworthyjer...@gmail.com> wrote: >> What are your thoughts on this module I created? >> > Here are a few steps to illustrate some good basic Python idioms worth > learning: > > Step 1: Replace many-branched if-elif with dict > > While translating characters in a string is a special case that > usually warrants using str.translate, a more general-purpose technique > to learn is to define a dict that captures the various branching > options, and then use the selecting value as a key to access the > desired branch. > Here is a dict containing your branches: > > LEET_LETTERS = { > "e" : "3", > "E" : "3", > "a" : "4", > "A" : "4", > "i" : "1", > "I" : "1", > "t" : "7", > "T" : "7", > "s" : "5", > "S" : "5", > "o" : "0", > "O" : "0", > "b" : "8", > "B" : "8", > } <snip> > LEET_LETTERS is so space-consuming, sometimes it is easier to use the > dict constructor with a list expression of list comprehension. That > is, instead of the built-in syntax P{}'s to define a dict, you can use > the dict constructor and pass a list of (key,value) tuples. > > LEET_LETTERS = dict( [("E","3"), ("e","3"), ("A","4"), > ("a","4"), ...] ) > > Well, my fingers are tired and I'm bored already, how about if we > could just list the two strings of key and value characters, and some > how build the tuples by pulling an item from each list one at a time. > Fortunately, that is what Python's zip() function does: > > LEET_LETTERS = dict( zip("eEaAiItTsSoObB", > "33441177550088") ) > > (I've listed the key-value pairs one above the other to illustrate how > the mapping will work, but of course, that isn't required.) > > Now if I want to add another leet-speak letter (like "6" for "G"), I > just add the two characters on the end of the two strings.
This I disagree with as being unnecessarily clever; the dict literal is just fine as-is and the zip() makes it less clear. However, I would definitely rewrite the dict to use less lines, which, after removing the capital dupes (as I mentioned in my post, just use .lower()), looks like: LEET_LETTERS = {"e" : "3", "a" : "4", "i" : "1", "t" : "7", "s" : "5", "o" : "0", "b" : "8"} which is better, IMHO. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com -- http://mail.python.org/mailman/listinfo/python-list