유명한 게임 "Tower of Hanoi"에 대한 연습을하고 있는데 코드를 실행할 때 오류가 있습니다. 그러나 나는 그것을 고치는 법을 모른다. 나는 그것이 IndexError 인상 실행할 때, 그래서하노이 타워 (클래스 포함) 인덱스가 범위를 벗어났습니다.
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)
: 여기 내 코드의 범위를 벗어난리스트 인덱스입니다 라인 (17)에, "만약 new_disk < = self.content [0] :"를 add_method
에서값이 목록에 없거나 범위를 벗어난 경우 Indexerror를 발생시킬 수 있지만 내 경우에 어떤 문제인지는 알 수 없습니다. 당신의 도움이
죄송합니다. 목록의 정수는 타워의 디스크와이 게임의 규칙을 나타냅니다. "더 작은 디스크는 위에 놓지 않아도됩니다. 디스크." – Tom92
내용을 인쇄 해보십시오. –