使用带函数的循环在Euler 17上获取IndexError

时间:2016-12-05 21:33:42

标签: python

我正在使用Project Euler#17并且我的索引超出了范围错误。

以下是问题的内容:

  

如果数字1到5用文字写出:一,二,三,四,五,那么总共有3 + 3 + 5 + 4 + 4 = 19个字母。

     

如果所有1到1000(一千)的数字都用文字写出来,会用多少个字母?

     

注意:不要计算空格或连字符。例如,342(三百四十二)包含23个字母,115(一百一十五)包含20个字母。使用"和"写出数字符合英国人的用法。

我想使用一个循环来创建一个列表,该循环将1到1000之间的数字存储为整数,然后使用一个可以将数字作为参数的函数,将其转换为一个用英语表示数字的字符串,然后计数每个单词中的单词数,并将其作为整数返回。

然后我创建一个for循环,从列表中获取整数并将每个整数放入函数中。

这是我的代码:

letter_count = []

#Function that intakes integer and returns number of words it has in english.
def numToWords(num):
    #Store strings that contain the names of the numbers.
    #The 0th place item is plank so that the numbers start at 1.
    units = ['', 'one', 'two',   'three','four','five','six','seven','eight','nine']
    teens = ['','eleven','twelve','thirteen','fourteen','fifteen','sixteen,'     'seventeen','eighteen','nineteen']
    tens =    ['','ten','twenty','thirty','forty','fifty','sixty','seventy','eighty','ninety']
    thousands = ['', 'thousand']

    words = []
    if num==0: words.append('zero') #Special case for when the number is 0.
    else:
        numStr = '%d'%num  #Stores number as string
        numStrLen = len(numStr)  #Checks length of string using decimal value
        groups = (numStrLen+2)/3 
        numStr = numStr.zfill(groups*3)
        for i in range(0, groups*3, 3):
            h,t,u = int(numStr[i]), int(numStr[i+1]), int(numStr[i+2])
            g = groups - (i/3+1)
            if h>=1:
                words.append(units[h])
                words.append('hundred')
                if num > 101 and num < 110:
                    words.append('and') #Adds the 'and' for numbers 101-109.
            if t>1:
                words.append(tens[t])
                if u>=1: words.append(units[u])
            elif t==1:
                if u>=1: words.append(teens[u])
                else: words.append(tens[t])
            else:
                if u>=1: words.append(units[u])
            if (g>=1) and ((h+t+u)>0): words.append(thousands[g]+',')
    return len(words)

#Loop to take integers in 1 to 1000 as arguments in the function 
#and append them to a new list
for i in range(1,1001,1):
    letter_count.append(numToWords(i))

#Print the sum of the new list to get the total number of words.
print(sum(letter_count))

当我运行代码时(使用El Cap&#39; s python bash命令),我收到以下错误消息:

  

追踪(最近一次通话):     文件&#34; euler017.py&#34;,第40行,in       letter_count.append(numToWords(i))的     在numToWords中输入文件&#34; euler017.py&#34;,第31行       如果你&gt; = 1:words.append(青少年[u])   IndexError:列表索引超出范围

我在一堆随机数上单独测试了这个功能,并且它有效。我还在1到10的数字循环上测试了它。当循环为100或更高时,我得到错误。

对于我在旧帖子中看到的修改过的功能: https://stackoverflow.com/a/19193721/5960074

我不确定这是怎么回事。我没有修改任何列表,只是创建一个新列表,那么某些内容如何超出范围?

感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

将逗号之间的逗号移到16和17之间:

你有

'sixteen,'     'seventeen'

但你想要

'sixteen', 'seventeen'

解释器没有注意到您的错误,因为它是有效的python:

String literal concatenation