Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Tower of Hanoi
- def moveTower(height, fromPole, toPole, withPole):
- print('if %s is greater than or equal to 1' %height)
- if height >= 1:
- print('first call, height is ', height)
- moveTower(height - 1, fromPole, withPole, toPole)
- print('executing moveDisk with height ', height)
- moveDisk(fromPole, toPole)
- print('second call, height is ', height)
- moveTower(height - 1, withPole, toPole, fromPole)
- print('height is ', height)
- def moveDisk(fp, tp):
- print('moving disk from', fp, 'to', tp) print('initial call, height is 3')
- moveTower(3, 'A', 'B', 'C')
- Print output:
- initial call, height is 3
- if 3 is greater than or equal to 1
- ('first call, height is %s', 3)
- if 2 is greater than or equal to 1
- ('first call, height is %s', 2)
- if 1 is greater than or equal to 1
- ('first call, height is %s', 1)
- if 0 is greater than or equal to 1
- executing moveDisk with height 1*
- ('moving disk from', 'A', 'to', 'B')
- ('second call, height is ', 1)
- if 0 is greater than or equal to 1
- ('height is ', 1)
- executing moveDisk with height 2*
- ('moving disk from', 'A', 'to', 'C')
- ('second call, height is ', 2)
- if 1 is greater than or equal to 1
- ('first call, height is %s', 1)
- if 0 is greater than or equal to 1
- executing moveDisk with height 1
- ('moving disk from', 'B', 'to', 'C')
- —execute as normal
- ('second call, height is ', 1)
- if 0 is greater than or equal to 1
- ('height is ', 1)
- ('height is ', 2)
- executing moveDisk with height 3*
- ('moving disk from', 'A', 'to', 'B')
- ('second call, height is ', 3)
- if 2 is greater than or equal to 1
- ('first call, height is %s', 2)
- if 1 is greater than or equal to 1
- ('first call, height is %s', 1)
- if 0 is greater than or equal to 1
- executing moveDisk with height 1
- ('moving disk from', 'C', 'to', 'A')
- ('second call, height is ', 1)
- if 0 is greater than or equal to 1
- ('height is ', 1)
- executing moveDisk with height 2
- ('moving disk from', 'C', 'to', 'B')
- ('second call, height is ', 2)
- if 1 is greater than or equal to 1
- ('first call, height is %s', 1)
- if 0 is greater than or equal to 1
- executing moveDisk with height 1
- ('moving disk from', 'A', 'to', 'B')
- ('second call, height is ', 1)
- if 0 is greater than or equal to 1
- ('height is ', 1)
- ('height is ', 2)
- ('height is ', 3)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement