0

I have a function that takes an integer as input and returns the number as words, it works as I want with the exception of 30,40,50,60,70,80 and 90, it returns for 90 = ninty zero, because the function works by splitting the number, how can I remove the zero being added for the above numbers. my code is as follows

d = {0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five',
     6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten',
     11: 'eleven', 12: 'twelve', 13: 'thirteen', 14: 'fourteen',
     15: 'fifteen', 16: 'sixteen', 17: 'seventeen', 18: 'eighteen',
     19: 'ninteen', 20: 'twenty',
     30: 'thirty', 40: 'fourth', 50: 'fifty', 60: 'sixty',
     70: 'seventy', 80: 'eighty', 90: 'ninty'}

def wordify(n):
    k = 1000
    m = k * 1000
    if n < 20:
        return d[n]
    if n < 100:
        if n % 100 == 0: return d[n]
        else: return d[n // 10 * 10] + ' ' + d[n % 10]
    if n < k:
        if n % 100 == 0: return d[n // 100] + ' hundred'
        else: return d[n // 100] + ' hundred ' + wordify(n % 100)
    if n < m:
        if n % k == 0: return wordify(n // k) + ' thousand'
        else: return wordify(n // k) + ' thousand, ' + wordify(n % k)


print wordify(90)
3
  • 1
    Check if the number is divisible by 10 Commented Aug 19, 2016 at 8:47
  • You might want to change 40: 'fourth' Commented Aug 19, 2016 at 8:52
  • @RolfofSaxony Thanks, over looked that completely Commented Aug 19, 2016 at 8:54

2 Answers 2

1

Changing the following line:

if n % 100 == 0: return d[n]

to

if n % 10 == 0: return d[n]

solves this issue. Since it will then always use the single word and not add the zero behind it whenever it's a multiple of 10.

Sign up to request clarification or add additional context in comments.

Comments

0

Just perform an extra pass to correct problems. Sometimes simpler than trying to figure out how to avoid them.

print wordify(90).replace(" zero","")

or: rename your wordify function into internal_wordify, then define wordify like that:

def wordify(n):
   return internal_wordify(n).replace(" zero","")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.