Recursive vs Iterative Functions Python

Question:

I am currently learning Python and would like some clarification on the difference between iterative and recursive functions. I understand that recursive functions call themselves but I am not exactly sure how to define an iterative function.

For instance, I wrote this code

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)

I thought that this was an iterative function but after doing some research I am not sure. I need to know specifically because the next exercise asks me to write a version of the function that is recursive/iterative (depending on what my first function is).

Asked By: Hassan

||

Answers:

so the question is “write an iterative and recursive version of sum”. great.

don’t use the built-in sum method, and write your own. i’ll give you the iterative, you should figure out the recursive:

def my_iterative_sum(a):
    res = 0
    for n in a:
        res += a
    return res

this is iterative because it iterates over all the values and sums them up.

edit: clearly your post is iterative. are you calling function f from within function f? no.

maybe reading up on what recursion is will help with this. https://www.google.com/search?q=recursion

Answered By: acushner

Recursive function call itself while does not reach the out poin whereas iterative function update calculating value through the iteration over the range.

Answered By: p.konstantyn

To those who might still want to see the difference between recursive and iterative function.

iterative

def iterative_sum(n):
    result = 1
    for i in range(2,n+1):
        result *= i
    return result
print(iterative_sum(5))

iteration is when a loop repeatedly executes until the controlling condition becomes false

recursive

def recursive_sum(n):
    if n == 1:
        return 1
    else:
        return n * recursive_sum(n-1)
print(recursive_sum(5))

recursive function is when a function calls itself

This link explains it much better
https://techdifferences.com/difference-between-recursion-and-iteration-2.html

Answered By: Kevin Mukuna

In case you came here looking for recursive functions in Python, here is an example of a recursive sum

from typing import Optional

>>> def r_sum(v: int, sum: Optional[int] = None) -> int:
...   if sum is None:
...     sum = 0
...   if v == 0:
...     return sum
...   else:
...     sum = sum + v
...     prev = v - 1
...     return r_sum(prev, sum)
... 
>>> r_sum(3)
6
>>> r_sum(4)
10
>>> r_sum(5)
15
Answered By: Vadym Tyemirov