Use python to implement the recursive tower example (tower recursive algorithm)

Source: Internet
Author: User

Use python to implement the tower of death. Demo with graphics

Copy codeThe Code is as follows:
From time import sleep

Def disp_sym (num, sym ):
Print (sym * num, end = '')

# Recusion
Def hanoi (a, B, c, n, tray_num ):
If n = 1:
Move_tray (a, c)
Disp (tray_num)
Sleep (0.7)

Else:
Hanoi (a, c, B, n-1, tray_num)
Move_tray (a, c)
Disp (tray_num)
Sleep (0.7)
Hanoi (B, a, c, n-1, tray_num)

Def move_tray (a, B ):
For I in:
If I! = 0:
For j in B:
If j! = 0:
B [B. index (j)-1] = I
A [a. index (I)] = 0
Return
B. append (I)
B. pop (0)
A [a. index (I)] = 0
Return

Def disp (tray_num ):
Global a, B, c
For I in range (tray_num ):
For j in ['A', 'B', 'C']:
Disp_sym (5 ,'')
Eval ('disp _ sym (tray_num-'+ j + "[I],'') ")
Eval ('disp _ sym ('+ j + "[I],' = ')")
Disp_sym (1, '| ')
Eval ('disp _ sym ('+ j + "[I],' = ')")
Eval ('disp _ sym (tray_num-'+ j + "[I],'') ")

Print ()

Print ('---------------------------------------------------------------------------')

Tray_num = int (input ("Please input the number of trays :"))
Tray = []
For I in range (tray_num ):
Tray. append (I + 1)
A = [0] * tray_num
B = a [:]
C = a [:]

A = tray [:]
Disp (tray_num)
Hanoi (a, B, c, tray_num, tray_num)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.