【发布时间】:2019-10-18 20:32:58
【问题描述】:
在一个特定的棋盘游戏中,只有一行,它包含 N 个空格,从左到右编号为 0 到 N - 1。还有 N 个弹珠,编号从 0 到 N - 1,最初以任意顺序放置。之后,有两个动作一次只能做一个:
- 切换:切换弹珠位置 0 和 1。
- 旋转:移动 位置 0 的弹珠到位置 N - 1,并移动所有其他弹珠 向左一格(低一格)。
目标是按顺序排列弹珠,每个弹珠 i 在位置 i。
我编写的代码适用于发布在问题 (1 3 0 2) 上的示例,但是当我将额外的数字 4 随机添加到列表中时,while 循环永远不会终止。查看排序后的序列,它似乎在重复循环多个相同的序列。我不确定为什么它适用于一个系列但不适用于下一个系列。
奖金,我似乎无法弄清楚如何将输出打印为用空格分隔的数字与带有括号和逗号的列表。问题要求我们将输出打印为用空格分隔的数字。对此的任何帮助将不胜感激。
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 __str__(self):
return str(self.board)
def __repr__(self):
return "%r " % (self.board)
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):
"""Move the marble in position 0 to position N - 1, and move all other marbles one space to the left (one index lower)"""
copy_board = self.board.copy()
copy_board[len(self.board)-1] = self.board[0]
for x in range(1, len(self.board)):
copy_board[x - 1] = self.board[x]
self.board = copy_board
return self.board
def is_sorted(self):
return self.board == sorted(self.board):
class Solver:
"""solves the marble sorting game when given a marble board as input"""
def __init__(self, MarblesBoard):
self.steps = 0
self.board = MarblesBoard.board
return
def solve(self):
n = len(self.board)
# print("n = ", n)
print(self.board)
while MarblesBoard.is_sorted(self) == False:
if self.board[0] > self.board[1]:
MarblesBoard.rotate(self)
print(self.board)
self.steps += 1
else:
MarblesBoard.switch(self)
print(self.board)
self.steps += 1
print("total steps: ", self.steps)
关于输出,代码在此处的示例输出中运行良好:
board2 = MarblesBoard((1,3,0,2))
solver = Solver(board2)
solver.solve()
[1, 3, 0, 2]
[3, 1, 0, 2]
[1, 0, 2, 3]
[0, 2, 3, 1]
[2, 0, 3, 1]
[0, 3, 1, 2]
[3, 0, 1, 2]
[0, 1, 2, 3]
total steps: 7
但是,如果我在起跑板上添加 4:
board2 = MarblesBoard((1,3,0,2,4))
solver = Solver(board2)
solver.solve()
[1, 3, 0, 2, 4]
[3, 1, 0, 2, 4]
[1, 0, 2, 4, 3]
[0, 2, 4, 3, 1]
[2, 0, 4, 3, 1]
[0, 4, 3, 1, 2]
[4, 0, 3, 1, 2]
[0, 3, 1, 2, 4]
[3, 0, 1, 2, 4]
[0, 1, 2, 4, 3]
[1, 0, 2, 4, 3]
[0, 2, 4, 3, 1]
[2, 0, 4, 3, 1]
[0, 4, 3, 1, 2]
[4, 0, 3, 1, 2]
[0, 3, 1, 2, 4]
[3, 0, 1, 2, 4]
请注意,3 0 1 2 4 作为第二次迭代和最后列出的迭代重复。由于 while 循环的结构,由于发生相同的序列,因此执行相同的步骤并且循环无限继续。
【问题讨论】:
-
您的
is_sorted方法可以简单地为return self.board == sorted(self.board)。很高兴您在条件为True时没有返回False。 -
@dumdum——只有当它完全回答了你的问题。
标签: python while-loop bubble-sort