Skip to content
Advertisement

How to add mathematical function as argument in python function

I know there are similar questions about passing functions into functions, but I’m not clear on the effective solution for my particular problem.

The following function works but the formula is static. It only works on a fixed function, namely (in mathy pseudocode) f(a) = 3^a mod 17 = b where f(11) = 7

JavaScript

I want to make a user pass in any given function. To start with, I implemented something just a little more complex but still pretty simple.

JavaScript

This works but I want to make it even more dynamic.

To try implement this, I created a new function that can be passed as an argument:

JavaScript

I’m not exactly sure how the trial value arg x should be handled or if it should even be in this function.

Then I “forked” the “get_a(b)” function that takes a callback I believe

JavaScript

Then I updated main():

JavaScript

I’m getting the following error messages:

JavaScript

I don’t know how to set it up right and do the variable passing so that I can pass the static variables once in main and the middle test variable x will always increment and eventually find the results I want.

Perhaps I just need to receive a function that begins with a “type” argument that acts as a kind of switch, and then takes a variable number of arguments depending on the type. For example, we could call the above a base-power-mod function or (bpm), where “power” is the answer we’re looking for, i.e. a is the pre-image of b in technical terms. Then just call

JavaScript

And then implement it that way? Thanks for your help!

Advertisement

Answer

Use *args to pass additional arbitrary number of arguments to the function.

JavaScript

Then call it in your main like this

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement