Ask your own question, for FREE!
MIT 6.00 Intro Computer Science (OCW) 5 Online
OpenStudy (anonymous):

in the sixth lecture : recursion about 24:40, the professor was trying an example with a tower of hanoi so he wrote: Code: def hanoi(n,f,t,s): if n == 1: print 'move from ' +f +' to ' +t else: hanoi(n-1,f,s,t) hanoi(1,f,t,s) hanoi(n - 1,s,t,f) which i didn't understand it because according to my understanding it if n equal 1 it will print : print 'move from ' +f +' = ' +t, and then exit the functionand if n doesn't equal 1 it will keep calling the fist call in the else dent : hanoi(n-1,f,s,t) only and not printing anything until n became

OpenStudy (anonymous):

...then it will print: 'move from ' +f +' = ' +t and than exit the function but for example if we call it with this argument: hanoi(4,'f','t','s') it will output: move from f to s move from f to t move from s to t move from f to s move from t to f move from t to s move from f to s move from f to t move from s to t move from s to f move from t to f move from s to t move from f to s move from f to t move from s to t What am i missing?

OpenStudy (rsmith6559):

Personally, I wish they wouldn't use the Towers of Hanoi to teach recursion. Recursion is one subject, the Towers of Hanoi is another. Try it with two rings. Try stepping through the code with two rings. ToH is an interesting program in itself.

OpenStudy (anonymous):

i tried and traced it and i finally got it, so it is gonna enter the first call with n-1 and than first call inside the n-1 call with n-2 and than the first call with n-3 until n=1 than print the statement and exit to previous call n=2 and than call the second call with 1 then print the statement because it's 1 and than the third call in the n=2 of first call with n-1 and then print the statement because it's 1 and then exit and returns to the first call of n=3 and call the second call and print the statement and than call the third call with n-1 which is 2 and the call the first call inside the third call with n-1 which is 1 and then print the statement and like that it continue thanks guys

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!