如何从try / except混乱中干掉方向逻辑

时间:2012-07-28 00:05:27

标签: python

我试图将我的解决方案简化为Project Euler's problem 11(在20x20网格中找到最大的4行数字产品)。

我对答案的主要抱怨是sub_lists_at_xy定义中的四个try / except子句。我的每个方向(东,南,东南和西南)都有一个可以在板上运行的四排列表。您对简化或干预此实施有什么建议吗?

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)

2 个答案:

答案 0 :(得分: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

你可能想检查一下我的指示是否错误 - 我通常会在整个地方发出错误信号 - 但你明白了。

[注意:这不是我自己会怎么做的,但这就是我如何简化你的代码。]

答案 1 :(得分: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)