Home > Blockchain >  How do I write a master function to call a different number of functions each time?
How do I write a master function to call a different number of functions each time?

Time:07-25

I have a program that has the following 4 functions.

Single(input)
Double(input)
Triple(input)
Quad(input)

I wish to create a master function where you can determine which functions you wish to call.

My current code is the following:

def master(*functions, site):
result = []
for function in functions:
    result.append([function(site)])
    
return result

An example of how I use this is as follows:

master(Single,Triple,Quad,site='google.com')

I wish to make the program take in an input that specifies which functions to use, and which site to use. I have tried doing:

master(input(),input())

Yet this does not work.

How would I go about achieving this?

Any advice is much appreciated. Thank you.

CodePudding user response:

For single function name

Why dont you try to put functions into hash map. For example :

function_map = {"single":Single,"double": Double, "triple":Triple} 

def master(function_name , function_input):
 function_map[function_name](function_input)

Then you can call like:

master(input(), input())

Of course , you need to check for out-of-scope inputs such as invalid function name.

For Multiple function name inputs

def master(function_names, function_input):
 results = [] 
 for function_name in function_names.split(','):
  results.append(function_map[function_name](function_input))
 return results

Still you need to check for out-of-scope input. In addition, your function names should be separated with comma

CodePudding user response:

You can create functions and then store them into a dictionary where you store the function name as the key and the function itself as the value. Here is an example of how that would work:

Output=['Time','Date','Sleep']

def Time():
    time= 'this is the time'
    return time

def Date():
    date= 'this is the date'
    return date

def Sleep():
    sleep= 'it is time for bed'
    return sleep

def Add(x,y):
    return x y

functions = {'Time':Time, 'Date':Date, 'Sleep':Sleep, 'Add':Add}

for x in Output:
    print functions[x]()

From here you could also call:

print functions['Add'](2,2)
  • Related