python - Why is the list appending the same element again and again?
问题描述
I am trying to solve this problem of finding the permutation of a given list using the code below. But, the list, final
keeps appending the same thing again and again. It should return [[1,2,3],[2,1,3],[2,3,1],[1,3,2],[3,1,2],[3,2,1]]
but instead it returns [[1,2,3],[1,2,3], [1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3]]
. I have been trying to fix this for a while now and would really appreciate your help.
class Solution(object):
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
self.final = []
l = 0
r = len(nums) -1
self.permutation(nums, l, r)
return self.final
def permutation(self, nums, l, r):
if l == r:
self.final.append(nums)
# print(nums)
print(self.final)
else:
for i in range(r+1):
nums[l], nums[i] = nums[i], nums[l]
self.permutation(nums, l+1, r)
nums[l], nums[i] = nums[i], nums[l]
A = Solution()
A.permute(['1','2','3'])
解决方案
您就地更改列表,而不是每次都创建新列表。您的最终列表最终包含对同一列表的引用。
一个解决方法是写
def permutation(self, nums, l, r):
if l == r:
self.final.append(nums.copy())
# instead of self.final.append(nums)
注意:itertools.permutations
会为你做这项工作。
这篇文章可能有助于了解这里发生了什么。
正如评论中提到的:你仍然没有得到所有的排列。这可能对你有用:
def permutation(self, nums, k):
r = [[]]
for i in range(k):
r = [[a] + b for a in nums for b in r if a not in b]
self.final = r
推荐阅读
- macos - 如何在 macOS 上安装 libarchive 并让编译器检测到它?
- sql - TERADATA SQL-如何在数据中查找序列
- java - 如何将浮点数组传递给 LWJGL 中的着色器
- node.js - 运行 webpack 抛出“回调已被调用”错误
- javascript - 如何从 JS 数组中删除不同类型的空值(元素)
- php - 如何从数据库中获取项目的ID
- python - 如何使用服务帐户生成的密钥进行身份验证使用 googleapi 客户端
- python - 如果需要,迭代 Pandas 系列中的值以替换值
- c# - 将滑块值从 jQuery 传递到后面的代码
- c++ - 这是定义一组递归规则的正确方法吗?