在 Python 中对数组进行打乱
假设我们有一个数组 A,我们必须对一组不重复的数字进行打乱。因此,如果输入是 [1,2,3],那么对于打乱,它将是 [1,3,2],重置后,如果我们再次打乱,它将是 [2,3,1]
为了解决这个问题,我们将遵循以下步骤 −
将有不同的方法。这些是 init()、reset()、shuffle()。这些将像下面的 −
init 将像 −
original := 给定数组的副本
temp := nums
indices := 从 0 到 nums 长度的数字列表 – 1
reset() 将返回原始数组
shuffle() 将类似于 −
如果 temp 的长度为 0,则返回空数组
i := 从 indices 数组中随机选择一个索引,j := 从 indices 数组中随机选择另一个索引
交换索引 i 和 j 处的元素
返回 temp
另一个名为 getAllPermutation() 的方法将采用 nums,i,最初 i = 0,将类似于 −
curr := i
如果 i = nums 的长度,则
将 nums 数组的副本插入另一个名为 all 的数组
返回
for j := curr to length of nums
将索引 j 处的元素与 nums 中的 curr 交换
call getAllPermutation(nums, curr + 1)
将索引 j 处的元素与 nums 中的 curr 交换
让我们看看下面的实现以便更好地理解 −
示例
import random class Solution(object): def __init__(self, nums): self.original = [x for x in nums] self.temp = nums self.indices = [x for x in range(len(nums))] def reset(self): return self.original def shuffle(self): if not len(self.temp): return [] i = random.choice(self.indices) j = random.choice(self.indices) self.temp[i], self.temp[j] = self.temp[j], self.temp[i] return self.temp ob = Solution([1,2,3]) print(ob.shuffle()) print(ob.reset()) print(ob.shuffle())
输入
Initialize with [1,2,3] , then call shuffle(), reset() and shuffle()
输出
[2, 1, 3] [1, 2, 3] [2, 3, 1]
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

