1

Trying to learn Python from the Think Python book and at the section about recursive functions. An exercise there made me wonder how to call a function with arguments using another function generically.

The answer to the exercise itself is already available in another thread, but all solutions involve modifying the third function do_n() to add additional arguments that will match the second function print_n()

def countdown(n): # FIRST FUNCTION
    if n <= 0:
        print("blastoise")
    else:
        print(n)
        countdown(n-1)

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

def do_n(f, s, n): # THIRD FUNCTION
    if n <= 0:
        return
    f(s, n)
    do_n(f, s, n-1)

How do you write the third function so that it is generic and works to call either the first function or second function or any other function by prompting you to enter the arguments for the called function instead of the solution above?

Thanks!

Comsavvy
  • 630
  • 9
  • 18
brownspecs
  • 13
  • 5

1 Answers1

0

How do you write the third function so that it is generic and works to call either first function or second function or any other function by prompting you to enter the arguments ...?

I don't know where it would be useful to have the arguments entered by the user, but since you ask for it:

def do_in(f, n):                        # prompt to enter arguments, call f n times
    try: a = eval(input('comma separated arguments: '))
    except SyntaxError: a = ()          # you may want more sophisticated error checks
    if not isinstance(a, tuple): a = a, # make single argument iterable
    for _ in range(n): f(*a)            # unpack arguments with starred expression
Armali
  • 18,255
  • 14
  • 57
  • 171