Last active
March 2, 2018 01:23
-
-
Save danthedaniel/45a47d5b5d7279b3ffe6db05667dcd9c to your computer and use it in GitHub Desktop.
Print an integer in English
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """Print a number.""" | |
| from __future__ import print_function | |
| size_names = [ | |
| "", "thousand", "million", "billion", "trillion", "quadrillion", | |
| "quintillion", "sexillion", "septillion", "nonillion", "decillion" | |
| ] | |
| num_names = [ | |
| "", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", | |
| "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", | |
| "seventeen", "eighteen", "nineteen" | |
| ] | |
| tens_names = [ | |
| "", "", "twenty", "thirty", "fourty", "fifty", "sixty", "seventy", "eighty", | |
| "ninety" | |
| ] | |
| def reverse(l): | |
| """Reverse iterable l.""" | |
| return l[::-1] | |
| def reverse_elems(l): | |
| """Reverse the iterable elements of an iterable l.""" | |
| return [x[::-1] for x in l] | |
| def pipe(val, *funcs): | |
| """Pipe a value through multiple functions.""" | |
| for func in funcs: | |
| val = func(val) | |
| return val | |
| def chunk(l, n=3): | |
| """Yield successive n-sized chunks from l.""" | |
| for i in range(0, len(l), n): | |
| yield l[i:i + n] | |
| def quantity(num): | |
| """Get string for a 3-digit number in English.""" | |
| tens = 0 | |
| segments = [] | |
| if len(num) > 2: | |
| hundreds = int(num[-3]) | |
| if hundreds > 0: | |
| segments.append("{} hundred".format(num_names[hundreds])) | |
| if len(num) > 1: | |
| tens = int(num[-2]) | |
| if tens > 1: | |
| segments.append(tens_names[tens]) | |
| if len(num) > 0: | |
| ones = int(num[-1]) | |
| if tens != 1: | |
| # We don't want the tens place to affect this section unless it's 1 | |
| tens = 0 | |
| segments.append(num_names[tens * 10 + ones]) | |
| return " ".join([x for x in segments if len(x) > 0]) | |
| def print_num(num): | |
| """Pretty print an integer in English.""" | |
| sign = "" | |
| if num == 0: | |
| print("zero") | |
| return | |
| if num < 0: | |
| sign = "negative " | |
| num = -num | |
| segments = pipe( | |
| num, | |
| str, | |
| reverse, | |
| chunk, | |
| reverse_elems, | |
| enumerate, | |
| list, | |
| reverse | |
| ) | |
| english_segments = [ | |
| "{} {}".format(quantity(seg), size_names[x]) | |
| for x, seg in segments | |
| if len(quantity(seg)) > 0 | |
| ] | |
| print(sign + " ".join(english_segments)) | |
| def main(): | |
| """Example driver.""" | |
| print_num(int(input("Enter a number: "))) | |
| if __name__ == "__main__": | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment