Home > Software engineering >  Write a function which takes parameters and with them generates a new function
Write a function which takes parameters and with them generates a new function

Time:10-18

For starters, let's set up what kind of function is needed, a cubic represented as a function:

def solve(x):
    return 5*x*x*x   4*x*x   3*x   2

This function would then be used as part of another function to solve this cubic where values would be substituted for x to eventually find the correct value. Simple enough.

However, I am now given the prompt where I need to grab numbers that will serve as coefficients in this function, these are stored in a list named termsList. With this list, I grab the numbers and need to use a function named cubic() and am told that the only parameters used in cubic() are the terms I will be using for this function, while also having cubic() generate a function on its own, solve(). It's difficult to describe but based on my understanding of the instructions the result should be something vaguely similar to this:

def cubic(a, b, c, d):
    def solve(x):
        return float(a)*x*x*x, float(b)*x*x, float(c)*x, float(d)

solve1= cubic(termsList[0], termsList[1], termsList[2], termsList[3])

solving(solve(x))

All of my attempts to make this work have failed and I'm not sure where to go from this. The only things that cannot change at all are:

  1. The result of using cubic() must be stored in variable solve1.
  2. The function named solve() must be created as a result of running cubic()
  3. The only 4 acceptable parameters for cubic() are the 4 values that will be used to make the function.
  4. The resulting function named solve() must be runnable in a separate function after running cubic() as shown above.

I've omitted other parts of the code for simplicity's sake but that's the situation I'm in. All other code, including the function that will be using solve() later, has been tested to work. I'm really and truly stumped. No libraries can be used.

CodePudding user response:

Your naming convention is odd, let's use more descriptive names:

def make_cubic(a, b, c, d):
    def func(x):
        return float(a)*x*x*x   float(b)*x*x   float(c)*x   float(d)
    return func

cubic = make_cubic(*termsList)

whatever(cubic(x))
  • Related