【问题标题】:How to randomly place symbols in a grid? - Python 3.4.3如何在网格中随机放置符号? - Python 3.4.3
【发布时间】:2015-10-24 13:34:27
【问题描述】:

假设我有一个 7x7 网格:

. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .

如何将 0 随机放置在网格中任意位置的 3 行/列中?

. . . . . . .
. . . . . . .
. . 0 0 0 . .
. . . . . . .
. . . . . 0 .
. . . . . 0 .
. . . . . 0 .

【问题讨论】:

  • 你需要多少块?它们可以重叠吗?
  • 您能展示一下您目前编写的任何代码吗?

标签: python


【解决方案1】:

你随机化方向...水平或垂直。 然后为“000”的位置随机化两个数字,但要根据方向进行。一个数字在范围 (0, 7) 内,另一个数字在范围 (0, 7-3) 内。 “-3”部分是为了让它不会被放在棋盘之外。

这是一些python代码...

from random import randint

def place_randomly(grid):
    orientation = ['h', 'v'][randint(0, 1)] #randomly choose orientation

    if orientation == 'h':
        x = randint(0, 4)
        y = randint(0, 6)
        grid[y][x] = grid[y][x+1] = grid[y][x+2] = '0'
    elif orientation == 'v':
        x = randint(0, 6)
        y = randint(0, 4)
        grid[y][x] = grid[y+1][x] = grid[y+2][x] = '0'
    print "XY:", x, y

def print_grid(grid):
    for i in grid:
        for j in i:
            print j,
        print ""

for i in range(10): # try it out 10 times
    grid = [['.' for x in range(7)] for x in range(7)]
    place_randomly(grid)
    print_grid(grid)
    print ""

【讨论】:

    猜你喜欢
    • 2022-01-14
    • 2013-11-21
    • 2014-10-10
    • 1970-01-01
    • 1970-01-01
    • 2019-05-12
    • 1970-01-01
    • 2011-01-28
    • 2012-12-26
    相关资源
    最近更新 更多