Convert a list of words to numbers
With respect to this article about "Why Python Programmers Should Learn Python (paradox?)", here is my solution to convert a list of words to numbers


# this is a fun script tha converts words to number. for e.g Nine Seven Three to 973
# Author (Jinal Jhaveri )

import sys
WORDS_TO_NUM = {
'zero':0, 'one':1, 'two':2, 'three':3, 'four':4, 'five':5, 'six':6,
'seven':7, 'eight':8, 'nine':9, 'ten':10
}

# Takes a list of words and generates a number out of it. Exits with error
# if the word is invalid and cannot be converted to a number
#
# NOTE THAT THIS ONLY WORKS FOR POSITIVE NUMBERS
#
# @arg words : list of words
# @return void
def WordsToNumber(words):
num = 0 # this will store the number
for word in words:
try:
num = num*10 + WORDS_TO_NUM[word.lower()]
except KeyError:
print "Found an invalid word"
sys.exit(1)
return num


if __name__=='__main__':
print WordsToNumber(sys.argv[1:])


Ok .....I know this isn't a challenging problem :)

Comments

Popular posts from this blog

Impossible