简体   繁体   English

在 Python 中实现堆的排列算法

[英]Implementing Heap's Algorithm for Permutations in Python

I'm trying to implement Heap's algorithm in python, but having trouble with it repeating some of the solutions.我正在尝试在 python 中实现 Heap 的算法,但是在重复某些解决方案时遇到了麻烦。 I'm stumped with where the bug is at.我对错误所在的位置感到困惑。 Here is the implementation:这是实现:

import copy

def _permute(l, n):
    if n == 1:
        print(l)
    else:
        for i in range(n - 1):
            # note: must copy here, or all answers will be same
            new_arr = copy.copy(l)
            _permute(new_arr, n - 1)

            if n % 2 == 0:
                l[i], l[n - 1] = l[n - 1], l[i]
            else:
                l[0], l[n - 1] = l[n - 1], l[0]

        _permute(l, n - 1)

For the input [0, 1, 2] and 3 , I get:对于输入[0, 1, 2]3 ,我得到:

[0, 1, 2]
[1, 0, 2]
[2, 1, 0]
[1, 2, 0]
[0, 1, 2] ** repeats from first answer **
[1, 0, 2] ** repeats from second answer **

With the last 2 results, repeating from first and second, missing:最后 2 个结果,从第一个和第二个重复,丢失:

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

I've searched multiple places and tried different implementations of this algorithm, but no matter how many times I try, I can't seem to get it to work.我搜索了多个地方并尝试了该算法的不同实现,但无论我尝试多少次,我似乎都无法让它工作。 What am I missing?我错过了什么?

You were placing your recursive call in the wrong place, this should do the trick (and you shouldn't use the copy):您将递归调用放在错误的位置,这应该可以解决问题(并且您不应该使用副本):

def _permute(l, n):
    if n == 1:
        print(l)
    else:
        _permute(l, n - 1)
        for i in range(n - 1):
            if n % 2 == 0:
                l[i], l[n - 1] = l[n - 1], l[i]
            else:
                l[0], l[n - 1] = l[n - 1], l[0]

            _permute(l, n - 1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM