6

我正在尝试简化我对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)
4

2 回答 2

3

要遵循不要重复自己的规则,您可以拉出方向逻辑:

def sub_lists_at_xy(array, length, x, y):
    directions = [(1, 0), (0, 1), (1, 1), (-1, 1)]
    sublists = []
    for dx, dy in directions:
        try:
            seq = [array[y+dy*i][x+dx*i] for i in range(length)]
            sublists.append(seq)
        except IndexError:
            pass
    return sublists

你可能想检查一下我没有弄错方向——我通常会到处犯错误——但你明白了。

[注意:这不是我自己会这样做的方式,而是我会简化您的代码的方式。]

于 2012-07-28T00:35:24.423 回答
2

你可以检查输入,但你也可以填充你的数组

with open("11.txt") as f:
    nums = [["X"] + [int(num) for num in line.split(' ')] + ["X"] for line in f.read().split('\n')]
    nums = ["X"]*(len(nums[0])+2) + nums + ["X"]*(len(nums[0])+2)

然后您可以过滤您的数据

reduce(mul, [x for x in lst if x != "X"], 1)
于 2012-07-28T00:15:10.953 回答