我正在做着名的游戏“河内塔”的练习,当我运行我的代码时出现错误。但我不知道如何解决它。这里是我的代码:河内塔(带类)索引超出范围
class HanoiT():
def __init__(self, content=None):
if content is None:
self.content=[]
else:
self.content=content
def addmethod(self, new_disk): #Add an element on the beginning of the list
if new_disk <= self.content[0]:
self.content.insert(0, new_disk)
else:
raise ValueError("No disk may be placed on top of a smaller disk")
def deletemethod(self): #Delete the first element of a list
self.content.pop(0)
def affichage(self): #Method to print the list which represent the "disk" putted on the tower from the top to bottom
for i in self.content:
print(i, end=" ")
def movedisk(self, Tsource, Ttarget):
Ttarget.addmethod(Tsource.content[0])
Tsource.deletemethod()
def movetower(self, N, Tour1, Tour3, Tour2):
if N >= 1:
self.movetower(N-1, Tour1, Tour2, Tour3)
self.movedisk(Tour1, Tour3)
self.movetower(N-1, Tour2, Tour3, Tour1)
N = 4
Tour1 = HanoiT([x for x in range(1, N+1)])
Tour1.affichage()
Tour2 = HanoiT([])
Tour3 = HanoiT([])
h = HanoiT()
h.movetower(N, Tour1, Tour2, Tour3)
所以,当我运行它引发IndexError:列表索引超出范围,在第17行,这就是 “如果new_disk < = self.content [0]:” 在add_method
我看到,如果值不在列表中或超出范围,可以引发Indexerror,但我不知道我的情况是什么问题。没有内容创建
感谢您的帮助
对不起,我忘了说列表中的整数代表塔上的磁盘,并且相对于这个游戏的规则:“没有磁盘可能放置在较小的顶部磁盘“。 – Tom92
尝试打印内容 –