How to run do_n?

141 views Asked by At

I'm currently working on recursive function on Think Python, page 44.

It wrote:

"Write a function called do_n that takes a function object and a number, n as arguments,

and that calls the given function n times."

I found a really good answer from this discussion Text

Okay, now I know how to type the code, but how do I actually run it?

def do_n(f, n):
    if n <= 0:
          return
    f(n)
    do_n(f, n-1)

The code like below looks really easy to figure out:

def print_n(s, n):
    if n <= 0:
         return
    print(s)
    print_n(s, n-1)

Just need to type Print("Anita", 2) and the output will be:

Anita
Anita

But the do_n I can't figure out what to type in order to run the code. I guess I am not familiar with do function.

Can anyone explain it?

2

There are 2 answers

0
ggorlen On

do_n(f, n)'s first argument is a function, not a string. You can either provide a lambda or normal def function as described in Passing a function into another function:

>>> def do_n(f, n):
...     if n <= 0:
...           return
...     f(n)
...     do_n(f, n-1)
...
>>> do_n(lambda x: print(x), 5)
5
4
3
2
1
>>> def do_stuff(x): print(x)
...
>>> do_n(do_stuff, 3)
3
2
1

As I mentioned in the comments, this is a misapplication of recursion (at least in a non-functional language like Python) -- you can blow the stack if you want to run a function more than ~1000 times (in CPython), creating a security risk for your app. And it's just easier to write the code as a loop:

>>> def do_n(f, n):
...     for i in range(n, 0, -1): f(i)
...
>>> do_n(lambda x: print(x), 5)
5
4
3
2
1
0
stoddabr On

ggorlen's answer is 99% correct, but the question didn't say to pass n into the function and his is a little hard to read for a beginner (required knowledge of lambdas and one-line loops).

Here's my solution:

def do_n(f, n):
  if n > 0:  # stopping condition to prevent looping forever
    f()  # trigger the function
    do_n(f, n-1)  # recourse, decrement n to eventually trigger stopping condition

Here's an example use

def test_f():
  print('test_f triggered')

do_n(test_f, 3)