我正在尝试简化我对Project Euler 问题 11 的解决方案(在 20x20 网格中找到 4-in-a-row 数字的最大乘积)。
我对我的回答的主要抱怨是 sub_lists_at_xy 定义中的四个 try/except 子句。我在每个方向(东、南、东南和西南)都有一个 4 行列表,这些列表可能会超出董事会。你对简化或干燥这个实现有什么建议吗?
from operator import mul
with open("11.txt") as f:
nums = [[int(num) for num in line.split(' ')] for line in f.read().split('\n')]
def prod(lst):
return reduce(mul, lst, 1)
def sub_lists_at_xy(array, length, x, y):
try:
east=array[y][x:x+length]
except IndexError:
east=[0]*length
try:
south=[list[x] for list in array[y:y+length]]
except IndexError:
south=[0]*length
try:
southeast=[array[y+i][x+i] for i in range(length)]
except IndexError:
southeast=[0]*length
try:
southwest=[array[y+i][x-i] for i in range(length)]
except IndexError:
southwest=[0]*length
return east, south, southeast, southwest
sub_lists=[]
for x in range(len(nums[0])):
for y in range(len(nums)):
sub_lists += sub_lists_at_xy(nums, 4, x, y)
best = max(prod(lst) for lst in sub_lists)
print(best)