LintCode Q227 Mock Hanoi Tower by Stacks in Python

  • Jinhai ZHOU
  • 6 Minutes
  • 2017年2月2日
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class Tower(object):
# create three towers (i from 0 to 2)
def __init__(self, i):
self.disks = []
# Add a disk into this tower
def add(self, d):
if len(self.disks) > 0 and self.disks[-1] <= d:
print "Error placing disk %s" % d
else:
self.disks.append(d)
# @param {Tower} t a tower
# Move the top disk of this tower to the top of t.
def move_top_to(self, t):
# Write your code here
if len(self.disks) < 1:
print "Error no disk"
else:
t.add(self.disks.pop())
# @param {int} n an integer
# @param {Tower} destination a tower
# @param {Tower} buffer a tower
# Move n Disks from this tower to destination by buffer tower
def move_disks(self, n, destination, buffer):
# Write your code here
if n <= 0:
return
if n > 0:
# step 1
self.move_disks(n - 1, buffer, destination)
# step 2
self.move_top_to(destination)
# step 3
buffer.move_disks(n - 1, destination, self)
def get_disks(self):
return self.disks
"""
Your Tower object will be instantiated and called as such:
towers = [Tower(0), Tower(1), Tower(2)]
for i in xrange(n - 1, -1, -1): towers[0].add(i)
towers[0].move_disks(n, towers[2], towers[1])
print towers[0], towers[1], towers[2]
"""
知识共享许可协议
本作品采用知识共享署名-相同方式共享 4.0 国际许可协议进行许可。