【问题标题】:Automate the Boring Stuff - Chapter 5 - Chess Dictionary Validator自动化无聊的东西 - 第 5 章 - 国际象棋词典验证器
【发布时间】:2020-05-18 14:26:52
【问题描述】:

第一篇文章,编程新手,玩得开心!欢迎对这篇文章的所有反馈和我的问题。

我正在研究 Automate the Boring Stuff 并解决第 5 章的第一个问题Chess Dictionary Validator

在本章中,我们使用了字典值 {'1h': 'bking', '6c': 'wqueen', '2g': 'bbishop', '5h': 'bqueen', '3e ': 'wking'} 表示棋盘。编写一个名为 isValidChessBoard() 的函数,它接受一个字典参数并根据棋盘是否有效返回 True 或 False。

一个有效的棋盘将恰好有一个黑王和一个白王。每个玩家最多只能有16个棋子,最多8个棋子,并且所有棋子必须在'1a'到'8h'的有效空间上;也就是说,一块不能在空间“9z”上。棋子名称以“w”或“b”开头,表示白色或黑色,然后是“pawn”、“knight”、“bishop”、“rook”、“queen”或“king”。此功能应检测错误何时导致棋盘不正确。

我的问题和代码:

  1. 通过这些 for 循环 + 多个 if 语句评估字典键/值是否是“最佳实践”?似乎有很多代码。如果在 for 循环中跟随另一个 if 语句,则更改为包含一些 elif 会导致问题。
  2. 第 23 行 if i[0] == 'b': 出错,因为空字符串值的国际象棋空间在 i[0] 处没有字符。表达/评估空值的最佳方式是什么?如果是'',我是否应该在评估值==''的循环中添加前导条件,然后'继续'?
  3. 为什么我不能将第 15 行折叠成第 11 行,这样我就有一个语句:if 'bking' or 'wking' not in board.values():?如果我尝试这样做,则语句结果为 True;但是字典包含这两个值,所以它不应该评估为 False 并保持代码运行吗?
def isValidChessBoard(board):
    while True:
        blackPieces = 0
        whitePieces = 0
        wpawn = 0
        bpawn = 0
        letterAxis = ('a','b','c','d','e','f','g','h')
        pieceColour = ('b','w')
        pieceType = ('pawn','knight','bishop','rook','queen','king')

        #one black king and one white king
        if 'bking' not in board.values():
            print('KingError')
            return False
            break
        if 'wking' not in board.values():
            print('KingError')
            return False
            break

        #each player has <= 16 pieces
        for i in board.values():
            if i[0] == 'b':
                blackPieces+=1
            if i[0] == 'w':
                whitePieces+=1
            if whitePieces >= 17:
                print('TotalPieceError')
                return False
                break
            if blackPieces >= 17:
                print('TotalPieceError')
                return False
                break

        #each player has <= 8 pawns
        for i in board.values():
            if i == 'wpawn':
                wpawn+=1
            elif i == 'bpawn':
                bpawn+=1
            if wpawn or bpawn >= 9:
                print('PawnError')
                return False
                break

        #all pieces must be on valid space from '1a' to '8h'
        for i in board.keys():
            if int(i[0]) >= 9:
                print('SpacesError')
                return False
                break
            if i[1] not in letterAxis:
                print('yAxisError')
                return False
                break

        #piece names begin with 'w' or 'b'
        for i in board.values():
            if i[0] not in pieceColour:
                print('WhiteOrBlackError')
                return False
                break

        #piece names must follow with 'pawn', 'knight', 'bishop', 'rook', 'queen', 'king'
        for i in board.values():
            if i[1:] not in pieceType:
                print('PieceTypeError')
                return False
        return 'This board checks out'

board = {'1a': 'bking','2a': 'bqueen','3a': 'brook','4a': 'brook',
'5a': 'bknight','6a': 'bknight','7a':'bbishop','8a': 'bbishop',
'1b': 'bpawn','2b': 'bpawn','3b': 'bpawn','4b':'bpawn',
'5b': 'bpawn','6b': 'bpawn','7b': 'bpawn','8b': 'bpawn',
'1c': 'wking','2c': 'wqueen','3c': 'wrook','4c': 'wrook',
'5c': 'wbishop','6c': 'wbishop','7c': 'wknight','8c':'wknight',
'1e': 'wpawn','2e': 'wpawn','3e': 'wpawn','4e': 'wpawn',
'5e': 'wpawn','6e': 'wpawn','7e': 'wpawn','8e': 'wpawn',
'1f': '','2f': '','3f': '','4f': '','5f': '','6f': '','7f': '','8f': '',
'1g': '','2g': '','3g': '','4g': '','5g': '','6g': '','7g': '','8g': '',
'1h': '','2h': '','3h': '','4h': '','5h': '','6h': '','7h': '','8h': '',}

print(isValidChessBoard(board))

Error:
Traceback (most recent call last):
line 23, in isValidChessBoard
    if i[0] == 'b':
IndexError: string index out of range

【问题讨论】:

  • 在第 23 行的 for 循环之后放置一个条件,即 if i: 围绕其他条件。这将删除索引超出范围错误。
  • 只是快速浏览了一下,您可以从代码中删除一件事,即 RETURN 语句之后的 BREAK 语句。这些不是必需的,如果函数到达 RETURN 语句,它会自动中断,因此不需要 BREAK 语句。
  • 如果 'bking' 不在 board.values() 中或 'wking' 不在 board.values() 中,您也可以使用 $$:$$
  • 'bking' or 'wking' not in board.values() 等价于 ( 'bking' ) or ( 'wking' not in board.values() ),它的计算结果始终为 'bking',这是真的。正确的版本是'bking' not in board.values() or 'wking' not in board.values(),但较短的版本使用集合:not {'bking', 'wking'}.issubset(board.values())

标签: python dictionary for-loop if-statement


【解决方案1】:

只是另一种选择

