def solve_ab_riddle(program): tokens = program.split() while True: changed = False i = 0 while i < len(tokens) - 1: if tokens[i] == 'A#' and tokens[i+1] == '#A': tokens.pop(i) tokens.pop(i) changed = True elif tokens[i] == 'A#' and tokens[i+1] == '#B': tokens[i] = '#B' tokens[i+1] = 'A#' i += 1 changed = True elif tokens[i] == 'B#' and tokens[i+1] == '#A': tokens[i] = '#A' tokens[i+1] = 'B#' i += 1 changed = True elif tokens[i] == 'B#' and tokens[i+1] == '#B': tokens.pop(i) tokens.pop(i) changed = True else: i += 1 if not changed: break return ' '.join(tokens) # Example usage program = "B# A# #B #A B#" result = solve_ab_riddle(program) print(f"Original program: {program}") print(f"Computed result: {result}")