Search code examples
pythonrecursioniterationpython-2.x

Recursive vs Iterative Functions Python


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).


Solution

  • 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