Hi folks, I've been trying to convert numbers from digits to words, I wrote the following code;
units = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'] teens = ['eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'] tens = ['ten', 'twenty', 'thirty', 'fourty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'] def num2word(num): wordlist = [] if len(str(num)) == 4: wordlist = [units[1] + 'thousand'] if len(str(num)) == 3: if num%100 == 0: wordlist = [units[eval(str(num)[-3])-1] + 'hundred'] else: wordlist = [units[eval(str(num)[-3])-1],'hundred', 'and', num2word(eval(str(num)[-2:]))] if len(str(num)) == 2: if num%10 == 0: wordlist = [tens[eval(str(num)[-2])-1]] elif 10<eval(str(num))<20: wordlist = [teens[eval(str(num)[-1])-1]] else: wordlist = [tens[eval(str(num)[-2])-1], units[eval(str(num)[-1])-1]] if len(str(num)) == 1: wordlist = [units[num-1]] return ' '.join(wordlist) for i in range(1, 200): print i, num2word(i) but when I let it run till i = 108, it gives me an invalid token error as follows; ... 99 ninety nine 100 onehundred 101 one hundred and one 102 one hundred and two 103 one hundred and three 104 one hundred and four 105 one hundred and five 106 one hundred and six 107 one hundred and seven 108 Traceback (most recent call last): File "C:/Windows.old/Users/Abasiemeka/Abasiemeka/GOOGLE University/Python/Python Code/MyCode/Project Euler code/Project Euler answer 17.py", line 33, in <module> print i, num2word(i) File "C:/Windows.old/Users/Abasiemeka/Abasiemeka/GOOGLE University/Python/Python Code/MyCode/Project Euler code/Project Euler answer 17.py", line 18, in num2word wordlist = [units[eval(str(num)[-3])-1],'hundred', 'and', num2word(eval(str(num)[-2:]))] File "<string>", line 1 08 ^ SyntaxError: invalid token >>> I am at a loss, please help. gratefully, Abasiemeka
_______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor