To solve my problem, I need to collect all possible arrays of length N containing -1, 0 and 1, and run them through some function to see if they meet a certain criterion.
I implemented 2 methods, process numbers method and recursion. They both return the correct results, both check the same number of arrays, no red flags, in addition, on my machine the triad method is almost 2 times slower. Is there a reason why this should be so? printIfTargetHit is a simple numerical function, not caching or other complications that might explain the problem.
def triadicIteraction(signsQty): signs = [None for _ in range(signsQty)] comb = int(3**signsQty-1) while (comb >= 0): combCopy = comb for n in range(signsQty): signs[n] = 1-combCopy%3 # [0,1,2] -> [1,0,-1], correct range for signs combCopy = combCopy//3 printIfTargetHit(signs) comb = comb - 1 def recursiveIteration(signsQty): def recursiveIterationInner(signs, newSign, currentOrder): if (currentOrder >= 0): signs[currentOrder] = newSign if currentOrder == (len(signs) - 1): printIfTargetHit(signs) else: recursiveIterationInner(signs,-1, currentOrder+1) recursiveIterationInner(signs, 0, currentOrder+1) recursiveIterationInner(signs, 1, currentOrder+1) recursiveIterationInner(signs = [None for _ in range(signsQty)], newSign = None, currentOrder = -1)
Full code on github, https://github.com/Yulia5/workspace/blob/master/P2/P3/PlusesMinuses1ToN.py , I did not publish all this because I believe that the above example is self-sufficient.
Performance, timing, calculated as the difference between datetime.datetime.now() , the first method is simple built-in loops.
Method name: <function embeddedLoopsFixed at 0x01D63D30> Combination quantity : 16560 Combinations evaluated : 14348907 Time elapsed : 0:01:56.440000 Method name: <function recursiveIteration at 0x01D63DB0> Combination quantity : 16560 Combinations evaluated : 14348907 Time elapsed : 0:02:20.526000 Method name: <function triadicIteraction at 0x01D63D70> Combination quantity : 16560 Combinations evaluated : 14348907 Time elapsed : 0:04:12.297000