Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/350.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么循环置换会产生所有相同的值?_Python_Loops_While Loop_Permutation - Fatal编程技术网

Python 为什么循环置换会产生所有相同的值?

Python 为什么循环置换会产生所有相同的值?,python,loops,while-loop,permutation,Python,Loops,While Loop,Permutation,我正在编写一个函数来获取给定输入的所有排列: e、 g.输入:nums=[1,2,3] 输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] def permute(nums): permutation_set = [] pointer_stand = 0 pointer_runner = 0 permutation_set.append(nums) while pointer_stand < l

我正在编写一个函数来获取给定输入的所有排列:

e、 g.输入:nums=[1,2,3] 输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

def permute(nums):
    permutation_set = []
    pointer_stand = 0
    pointer_runner = 0
    permutation_set.append(nums)

    while pointer_stand < len(nums)-1:

        while pointer_runner < len(nums)-1:
            
            pointer_runner +=1
            nums[pointer_stand], nums[pointer_runner] = nums[pointer_runner], nums[pointer_stand]
            permutation_set.append(nums)

        pointer_stand += 1
        pointer_runner = pointer_stand


    return permutation_set
def排列(nums):
置换_集=[]
指针=0
指针\u runner=0
置换集合追加(nums)
当指针处于
我似乎看不出哪里出了问题,但我得到的输出是[[3,2,1],[3,2,1],[3,2,1],[3,2,1],[3,2,1],[3,2,1]]

def permute(nums):
    permutation_set = []
    pointer_stand = 0
    pointer_runner = 0
    permutation_set.append(nums)

    while pointer_stand < len(nums)-1:

        while pointer_runner < len(nums)-1:
            
            pointer_runner +=1
            nums[pointer_stand], nums[pointer_runner] = nums[pointer_runner], nums[pointer_stand]
            permutation_set.append(nums)

        pointer_stand += 1
        pointer_runner = pointer_stand


    return permutation_set
知道代码哪里错了吗?因为当我写出来的时候,它应该是有效的!谢谢


另外,我知道上面的代码并没有生成所有的排列,我仍然需要“旋转”原始输入以获得其余的排列,但根据我上面的问题,目前我无法交换每个索引。谢谢

我不知道你的代码为什么不起作用,但是你试过使用随机库吗?你可以直接使用python中的置换函数。与Python中的其他容器一样,列表存储对对象的引用。修改同一对象“nums”,并将多个引用附加到“置换集”。相反,总是创建一个带有“nums[:]”的浅拷贝并附加它。可能会解决你的问题和@MichaelButscher。迈克尔,我完全明白你在说什么——吸取了教训。