python - 如何列出具有 3 种不同状态的 3x3 板的所有可能性?

标签 python

我试图列出 3x3 网格的所有可能性,具有 3 种状态:0、1 和 2。棋盘采用列表格式,因此我们列出

[0,0,0,0,0,0,0,0,0], 
[1,0,0,0,0,0,0,0,0], 
[2,0,0,0,0,0,0,0,0], 
[0,1,0,0,0,0,0,0,0]

我试图通过这样计数来做到这一点:http://hastebin.com/ozapigageb.py ,但它导致计数由于某种原因只生成 1。我要么想知道一种更有效的方法,要么我做错了什么。提前感谢您的帮助。

最佳答案

你可以使用 itertools.product:

for board in itertools.product([0, 1, 2], repeat=9):
    ...

在您的代码中,您或多或少地实现了以 3 为基数的加法。您可以将每个单板表示为 0 和 3^9 - 1 = 19,682 之间的整数,并减少您的问题仅将基数 10 转换为基数 3:

def base_convert(n, base):
    if n == 0:
        return [0]

    digits = []

    while n:
        digits.append(n % base)
        n /= base

    return digits[::-1]

for n in range(3**9):
    digits = base_convert(n, 3)
    board = ([0, 0, 0, 0, 0, 0, 0, 0] + digits)[-9:]  # pad with 0s to 9 digits

    ...

关于python - 如何列出具有 3 种不同状态的 3x3 板的所有可能性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38448013/

相关文章:

python - 什么时候在 python 中使用 "_."

python - URL 在 Python 中编码一个非值对

python - 使用任意 wx 对象作为 wx.ListCtrl 中的列

python - 简单的解析器,但不是计算器

python - 如何在python中迭代列表的元组列表,并一一获取所有元素?

python - YIN算法到python寻找基频

python - replace() 方法不适用于 Pandas DataFrame

python - 如何在 PYTHON 中使用 CURL 命令

python - 如何在Python中使用zeep设置默认xmlns?

python - 每个 GPU 的 Nvenc session 限制