Euler Project question 17 in python way

本文介绍了一个用于计算从1到1000所有数字英文拼写中字母总数的Python算法。通过建立数字与字母数量之间的映射关系,并考虑了英语数字书写规范,实现了高效计算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

# This Python file uses the following encoding: utf-8
# If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.

# If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?


# NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of "and" when writing out numbers is in compliance with British usage.
import time
start = time.time()
d = {0:0, 1:3, 2:3, 3:5, 4:4, 5:4, 6:3, 7:5, 8:5, 9:4, 10:3, 11:6, 12:6, 13:8, 14:8, 15:7, 16:7, 17:9, 18:8, 19:8, 20:6, 30:6, 40:5, 50:5, 60:5, 70:7, 80:6, 90:6, 100:7, 1000:8, 'and':3}
letters = 0
for i in xrange(1, 1001):
    if i <= 20:
        letters += d[i]
    if 20 < i < 100:
        letters += d[i - i%10] + d[i%10]
    if 100 <= i < 1000:
        letters += d[i/100] + d[100]
        if i%100 != 0:
            letters += d['and']
            if i%100 <= 20:
                letters += d[i%100]
            else:
                letters += d[i%100 - i%100%10] + d[i%10]
    if i == 1000:
        letters += d[1]
        letters += d[1000]

print "%s letters in %s seconds" % (letters, time.time() - start)

转载于:https://www.cnblogs.com/cyberpaz/p/4060584.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值