class Node:
def __init__(self, value):
self.value = value
self.next = None
def __str__(self):
return "Node({})".format(self.value)
__repr__ = __str__
class Stack:
def __init__(self):
self.top = None
def __str__(self):
#output presentation:
#format show: top and stack.
temp=self.top
out=[]
while temp:
out.append(str(temp.value))
temp=temp.next
out='\n'.join(out)
return ('Top:{}\nStack:\n{}'.format(self.top,out))
__repr__=__str__
def isEmpty(self):
#write your code here
return self.top == None
def len(self):
#write your code here
current = self.top
len = 0
while current:
len += 1
current = current.next
return len
def peek(self):
#write your code here
if self.isEmpty():
return None
else:
return self.top.value
def push(self,value):
#write your code here
node = Node(value)
if self.top is None:
self.top = node
else:
node.next = self.top
self.top = node
def pop(self):
#write your code here
if self.isEmpty():
return "Stack is Empty"
else:
popped = self.top.value
self.top = self.top.next
return popped
class StackTower:
def __init__(self, numDisks, A = Stack(), B = Stack(), C = Stack()):
self.numDisks = numDisks
self.A = A
self.B = B
self.C = C
def validMove(self, A, B):
if not len(A):
A.push(B.pop())
elif not len(B):
B.push(A.pop())
elif peek(A) > peek(B):
A.push(B.pop())
else:
B.push(A.pop())
def hanoi(self, n):
if n%2==0:
self.B, self.C, self.A = self.C, self.A, self.B
for i in range(1, 2**n-1):
if i%3 == 1:
validMove(A, C)
if i%3 == 2:
validMove(A, B)
if i%3 == 0:
validMove(B, C)
n = int(input("enter number: "))
tower = StackTower(3, "A", "B", "C")
tower.hanoi(n)
print(tower)
对于此作业,我必须编写迭代的python代码以展示河内塔算法的步骤。
输出表明未定义函数validMove。我了解伪代码,但是我不精通python。
除此之外,显示每一步输出的最有效方法是什么?
请帮助我。谢谢!我非常感谢您的帮助。