0

I have somewhat of a handle with recursion. A recursive function is a function that calls on itself to run, sort of like a loop. However, I am having an issue with tail end and forward recursion.

From what I understand tail end does the calculations in place while forward does them at the end of the "recursive loop." I have to make a 2 factorial functions and I was wandering if I can get some input as to whether I am on the right path or not. Thanks

def tailfactorial(n,counter):
    if counter == 0:
        return n    
    else:
        return tailfactorial(n * counter ,counter-1)
print(tailfactorial(6,5))
#tailfactorial(6,5)
#tailfactorial(30,4)
#tailfactorial(120,3)
#tailfactorial(360,2)
#tailfactorial(720,1)
#tailfactorial(720,0)
#720

def factorialforward(n):
    if n==0:
        return 1
    else:
        return n * factorialforward(n-1)
print(factorialforward(6))
#factorialforward(6)
#6 * factorialforward(5)
#6 * 5 * factorialforward(4)
#6 * 5 * 4 * factorialforward(3)
#6 * 5 * 4 * 3 * factorialforward(2)
#6 * 5 * 4 * 3 * 2 * factorialforward(1)
#6 * 5 * 4 * 3 * 2 * 1 * factorialforward(0)
#6 * 5 * 4 * 3 * 2 * 1 * 1 = 720
Luis
  • 21
  • 5
  • 1
    so tail end recursion, in this example, just means you do the math inside the parenthesis? – Luis Oct 01 '15 at 04:31
  • @TessellatingHeckler Do you have some assembler to back up your claim? On this example I think most compilers/interpreters would be smart enough to do the multiplications in place. While the forward may be done in place and tail approach needs to store on the stack the partial results. But yes, in more general cases you are probably right. Don't trust anything above assembler. Always benchmark and test your assumptions if they are important to you. – Sorin Oct 01 '15 at 09:29
  • See http://stackoverflow.com/questions/3042954/tail-recursion-vs-forward-recursion – Janne Karila Oct 12 '15 at 19:23

0 Answers0