I want to generate some Python scripts based on different conditions. It means: I have a constant body of my Python scripts, which is exactly the same in all the different conditions, but due to the fact that I have several different conditions, there are some regions in those Python scripts that should be changed. Let's say this is my constant part, which is similar for all the conditions:
import numpy as np
variables = []
for i in range(100):
variables.append(tempVariable)
print variables
And I have 4 different conditions, where tempVariable is calculated differently as:
Condition 1: tempVariable = i
Condition 2: tempVariable = i**2
Condition 3: tempVariable = i**3
Condition 4: tempVariable = i + 4.34
Note that I don't want to use if statement to switch over these four conditions cause these conditions are in fact different cases and are not related together. At the end, I want to have variables for these four different conditions and cases independently. My idea is that to put these four cases or conditions into a txt file and treat the constant part of the Python script as an another txt file and iterate over all these four conditions or cases and add the necessary part for calculating the tempVariable before appending it into variables. Of course, it looks pretty ugly and more importantly I want to ship it to other people to be able to use it. I appreciate if there is any more nice and generic approach to it. In my real application, I have 94 different conditions or cases, which would be really ugly, if I want to put them under some if or elif statements. Any suggestion or idea is appreciated.
If you are always using a polynomial, you could have a list of the coefficients that is passed to your function.
For the conditions you have provided, an object like:
mylist = [[0,1,0,0],[0,0,1,0],[0,0,0,1],[4.34,1,0,0]]
Then your nth condition line would just have to read:
Condition: tempVariable = mylist[n][0] + mylist[n][1]*i + mylist[n][2]*i**2 + mylist[n][3]*i**3
By building up a generalized condition you won't need multiple copies of this function
If you don't need to change conditions on run time but when executing the program:
You can add constant variables at the beginning of the file, or you can create a file like parameters and store all conditions and which one is active in that file.
Then import that file and take the active condition(parameter) and act as it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With