为了账号安全,请及时绑定邮箱和手机立即绑定

回溯创建正方形

回溯创建正方形

慕容708150 2023-02-22 15:49:49
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]], ...]
查看完整描述

1 回答

?
紫衣仙女

TA贡献1839条经验 获得超15个赞

顺序可能与您预期的结果不同,但这对标准库itertools模块来说是个窍门:


import itertools


def make_squares(w):

    size = w * w

    for perm in itertools.permutations(range(1, size + 1)):

        # "grouper" from the itertools recipe list

        yield list(itertools.zip_longest(*[iter(perm)] * w))


for square in make_squares(3):

    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)]

...


查看完整回答
反对 回复 2023-02-22
  • 1 回答
  • 0 关注
  • 96 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信