[英]exponential sum using recursion.python
I need to write a function using recursion that accepts the following variables: 我需要使用递归编写一个接受以下变量的函数:
n: int
x: real
and returns the exponential sum function: 并返回指数求和函数:
I can't use loops at all, only recursion. 我根本不能使用循环,只能使用递归。
I started by writing two recursive functions for sum and factorial but when I tried to combine the two of them I got the error message: 我首先为sum和factorial编写了两个递归函数,但是当我尝试将它们两个结合时,我得到了错误消息:
TypeError: 'int' object is not iterable
I don't quite understand what it means because I didn't use loops, only recursion. 我不太明白这是什么意思,因为我不使用循环,仅使用递归。 Here is my code:
这是我的代码:
def sum_exp(n):
if n == 0:
return 0
return n + sum(n - 1)
def factorial(n):
if n == 0:
return 1
else:
return n*factorial(n-1)
def exp_n_x(n, x):
if n == 0:
return 1
else:
return sum_exp(x*(1/factorial(n)))
print(exp_n_x(10, 10))
I would love to get some help with this. 我很乐意为此提供一些帮助。 Thanks a lot in advance.
非常感谢。
you've made a typo in: 您输入了错字:
def sum_exp(n):
if n == 0:
return 0
return n + sum(n - 1)
^^^
where you use the global function sum()
which takes an iterable and returns the sum of its elements. 使用全局函数
sum()
地方,该函数接受一个可迭代并返回其元素的总和。 Thus: 从而:
>>> sum(42)
TypeError: 'int' object is not iterable
whereas 而
>>> sum([42])
42
so your fix is straightforward: 因此您的解决方法很简单:
def sum_exp(n):
if n == 0:
return 0
return n + sum_exp(n - 1)
NB: This answer is only meant to fix your issue with the TypeError, and get you going to the next error you'll hit, which is an infinite recursion. 注意: 此答案仅用于解决TypeError问题,并使您转到下一个遇到的错误,这是无限递归。 As an advice you should double check your stop condition and recursion step.
作为建议,您应该仔细检查停止条件和递归步骤。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.