Python ::"IndexError:列表索引超出范围"; [英] Python:: "IndexError: list index out of range"

查看:84
本文介绍了Python ::"IndexError:列表索引超出范围";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试一些python编程元素,并尝试在此过程中生成加泰罗尼亚数字数组.

I'm experimenting with a few python programming elements and trying to produce an array of Catalan Numbers in the process.

我不断收到上述错误,但是我似乎无法推理出原因或找到任何启​​发性的信息来源.

I keep getting the aforementioned error, but I can't seem to reason out why or find any enlightening sources of info.

该函数使用当前元素从C [0] = 0开始计算列表C的下一个元素.

The function calculates the next element of list C using the current element, starting with C[0]=0.

我简化了代码,使事情变得更简单,但仍然保留了错误.

I've reduced my code to make things simpler yet still preserve the error.

from math import *

C = []
C += [0]
def ppC(n,C):  # increment list C
    print( C[n] ) # list index out of range
    C += [ C[n]*(4*n+2)/(n+2) ]
    n += 1
    ppC(n+1,C) # recursive

ppC(0,C)        # RUN

推荐答案

n += 1
ppC(n+1,C) # recursive

使用这两行,第二次调用ppCn值将为2,这是数组末尾的1.尝试仅将n递增一次.

With these two lines, your second call to ppC will have an n value of two, which is one past the end of the array. Try only incrementing n once.

from math import *

C = []
C += [0]
def ppC(n,C):  # increment list C
    print( C[n] ) # list index out of range
    C += [ C[n]*(4*n+2)/(n+2) ]
    ppC(n+1,C) # recursive

ppC(0,C)        # RUN


您可能还应该进行某种检查,以确定何时应该停止生成数字,否则该功能将永远运行. (或者更确切地说,它将运行一千次并崩溃,并显示超过最大递归深度"错误.)例如:


You should probably also have some kind of check to determine when you should stop generating numbers, or else the function will run forever. (or rather, it will run one thousand times and crash with a "maximum recursion depth exceeded" error.) For example:

from math import *

C = []
C += [1]
def ppC(n,C):  # increment list C
    print( C[n] ) # list index out of range
    C += [ C[n]*(4*n+2)/(n+2) ]
    if len(C) > 100: 
        return
    ppC(n+1,C) # recursive

ppC(0,C)        # RUN


还有一件事.第一个加泰罗尼亚语数字不是1还是不是0?


One more thing. Isn't the first Catalan number one and not zero?

from math import *

C = []
C += [1]
def ppC(n,C):  # increment list C
    print( C[n] ) # list index out of range
    C += [ C[n]*(4*n+2)/(n+2) ]
    if len(C) > 10: 
        return
    ppC(n+1,C) # recursive

ppC(0,C)        # RUN

结果:

1
1
2
5
14
42
132
429
1430
4862

这篇关于Python ::"IndexError:列表索引超出范围";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