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

dyl*_*yln 6 python

我正在尝试简化我对Project Euler问题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)
Run Code Online (Sandbox Code Playgroud)

DSM*_*DSM 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
Run Code Online (Sandbox Code Playgroud)

你可能想检查一下我的指示是否有误——我通常会到处犯错误——但你明白了。

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