函数导数计算多项式的导数;每个项的阶数需要减少1,每个项必须乘以上一个阶数,阶数[0]处的项需要删除。你知道吗
此代码
lst = [1,2,3] """This list represents the polynomial 3x^2+2x+1"""
"""This function moves each entry one index down and removes the last
entry"""
def move(lst):
copy = list(lst)
for i in range(len(lst)):
lst[i-1] = copy[i]
del lst[-1]
print lst
move(lst)
产生以下结果:
Samuels-MacBook:python barnicle$ python problemset2.py
[2, 3]
此代码:
def derivative(poly):
copy = list(poly)
degree = 0
for i in range(len(poly)):
i = degree*(i+1)
poly[i-1] = copy[i]
degree += 1
del poly[-1]
print poly
derivative(lst)
产生此错误:
Samuels-MacBook:python barnicle$ python problemset2.py
Traceback (most recent call last): File "problemset2.py", line 59,
in <module>
derivative(lst) File "problemset2.py", line 55, in derivative
poly[i-1] = copy[i] IndexError: list index out of range
所以,我想出来了。这是我新的工作函数,重命名为ddx2:
lst = [0,3,5,4] #lst represents the polynomial 4x^3+3x^2+5x
def ddx2(lst):
for i in range(len(lst)):
lst[i] = lst[i]*i
if i != 0:
lst[i-1] = lst[i]
del lst[-1]
print lst
ddx2(lst) #Here I call the function
当我调用函数时,我得到了正确格式的正确导数,即[3,10,12]。我想我收到的错误信息是因为我试图在退出循环之前缩短列表的长度。你知道吗
索引
i
及其计算i = degree*(i+1)
将增长等于或大于len(poly)
和len(copy)
,因此超出范围这里是一个快速的黑客我做:)希望它能满足您的要求,你只是要知道名单的长度。你知道吗
好好享受!你知道吗
线
i = degree*(i+1)
基本上是指平方指数。您有一个长度为i
的数组,但试图获取索引为i*i
的元素。你知道吗相关问题 更多 >
编程相关推荐