【问题标题】:Cleaning up IF statements Python清理 IF 语句 Python
【发布时间】:2021-03-12 14:54:36
【问题描述】:

我正在尝试清理我的 if 语句,我们正在做一个小组项目,我的同行说这段代码看起来太混乱了。请给我一些关于缩短或清理它的提示,代码目前看起来像这样;

for r in range(n):
        for col in range(n):
 
            # Skip, if it contains a mine
            if numbers[r][col] == -1:
                continue
 
            # Check up  
            if r > 0 and numbers[r-1][col] == -1:
                numbers[r][col] = numbers[r][col] + 1
            # Check down    
            if r < n-1  and numbers[r+1][col] == -1:
                numbers[r][col] = numbers[r][col] + 1
            # Check left
            if col > 0 and numbers[r][col-1] == -1:
                numbers[r] = numbers[r] + 1
            # Check right
            if col < n-1 and numbers[r][col+1] == -1:
                numbers[r][col] = numbers[r][col] + 1
            # Check top-left    
            if r > 0 and col > 0 and numbers[r-1][col-1] == -1:
                numbers[r][col] = numbers[r][col] + 1
            # Check top-right
            if r > 0 and col < n-1 and numbers[r-1][col+1]== -1:
                numbers[r][col] = numbers[r][col] + 1
            # Check below-left  
            if r < n-1 and col > 0 and numbers[r+1][col-1]== -1:
                numbers[r][col] = numbers[r][col] + 1
            # Check below-right
            if r < n-1 and col< n-1 and numbers[r+1][col+1]==-1:
                numbers[r][col] = numbers[r][col] + 1

【问题讨论】:

    标签: python-3.x if-statement code-cleanup


    【解决方案1】:

    鉴于问题的限制,您的解决方案是合理的。但是,如果你想安抚你的同行,你可以尝试这样的事情。它唯一真正的优点是它将识别有效相邻单元格的关注与增加单元格计数器的关注分开。通过分离关注点,理论上您可以将相邻的单元生成器重用于其他目的,并且更容易调试一个或其他关注点。

    def iter_adjacent_cells(r, c, n):
        for rd in range(-1,2):
            for cd in range(-1,2):
                # skip the current cell
                if rd == 0 and cd == 0:
                    continue
                if 0 <= r + rd < n and 0 <= c + cd < n:
                    yield r + rd, c + cd
    
    for r in range(n):
        for c in range(n):
     
            # Skip, if it contains a mine
            if numbers[r][c] == -1:
                continue
    
            for ar, ac in iter_adjacent_cells(r, c, n):
                if numbers[ar][ac] == -1:
                    numbers[r][c] += 1
    

    【讨论】:

      猜你喜欢
      • 2017-06-06
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 2022-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-05
      相关资源
      最近更新 更多