Consider:
def itr(n):
s = 0
for i in range(0, n+1):
s = s + i * i
return s
This is a simple iterative function that I would like to change into a recursive function.
def rec(n):
import math
if n!=0:
s=n-(2*math.sqrt(n))
if s!=0:
return(s+rec(n))
else:
return(n)
else:
return n
This is my try at doing the said thing, but I cannot quite get it right.
Why does not my solution work? What is the solution?
Use:
def recursive(total, n):
if n == 0:
return total
else:
return recursive(total + n * n, n - 1)
A couple of thoughts:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.