此Python代码解析Reversi板的字符串表示,并将它们转换为适合于位字符串模块:b = BitArray('0b110')或位数组模块:a = bitarray('000111') (如果blackInit和whiteInit初始化为空字符串)的位字符串。
我感兴趣的是用Python做这件事的更简单的方法。我希望保留这样的想法,即将董事会的人类可读的字符串表示转换为2位字符串,一条用于黑色片段,另一条用于白色部分。如果它只是一个拆分,然后是一个映射,而不是一个循环,它看起来可能会更简单,但是我希望能够逐行看到字符串,而不知道如何解决这个问题。
board1 = [
'_|_|_|_|_|_|_|_',
'_|_|_|_|_|_|_|_',
'_|_|_|_|_|_|_|_',
'_|_|_|_|_|_|_|_',
'_|_|_|_|_|_|_|_',
'_|_|_|_|_|_|_|_',
'_|_|_|_|_|_|_|_',
'_|_|_|_|_|_|_|_']
board2 = [
'B|_|_|_|_|_|_|W',
'_|_|_|_|_|_|_|_',
'_|_|_|_|_|_|_|_',
'_|_|_|_|_|_|_|_',
'_|_|_|_|_|_|_|_',
'_|_|_|_|_|_|_|_',
'_|_|_|_|_|_|_|_',
'W|_|_|_|_|_|_|B']
board3 = [
'W|W|W|W|B|B|B|B',
'W|_|_|_|_|_|_|B',
'W|_|_|_|_|_|_|B',
'W|_|_|_|_|_|_|B',
'B|_|_|_|_|_|_|W',
'B|_|_|_|_|_|_|W',
'B|_|_|_|_|_|_|W',
'B|B|B|B|W|W|W|W']
board4 = [
'_|_|_|_|_|_|_|_',
'_|_|_|_|_|_|_|_',
'_|_|_|_|_|_|_|_',
'_|_|_|W|B|_|_|_',
'_|_|_|B|W|_|_|_',
'_|_|_|_|_|_|_|_',
'_|_|_|_|_|_|_|_',
'_|_|_|_|_|_|_|_']
board5 = [
'W|_|_|_|_|_|_|B',
'_|W|_|_|_|_|B|_',
'_|_|W|_|_|B|_|_',
'_|_|_|W|B|_|_|_',
'_|_|_|B|W|_|_|_',
'_|_|B|_|_|W|_|_',
'_|B|_|_|_|_|W|_',
'B|_|_|_|_|_|_|W']
def parse_board(board):
def map_black(spot):
return str(int(spot == 'B'))
def map_white(spot):
return str(int(spot == 'W'))
blackInit = '0b'
whiteInit = '0b'
for line in board:
squares = line.split('|')
blackInit = blackInit + ''.join(map(map_black,squares))
whiteInit = whiteInit + ''.join(map(map_white,squares))
return (blackInit,whiteInit)
print(parse_board(board1))
print(parse_board(board2))
print(parse_board(board3))
print(parse_board(board4))
print(parse_board(board5))发布于 2012-08-01 14:10:09
def parse_board(board):
def map_black(spot):这个名称表示函数是地图上的一个变体。而它实际上打算用作地图上的参数
return str(int(spot == 'B'))
def map_white(spot):
return str(int(spot == 'W'))两种功能都很相似,你能重构吗?
blackInit = '0b'
whiteInit = '0b'python样式指南建议局部变量名为“lowercase_with_underscores”。
for line in board:
squares = line.split('|')
blackInit = blackInit + ''.join(map(map_black,squares))
whiteInit = whiteInit + ''.join(map(map_white,squares))重复添加字符串并不是非常有效的python。
return (blackInit,whiteInit)你的功能中的每一件事都做了两次。一次是“B”,一次是“W”。我建议您应该有一个以'B‘或'W’为参数的函数,并将其调用两次。
我该怎么处理这件事:
def bitstring_from_board(board, letter):
bits = []
for line in board:
bits.extend( spot == letter for spot in line.split('|') )
return '0b' + ''.join(str(int(x)) for x in bits)
def parse_board(board):
return bitstring_from_board(board, 'B'), bitstring_from_board(board, 'W')https://codereview.stackexchange.com/questions/14187
复制相似问题