简体   繁体   中英

add exceptions to python function

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)

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.

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","")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM