我在这里错过了什么? (ProjectEuler P017)

时间:2013-07-19 13:43:52

标签: python string

所以,我在查看这个简单的代码时遇到了麻烦:

a = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
b = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']
c = ['twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']
d = ['hundred', 'thousand', 'and']
e = a + b + c + d

sum_0 = 0
for i in e:
    sum_0 += len(i)

# 21, 22.. 99
sum_1 = 0
for i in c:
    for j in a:
        sum_1 += len(i + j)

# 100, 200.. 900
sum_2 = 0
for i in a:
    sum_2 += len(i + d[0])

# 101, 102.. 909
sum_3 = 0
for i in a:
    for j in a:
        sum_3 += len(i + d[0] + d[2] + j)

# 110, 111.. 119
sum_4 = 0
for i in a:
    for j in b:
        sum_4 += len(i + d[0] + d[2] + j)

# 120, 130.. 990
sum_5 = 0
for i in a:
    for j in c:
        sum_5 += len(i + d[0] + d[2] + j)

# 121, 122.. 999
sum_6 = 0
for i in a:
    for j in c:
        for k in a:
            sum_6 += len(i + d[0] + d[2] + j + k)

当我print sum_0 + sum_1 + sum_2 + sum_3 + sum_4 + sum_5 + sum_6 + 3时,我得到21134,这比正确答案多10。我在这里缺少什么?

*顺便说一下,3之后的sum_6是'一千'中'一'的长度

1 个答案:

答案 0 :(得分:3)

您正在计算100 (one hundred)两次。

第一次使用{实际'hundred', 'and',但oneand都是三个字母长):

d = ['hundred', 'thousand', 'and']
e = a + b + c + d

sum_0 = 0
for i in e:
    sum_0 += len(i)

第二次来到这里:

# 100, 200.. 900
sum_2 = 0
for i in a:
    sum_2 += len(i + d[0])