```
chessboard = {'1a': 'bking', '2a': 'bqueen', '3a': 'brook', '4a': 'brook',
              '5a': 'bknight', '6a': 'bknight', '7a': 'bbishop', '8a': 'bbishop',
              '1b': 'bpawn', '2b': 'bpawn', '3b': 'bpawn', '4b': 'bpawn',
              '5b': 'bpawn', '6b': 'bpawn', '7b': 'bpawn', '8b': 'bpawn',
              '1c': 'wking', '2c': 'wqueen', '3c': 'wrook', '4c': 'wrook',
              '5c': 'wbishop', '6c': 'wbishop', '7c': 'wknight', '8c': 'wknight',
              '1e': 'wpawn', '2e': 'wpawn', '3e': 'wpawn', '4e': 'wpawn',
              '5e': 'wpawn', '6e': 'wpawn', '7e': 'wpawn', '8e': 'wpawn',
              '1f': '', '2f': '', '3f': '', '4f': '', '5f': '', '6f': '', '7f': '', '8f': '',
              '1g': '', '2g': '', '3g': '', '4g': '', '5g': '', '6g': '', '7g': '', '8g': '',
              '1h': '', '2h': '', '3h': '', '4h': '', '5h': '', '6h': '', '7h': '', '8h': '', }


def check_location(board):
    for location in board.keys():
        row = int(location[:1])
        column = location[1:]
        if not ((1 <= row <= 8) and ('a' <= column <= "h")):
            print(f"Invalid to have {board[location]} at postion {location}")
            return False


def check_piece_count(board):
    pieces = ['wpawn', 'bpawn', 'wknight', 'bknight', 'bbishop',
              'wbishop', 'wrook', 'brook', 'wqueen', 'bqueen', 'wking', 'bking']
    max_pieces = [8, 8, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1]

    for piece in zip(pieces, max_pieces, board.keys()):
        if sum(value == piece[0] for value in board.values()) > piece[1]:
            return False
    return True


if check_location(chessboard) == None and check_piece_count(chessboard) == True:
    print(True)
else:
    print(False)

【讨论】:

    【解决方案2】:

    我采取了不同的方法。我决定将正确的 chess_board 与提供的 test_board 进行比较。

    chess_board = {
        "1a": "wrook", "1b": "wknight", "1c": "wbishop", "1d": "wqueen",
        "1e": "wking", "1f": "wbishop", "1g": "wknight", "1h": "wrook",
        "2a": "wpawn", "2b": "wpawn", "2c": "wpawn", "2d": "wpawn",
        "2e": "wpawn", "2f": "wpawn", "2g": "wpawn", "2h": "wpawn",
        "8a": "brook", "8b": "bknight", "8c": "bbishop", "8d": "bqueen",
        "8e": "bking", "8f": "bbishop", "8g": "bknight", "8h": "brook",
        "7a": "bpawn", "7b": "bpawn", "7c": "bpawn", "7d": "bpawn",
        "7e": "bpawn", "7f": "bpawn", "7g": "bpawn", "7h": "bpawn",    
    }
    # list keeps broken positions
    results_b = []
    
    # TODO: check if figures positions are correct
    
    def isValidChessBoard(board_check):
        for key in board_check:
            if board_check[key] == chess_board[key]:
    # this print is just for visualization 
                print(f"{key} has a correct value of {chess_board[key]}")
            if board_check[key] != chess_board[key]:
    # this print is just for visualization 
                print(f"{key} has broken value of {chess_board[key]}")
                results_b.append(chess_board[key])
    # print broken positions
        for i in results_b:
            print(f"Figure {i} is in a bad position.")
    
    
    test_board = {
        "1a": "wrook",
        "7h": "wpawn",    
        "7g": "bpawn",
        "1b": "bknight",
    }
    isValidChessBoard(test_board)
    

    结果:

    1a has a correct value of wrook
    7h has broken value of bpawn      
    7g has a correct value of bpawn     
    1b has broken value of wknight    
    Figure bpawn is in a bad position.  
    Figure wknight is in a bad position.
    

    【讨论】:

      【解决方案3】:
      #validate chess board 
      dict_chess ={'1a':'bking', '8f':'wking', '1b':'bqueen', '6d': 'wqueen', \
                '5c': 'wrook'}
      
      
      chessHeightLocation = ['a','b','c','d','e','f','g','h']
      chessWidthLocation = [1, 2, 3, 4, 5, 6, 7, 8]
      colors = ['w', 'b']
      pieces = ['pawn', 'knight', 'bishop', 'rook', 'queen', 'king']
      def isValidChessBoard(dictChess):
          playerCount = {'bpawn': 0, 'wpawn': 0, 'wking': 0, 'bking': 0, 'wpieceCount': 0, 'bpieceCount': 0}
          for keysInChessBoard in dictChess:
              #check for Space
              #print(int(keysInChessBoard[0]) not in chessWidthLocation)
              if (int(keysInChessBoard[0]) not in chessWidthLocation) or (keysInChessBoard[1] not in chessHeightLocation):
                  print('Not valid space: ' + keysInChessBoard)
                  return False
              
              #check for black and white
              if dictChess[keysInChessBoard][0] not in colors:
                  print('Not valid color of piece should have b for black or w for white: ' + dictChess[keysInChessBoard])
                  return False
              
              #check for piece
              if dictChess[keysInChessBoard][1:] not in pieces:
                  print('Not valid piece: ' + dictChess[keysInChessBoard])
                  return False
              
              #check for pawns
              if dictChess[keysInChessBoard] == 'bpawn' or dictChess[keysInChessBoard] == 'wpawn':
                  playerCount[dictChess[keysInChessBoard]] += 1
                  if playerCount[dictChess[keysInChessBoard]] > 8:
                      print('More than 8 pawns in one player')
                      return False
              
              #check for king
              if dictChess[keysInChessBoard] == 'bking' or dictChess[keysInChessBoard] == 'wking':
                  playerCount[dictChess[keysInChessBoard]] += 1
                  if playerCount[dictChess[keysInChessBoard]] > 1:
                      print('More than 1 king')
                      return False
              #pieceCount
              if dictChess[keysInChessBoard][0] in colors:
                  if dictChess[keysInChessBoard][0] == 'w':
                      playerCount[dictChess[keysInChessBoard][0]+'pieceCount'] += 1
                  elif dictChess[keysInChessBoard][0] == 'b':
                      playerCount[dictChess[keysInChessBoard][0]+'pieceCount'] += 1
                  if playerCount[dictChess[keysInChessBoard][0]+'pieceCount'] > 16:
                      print('More than 16 piece')
                      return False
              #print(playerCount)
         return True
      print(isValidChessBoard(dict_chess))
      

      【讨论】:

      • 欢迎来到 StackOverflow。虽然此代码可能会回答问题,但提供有关 如何 和/或 为什么 解决问题的附加上下文将提高​​答案的长期价值。
      【解决方案4】:

      这就是我解决这个问题的方法。我添加了本书未在此问题中提及的有效董事会条件的标准。我检查了有效的后、马、车和象的数量,以使其更准确地显示棋盘应该是怎样的。

      def isValidChessBoard(board: dict) -> bool:
          """Return True or False depending on if  a board is valid in chess."""
          board_pieces = list(board.values()) #initiate variable for repeated use
          all_pieces = ['king', 'queen', 'bishop','knight','rook','pawn']
          blacks, whites = 0, 0 #variable to keep count of black/white pieces
          
          def pCount(to_count: str) -> int:
              """Return count value of the piece"""
              return board_pieces.count(to_count)
              
          #check if board has one king and at most one queen for each side
          if (pCount('bking') != 1) or (pCount('wking') != 1) or \
             (pCount('bqueen') > 1) or (pCount('wqueen') > 1):
              return False  
          
          #check if all pieces names are valid 
          for piece in board_pieces:
              if piece[0] not in 'bw' or piece[1:] not in all_pieces:
                  return False
                       
          #check if the position is valid (between 1a and 8h)
          for p in board.keys():
              if p[0] not in '12345678' or p[1] not in 'abcdefgh':
                  return False
                     
          #check if each side has a valid number of pieces
          for i in board_pieces:
              if i[0] == 'b':
                  blacks += 1
              elif i[0] == 'w':
                  whites += 1
          
          if (blacks or whites) > 16:
              return False
          elif (pCount('bpawn') or pCount('wpawn')) > 8:
              return False    
          elif (pCount('bbishop') or pCount('bknight') or pCount('brook')) > 2 \
          or   (pCount('wbishop') or pCount('wknight') or pCount('wrook')) > 2:
              return False
                  
          return True
      

      我确实想知道我是否可以更有效地计算车、骑士和主教,而不是单独检查所有棋子。

      为了验证代码是否按预期工作,我制作了一些测试板,如下所示:

      #more than 2 kings
      test_1  = {'1a':'bking', '8f':'wking', '2a': 'bking', '5d':'wking'}
      
      #more than 8 pawns for one side
      test_2 = {'2a':'bpawn', '2b': 'bpawn', '2c':'bpawn', '2d': 'bpawn', '2e': 'bpawn',\
               '2f': 'bpawn', '2g': 'bpawn', '2h': 'bpawn',\
               '7a': 'bpawn', '7b': 'wpawn', '8e': 'wking', '1e': 'bking'}
      
      #more than 16 pieces for one player
      test_3 = {'2a':'bpawn', '2b': 'bpawn', '2c':'bpawn', '2d': 'bpawn', '2e': 'bpawn',\
               '2f': 'bpawn', '2g': 'bpawn', '2h': 'bpawn',\
               '1a': 'brook', '1b': 'bknight', '1c': 'bbishop', '1d': 'bqueen', \
               '1e':'bking', '1f': 'brook', '1g': 'bknight', '1h': 'bbishop', \
               '3a': 'bpawn', '7b': 'wking', '7c': 'wqueen'}
      
      #invalid space 9d
      test_4 = {'1a':'bking', '8f':'wking', '1b':'bqueen', '9d': 'wqueen'}
      
      #names don't begin with 'w' or 'b'
      test_5 = {'1a':'bking', '8f':'wking', '1b':'zqueen', '6d': 'wqueen'}
      
      #pieces names 
      test_6 = {'1a':'bking', '8f':'wking', '1b':'bqueen', '6d': 'wqueen',\
                '7b':'wknightt'}
      
      #too many white rooks
      test_7 = {'1a':'bking', '8f':'wking', '1b':'bqueen', '6d': 'wqueen', \
                '5c': 'wrook', '8c':'wrook', '7d': 'wrook'}
      
      #this board should be valid
      test_8 = {'1a':'bking', '8f':'wking', '1b':'bqueen', '6d': 'wqueen', \
                '5c': 'wrook'}
      

      【讨论】:

        【解决方案5】:

        我也在使用同一本书学习 Python。我发现这些练习的需求定义有时有点模糊;这意味着必须做出一些假设。

        我的假设是:

        1. 要编写的函数应该只返回 False 或 True,而不是任何关于为什么板子不验证的额外信息。

        2. 棋盘验证是“无状态的”,这意味着检查当前棋盘定义,而不是,例如,是否遵循国际象棋规则等。

        3. 不需要验证空格。如果一个棋子没有被声明在一个特定的位置,那个位置是空的,即我遵循棋盘中出现的棋子的“明确声明”的规则。

        另外请注意,如果玩家/颜色申报的总件数是否超过 16 件,则不需要检查,因为如果每件件的数量正确,那么总数也必须正确。

        我添加了 cmets,应该提供足够的解释每个部分的作用,但主要分为三个部分:

        • 常量定义,使此代码更易于移植。
        • “辅助”函数的定义,用于检查棋盘中每一块的数量是否是允许的。
        • 练习请求的函数。

        该代码也是我第一次尝试遵循 PEP 8 建议/规则,因此,如果我在正确的方式上提供任何反馈,或者有什么问题,当然欢迎。

        我还想澄清一下,代码显然是我的创作,但我也试图从其他贡献/帖子/答案中汲取一些想法;最后,stackoverflow 的范围是支持互助和贡献。

        该代码已使用为范围创建的一些板示例进行了测试,并且似乎可以正常工作,但是如果您发现任何错误,请在 cmets 中告诉我。

        谢谢。

        PS 由于一些语法错误以及为了更好地解释第三个假设而编辑。

        #!/usr/bin/env python3
        
        
        # Using lists instead of sets for COLORS and PIECES should work.
        #
        #
        # However, because it is important to stress that those constant define
        # a *set* of permitted values, using sets sounds more acceptable.
        
        
        # Please, note that sets are not explained in the chapter this exercise
        # was taken from.
        
        COLORS = {'b', 'w'}
        
        PIECES = {
            'king',
            'queen',
            'rook',
            'bishop',
            'knight',
            'pawn'
            }
        
        VALID_QUANTITY = {
            'king': (1, 1),
            'queen': (0, 1),
            'rook': (0, 2),
            'bishop': (0, 2),
            'knight': (0, 2),
            'pawn': (0, 8),
            }
        
        
        # The following constants can be easily made using set('12345678') and
        # set('abcdefgh').
        
        ROWS = {'1', '2', '3', '4', '5', '6', '7', '8'}
        COLUMNS = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'}
        
        
        # This function verifies if black pieces or white pieces quantity
        # is correct, comparing the total pieces of each kind in the board, with
        # the acceptable values defined in VALID_QUANTITY.
        
        def verify_quantity(pieces):
            for piece, quantity in pieces.items():
                low, high = VALID_QUANTITY[piece]
                if low <= quantity <= high:
                    return True
                else:
                    return False
        
        
        # This is the main function object of the exercise.
        
        def is_valid_chess_board(board):
            
            black_pieces = {}
            white_pieces = {}
            
            for position, player_piece in board.items():
                
                row, column = position
                player = player_piece[0]
                piece = player_piece[1:]
        
        
                # First it is checked that the positions of the pieces, their
                # kind and colors are the ones allowed.
                
                if (row not in ROWS) or (column not in COLUMNS):
                    return False
                if player not in COLORS:
                    return False
                if piece not in PIECES:
                    return False
        
        
                # The pieces present in the board are counted for each color.
                
                if player == 'b':
                    black_pieces[piece] = black_pieces.get(piece, 0) + 1
                else:
                    white_pieces[piece] = white_pieces.get(piece, 0) + 1
        
        
                # The quantity is finally checked to see if it is the one
                # allowed by the rules.
                
                if not(verify_quantity(black_pieces) or verify_quantity(white_pieces)):
                    return False
        
            return True
        

        【讨论】:

          【解决方案6】:

          国际象棋的晋级规则要求棋子达到 第八名将由玩家选择的主教、骑士、 车,或相同颜色的女王。选择的作品不能是另一件 国王也不是另一个棋子。 /维基百科

          board = {'e3': 'wking', 'c6': 'wqueen',
               'g2': 'bbishop', 'd2': 'bqueen', 'g3': 'bking',
               'a1': 'bpawn', 'm1': 'bpawn', 'c1': 'bpawn', 'd1': 'bpawn', 
               'e1': 'bpawn', 'f1': 'bpawn', 'g1': 'bpawn', 'h1': 'bpawn', 
               'e2': 'bpawn', 'a2': 'bpawn'}
          
          def isValidChessBoard(board):
              wKing, bKing, wPieces, bPieces = 0, 0, 0, 0
              wPawns, bPawns, spaces, check = 0, 0, [], True
          
              for x in ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'):
                  for y in range(1,9):
                      spaces.append(x + str(y))
          
              for space, piece in board.items():
          
                  if space not in spaces:
                      print('Space is wrong: ' + space + ' ' + piece)
                      check = False
                  if piece == 'wking':
                      wKing += 1
                  if piece == 'bking':
                      bKing += 1
                  if piece == 'wpawn':
                      wPawns += 1
                  if piece == 'bpawn':
                      bPawns += 1
                  if piece.startswith('w'):
                      wPieces += 1
                  if piece.startswith('b'):
                      bPieces += 1
              if wKing != 1:
                  print('White king != 1 : ' + str(wKing))
                  check = False
              if bKing != 1:
                  print('Black king != 1 : ' + str(bKing))
                  check = False
              if wPieces > 16:
                  print('Total white pieces on board > 16: ' + str(wPieces))
                  check = False
              if bPieces > 16:
                  print('Total black pieces on board > 16: ' + str(bPieces))
                  check = False
              if wPawns > 8:
                  print('White pawns on board > 8: ' + str(wPawns))
                  check = False
              if bPawns > 8:
                  print('Black pawns on board > 8: ' + str(bPawns))
                  check = False
            
              if check:
                  return True
              else:
                  return False    
          
          print(isValidChessBoard(board))
          

          【讨论】:

            【解决方案7】:
            piece = {}
            
            
            # enter chess piece and position
            def pieceSet():
                while True:
                    print("Enter chess piece: (start with 'b' or 'w' + piece) or  enter 'q' to exit")
                    pc = str(input())
                    if pc == 'q':
                        break
                    print("Place the piece on the chess board: ")
                    position = str(input())
                    piece[str(position)] = str(pc)
            
            
            def isValidChessBoard():
                # board position and coordinates
                board = []
                for row in range(1, 9):
                    for col in ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'):
                        board.append(str(row)+str(col))
            
                # check if both kings are still on the board
                if 'wking' not in piece.values() or 'bking' not in piece.values():
                    print('---The Board is Invalid!---')
                    print("King is not on the board!")
                    return False
            
                # check the position of every piece on the board
                for key in piece.keys():
                    if key not in board:
                        print('---The Board is Invalid!---')
                        print("Chess Board only has 8 boxes per row ('a' to 'h') and 8 boxes percolumn ('1 to 8')")
                        return False
            
                # check if the name starts with a "w" or "b"
                for pieces in piece.values():
                    if pieces[0] != "b" and pieces[0] != "w":
                        print('---The Board is Invalid!---')
                        print("Chess pieces only have 2 colors: (b)lack and (w)hite")
                        return False
            
                # check the quantity of every chess pieces and see if every piece is valid
                bpawn = 0
                wpawn = 0
                bking = 0
                wking = 0
                bqueen = 0
                wqueen = 0
                bbishop = 0
                wbishop = 0
                bknight = 0
                wknight = 0
                brook = 0
                wrook = 0
                for value in piece.values():
                    if value == 'bpawn':
                        bpawn += 1
                        if bpawn > 8:
                            print('---The Board is Invalid!---')
                            print("Exceeded the limit of bpawn!")
                            return False
                        else:
                            continue
                    elif value == 'wpawn':
                        wpawn += 1
                        if wpawn > 8:
                            print('---The Board is Invalid!---')
                            print("Exceeded the limit of wpawn!")
                            return False
                        else:
                            continue
                    elif value == 'bking':
                        bking += 1
                        if bking > 1:
                            print('---The Board is Invalid!---')
                            print("Exceeded the limit of bking!")
                            return False
                        else:
                            continue
                    elif value == 'wking':
                        wking += 1
                        if wking > 1:
                            print('---The Board is Invalid!---')
                            print("Exceeded the limit of wking!")
                            return False
                        else:
                            continue
                    elif value == 'bqueen':
                        bqueen += 1
                        if bqueen > 1:
                            print('---The Board is Invalid!---')
                            print("Exceeded the limit of bqueen!")
                            return False
                        else:
                            continue
                    elif value == 'wqueen':
                        wqueen += 1
                        if wqueen > 1:
                            print('---The Board is Invalid!---')
                            print("Exceeded the limit of wqueen!")
                            return False
                        else:
                            continue
                    elif value == 'bbishop':
                        bbishop += 1
                        if bbishop > 2:
                            print('---The Board is Invalid!---')
                            print("Exceeded the limit of bbishop!")
                            return False
                        else:
                            continue
                    elif value == 'wbishop':
                        wbishop += 1
                        if wbishop > 2:
                            print('---The Board is Invalid!---')
                            print("Exceeded the limit of wbishop!")
                            return False
                        else:
                            continue
                    elif value == 'bknight':
                        bknight += 1
                        if bknight > 2:
                            print('---The Board is Invalid!---')
                            print("Exceeded the limit of bknight!")
                            return False
                        else:
                            continue
                    elif value == 'wknight':
                        wknight += 1
                        if wknight > 2:
                            print('---The Board is Invalid!---')
                            print("Exceeded the limit of wknight!")
                            return False
                        else:
                            continue
                    elif value == 'brook':
                        brook += 1
                        if brook > 2:
                            print('---The Board is Invalid!---')
                            print("Exceeded the limit of brook!")
                            return False
                        else:
                            continue
                    elif value == 'wrook':
                        wrook += 1
                        if wrook > 2:
                            print('---The Board is Invalid!---')
                            print("Exceeded the limit of wrook!")
                            return False
                        else:
                            continue
                    else:
                        print('---The Board is Invalid!---')
                        print(str(value) + " piece not included!")
                        return False
            
            
            def result():
                if isValidChessBoard() == False:
                    return False
                else:
                    print('---The Board is Valid!---')
                    return True
            
            
            pieceSet()
            print('piece =', piece)
            print(result())
            

            【讨论】:

              【解决方案8】:

              def isValidChessBoard(棋盘): 板= {'1a':板['1a'],'1b':板['1b'],'1c':板['1c'],'1d':板['1d'],'1e' :板['1e'],'1f':板['1f'], '1g':板['1g'],'1h':板['1h'], '2a':板['2a'],'2b':板['2b'],'2c':板['2c'],'2d':板['2d'],'2e':板[ '2e'], '2f': 板['2f'], '2g':板['2g'],'2h':板['2h'], '3a':板['3a'],'3b':板['3b'],'3c':板['3c'],'3d':板['3d'],'3e':板[ '3e'],'3f':板['3f'], '3g': 板['3g'], '3h': 板['3h'], '4a':板['4a'],'4b':板['4b'],'4c':板['4c'],'4d':板['4d'],'4e':板[ '4e'], '4f': 板['4f'], '4g':板['4g'],'4h':板['4h'], '5a':板['5a'],'5b':板['5b'],'5c':板['5c'],'5d':板['5d'],'5e':板[ '5e'], '5f': 板['5f'], '5g':板['5g'],'5h':板['5h'], '6a':板['6a'],'6b':板['6b'],'6c':板['6c'],'6d':板['6d'],'6e':板[ '6e'],'6f':板['6f'], '6g':板['6g'],'6h':板['6h'], '7a':板['7a'],'7b':板['7b'],'7c':板['7c'],'7d':板['7d'],'7e':板[ '7e'], '7f': 板['7f'], '7g': 板['7g'], '7h': 板['7h'], '8a':板['8a'],'8b':板['8b'],'8c':板['8c'],'8d':板['8d'],'8e':板[ '8e'],'8f':板['8f'], '8g':板['8g'],'8h':板['8h']} # 标准 1 - 1 次 bbking 和 1 次 wking

              count = {}
              
              for v in board.values():
                  count.setdefault(v, 0)
                  count[v] = count[v] + 1
              print(count)
              # Criteria 2 - Each player can have at most 16 pieces, at most 8 pawns
              
              del count['']
              #print(count)
              pieces = 0
              for v in count.values():
                  pieces = pieces + v
              #print(pieces)
              
              # Criteria 3 and 4 - All pieces must be on a valid space '1a' to '8h', not '9z'. Names must start with w or b.
              
              validSpace = {'1a': 'brook', '1b': 'bknight', '1c': 'bbishop', '1d': 'bking', '1e': 'bqueen', '1f': 'bbishop',
                       '1g': 'bknight', '1h': 'brook',
                       '2a': 'bpawn', '2b': 'bpawn', '2c': 'bpawn', '2d': 'bpawn', '2e': 'bpawn', '2f': 'bpawn',
                       '2g': 'bpawn', '2h': 'bpawn',
                       '3a': '', '3b': '', '3c': '', '3d': '', '3e': '', '3f': '',
                       '3g': '', '3h': '',
                       '4a': '', '4b': '', '4c': '', '4d': '', '4e': '', '4f': '',
                       '4g': '', '4h': '',
                       '5a': '', '5b': '', '5c': '', '5d': '', '5e': '', '5f': '',
                       '5g': '', '5h': '',
                       '6a': '', '6b': '', '6c': '', '6d': '', '6e': '', '6f': '',
                       '6g': '', '6h': '',
                       '7a': 'wpawn', '7b': 'wpawn', '7c': 'wpawn', '7d': 'wpawn', '7e': 'wpawn', '7f': 'wpawn',
                       '7g': 'wpawn', '7h': 'wpawn',
                       '8a': 'wrook', '8b': 'wknight', '8c': 'wbishop', '8d': 'wking', '8e': 'wqueen', '8f': 'wbishop',
                       '8g': 'wknight', '8h': 'wrook'
                       }
              print(count['bking'])
              print(count['bpawn'])
              if count['bking'] == 1:
                  if count['wking'] == 1:
                      if pieces == 32:
                          if count['bpawn'] == 8:
                              if count['wpawn'] == 8:
                                  if board == validSpace:
                                      return True
              

              chessBoardOne = {'1a': 'brook', '1b': 'bknight', '1c': 'bbishop', '1d': 'bking', '1e': 'bqueen', '1f': 'bbishop', '1g':'bknight','1h':'布鲁克', '2a':'bpawn','2b':'bpawn','2c':'bpawn','2d':'bpawn','2e':'bpawn','2f':'bpawn', '2g':'bpawn','2h':'bpawn', '3a': '', '3b': '', '3c': '', '3d': '', '3e': '', '3f': '', '3g': '', '3h': '', '4a':'','4b':'','4c':'','4d':'','4e':'','4f':'', '4g': '', '4h': '', '5a': '', '5b': '', '5c': '', '5d': '', '5e': '', '5f': '', '5g': '', '5h': '', '6a':'','6b':'','6c':'','6d':'','6e':'','6f':'', '6g': '', '6h': '', '7a':'wpawn','7b':'wpawn','7c':'wpawn','7d':'wpawn','7e':'wpawn','7f':'wpawn', '7g': 'wpawn', '7h': 'wpawn', '8a':'wrook','8b':'wknight','8c':'wbishop','8d':'wking','8e':'wqueen','8f':'wbishop', '8g':'wknight','8h':'wrook' }

              打印(isValidChessBoard(chessBoardOne)) #print(答案)

              【讨论】:

              • 虽然您的回答可能会解决问题,但 including an explanation 关于如何以及为什么解决问题将真正有助于提高您的帖子质量,并可能导致更多的赞成票。请记住,您正在为将来的读者回答问题,而不仅仅是现在提问的人。请编辑您的答案以添加解释并说明适用的限制和假设。 - From Review
              • @Adam,我的代码分为三个部分。有关如何正确格式化我的代码的任何提示?
              【解决方案9】:

              你们没有遵循这本书。你们正在编写的代码甚至会让最伟大的专家甚至作者本人都感到困惑。编写此代码的所有提示都在书中。这意味着你们没有读过这本书。如果您阅读它,您就不会在代码中犯所有这些错误。请在下面找到最终答案,它比你们在这个线程中发布的所有代码都简单高效并且更好:

              def isValidChessBoard(board):
                  board = {'1a': 'brook', '1b': 'bknight', '1c': 'bbishop', '1d': 'bking', '1e': 'bqueen', '1f': 'bbishop',
                           '1g': 'bknight', '1h': 'brook',
                           '2a': 'bpawn', '2b': 'bpawn', '2c': 'bpawn', '2d': 'bpawn', '2e': 'bpawn', '2f': 'bpawn',
                           '2g': 'bpawn', '2h': 'bpawn',
                           '3a': '', '3b': '', '3c': '', '3d': '', '3e': '', '3f': '',
                           '3g': '', '3h': '',
                           '4a': '', '4b': '', '4c': '', '4d': '', '4e': '', '4f': '',
                           '4g': '', '4h': '',
                           '5a': '', '5b': '', '5c': '', '5d': '', '5e': '', '5f': '',
                           '5g': '', '5h': '',
                           '6a': '', '6b': '', '6c': '', '6d': '', '6e': '', '6f': '',
                           '6g': '', '6h': '',
                           '7a': 'wpawn', '7b': 'wpawn', '7c': 'wpawn', '7d': 'wpawn', '7e': 'wpawn', '7f': 'wpawn',
                           '7g': 'wpawn', '7h': 'wpawn',
                           '8a': 'wrook', '8b': 'wknight', '8c': 'wbishop', '8d': 'wking', '8e': 'wqueen', '8f': 'wbishop',
                           '8g': 'wknight', '8h': 'wrook'
                           }
                  # Criteria 1 - 1 bbking and 1 wking
              
                  count = {}
              
                  for v in board.values():
                      count.setdefault(v, 0)
                      count[v] = count[v] + 1
                  # print(count)
                  # Criteria 2 - Each player can have at most 16 pieces, at most 8 pawns
              
                  del count['']
                  #print(count)
                  pieces = 0
                  for v in count.values():
                      pieces = pieces + v
                  #print(pieces)
              
                  # Criteria 3 - All pieces must be on a valid space '1a' to '8h', not '9z'
              
                  validSpace = {'1a': 'brook', '1b': 'bknight', '1c': 'bbishop', '1d': 'bking', '1e': 'bqueen', '1f': 'bbishop',
                           '1g': 'bknight', '1h': 'brook',
                           '2a': 'bpawn', '2b': 'bpawn', '2c': 'bpawn', '2d': 'bpawn', '2e': 'bpawn', '2f': 'bpawn',
                           '2g': 'bpawn', '2h': 'bpawn',
                           '3a': '', '3b': '', '3c': '', '3d': '', '3e': '', '3f': '',
                           '3g': '', '3h': '',
                           '4a': '', '4b': '', '4c': '', '4d': '', '4e': '', '4f': '',
                           '4g': '', '4h': '',
                           '5a': '', '5b': '', '5c': '', '5d': '', '5e': '', '5f': '',
                           '5g': '', '5h': '',
                           '6a': '', '6b': '', '6c': '', '6d': '', '6e': '', '6f': '',
                           '6g': '', '6h': '',
                           '7a': 'wpawn', '7b': 'wpawn', '7c': 'wpawn', '7d': 'wpawn', '7e': 'wpawn', '7f': 'wpawn',
                           '7g': 'wpawn', '7h': 'wpawn',
                           '8a': 'wrook', '8b': 'wknight', '8c': 'wbishop', '8d': 'wking', '8e': 'wqueen', '8f': 'wbishop',
                           '8g': 'wknight', '8h': 'wrook'
                           }
              
                  if count['bking'] == 1:
                      if count['wking'] == 1:
                          if pieces == 32:
                              if count['bpawn'] == 8:
                                  if count['wpawn'] == 8:
                                      if board == validSpace:
                                          #return 'True: This is a Vaild Chessboard'
                                          return True
              
              
              
              chessBoardOne = {'1a': 'wrook', '1b': 'wknight', '1c': 'wbishop', '1d': 'wqueen', '1e': 'wking', '1f': 'wbishop',
              '1g': 'wknight', '1h': 'wrook','2a': 'wpawn', '2b': 'wpawn', '2c': 'wpawn', '2d': 'wpawn', '2e': 'wpawn',
              '2f': 'wpawn', '2g': 'wpawn', '2h': 'wpawn', '3a': '', '3b': '', '3c': '', '3d': '', '3e': '', '3f': '',
              '3g': '', '3h': '', '4a': '', '4b': '', '4c': '', '4d': '', '4e': '', '4f': '', '4g': '', '4h': '',
              '5a': '', '5b': '', '5c': '', '5d': '', '5e': '', '5f': '', '5g': '', '5h': '',
              '6a': '', '6b': '', '6c': '', '6d': '', '6e': '', '6f': '', '6g': '', '6h': '',
              '7a': 'bpawn', '7b': 'bpawn', '7c': 'bpawn', '7d': 'bpawn', '7e': 'bpawn', '7f': 'bpawn', '7g': 'bpawn', '7h': 'bpawn',
              '8a': 'brook', '8b': 'bknight', '8c': 'bbishop' , '8d': 'bqueen', '8e': 'bking', '8f': 'bbishop',
              '8g': 'bknight','8h': 'brook'}
              
              print(isValidChessBoard(chessBoardOne))
              #print(Answer)
              

              【讨论】:

              • 如果您需要代码,请联系我,我会发送给您。这个线程没有正确格式化我的代码。
              • 请勿使用此代码。我发现我的代码中有一个错误。老实说,我最初并没有用错误的棋盘来测试它。现在我有了,我注意到即使你有 9 个棋子而不是 8 个棋子,它也会返回 true。对不起,所有人。
              【解决方案10】:
              def isValid(board):
                  # PUT TOGETHER A LIST OF ALL POSSIBLE PIECES
                  pieces = ['king', 'queen', 'rook', 'knight', 'bishop', 'pawn']
                  colors = ['b', 'w']
                  all_pieces = {}
                  possible_pieces = ['']
                  color_count = {'b': 0, 'w': 0}
                  for piece in pieces:
                      for color in colors:
                          possible_pieces.append('{}{}'.format(color, piece))
                          all_pieces.setdefault('{}{}'.format(color, piece), 0)
              
                  # CHECKS IF PIECES HAVE VALID NAMES
                  for v in board.values():
                      if v not in possible_pieces:
                          print('Error: Invalid chess piece type')
                          return False
              
                  # ITERATE THROUGH BOARD, AND COUNT PIECES AND COLORS
                  for k in board:
                      if board.get(k) == '':
                          continue
                      all_pieces[board.get(k)] += 1      # INCREASE PIECE TYPE
                      color_count[board.get(k)[0]] += 1  # INCREASE COLOR COUNT
              
                  # CHECK TOTAL WHITE/BLACK PIECES
                  if color_count['w'] > 16 or color_count['b'] > 16:
                      print('Error: Invalid number of white or black pieces')
                      return False
              
                  # CHECKS IF VALID NUMBER OF PIECES
                  for i in possible_pieces:
                      num = all_pieces.get(i)
                      if i == 'bking' or i == 'wking':
                          if num != 1:
                              print('Error: Invalid number of Kings')
                              return False
                      elif i == 'bqueen' or i == 'wqueen':
                          if num > 1:
                              print('Error: Invalid number of Queens')
                              return False
                      elif i == 'brook' or i == 'wrook':
                          if num > 2:
                              print('Error: Invalid number of Rooks')
                              return False
                      elif i == 'bknight' or i == 'wknight':
                          if num > 2:
                              print('Error: Invalid number of Knights')
                              return False
                      elif i == 'bbishop' or i == 'wbishop':
                          if num > 2:
                              print('Error: Invalid number of Bishops')
                              return False
                      elif i == 'bpawn' or i == 'wpawn':
                          if num > 8:
                              print('Error: Invalid number of Pawns')
                              return False
              
                  # CHECK ALL VALID SPACES
                  for s in board:
                      if s[0] not in '12345678' or s[1] not in 'abcdefgh':
                          print('Error: Space is not valid!')
                          return False
              
                  # IF PASS ALL CHECKS, THE BOARD IS VALID 
                  return True
              

              【讨论】:

                【解决方案11】:

                这是我的尝试。 我很想从更有经验的人那里得到一些反馈。

                board_width = ['1', '2', '3', '4', '5', '6', '7', '8']
                board_height = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
                board = []
                for x in board_width:  #create a list of possible board positions
                    for y in board_height:
                        board.append(x + y)
                
                
                
                pieces = ['king', 'queen', 'rook', 'rook',
                          'bishop', 'bishop', 'knight', 'knight',
                          'pawn', 'pawn', 'pawn', 'pawn', 'pawn',
                          'pawn', 'pawn', 'pawn']    #list of all pieces for each player
                
                white_pieces = pieces.copy()
                black_pieces = pieces.copy()
                
                def is_valid_chess_board(chess_dict):
                
                    if 'wking' and 'bking' in chess_dict.values():
                
                        for key, value in chess_dict.items(): #iterate each dict elements
                
                            if value == '':
                                board.remove(key)
                
                            elif value.startswith('w') and key in board:  
                                lis_val = list(value)
                                lis_val.remove('w')
                                val_str = "".join(lis_val)
                                if val_str in white_pieces:
                                    white_pieces.remove(val_str)
                                    board.remove(key)
                                    print(f"The White {val_str} was placed at {key}")
                                else:
                                    print(f"This {val_str} is not a proper Chess piece")
                
                            elif value.startswith('b') and key in board:
                                lis_val = list(value)
                                lis_val.remove('b')
                                val_str = "".join(lis_val)
                                if val_str in black_pieces:
                                    black_pieces.remove(val_str)
                                    board.remove(key)
                                    print(f"The Black {val_str} was placed at {key}")
                                else:
                                    print(f"This {val_str} is not a proper Chess piece")
                
                            else:
                                print("You have an incomplete Chess board")
                                break
                    else:
                        print("You have an incomplete Chess board!")
                
                    print(board)
                

                【讨论】:

                • 欢迎来到 SO!这不是问题的答案。 OP没有要求其他版本。他们正在就他们版本的特定部分征求意见。如果您想让其他人查看您的版本,请开始一个具有特定要点的新问题。或在Code Review 上试用。
                【解决方案12】:

                编辑:当你定义有效计数时,它没有考虑到你可能会在棋盘的另一端得到一个棋子并最终得到两个皇后,尽管我不知道你如何解决这个问题导致程序接受不可靠的答案(例如游戏开始时的两个皇后)。如有任何帮助,我们将不胜感激!

                既然你问是否有替代方案,我提出以下内容。

                步骤

                • 定义所有棋子的集合
                • 按类型定义有效件数范围
                • 数一数棋子
                • 检查件数在有效范围内
                • 检查职位是否有效
                • 检查作品名称是否有效

                代码

                def isValidChessBoard(board):
                      """Validate counts and location of pieces on board"""
                    
                      # Define pieces and colors
                      pieces = ['king','queen','rook', 'knight','bishop', 'pawn']
                      colors = ['b', 'w']
                      # Set of all chess pieces
                      all_pieces = set(color+piece for piece in pieces for color in colors)
                    
                      # Define valid range for count of chess pieces by type (low, high) tuples
                      valid_counts = {'king': (1, 1),
                                  'queen': (0, 1),
                                  'rook': (0, 2),
                                  'bishop': (0, 2),
                                  'knight': (0, 2),
                                  'pawn': (0, 8)}
                    
                      # Get count of pieces on the board
                      piece_cnt = {}
                      for v in board.values():
                        if v in all_pieces:
                          piece_cnt.setdefault(v, 0)
                          piece_cnt[v] += 1
                    
                      # Check if there are a valid number of pieces
                      for piece in all_pieces:
                        cnt = piece_cnt.get(piece, 0)
                        lo, hi = valid_counts[piece[1:]]
                        if not lo <= cnt <= hi:   # Count needs to be between lo and hi
                          if lo != hi:
                            print(f"There should between {lo} and {hi} {piece} but there are {cnt}")
                          else:
                            print(f"There should be {lo} {piece} but there are {cnt})")
                          return False
                    
                      # Check if locations are valid
                      for location in board.keys():
                        row = int(location[:1])
                        column = location[1:]
                        if not ((1 <= row <= 8) and ('a' <= column <= "h")):
                          print(f"Invaid to have {board[location]} at postion {location}")
                          return False
                
                      # Check if all pieces have valid names
                      for loc, piece in board.items():
                        if piece:
                          if not piece in all_pieces:
                            print(f"{piece} is not a valid chess piece at postion {loc}")
                            return False
                
                      return True
                

                【讨论】:

                • 唯一要比较的是:A. 棋子的数量(必须
                【解决方案13】:

                我的解决方案 - 我使用集合来检查有效空间,但这也可以通过列表来实现。

                
                board = {'1a': 'wrook', '1b': 'wknight', '1c': 'wbishop', '1d': 'wqueen', '1e': 'wking', '1f': 'wbishop',
                '1g': 'wknight', '1h': 'wrook','2a': 'wpawn', '2b': 'wpawn', '2c': 'wpawn', '2d': 'wpawn', '2e': 'wpawn',
                '2f': 'wpawn', '2g': 'wpawn', '2h': 'wpawn', '3a': '', '3b': '', '3c': '', '3d': '', '3e': '', '3f': '',
                '3g': '', '3h': '', '4a': '', '4b': '', '4c': '', '4d': '', '4e': '', '4f': '', '4g': '', '4h': '',
                '5a': '', '5b': '', '5c': '', '5d': '', '5e': '', '5f': '', '5g': '', '5h': '',
                '6a': '', '6b': '', '6c': '', '6d': '', '6e': '', '6f': '', '6g': '', '6h': '',
                '7a': 'bpawn', '7b': 'bpawn', '7c': 'bpawn', '7d': 'bpawn', '7e': 'bpawn', '7f': 'bpawn', '7g': 'bpawn', '7h': 'bpawn',
                '8a': 'brook', '8b': 'bknight', '8c': 'bbishop' , '8d': 'bqueen', '8e': 'bking', '8f': 'bbishop',
                '8g': 'bknight','8h': 'brook'}
                
                
                
                def isValidChessBoard(board_dict):
                    #check for 1 black king and 1 white king
                    bking=0
                    wking=0
                    for king in board_dict.values():
                        if king == 'bking':
                            bking += 1
                        if king == 'wking':
                           wking += 1
                    if bking != 1 or wking != 1:
                        return False
                
                    # check for 8 black pawns and 8 white pawns
                    bpawn = 0
                    wpawn = 0
                    for pawn in board_dict.values():
                        if pawn == 'bpawn':
                            bpawn += 1
                        if pawn == 'wpawn':
                            wpawn += 1
                    if wpawn != 8 or wpawn != 8:
                        return False
                
                
                    #check for valid spaces
                    valid_spaces = {'1a', '1b', '1c', '1d', '1e', '1f', '1g', '1h','2a', '2b', '2c', '2d', '2e', '2f', '2g', '2h',
                    '3a', '3b', '3c', '3d', '3e', '3f', '3g', '3h','4a', '4b', '4c', '4d', '4e', '4f', '4g', '4h',
                    '5a', '5b', '5c', '5d', '5e', '5f', '5g', '5h','6a', '6b', '6c', '6d', '6e', '6f', '6g', '6h',
                    '7a', '7b', '7c', '7d', '7e', '7f', '7g', '7h','8a', '8b', '8c', '8d', '8e', '8f', '8g', '8h'}
                
                    spaces = set()
                    for i in board_dict.keys():
                        spaces.add(i) # use set add method (like append for lists)
                    if spaces != valid_spaces:
                        return False
                
                
                    #check for 16 pieces per player
                    piece_count = 0
                    for piece in board_dict.values():
                        if piece != '': # don't count the empty spaces (no pieces)
                            piece_count += 1
                    if piece_count != 32: # 16 x 2 = 32 total pieces
                        return False
                
                    return 'This is a valid board'
                
                
                print(isValidChessBoard(board))
                

                【讨论】:

                  【解决方案14】:

                  由于国际象棋词典验证器问题不需要输出棋盘中错误的位置,所以这是我的答案:

                  def valid_chess_board(board):
                      bpieces, wpieces = 0, 0
                      pieces = ("king", "queen", "rook", "bishop", "knight", "pawn")
                      board_pieces = list(board.values())
                  
                      # Checking the kings
                      if board_pieces.count("bking") != 1 or board_pieces.count("wking") != 1:
                          return False
                  
                      # Checking the pawns
                      if board_pieces.count("bpawn") > 8 or board_pieces.count("wpawn") > 8:
                          return False
                  
                      # Checking the colors
                      for p in board_pieces:
                          if p[0] == "b" and p[1:] in pieces:
                              bpieces += 1
                          elif p[0] == "w" and p[1:] in pieces:
                              wpieces += 1
                          else:
                              return False
                  
                      # Checking the pieces
                      if bpieces > 16 or wpieces > 16:
                          return False
                  
                      # Checking the spaces
                      for s in board:
                          if s[0] not in "12345678" or s[1] not in "abcdefgh":
                              return False
                  
                      return True
                  
                  chess_board = {
                      "1a": "wrook",
                      "2a": "wpawn",
                      "6a": "bpawn",
                      "8a": "brook",
                      "2b": "wpawn",
                      "5b": "bpawn",
                      "1c": "wbishop",
                      "2c": "wbishop",
                      "3c": "wpawn",
                      "6c": "bknight",
                      "7c": "bpawn",
                      "1d": "wqueen",
                      "2d": "wknight",
                      "5d": "bpawn",
                      "8d": "bqueen",
                      "6e": "bbishop",
                      "7e": "bbishop",
                      "1f": "wrook",
                      "2f": "wpawn",
                      "3f": "wknight",
                      "6f": "bknight",
                      "8f": "brook",
                      "1g": "wking",
                      "2g": "wpawn",
                      "7g": "bpawn",
                      "8g": "bking",
                      "2h": "wpawn",
                      "7h": "bpawn",
                  }
                  
                  print(valid_chess_board(chess_board))
                  

                  【讨论】:

                    【解决方案15】:

                    这是我的版本:

                    • 删除你的while True:循环和你所有的break

                    • 使用字典更容易解决黑白检查(如果每种颜色都不需要两个)

                    • 在同一个循环检查片中检查位置值

                    • 添加了一个检查每个颜色只有一个国王

                    • 您还可以使用以片段类型为关键字的字典轻松检查每个片段类型计数。

                    def isValidChessBoard(board):
                        piecesCount = {'b': 0, 'w': 0}
                        pawnCount = {'b': 0, 'w': 0}
                        hasKing = {'b': False, 'w': False}
                        letterAxis = ('a','b','c','d','e','f','g','h')
                        pieceColour = ('b','w')
                        pieceType = ('pawn','knight','bishop','rook','queen','king')
                    
                        #each player has <= 16 pieces
                        for pos, i in board.items():
                            # check position value
                            #all pieces must be on valid space from '1a' to '8h'
                            if int(pos[0]) >= 9:
                                print('SpacesError')
                                return False
                    
                            if pos[1] not in letterAxis:
                                print('yAxisError')
                                return False
                    
                            # check piece data
                            if i != "":
                                #piece names begin with 'w' or 'b'
                                if i[0] not in pieceColour:
                                    print('WhiteOrBlackError')
                                    return False
                    
                                thisPieceColour = i[0]
                                piecesCount[thisPieceColour] += 1
                    
                                if piecesCount[thisPieceColour] >= 17:
                                    print('TotalPieceError')
                                    return False
                    
                                #piece names must follow with 'pawn', 'knight', 'bishop', 'rook', 'queen', 'king'
                                thisPieceType = i[1:]
                    
                                if thisPieceType not in pieceType:
                                    print('PieceTypeError')
                                    return False
                    
                                elif thisPieceType == 'pawn':
                                    pawnCount[thisPieceColour] += 1
                    
                                    #each player has <= 8 pawns
                                    if pawnCount[thisPieceColour] >= 9:
                                        print('PawnError')
                                        return False
                    
                                elif thisPieceType == 'king':
                                    # one black king and one white king
                                    if hasKing[thisPieceColour] == True:
                                        print("AlreadyHasKingError")
                    
                                    hasKing[thisPieceColour] = True
                    
                        if list(hasKing.values()) != [True, True]:
                            print("MissingKingError")
                            return False
                    
                        return 'This board checks out'
                    
                    board = {'1a': 'bking','2a': 'bqueen','3a': 'brook','4a': 'brook',
                    '5a': 'bknight','6a': 'bknight','7a':'bbishop','8a': 'bbishop',
                    '1b': 'bpawn','2b': 'bpawn','3b': 'bpawn','4b':'bpawn',
                    '5b': 'bpawn','6b': 'bpawn','7b': 'bpawn','8b': 'bpawn',
                    '1c': 'wking','2c': 'wqueen','3c': 'wrook','4c': 'wrook',
                    '5c': 'wbishop','6c': 'wbishop','7c': 'wknight','8c':'wknight',
                    '1e': 'wpawn','2e': 'wpawn','3e': 'wpawn','4e': 'wpawn',
                    '5e': 'wpawn','6e': 'wpawn','7e': 'wpawn','8e': 'wpawn',
                    '1f': '','2f': '','3f': '','4f': '','5f': '','6f': '','7f': '','8f': '',
                    '1g': '','2g': '','3g': '','4g': '','5g': '','6g': '','7g': '','8g': '',
                    '1h': '','2h': '','3h': '','4h': '','5h': '','6h': '','7h': '','8h': '',}
                    
                    print(isValidChessBoard(board))
                    
                    1. 看看我是如何重构代码的

                    2. 在访问之前检查if i != ""

                    3. 好吧,您不能那样做,因为您想将两个值与其他几个值进行比较。这是可能的,例如使用 set.intersection,但在你的情况下似乎有点过分了。

                    【讨论】:

                      猜你喜欢
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      • 2019-10-09
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      • 2023-03-11
                      • 1970-01-01
                      相关资源
                      最近更新 更多