Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from typing import List
- def numberToWords(num: int) -> str:
- # Shortcut return if zero:
- if num == 0:
- return "Zero"
- # Use divmod to parse number into chunks
- chunks = numberSplitter(num, 1000)
- ordinals = ['Billion', 'Million', 'Thousand', '']
- words = []
- for chunk in chunks:
- # convert chunk into words, add appropriate ordinal
- words.append(hundredUnitToWords(chunk, ordinals.pop()))
- numberWords = ""
- for word in reversed(words):
- if word:
- numberWords += f" {word}"
- return numberWords.strip()
- def hundredUnitToWords(num: int, ordinal: str) -> str:
- hundreds, remainder = divmod(num, 100)
- digits = {0: "", 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: "Nineteen"}
- tens = {0: "", 2: "Twenty", 3: "Thirty", 4: "Forty", 5: "Fifty", 6: "Sixty", 7: "Seventy", 8: "Eighty", 9: "Ninety"}
- hundred = "Hundred"
- # Compose number within 3 digit block
- words = ""
- if hundreds:
- words += f"{digits[hundreds]} {hundred}"
- if remainder:
- # Fix spacing:
- if hundreds:
- words += " "
- if remainder < 20:
- # Special case for numbers less than 20 to cover teens
- words += digits[remainder]
- else:
- # get 10s portion, add units portion
- ten, one = divmod(remainder, 10)
- words += f"{tens[ten]}{'' if (ten == 0 or one == 0) else '-'}{digits[one]}"
- if words:
- words += f" {ordinal}"
- return words
- # Splits a positive integer in groups specified by split, returns them in least to most significant order
- def numberSplitter(num: int, split: int) -> List[int]:
- splits = []
- while num > 0:
- sub = divmod(num, split)
- splits.append(sub[1])
- num = sub[0]
- return splits
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement