Categories
Programming

Python: Facing the Snake

I’m starting to get back into the learning mode, and the first thing on the TODO list, Python. It’s a lot more impressive than PHP. It’s easier to learn the basics, and yet has so much power from what I’ve seen so far. Maybe I can make use of it in my new job.

I started to try to make a script to print all possible words that a phone number can make, but I found that it was harder than it seemed. I could do it, but I estimate there to be around 729 possible combinations (9 digits, 3 combinations on most keys… if my math is right, that’s 9³), I didn’t want to fool with it and any potential memory problems.

I hate to say it, but I’m ready to go back to school… Well, mainly work. I’m running out of games to take up my time.

Update: Ok, I was wrong. The possible combinations is 39, which turns out to be 19683 possibilities, where each key has 3 letters. That does not account for the letters q or z, or the number 1 or 0. I actually came up with a program that’s only 15 lines long using recursion. For anyone who cares, I’ll put the code here:

#! /usr/bin/env python

digits=['_', '.,!?', 'abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz']

def phoneLetters(phone, r=''):
  if(len(phone) == 0):
    print r
    return
  if(phone[0] >= '0' and phone[0] <= '9'):
    for i in digits[int(phone[0])]:
      phoneLetters(phone[1:], r + i)
  else:
    phoneLetters(phone[1:], r)

import sys
if(sys.argv[1]):
  phoneLetters(sys.argv[1])