错误的打印输出

时间:2013-12-11 02:46:54

标签: python printing

这是我的文本文件:

4
0 2 0 1
1 1 1 0
2 0 0 0
0 0 2 0
0 0 0 0
0 2 0 0

This is the board from problem solving.  It is 4x4 with
three trees.

基本上,第一行表示4x4维度。

def getSuccessors(config):
    """
    Get the successors of config.  Input is:
        config: The config (TentsConfig)

    Returns: A list of successor configs (list of TentsConfig)
    """

    # YOUR IMPLEMENTATION REPLACES THIS
    successors = list()
    col = 0
    while col < config.DIM:
        row = 0
        while row < config.DIM:
            newConfig = newConfig2 = deepcopy(config)
            if newConfig.board[row][col] == 0:
                newConfig.board[row][col] = 3
                newConfig.tents+=1
                newConfig.lastSpot = (col, row)
                successors.append(newConfig)
            row += 1
        col += 1
    return successors

def isValid(config):
    """
    Checks the config to see if it is valid.  Input is:
        config: The config (TentsConfig)

    Returns: True if the config is valid, False otherwise
    """
    Tree = False
    Tent = 0
    # YOUR IMPLEMENTATION REPLACES THIS
    for row in config.board[config.lastSpot[1] -1: config.lastSpot[1] + 2]:
        for col in row[config.lastSpot[0] -1:config.lastSpot[0] + 2]:
            if col == 2:
                Tree = True
            if col == 3:
                Tent +=1
    if Tent <= 1:
        return Tree == True
    return False

我认为问题出现在isValidgetSuccessors函数中。我似乎找到了isValid的问题。如果我要更改一下代码:

for row in config.board[config.lastSpot[1] -1: config.lastSpot[1] + 2]:

for row in config.board[config.lastSpot[1] +1: config.lastSpot[1] + 2]:

我明白了:

Solution:
  0 2 0 1 
  -------
1|2 3 3 0|
1|0 0 2 0|
1|0 3 0 0|
0|0 2 0 0|
  -------

几乎就在那里。只是缺少3旁边的3。

除此之外...... 这是打印出来的:

Solution:
  0 2 0 1 
  -------
1|2 0 0 0|
1|0 3 2 3|
1|0 0 0 0|
0|0 2 3 0|
  -------

现在,我正在试图找出如何打印这个:

Solution:
  0 2 0 1 
  -------
1|2 3 0 0|
1|0 0 2 3|
1|0 3 0 0|
0|0 2 0 0|

-------

0 - Empty
2 - Trees
3 - Tents

如果你们有人听说过帐篷和树木游戏吗?来自这个网站: http://www.brainbashers.com/tents.asp

代码并不重要,但如果您需要更多信息:

    from copy import deepcopy
from sys import argv

# STUDENTS ARE FREE TO ADD ADDITIONAL SLOTS TO THIS CLASS, BUT DO NOT CHANGE
# ANY OF THE EXISTING SLOTS!!!!
class TentsConfig():
    """
    A class that represents a tents configuration.
        DIM - square board DIMension (int)
        colVals - number of tents in each column, left to right 
            (list of DIM int's)
        rowVals - number of tents in each row, top to bottom
            (list of DIM int's)
        board - square grid of values 
            (list of list of int's, size DIM*DIM)
    """
    __slots__ = ('DIM', 'colVals', 'rowVals', 'board', 'trees', 'tents', 'lastSpot')

    """Names for each possible board value"""
    EMPTY = 0   # can be referenced anywhere as: TentsConfig.EMPTY
    GRASS = 1   # can be referenced anywhere as: TentsConfig.GRASS
    TREE  = 2   # can be referenced anywhere as: TentsConfig.TREE
    TENT  = 3   # can be referenced anywhere as: TentsConfig.TENT

