简体   繁体   中英

Changing an iterative function into a recursive one

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:

  • This can be refactored to using only a single argument, but by supplying both the total and the current iteration count, it is easier to see how to transform the iterative approach to a recursive one.
  • While this function can be made recursive, it should not be, as there isn't any advantage over the iterative approach.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM