python - 代码不返回排列
问题描述
我已经编写了 python 代码来排列数字列表。
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]]
我认为这与范围界定有关,但我不知道我做错了什么以使列表不返回任何内容。
解决方案
当您附加chosen
到 self.permutations 时,您在事后所做的任何更改也chosen
将影响self.permutations
. 通过稍后调用chosen.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]]
chosen
您可以附加to的浅表副本self.permutations
,在这种情况下,chosen
之后对self.permutations
.
if nums == []:
print chosen
self.permutations.append(chosen[:])
结果:
[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]]
推荐阅读
- javascript - 根据标签在页面上创建导航/指标
- c - IORING_ENTER_SQ_WAKEUP - 对“io_uring_enter”的未定义引用
- javascript - 未捕获的 ReferenceError:函数未在 HTMLDivElement.onclick 中定义
- r - Rmarkdown 文件不是编织的,它不允许执行 for 循环
- nlp - ValueError:使用 MFCC 提取特征时,无法使用“常量”或“空”以外的模式扩展空轴 0
- python - 使用 AWS Lambda 函数将 .txt 转换为 .csv
- azure - .NET Core 3.1 的应用程序洞察实时指标没有数据
- jquery - 第一次ajax成功后,jquery Ajax徽标删除不起作用Laravel 7 jquery
- linux - 我正在尝试将 I2C 与 beaglebone 一起使用,但我不能写入超过 1 个字节
- java - 求解 N=N+1 Java 算法