回溯创建正方形

a = []

def make_squares(arr, length, nums):

    if not nums:

        print(arr)

        a.append(arr)

        return

    r = 0

    while r < len(arr) and len(arr[r]) == length:

        r += 1

    for i in nums:

        nums.remove(i)

        arr[r].append(i)

        make_squares(arr, length, nums)

        nums.append(i)

        arr[r] = arr[r][:-1]

make_squares([[] for i in range(3)], 3, [i+1 for i in range(3**2)])

print(a)

我正在尝试使用上面的代码创建nxn矩阵,每个矩阵都有一个 numbers 的排列i+1...n^2。我已经打印了每个附加到 a 的矩阵,它们看起来是正确的,但是当我最后打印 a 时,我得到了[[[], [], []], [[], [], []], ...]。这对我来说没有任何意义。


预期的结果是


[[[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[1, 2, 3], [4, 5, 6], [7, 9, 8]], ...]


慕容708150
浏览 97回答 1
1回答

紫衣仙女

顺序可能与您预期的结果不同,但这对标准库itertools模块来说是个窍门:import itertoolsdef make_squares(w):&nbsp; &nbsp; size = w * w&nbsp; &nbsp; for perm in itertools.permutations(range(1, size + 1)):&nbsp; &nbsp; &nbsp; &nbsp; # "grouper" from the itertools recipe list&nbsp; &nbsp; &nbsp; &nbsp; yield list(itertools.zip_longest(*[iter(perm)] * w))for square in make_squares(3):&nbsp; &nbsp; print(square)印刷[(1, 2, 3), (4, 5, 6), (7, 8, 9)][(1, 2, 3), (4, 5, 6), (7, 9, 8)][(1, 2, 3), (4, 5, 6), (8, 7, 9)][(1, 2, 3), (4, 5, 6), (8, 9, 7)][(1, 2, 3), (4, 5, 6), (9, 7, 8)][(1, 2, 3), (4, 5, 6), (9, 8, 7)][(1, 2, 3), (4, 5, 7), (6, 8, 9)][(1, 2, 3), (4, 5, 7), (6, 9, 8)][(1, 2, 3), (4, 5, 7), (8, 6, 9)][(1, 2, 3), (4, 5, 7), (8, 9, 6)][(1, 2, 3), (4, 5, 7), (9, 6, 8)][(1, 2, 3), (4, 5, 7), (9, 8, 6)][(1, 2, 3), (4, 5, 8), (6, 7, 9)][(1, 2, 3), (4, 5, 8), (6, 9, 7)][(1, 2, 3), (4, 5, 8), (7, 6, 9)]...
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python