fork download
  1. ZILLIONS = [
  2. "",
  3. "thousand",
  4. "million",
  5. "billion"
  6. ]
  7.  
  8. TENS = [
  9. "",
  10. "ten",
  11. "twenty",
  12. "thirty",
  13. "forty",
  14. "fifty",
  15. "sixty",
  16. "seventy",
  17. "eighty",
  18. "ninety"
  19. ]
  20.  
  21. # this goes all the way down to ten because that way I can handle it
  22. # by checking the tens digit against 1 and then just straight indexing
  23. # with the ones digit.
  24. TEENS = [
  25. "ten",
  26. "eleven",
  27. "twelve",
  28. "thirteen",
  29. "fourteen",
  30. "fifteen",
  31. "sixteen",
  32. "seventeen",
  33. "eighteen",
  34. "nineteen"
  35. ]
  36.  
  37. ONES = [
  38. "",
  39. "one",
  40. "two",
  41. "three",
  42. "four",
  43. "five",
  44. "six",
  45. "seven",
  46. "eight",
  47. "nine"
  48. ]
  49.  
  50. ZERO = "zero"
  51.  
  52. def say(n):
  53. """Renders the name of a non-negative integer under a trillion in English.
  54.  
  55. n: the number
  56.  
  57. returns: the number as a string in English.
  58.  
  59. Note that this is, by current US pedagogy, the wrong way, because apparently
  60. they insist that "and" be reserved specifically for separating the whole and
  61. fractional parts. Oh well.
  62. """
  63. # handle special cases first.
  64.  
  65. if n == int(n):
  66. n = int(n)
  67. else:
  68. raise TypeError("non-integers not handled.")
  69. if n >= 10 ** (len(ZILLIONS) * 3):
  70. raise AttributeError("not enough zillions defined")
  71. if n < 0:
  72. raise AttributeError("negative numbers not handled.")
  73. if n == 0:
  74. return ZERO
  75.  
  76. # break it up into three-digit groups.
  77.  
  78. groups = []
  79. while n:
  80. n, group = divmod(n, 1000)
  81. groups.append(group)
  82.  
  83. # now handle each group.
  84.  
  85. all_words = []
  86. for zillion, group in enumerate(groups):
  87. group_words = []
  88. hundreds, cents = divmod(group, 100)
  89. tens, ones = divmod(cents, 10)
  90. if hundreds:
  91. group_words.append(ONES[hundreds])
  92. group_words.append('hundred')
  93. # "and" separates "cents" from either a corresponding hundred
  94. # or, if this is the ones group, from the other groups.
  95. if cents and (hundreds or zillion == 0 and len(groups) > 1):
  96. group_words.append('and')
  97. if tens == 1:
  98. group_words.append(TEENS[ones])
  99. elif cents:
  100. # glom tens and ones together with a dash if necessary.
  101. cent_words = []
  102. if tens:
  103. cent_words.append(TENS[tens])
  104. if ones:
  105. cent_words.append(ONES[ones])
  106. group_words.append('-'.join(cent_words))
  107. if zillion and group:
  108. group_words.append(ZILLIONS[zillion])
  109. if group_words:
  110. all_words.append(' '.join(group_words))
  111. return ' '.join(reversed(all_words))
  112.  
  113. if __name__ == '__main__':
  114. print(say(1100))
Success #stdin #stdout 0.01s 27704KB
stdin
Standard input is empty
stdout
one thousand one hundred