Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
67 views
in Technique[技术] by (71.8m points)

python - wondering how the function work step by step


def main():
    move_discs(3,1,3,2)
    
def move_discs(num, from_peg, to_peg, temp_peg):
    if num > 0:
     move_discs(num-1, from_peg, temp_peg, to_peg)
     print(num,'Move a disc from peg', from_peg, 'to peg', to_peg)
     move_discs(num-1, temp_peg, from_peg, to_peg)

main()

i wrote the code from the textbook that i am currently learning about the recursion, this function returned the output:

1 Move a disc from peg 1 to peg 3
2 Move a disc from peg 1 to peg 2
1 Move a disc from peg 3 to peg 1
3 Move a disc from peg 1 to peg 3
1 Move a disc from peg 2 to peg 3
2 Move a disc from peg 2 to peg 1
1 Move a disc from peg 3 to peg 2

i am very confusing how this function can returned this such output and with just a small changed? can anyone explain it for me about every single steps that the function executed? i will be very appreciated. ps: the function is just displaying a solution for the Tower of Hanoi game. enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This an example Tower of Hanoi. move_discs is an example recursive function, which calls itself while num > 0. You should also check The Tower of Hanoi program here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.7k users

...