python 递归迭代 多项式函数 导数
我正在尝试写一个类,这个类可以初始化一些参数,这些参数会在不同的方法中反复使用。不过,当我根据这些初始化的值写一个简单的递归算法时,总是出现错误信息,我自己也不知道该怎么解决。
这个算法应该是这样的:
def normal_recursion(poly):
if len(poly) == 1:
return poly[0]
else:
return poly[0] + normal_recursion(poly[1:])
>>> print(normal_recursion([1,2,3]))
>>> 6
这正是我想要的结果。
现在我的类看起来是这样的:
class Ps2(object):
def __init__(self, poly):
self.poly = poly
def testFunction(self):
'''Computes the sum of the elements of an indexable object.'''
if len(self.poly) == 1:
return self.poly[0]
else:
return self.poly[0] + self.testFunction(self.poly[1:])
如果:
test = Ps2([1,2,3])
并且:
test.testFunction()
那么:
TypeError: testFunction() takes 1 positional argument but 2 were given
我尝试了各种不同的写法,比如 'def testFunction(self):' 和 'def testFunction(self, self.poly)',但都没有成功。
不过,Stackoverflow上有一个相关的问题:Python类中的递归,我应该提到这个算法是可以工作的。
我遇到的问题是,我想用 'def init():' 中的值作为我方法的输入。
总之,非常感谢你的帮助。
1 个回答
2
def testFunction(self,poly = None):
'''Computes the sum of the elements of an indexable object.'''
poly = self.poly if poly is None else poly
if len(poly) == 1:
return poly[0]
else:
return poly[0] + self.testFunction(poly[1:]) #since you send it an argument here you must have a argument in the function declaration
当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。