Learning Python With Practice Problems

Learning Python With Practice Problems Posted April 5, 2009 @ 6:32pm by Phil

It seems that everywhere I go these days people are preaching the word of Python, so today I thought I would give it a try. To start, I did a quick search for python practice problems since I couldn't think of a small project I wanted to use Python for on my own. I came across this page with the following problems (my solutions are posted at the end):

1. Let's say I have a list of words, and I want to find all the "Hebrew" words. We'll define a "Hebrew" word to be one without any vowels. For example: "xyzzy" could be considered a Hebrew word, if we don't count 'y' as a vowel. Can you write a program to tell the user if a word has the Hebrew nature or not?

2. Have you heard of ROT13? It's a very funny encryption scheme that scrambles a word in a Caesar-cypher style. Each letter of a word will be "rotated" by 13, that is:

a -> n
b -> o
...
m -> z
n -> a
o -> b

For example:

>> rot13("foobar")
's b b o n e'

>>> rot13("alphatransparency")
'n y c u n g e n a f c n e r a p l'

(Hmm... I forgot to tell string.join() not to use spaces in joining. Ooops.)

Can you write a program that will give back the ROT13 of a word? What's also neat about this problem is that if you ROT13 something twice, you'll get back your original word.

>>> rot13("sbbone")
'f o o b a r'

Also, ROT13 is used in USENET newsgroups a lot, when sensitive material is being expressed. The ord() and chr() functions might be useful in solving this problem.

3. This one is challenging: There's a classical CS problem called the anagram solver. Let me see if I can paraphrase the question properly.

First, I'd better say what an anagram is, just for clarity: an anagram is a rearrangement of the letter of a word, so that it too is a word. I have examples of anagrams below.

Let's say that you're given a list of dictionary words, one per line. Also, let's say that you'd like to find all of the anagrams of a single word. Your program should lookup the words in the dictionary, and show which words are anagrams. For example, here are a few anagrams:

liens, lines
defrost, frosted
earls, lares, laser, reals
pares, parse, pears, rapes, reaps, spare, spear
drawer, redraw, rewar, warder, warred
alger, glare, lager, large, regal

I always find it easier to learn something if I have problem to solve using it, which is why I chose to use these practice problems. Overall, I think Python is a very nice language. You can write complex programs simply in a small number of lines. It also removes some tedious tasks and makes programming even more fun.

My Solutions

Hebrew:

import sys

vowels = ("a", "e", "i", "o", "u")

def isHebrew (word):
  for v in vowels:
    if word.count(v) > 0:
      return 1;
  return 0;

for arg in sys.argv[1:]:
  print "%s: %d" % (arg, isHebrew(arg))


Download Source: hebrew.py

Rot13:

import sys

def rot13 (str):
  new = ""
  a = ord("a");
  for s in str:
    new += chr((ord(s) - a + 13) % 26 + a)
  return new
  
print rot13(sys.argv[1])
  

Download Source: rot13.py

Anagram Solver:

import sys

dict = {}

def sortWord (word):
  return "".join(sorted(list(word)))

# Read dictionary
file = open("dict.txt", "r")
for line in file:
  # Remove trailing newline
  if line[-1:] == "\n":
    line = line[:-1]

  word = sortWord(line)
  if word in dict:
    dict[word].append(line)
  else:
    dict[word] = [line]

word = sys.argv[1]
sortedWord = sortWord(word)
if sortedWord in dict:
  print "%s: %s" % (word, ", ".join(dict[sortedWord]))

Download Source: anagram.py

Tags: Python