def mkTentsConfig(dim, colVals, rowVals, board):
    """
    Create a TentsConfig object.  Inputs are:
        dim     # square DIMension of board
        colVals # DIM values left to right
        rowVals # DIM values top to bottom
        board   # initial configuration of board as 2D list

    Returns: A config (TentsConfig)
    """

    config = TentsConfig()

    config.DIM = dim
    config.colVals = colVals
    config.rowVals = rowVals
    config.board = board
    trees = 0
    for row in config.board:
        for col in row:
            if col == 2:
                trees += 1
    config.trees = trees
    config.tents = 0
    config.lastSpot = (0,0)

    # additional initialization

    return config

def mkConfigString(config):                       
    """
    Creates a string representation of the config.  Input is:
        config  # a TentsConfig object

    Returns: a string representation of the config.
    """

    # top row
    result = '  '
    for val in config.colVals:
        result += str(val) + ' '
    result += '\n  ' + '-' * (config.DIM*2-1) + '\n'

    # board rows
    for row in range(config.DIM):
        result += str(config.rowVals[row]) + '|'
        for col in range(config.DIM):
            result += str(config.board[row][col])
            if col != config.DIM-1: result += ' '
        result += '|\n'

    # bottom row
    result += '  ' + '-' * (config.DIM*2-1) + '\n'

    return result

def readBoard(filename):
    """
    Read the board file.  It is organized as follows:
        DIM     # square DIMension of board
        colVals # DIM values, left to right
        rowVals # DIM values, top to bottom
        row 1 values    # 0 for empty, 2 for tree
        row 2 values    # 0 for empty, 2 for tree
        ...
    Input is:
        filename  # The file name (string)

    Returns: A config (TentsConfig) containing the board info from file
    """

    f = open(filename)
    DIM = int(f.readline().strip())
    colVals = [int(val) for val in f.readline().split()]
    rowVals = [int(val) for val in f.readline().split()]
    board = list()
    for _ in range(DIM):
        line = [int(val) for val in f.readline().split()]
        board.append(line)
    f.close()
    return mkTentsConfig(DIM, colVals, rowVals, board)

def isGoal(config):
    """
    Checks whether a config is a goal or not.  Input is:
        config: The config (TentsConfig)

    Returns: True if config is a goal, False otherwise
    """
    # YOUR IMPLEMENTATION REPLACES THIS
    """
    val = True
    for row in config:
        for col in row:
            if col == None:
                val = False
    return val
    """

    return config.trees == config.tents

def solve(config, debug):
    """
    Generic backtracking solver.  Inputs are:
        config: the current config (TentsConfig)
        debug: print debug output? (Bool)

    Returns:  A config (TentsConfig), if valid, None otherwise
    """

    if isGoal(config):
        return config
    else:
        if debug: print('Current:\n' + mkConfigString(config))
        for successor in getSuccessors(config):
            if isValid(successor):
                if debug: print('Valid Successor:\n' + mkConfigString(successor))
                solution = solve(successor, debug)
                if solution != None:
                    return solution
        return None

def main():
    """
    The main program.
        Usage: python3 tents.py [filename] [debug]
            [filename]: The name of the board file
            [debug]: True or False for debug output
    """

    # if no command line arguments specified, prompt for the filename
    # and debug choice
    if len(argv) == 1:
        filename = input('Enter board file: ')
        debug = eval(input("Debug output (True or False): "))
    # otherwise, use the command line arguments
    elif len(argv) == 3:
        filename = argv[1]
        debug = eval(argv[2])
    # incorrect number of command line arguments
    else:
        print("Usage: python3 tents.py [filename debug]")
        print("optional command line arguments:" )
        print("  filename: The name of the board file")
        print("  debug: True or False for debug output")
        return -1

    # read and display the initial board
    initConfig = readBoard(filename)
    print('Initial Config:\n' + mkConfigString(initConfig))

    # solve the puzzle
    solution = solve(initConfig, debug)

    # display the solution, if one exists
    if solution != None:
        print('Solution:\n' + mkConfigString(solution))
    else:
        print('No solution.')

if __name__ == '__main__':
    main()

希望你们能帮助我!谢谢!

0 个答案:

没有答案