python - How to implement variants/variations of a function -


this first question, sincerely apologize posting mistakes sure make. did first search through answered questions, didn't find suitable solution, although recognize might not have searched using correct terminology or keywords.

i have general function have evaluated in python. gets passed optimizer (fmin_cobyla), , i'd prefer take single argument. i'd able have option of using different variations (variants? flavors?) of function might controlled flag. since want evaluated doesn't make sense have bunch of if or case statements within function (right?), have if statements around definitions of function variants:

if flag==1:     def f(x):         in range(0,len(x)*3,3):             a[i:i+3,i:i+3]=1/x[i/3]*np.eye(3)         tmp=np.linalg.solve(a,b)         y=somecmodulefunction(tmp)         return y elif flag==2:     def f(x):         in range(0,len(x)*3,3):             a[i:i+3,i:i+3]=x[i/3]*np.eye(3)         tmp=np.linalg.solve(a,b)         y=somecmodulefunction(tmp)         return y ... 

the functions identical exception of 1 line. right way it? there anyway if have 10 different variants, it's not long unwieldy block of code?

thanks!

why don't pass flag variable input function well?

def f(x, flag):     in range(0,len(x)*3,3):         if flag == 1:            a[i:i+3,i:i+3]=1/x[i/3]*np.eye(3)         elif flag == 2:            a[i:i+3,i:i+3]=x[i/3]*np.eye(3)     tmp=np.linalg.solve(a,b)     y=somecmodulefunction(tmp)     return y 

if there default value of flag, can use, default argument values:

def f(x, flag=1):     in range(0,len(x)*3,3):         if flag == 1:            a[i:i+3,i:i+3]=1/x[i/3]*np.eye(3)         elif flag == 2:            a[i:i+3,i:i+3]=x[i/3]*np.eye(3)     tmp=np.linalg.solve(a,b)     y=somecmodulefunction(tmp)     return y 

so that, when do, f(10), function f() executed using flag equals 1.

if want use flag value, can do: f(10,2).


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -