Skip to content

Instantly share code, notes, and snippets.

@BBischof
Created December 6, 2013 00:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BBischof/7816809 to your computer and use it in GitHub Desktop.
Save BBischof/7816809 to your computer and use it in GitHub Desktop.
Some little programming puzzle I found. Apparently Facebook asked this sometime. A message containing letters from A-Z is being encoded to numbers using the following mapping: a -> 1, b -> 2, ... etc. How many decodings of some given number. Takes an input of numeral characters.
import sys
### Some little programming puzzle I found. Apparently Facebook asked this sometime.
###
### A message containing letters from A-Z is being encoded to numbers using the following mapping: a -> 1, b -> 2, ... etc. How many decodings of some given number.
###
### Takes an input of numeral characters.
input = sys.argv[1]
def howMany( string, l ):
if not string.isdigit():
return "error: howMany takes strings with numeral characters"
elif l == 0: #base cases
return 0
elif l == 1: #base cases
if string == "0":
return 0
else:
return 1
elif l == 2: #base cases
if "0" in string:
return isValid(string)
else:
return isValid(string)+1
else:
return howMany(string[0:-1], l-1)*(string[l-1] != "0")+howMany(string[0:-2], l-2)*isValid(string[-2:l]) #recursive call
def isValid( tail ):
if len(tail) != 2:
print "error: isValid takes strings of length 2 with numeral characters"
elif int(tail) > 26 or tail[0] == "0":
return 0
else:
return 1
def decode( message ):
if "00" in message: #any 00 invalidates the string
return 0
else:
return howMany(message, len(message))
print decode(input)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment