Tiny Code

I just found out about this neat little subreddit,  http://www.reddit.com/r/tinycode, and thought I should spread the word.  The idea is to share neat snippets of code that do impressive things with a focus on minimalism.  One thing I especially like is that the site isn’t merely code golf and obfuscation, but instead powerful solutions in relatively few lines of code.  The major benefit of keeping things small is that you’ve boiled a problem down to as few operations as possible.

As a matter of finding learning material, you usually only want the part of the solution you don’t yet understand and not a full-blown application with features currently over your head.  After all, when trying to work out the tiny but complicated and time-consuming portions of a project I’ll search through blog posts and Stack Overflow submissions until I piece together to a solution suitable for my implementation.  If a snippet is too long it’s not likely it will work well in a general case.  If it’s too complicated to be readily understood it’ll get put on the back-burner until I find a better solution or give up and start digesting it.

Here’s a submission that won’t take long to wrap your head around: Four lines of Python for a Spellchecker

import sys
a = sys.argv[1:]
s = [x.lower()[:-1] for x in open("/usr/share/dict/words")]
print " ".join([("\x1b[31m"+w+"\x1b[0m" if w in [_ for _ in a if _ not in s] else w) for w in a])

$./spellchecker.py hello this woard is wrong
hello this woard is wrong

I will admit code golf can be pretty cool, this little gem emerged in the comments:

print(' '.join('! '[w+'\n'in open("/usr/share/dict/words")]+w for w in __import__('sys').argv[1:]))

$./spellchecker.py hello this woard is wrong
hello this !woard is wrong

As for actually creating a more sophisticated spell checker, I recommend Peter Novig’s write-up norvig.com/spell-correct.html, and coursera.org‘s NLP class. As an added benefit I learned about the “words” package, which is nice because I always forget where I store my one time use dictionary files.