Created
January 11, 2009 07:25
-
-
Save khafatech/45664 to your computer and use it in GitHub Desktop.
This file contains 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
# Euler project problem 17 | |
words = ['', 'one', 'two', 'three', 'four','five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'] | |
debug = 0 | |
def build_word(n): | |
# --debug | |
if debug: | |
print "build_word(%d)" % n | |
# --debug end | |
# --- special cases --- | |
if n < 0: | |
# return None | |
return 'negative ' + ('' or build_word(-1 * n)) | |
if n < 20 and n >= 0: | |
if n == 0: | |
return 'zero' | |
return words[n] | |
if n < 100: | |
# words[]? ' ' + words : '' | |
return words[n/10 + 18] + ('' or (words[n % 10] and (' '+words[n%10]))) | |
# --- special cases end --- | |
# start, end, name | |
magnitudes = ((100, 1000, 'hundred'), | |
(1000, 10**6, 'thousand'), | |
(10**6, 10**9, 'million'), | |
(10**9, 10**12, 'billion'), | |
(10**12, 10**18, 'trillion')) | |
for mag, end, name in magnitudes: | |
if n < end: | |
# <number> <name> [<number if not 0>] | |
# --debug | |
if debug: | |
print "build_word(%d) + %s%s" % (n/mag, name, \ | |
(n%mag or '') and (' + build_word(%d)' % (n % mag))) | |
# --debug end | |
return build_word(n/mag) + ' ' + name + \ | |
((n % mag or '') and (' and ' + build_word(n % mag))) | |
def print_num(n): | |
print '%d: %s.' % (n, build_word(n)) | |
def get_sum_words(n): | |
"Returns the number of letters used if the number is written in words." | |
number = build_word(n) | |
return number and len(number.replace(' ', '')) | |
n = 1000 | |
# print the sum of letters in words from 1 to n | |
# n = 5 # 19, pass! | |
# print sum([len(l.replace(' ', '')) for l in [build_word(i) for i in range(1, n+1)]]) | |
# -- print the sum of an individual number | |
# 115: 20 | |
# 342: 23 | |
# print get_sum_words(342) | |
# -- print numbers | |
""" | |
for i in range(0, 1001): | |
print "%s." % build_word(i).capitalize(), | |
""" | |
print "Enter integers" | |
while n: | |
try: | |
n = int(raw_input()) | |
print build_word(n) | |
except ValueError: | |
print "Invalid number" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment