Source

codeeval_challenges / 052_TextDollar / text_dollar.py

Full commit
#! /usr/bin/env python

import sys
from optparse import OptionParser

ONES = [
    '',
    'One',
    'Two',
    'Three',
    'Four',
    'Five',
    'Six',
    'Seven',
    'Eight',
    'Nine',
]

TENS = [
    'Ten',
    'Eleven',
    'Twelve',
    'Thirteen',
    'Fourteen',
    'Fifteen',
    'Sixteen',
    'Seventeen',
    'Eighteen',
    'Nineteen',
]

TWENTIES = [
    '', '',
    'Twenty',
    'Thirty',
    'Forty',
    'Fifty',
    'Sixty',
    'Seventy',
    'Eighty',
    'Ninety',
]

THOUSANDS = [
    '',
    'Thousand',
    'Million',
    'Billion',
]

def convert_triplet(triplet):
    """ Converts the number in triplet into english language.

        Returns string representing the number.
    """
    text = []
    one = triplet[-1]

    if len(triplet) == 3:
        text += [
            ONES[triplet[0]],
            'Hundred',
        ]

    if len(triplet) > 1:
        ten = triplet[-2]
        if ten == 0:
            text.append(
                ONES[triplet[2]]
            )
        elif ten == 1:
            text.append(
                TENS[one]
            )
        else:
            text.append(
                TWENTIES[ten],
            )
            if one > 0:
                text.append(
                    ONES[one],
                )
    else:
        text.append(
            ONES[one]
        )
    return text

def convert_number_to_text(number, suffix='Dollars'):
    """ Converts number repesented as string into English language.
        
        Returns number converted to text as string.
    """
    number = [int(x) for x in list(number)]

    text = []
    for count, idx in enumerate(xrange(0, len(number), 3)):
        number, triplet = number[:-3], number[-3:] 

        if sum(triplet) != 0: 
            text = convert_triplet(triplet) + [THOUSANDS[count]] + text

    return '%s%s' % (''.join(text), suffix)

def main():
    parser = OptionParser('%s testcase.txt' % __file__)
    options, args = parser.parse_args()

    if len(args) < 1:
        parser.error("No input file provided.")

    test_cases = open(sys.argv[1], 'r')

    for test in test_cases:
        test = test.strip()

        if test != '':
            print convert_number_to_text(test)

    test_cases.close()


if __name__ == "__main__":
    main()