[Python] Python: Marble Sorting game: works for some numbers -- infinite loop for others

Discussão em 'Python' iniciado por Stack, Julho 26, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to code a marble sorting game in Python. Have it working for some cases, but it fails for others (esp longer number tuples). In general, I am using a basic method to determine whether to switch or rotate (based on just a comparison of first two numbers). It just injects some randomness to the selection -- not perfect but should work?

    My goal is to two fold

    1. What am I doing wrong? Have the two classes been structured right?
    2. Once I get the code working (regardless of time optimization), I would like to explore alternate ways / better ways to select rotate or switch.

    The Board class

    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]


    The Solver class

    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)


    Test 1 - works

    board1 = MarblesBoard((1,3,0,2))
    solver1 = Solver(board1)
    solver1.solve()


    Test 2 - fails

    board2 = MarblesBoard((1,3,0,2,4))
    solver2 = Solver(board2)
    solver2.solve()

    Continue reading...

Compartilhe esta Página