I would like to get a guess on the computaional effort of my algorithms, meaning in this case: How often do I add, subtract, multiply and divide in my algorithm .
Example:
def b(a):
a = a + 3 #1
a = a * a #2
a = a * -1 #3
return a
if __name__ == "__main__":
for i in range(10):
b(1)
the ouput of the analysis should be:
1: + --> 1 mathmatical operation
2: * --> 1 mathmatical operation
3: +, - --> 2 mathmatical operations
for every loop, therefore the analyzer run on this program should return 40 .
A Pythonic solution might be to create a class Operand, with associated operators +, -, *, /, specified with special methods (__add__, __radd__, __mult__, __rmult__, etc.). If you use the "__r" methods correctly you can start also including litterals (1, 2.0, 3.0) in pretty much any order, as long as there is one Operand.
The class would have a counter, set to zero at creation time. Each call adds 1, but also adds the counter of each operator (default = 0).
Then you could write:
a = Operand(2)
b = a+2-5
assert b.effort == 3
Then you can go ahead and calculate your effort:
a = Operand(5)
a = a + 3 #1
a = a * a #2
a = a * -1 #3
print(a.effort)
In the first line, you create the object. In the second line, the result of a + 3 is 8, and the resulting object has an effort of 1 . In the third, it has an effort of 3 (1 + 1 for a + 1 for a). In the fourth, it has an effort of 4. Etc.
I haven't implemented and tested it, but it should work more or less according to those principles.
Note about litterals: a + 2 + 3 would give you a count of 3, but 2 + 3 + a might give you a count of 2 (since 5 is still an integer, and not an Operand). So perhaps you want to avoid the __r methods, to stay on the safe side... it depends.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.