0

I have to create a function mega_calculator, that takes in two inputs: a function and the number of times, I should repeat it. The function should return a value when I call it. inside the parent function(mega_calculator), now I have to create a second function that takes in the same number of inputs as the parent function mega_calculator by giving it parameters *args when I create it. My question is, how do I access the parent function parameters inside the second function?

I thought that *args was a list of parameters and therefore if I called the first and second values, I could save the function operation and repeat amounts onto variables, to later use inside the second function, but this did not work.

What should I do for that?, any help is loved and appreciated greatly. we must have the weird function setup, so unfortunately I can't just make a nice simple while loop.

    def mega_calculator(fn, repeat = 1000):
        def helper(*args):
            function = *args[0]
            bob = *args[1]
            while bob > 0:
                total += function
                return (total/repeat)
        return helper()

`

1 Answer 1

5

You misunderstood; args captures any arguments (not already named explicitly) passed to helper() but you don't pass any arguments to that function.

You instead call it directly with no arguments whatsoever.

You don't need to pass in arguments here however, as fn and repeat are directly accessible from the closure.

Most likely the assignment asks you to return helper and call fn with those arguments:

def mega_calculator(fn, repeat=1000):
    def helper(*args):
        total = 0
        for _ in range(repeat):
            total += fn(*args)
        return total / repeat
    return helper

Now mega_calculator() returns a new function object, that when called, passes on any arguments given on to fn when it calls that function.

A small demo:

>>> def mega_calculator(fn, repeat=1000):
...     def helper(*args):
...         total = 0
...         for _ in range(repeat):
...             total += fn(*args)
...         return total / repeat
...     return helper
... 
>>> def add(a, b):
...     return a + b
... 
>>> repeated = mega_calculator(add, 10)
>>> repeated(5, 6)
11

The add() function was called 10 times, but because the helper also divides the resulting sum by the number of repetitions, it's still 11 that is returned.

Sign up to request clarification or add additional context in comments.

1 Comment

thank you very much, it worked! sad thing is we tried separate pieces of it, but i guess we had to make all those changes together. i will choose this as the solution as soon as the time is up

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.