我正在寻找关于微观(单个代码行)和宏(总体设计)规模的评论。我的输入/输出格式是一个字符串,换行符分隔行,'*'/' '分别表示活动和死。
from itertools import product
from enum import Enum
class Direction(Enum): forwards = 1; backwards = 0
class State:
table = {'*':True, ' ':False}
def convert(self, grid, direction):
if direction == Direction.forwards:
table = self.table
elif direction == Direction.backwards:
table = {value:key for (key,value) in self.table.items()}
else:
raise ValueError("Invalid conversion direction!")
return [[table[x] for x in row] for row in grid]
def __init__(self, grid):
grid = list(filter(None, grid.split('\n')))
self.rows = len(grid); self.cols = len(grid[0])
if not all(len(grid[i]) == self.cols for i in range(self.rows)):
raise ValueError("Invalid game state!")
self.grid = self.convert(grid, Direction.forwards)
def __getitem__(self, i):
return self.grid[i]
def __str__(self):
return '\n'.join(map(lambda x: ''.join(x), self.convert(self.grid, Direction.backwards)))
def game(state):
''' Takes a state in the input format and yields states in the output format. '''
state = State(state)
def alive(x,y):
try:
return state[x][y]
except IndexError:
return False
while True:
state.grid = [
[2 <= sum(alive(xx,yy) for xx, yy in product([x-1,x+1], [y-1,y+1])) <= 3
for (y,col) in enumerate(row)]
for (x,row) in enumerate(state.grid)
]
yield str(state)发布于 2017-06-20 03:22:57
例如,替换:
from itertools import product
from enum import Enum
class Direction(Enum): forwards = 1; backwards = 0通过
from itertools import product
from enum import Enum
class Direction(Enum):
forwards = 1
backwards = 0关于执行情况:
当您提出例外时,请始终给出原因:
raise ValueError("Invalid conversion direction {0!r}! Only backwards or forwards.".format(direction))事实上,convert()函数可以被“保护”,因为它不是在类之外使用的,而且没有必要检查方向值是否是来回的。
按照惯例,您可以将alive函数重命名为is_alive,因为它是一个谓词(它返回布尔值)。这个函数应该是State类的一个方法,因为它使用state变量。
出于同样的原因,game函数也应该是一个方法。我不喜欢它的名字,因为我们无法理解它是一个发电机。像next_state这样的东西可能会更好。
最后,计算sum的alive()值,这些值是布尔值。我认为这是一种糟糕的做法:最好使用0和1。
https://codereview.stackexchange.com/questions/166177
复制相似问题