Python 不返回置换的代码
我已经编写了python代码来排列数字列表Python 不返回置换的代码,python,math,scope,permutation,Python,Math,Scope,Permutation,我已经编写了python代码来排列数字列表 class Solution: def __init__(self): self.permutations = [] def permute_helper(self, nums, chosen): if nums == []: print chosen self.permutations.append(chosen) else:
class Solution:
def __init__(self):
self.permutations = []
def permute_helper(self, nums, chosen):
if nums == []:
print chosen
self.permutations.append(chosen)
else:
for num in nums:
#choose
chosen.append(num)
temp = nums[:]
temp.remove(num)
#explore
self.permute_helper(temp, chosen)
#un-choose
chosen.remove(num)
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
self.permute_helper(nums, [])
return self.permutations
s = Solution()
input = [1,2,3]
print s.permute(input)
它返回:
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]
[[], [], [], [], [], []]
我希望所有的排列都像这样出现在返回的列表中
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
我认为这与范围界定有关,但我不知道我做错了什么,使列表不返回任何内容。当您将self.permutations附加到self.permutations后,您对self.permutations所做的任何更改也将影响self.permutations的每个元素。稍后通过调用selected.remove,您也可以从self.permutations中删除数字。考虑这个简单的例子:
>>> a = [1,2,3]
>>> b = []
>>> b.append(a)
>>> b.append(a)
>>> b.append(a)
>>> a.remove(2)
>>> b
[[1, 3], [1, 3], [1, 3]]
您可以将Selected的浅层副本附加到self.permutations,在这种情况下,之后对Selected所做的更改将不会对self.permutations产生影响
结果:
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
知道itertools已经有了一个随时可用的置换函数,这有帮助吗?或者这是我必须自己编写的情况之一?这是我必须自己编写的情况之一。排列算法有效,只是我的代码存在范围问题。我们不应该教list.copy而不是list[:]吗?它更清晰,而且只慢了一点。@MegaIng,当然,复制是一种很好的方法,只要您的Python版本支持它。我怀疑OP仍在使用2.7,所以我采用了旧的方法。
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]