代码之家  ›  专栏  ›  技术社区  ›  Bryce Guinta

这个很长的if语句怎么能简化呢?

  •  6
  • Bryce Guinta  · 技术社区  · 14 年前

    http://i.stack.imgur.com/PtHO1.png

    如果语句完成,则在x和y坐标处设置一个块。

    for y in range(MAP_HEIGHT):
        for x in range(MAP_WIDTH):
            if (x%5 == 2 or x%5 == 3 or x%5 == 4) and \
                (y%5 == 2 or y%5 == 3 or y%5 == 4) and \
                not(x%5 == 2 and y%5 == 2) and \
                not(x%5 == 4 and y%5 == 2) and \
                not(x%5 == 2 and y%5 == 4) and \
                not(x%5 == 4 and y%5 == 4):
                ...
    
    6 回复  |  直到 14 年前
        1
  •  15
  •   David Webb    14 年前

    这是一样的:

    if (x % 5 == 3 and y % 5 > 1) or (y % 5 == 3 and x % 5 > 1): 
    
        2
  •  12
  •   martineau    14 年前

    基本上你是平铺一个5x5二进制模式。这里有一个明确的表达:

    pattern = [[0, 0, 0, 0, 0],
               [0, 0, 0, 0, 0],
               [0, 0, 0, 1, 0],
               [0, 0, 1, 1, 1],
               [0, 0, 0, 1, 0]]
    
    for y in range(MAP_HEIGHT):
        for x in range(MAP_WIDTH):
            if pattern[x%5][y%5]:
               ...
    

    这是一种非常简单和通用的方法,可以很容易地修改模式。

        3
  •  7
  •   Konrad Rudolph    14 年前

    • 缓存的结果 x % 5 y % 5
    • 使用 in 或是链子 <

    另外,测试 <= 4 (或 < 5 每一个 lx ly

    for y in range(MAP_HEIGHT):
        for x in range(MAP_WIDTH):
            lx = x % 5 # for local-x
            ly = y % 5 # for local-y
            if lx > 1 and y > 1 and \
               not (lx == 2 and ly == 2) and \
               not (lx == 4 and ly == 2) and \
               not (lx == 2 and ly == 4) and \
               not (lx == 4 and ly == 4):
    

    或者您可以保留一个实际允许的元组的列表:

    cross_fields = [(2, 3), (3, 2), (3, 3), (3, 4), (4, 3)]
    
    for y in range(MAP_HEIGHT):
        for x in range(MAP_WIDTH):
            if (x % 5, y % 5) in cross_fields:
    
        4
  •  2
  •   Daniel Roseman    14 年前

    基于Konrad的答案,您可以进一步简化它:

    for y in range(MAP_HEIGHT):
        for x in range(MAP_WIDTH):
            lx = x % 5 # for local-x
            ly = y % 5 # for local-y
            if (1 < lx < 5 and 1 < y < 5 and 
               (lx, ly) not in ((2, 2), (4, 2), (2, 4), (4, 2))):
    
        5
  •  1
  •   Iain Galloway    14 年前

    cross_fields = [(2, 3), (3, 2), (3, 3), (3, 4), (4, 3)]
    
    for y in range(MAP_HEIGHT):
      for x in range(MAP_WIDTH):
        if (x % 5, y % 5) in cross_fields:
    

    可能是最好的。

    不过,我会贡献:-

    for y in range(MAP_HEIGHT):
      for x in range(MAP_WIDTH):
        lx = x % 5
        ly = y % 5
        if (lx > 1 and ly == 3) or (ly > 1 and lx == 3):
    
        6
  •  0
  •   Ben Jackson    14 年前

    Karnaugh map . 您的truth表将是您想要的文字加形状,行和列是您的模块化测试。