0

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

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)

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

*顺便说一下,3后面sum_6是“一”在“一千”中的长度

4

1 回答 1

3

你在数100 (one hundred)两次。

第一次在这里(实际上'hundred', 'and'是使用,但one都是and三个字母长):

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])
于 2013-07-19T13:54:01.843 回答