自下而上的最小变化算法问题

时间:2019-03-21 21:50:27

标签: python-3.x algorithm repeat

我正在尝试获取数字4的所有排列,例如1,12,21,123,132,... 1234,1243,1423,4123,... ect(有24个),我们必须使用底部的最小变化算法,但是在我的代码中应该继续前进时,它陷入了1,2和2,1的状态,所以我想知道是否有人可以提供帮助。我的代码是一种您调用并给出数字的方法,然后它应该给您返回所有排列的列表。所有打印语句都需要调试,因此最终它们将不在那里。任何帮助都将是惊人的!谢谢

def min_change(num):
    end=[]
    A=[]
    for i in range(1,num):
        A.append(i)
        print("appened i",A)
        end.append(A)

        for j in end:
            print("entered j",j)
            if len(j)==i:
                print("made past if")
                if len(j)!=1:             
                    x=len(j)-1
                    while x>0:
                        print("this is x ",x)
                        B=A
                        end.append(B)
                        temp=B[x-1]
                        B[x-1]=B[x]
                        B[x]=temp
                        print(B)
                        x=x-1

    return end 

1 个答案:

答案 0 :(得分:-2)

您可以将itertools用于该任务:

# Option 1.
list(it.chain(*(it.permutations(range(1, i+1)) for i in range(1, 5))))

# Option 2.
list(j for i in range(1, 5) for j in it.permutations(range(1, i+1)))

输出是33种可能的排列:

[(1,),
 (1, 2),
 (2, 1),
 (1, 2, 3),
 (1, 3, 2),
 (2, 1, 3),
 (2, 3, 1),
 (3, 1, 2),
 (3, 2, 1),
 (1, 2, 3, 4),
 (1, 2, 4, 3),
 (1, 3, 2, 4),
 (1, 3, 4, 2),
 (1, 4, 2, 3),
 (1, 4, 3, 2),
 (2, 1, 3, 4),
 (2, 1, 4, 3),
 (2, 3, 1, 4),
 (2, 3, 4, 1),
 (2, 4, 1, 3),
 (2, 4, 3, 1),
 (3, 1, 2, 4),
 (3, 1, 4, 2),
 (3, 2, 1, 4),
 (3, 2, 4, 1),
 (3, 4, 1, 2),
 (3, 4, 2, 1),
 (4, 1, 2, 3),
 (4, 1, 3, 2),
 (4, 2, 1, 3),
 (4, 2, 3, 1),
 (4, 3, 1, 2),
 (4, 3, 2, 1)]