欧拉计划 17

如果用英文写出数字1到5: one, two, three, four, five, 那么一共需要3 + 3 + 5 + 4 + 4 = 19个字母。

如果数字1到1000(包含1000)用英文写出,那么一共需要多少个字母?

注意: 空格和连字符不算在内。例如,
342 (three hundred and forty-two)包含23个字母;
115 (one hundred and fifteen)包含20个字母。
“and” 的使用与英国标准一致。

# 分类求解1
all_text = open('euler17.txt').read()
all_text = all_text.splitlines()
arr_dict = {0: 0, 'and': 3}
for line in all_text:
    num, english = line.split(' ')
    arr_dict[int(num)] = len(english)

len_1_9 = sum([arr_dict[i] for i in range(1, 10)])
len_10_19 = sum([arr_dict[i] for i in range(10, 20)])
len_20_99 = sum([arr_dict[i] * 10 for i in range(20, 100, 10)]) + len_1_9 * 8
len_100_999 = len_1_9 * 100 + \
    arr_dict[100] * 900 + arr_dict['and'] * (900 - 9) + (len_1_9 + len_10_19 + len_20_99) * 9
len_1000 = arr_dict[1000] + arr_dict[1]
print(len_1_9 + len_10_19 + len_20_99 + len_100_999 + len_1000)


# 分类求解2
len_all = 0
for i in range(1, 1000):
    if i < 20:
        len_all += arr_dict[i]
    elif i < 100:
        n_1 = i % 10
        n_2 = i - n_1
        len_all += arr_dict[n_1] + arr_dict[n_2]
    elif i < 1000:
        n_1 = i % 10
        n_2 = i // 10 % 10 * 10
        n_3 = i // 100
        len_all += arr_dict[n_3] + arr_dict[100]
        if n_2 != 0 or n_1 != 0:
            len_all += arr_dict['and']
            if n_2 < 20:
                len_all += arr_dict[n_2 + n_1]
            else:
                len_all += arr_dict[n_2] + arr_dict[n_1]
print(len_all + len_1000)

txt内容

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
20 twenty
30 thirty
40 forty
50 fifty
60 sixty
70 seventy
80 eighty
90 ninety
100 hundred
1000 thousand
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值