我正在试图弄清楚如何解决(冒泡排序算法变体)正常工作。它应该采用MarblesBoard类的一个实例,然后切换前两个项目(如果两个都不是0)或旋转它们,打印板并重复直到解决(大理石按升序排序)。
这是MarblesBoard类:
class MarblesBoard:
def __init__(self, marbles):
self.input = list(marbles)
print(marbles)
def switch(self):
self.input[1], self.input[0] = self.input[0], self.input[1]
print self.input
def rotate(self):
return self.input[1:] + self.input[:1]
print self.input
def is_solved(self):
if all(self.input[i] <= self.input[i+1] for i in range(len(self.input)-1)):
return True
print "True"
else:
print "Not solved!"
board = MarblesBoard((3,6,7,4,1,0,8,2,5))
board.switch()
board.rotate()
board.is_solved()
输出:
(3, 6, 7, 4, 1, 0, 8, 2, 5)
[6, 3, 7, 4, 1, 0, 8, 2, 5]
Not solved!
这是Solver类:
class Solver:
def __init__(self, MarblesBoard):
#print self
self.board = MarblesBoard
def solve(self):
if all(self.board.input[i] <= self.board.input[i+1] for i in range(len(self.board.input)-1)):
return True
#break
else:
if self.board.input[0] & self.board.input[1] != 0:
if self.board.input[1] < self.board.input[0]:
self.board = self.board.switch()
print self.board
else:
self.board = self.board.rotate()
print self.board
else:
self.board = self.board.rotate()
print self.board
return
player = Solver(board)
player.solve()
输出:
[6, 7, 4, 1, 0, 8, 2, 5, 3]
我不认为return在我的Sorter类中按照我的意愿工作,并且我已经尝试通过将所有内部if else循环置于其中来替换初始if if和while循环,而条件是假。这导致了无限循环。请指教。