目前我正在学习Python和想迭代和递归函数的区别一些澄清。据我所知,递归函数调用自己,但我不完全知道如何定义一个迭代函数。
举例来说,我写了这个代码
random_list = ['6', 'hello', '10', 'find', '7']
def sum_digits(string):
return sum(int(x) for x in string if x.isdigit())
print "Digits:", sum_digits(random_list)
我认为这是一个迭代函数,但做了一些研究之后,我不知道。我需要知道具体是因为下一个练习要求我写一个版本的功能是递归/迭代(取决于我的第一个功能是什么)。
所以,问题是“写总和的迭代和递归版本”。大。
不使用内置的总和法,并自己编写。我给你的迭代,你应该搞清楚递归:
def my_iterative_sum(a):
res = 0
for n in a:
res += a
return res
这是迭代的,因为它遍历所有的值,并总结起来。
编辑:明明你的文章是重复的。你从功能f
内调用函数f
?没有。
也许读了什么递归会与此有所帮助。 https://www.google.com/search?q=recursion
递归函数调用本身,而不会通过遍历所有范围达到了POIN而迭代函数更新计算值。
对于那些谁可能仍然希望看到递归和迭代函数之间的区别。
迭代
def iterative_sum(n):
result = 1
for i in range(2,n+1):
result *= i
return result
print(iterative_sum(5))
迭代是当一个循环中重复执行,直到控制条件为假
递归
def recursive_sum(n):
if n == 1:
return 1
else:
return n * recursive_sum(n-1)
print(recursive_sum(5))
递归函数是当一个函数调用自身
此链接解释它更好https://techdifferences.com/difference-between-recursion-and-iteration-2.html