Advertisement
Guest User

Untitled

a guest
Jul 15th, 2019
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.54 KB | None | 0 0
  1. def number_to_word(n):
  2. """Assumes is an integer from 1 - 1000.
  3. Returns number in words ex: 122 --> one hundred and twenty-two."""
  4. # num_to_alpha contains the unique values for numbers that will be returned according to repetitive patterns
  5. num_to_alpha =
  6. {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten',
  7. 11: 'eleven', 12: 'twelve', 13: 'thirteen', 14: 'fourteen', 15: 'fifteen', 16: 'sixteen', 17: 'seventeen',
  8. 18: 'eighteen', 19: 'nineteen', 20: 'twenty', 30: 'thirty', 40: 'forty', 50: 'fifty', 60: 'sixty',
  9. 70: 'seventy', 80: 'eighty', 90: 'ninety', 100: 'one hundred', 1000: 'one thousand'}
  10. # Numbers below 21 , 100, 1000 are unique words (cannot be formed using a repetitive rule)
  11. if 0 < n < 21 or n == 100 or n == 1000:
  12. return num_to_alpha[n]
  13. mod = n % 10
  14. # Numbers in range (21 - 99) have a single rule except the multiples of 10 (formed by a single word)
  15. if 20 < n < 100:
  16. if n % 10 != 0:
  17. return f'{num_to_alpha[n // 10 * 10]}-{num_to_alpha[mod]}'
  18. return num_to_alpha[n]
  19. # Numbers above 100 have a single rule except the following:
  20. if 100 < n < 1000:
  21. # a) multiples of 100
  22. if n % 100 == 0:
  23. return f'{num_to_alpha[n // 100]} hundred'
  24. # b) numbers whose last 2 digits are above 20 and are also multiples of 10
  25. if not n % 100 == 0 and n % 100 > 20 and n % 10 == 0:
  26. return f'{num_to_alpha[n // 100]} hundred and {num_to_alpha[n % 100]}'
  27. # c) numbers whose last 2 digits are below 20 and not multiples of 10
  28. if n % 100 < 21:
  29. second_part = num_to_alpha[n % 100]
  30. return f'{num_to_alpha[n // 100]} hundred and {second_part}'
  31. # d) numbers whose last 2 digits are above 20 and not multiples of 10
  32. if n % 100 > 20:
  33. return f'{num_to_alpha[n // 100]} hundred and {num_to_alpha[((n % 100) // 10) * 10]}-'
  34. f'{num_to_alpha[(n % 100) % 10]}'
  35. # To prevent counting False values
  36. if n <= 0 or n > 1000:
  37. return ''
  38.  
  39.  
  40. def count():
  41. """Cleans numbers from spaces and hyphens and returns count."""
  42. all_numbers = [number_to_word(x) for x in range(1, 1001)]
  43. numbers_without_spaces = [number.replace(' ', '') for number in all_numbers]
  44. clean_numbers = [number.replace('-', '') for number in numbers_without_spaces]
  45. total = 0
  46. for clean_number in clean_numbers:
  47. total += len(clean_number)
  48. return total
  49.  
  50.  
  51. if __name__ == '__main__':
  52. print(count())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement