【问题标题】:How to make a chessboard pattern with a nested loop?如何使用嵌套循环制作棋盘图案?
【发布时间】:2015-11-11 02:02:24
【问题描述】:

我需要制作一个看起来像这样的模式:

1 0 1 0 1 0 1 0

0 1 0 1 0 1 0 1

1 0 1 0 1 0 1 0

0 1 0 1 0 1 0 1

1 0 1 0 1 0 1 0

0 1 0 1 0 1 0 1

1 0 1 0 1 0 1 0

0 1 0 1 0 1 0 1

到目前为止,我只能用它们制作对角线,但我需要一些帮助来了解如何做到这一点。

到目前为止我的代码:

dimension = int(input('Enter dimension of board: '))

if dimension < 2:    
    print('Invalid input')    
else:
    for r in range(dimension):
        for c in range(dimension):
            print(int(c == r), end=' ')
        print()

【问题讨论】:

    标签: python loops for-loop nested


    【解决方案1】:

    (c + r + 1) % 2 应该可以代替 int(c==r)

    【讨论】:

      【解决方案2】:

      这应该会让你到达你想去的地方。

      for r in range(dimension):
          for c in range(dimension):
              print(int((c + r + 1) % 2), end=' ')
          print()
      

      【讨论】:

        【解决方案3】:

        这将为您提供所需的电路板输出:

        def printBoard(dimensions):
            for row in range(dimensions**2):
                if row % dimensions == 0 and row != 0:
                    print()
                    print((row + 1) % 2, end=' ')
                else:
                    print((row + 1) % 2, end=' ')
        

        【讨论】:

        • 这在dimensions 是偶数时不能正常工作:所有行都以'1'开头。
        【解决方案4】:

        这是巴拉比技术的一种变体。它使用嵌套列表推导来构造偶数行和奇数行,然后使用str.join 方法将每行的单元格连接成一个字符串。 make_board 函数返回一个行字符串列表,这些行字符串连接成一个字符串,以便使用另一个 .join 调用进行打印。

        def make_board(side):
            r = range(side)
            rows = [' '.join(['01'[(i + p) % 2] for i in r]) for p in (1, 0)]
            return [rows[i % 2] for i in r]
        
        # Test
        for i in range(0, 9):
            board = make_board(i)
            print('{0}:\n{1}\n'.format(i, '\n'.join(board)))
        

        输出

        0:
        
        
        1:
        1
        
        2:
        1 0
        0 1
        
        3:
        1 0 1
        0 1 0
        1 0 1
        
        4:
        1 0 1 0
        0 1 0 1
        1 0 1 0
        0 1 0 1
        
        5:
        1 0 1 0 1
        0 1 0 1 0
        1 0 1 0 1
        0 1 0 1 0
        1 0 1 0 1
        
        6:
        1 0 1 0 1 0
        0 1 0 1 0 1
        1 0 1 0 1 0
        0 1 0 1 0 1
        1 0 1 0 1 0
        0 1 0 1 0 1
        
        7:
        1 0 1 0 1 0 1
        0 1 0 1 0 1 0
        1 0 1 0 1 0 1
        0 1 0 1 0 1 0
        1 0 1 0 1 0 1
        0 1 0 1 0 1 0
        1 0 1 0 1 0 1
        
        8:
        1 0 1 0 1 0 1 0
        0 1 0 1 0 1 0 1
        1 0 1 0 1 0 1 0
        0 1 0 1 0 1 0 1
        1 0 1 0 1 0 1 0
        0 1 0 1 0 1 0 1
        1 0 1 0 1 0 1 0
        0 1 0 1 0 1 0 1
        

        【讨论】:

          【解决方案5】:
          #List comprehension can be used here.
          def print_board():
              n=int(input('Enter dimension of board: '))
              row=[[(x+1)%2 for x in range(n)], [x%2 for x in range(n)]] 
              board=[row[x%2] for x in range(n)]  
              for r in board:
                  for c in r: print(c, end=' ')
                  print(' ')
          

          【讨论】:

          • 这行得通,尽管它使左上角为“0”而不是“1”。
          【解决方案6】:

          我知道,可能有点晚了,但这里有一个非常通用且同时快速的解决方案:

            1 import numpy as np
            2 import matplotlib.pyplot as plt
            3 import time
            4 from PIL import Image
            5 import os
            6
            7 def divmod_max_into(div_mod):
            8     if div_mod[1] > 0:
            9         return div_mod[0] + 1
           10     else:
           11         return div_mod[0]
           12 def create_chessboard(dim_x, dim_y, cube_size):
           13     start = time.time()
           14     light_grey = 230
           15     dark_grey = 90
           16     divmod_x_cube = divmod(dim_x, cube_size*2)
           17     divmod_y_cube = divmod(dim_y, cube_size*2)
           18     large_cube = np.full([cube_size*2, cube_size*2], False)
           19     large_cube[:cube_size, :cube_size] = True
           20     large_output = np.tile(large_cube, (divmod_max_into(divmod_x_cube), divmod_max_into(divmod_y_cube)))
           21     large_output = np.transpose(large_output) + large_output == 2
           23     output = np.full(large_output.shape, dark_grey, dtype=np.uint8)
           24     output[large_output] = 230
           25     print("Execution took {:.6f} seconds!".format(time.time()-start))
           26     return output[:dim_x, :dim_y]
           27
           28 Image.fromarray(create_chessboard(5000, 5000, 3)).save(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'out.tif'))
          

          您还可以定义应该重复的立方体的大小。在我的 PC 上创建 5000x5000 阵列大约需要 0.74 秒。

          如果有不清楚的地方,请随时提问。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2022-11-04
            • 2021-05-10
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-10-10
            • 2021-07-07
            相关资源
            最近更新 更多