我正在尝试用Python编写一个大理石排序游戏。让它在某些情况下有效,但在其他情况下失败(尤其是较长的数字元组(。一般来说,我使用一种基本方法来确定是切换还是旋转(仅基于前两个数字的比较(。它只是给选择注入了一些随机性——不完美,但应该有效吗?
我的目标是两倍
- 我做错了什么?这两个班的结构正确吗
- 一旦我让代码工作起来(不管时间优化如何(,我想探索选择旋转或切换的替代方法/更好的方法
板级
class MarblesBoard:
"""creates a marble board with number marbles in specific spots"""
def __init__(self, marble_sequence):
self.board = [x for x in marble_sequence]
def switch(self):
"""switch the marbles in position 0 and 1"""
self.board[0], self.board[1] = self.board[1], self.board[0]
return self.board
def rotate(self):
"""
Rotates item in position o to position N-1. All remaning items are moved as a result (1 step to the left)
"""
self.board = self.board[1:] + [self.board[0]]
return self.board
def is_sorted(self):
return self.board == sorted(self.board)
def should_rotate(self):
# condition can be used to determine whether to start with rotate of switch
return self.board[0] > self.board[1]
解算器类
class Solver:
"""solves the marble sorting game when given a marble board as input"""
def __init__(self, marbles_board):
self.marbles_board = marbles_board
def solve(self):
steps = 0
while not self.marbles_board.is_sorted():
if steps == 10:break
if self.marbles_board.should_rotate():
self.marbles_board.rotate()
else:
self.marbles_board.switch()
steps += 1
print(f"Number of steps: {steps}")
print(self.marbles_board)
测试1-工作
board1 = MarblesBoard((1,3,0,2))
solver1 = Solver(board1)
solver1.solve()
测试2-失败
board2 = MarblesBoard((1,3,0,2,4))
solver2 = Solver(board2)
solver2.solve()
当你看到它时,你会踢自己的!!!扰流板警告您正在将已解决的板1从第一次测试传递到第二次测试,因此它已经排序。因此它返回步数:0
board2 = MarblesBoard((1,3,0,2,4))
solver2 = Solver(board1) #<<<<< Here
solver2.solve()
应该看起来像这个
board1 = MarblesBoard((1,3,0,2))
solver1 = Solver(board1)
solver1.solve()
board2 = MarblesBoard((1,3,0,2,4))
solver2 = Solver(board2)
solver2.solve()
为了解决您的第二个担忧。这样切换很好。或者,你可以将切换状态保存在一个列表中,然后这样选择。
我建议您考虑在求解方法中做一些不同的事情,即不使用break语句,并用逻辑打破while循环。例如,当步骤==10时变为true的标志。Break语句相当于空异常。它可能会暂时解决问题,但当您的代码偏离轨道时,它不会提供任何帮助。
干杯!