0
import random

class Solution(object):
    def __init__(self, nums):
        """
        :type nums: List[int]
        :type size: int
        """
        self.nums = nums

    def reset(self):
        """
        Resets the array to its original configuration and return it.
        :rtype: List[int]
        """
        return self.nums

    def shuffle(self):
        """
        Returns a random shuffling of the array.
        :rtype: List[int]
        """
        ret = list(self.nums)
        random.shuffle(ret)
        return ret

Why do we use ret = list(self.nums)? I tried to use ret = left.nums, but it doesn't pass through the LeetCode solution. I don't understand why we put list() in front of self.nums. My guess is that self.nums is already a list.

John Sun
  • 11
  • 1
  • 1
    Maybe using `self.nums.copy()` instead of `list(self.nums)` would carry more "meaning" while doing the same thing. – MSeifert Jan 16 '17 at 05:01

2 Answers2

1

Calling list() here will create a copy of self.nums (see How to clone or copy a list? ):

>>> l = [1, 2, 3]
>>> x = l
>>> l.append(4)
>>> x, l
([1, 2, 3, 4], [1, 2, 3, 4])
>>> y = list(l)
>>> l.append(5)
>>> y, l
([1, 2, 3, 4], [1, 2, 3, 4, 5])

This means that shuffle() leaves the underlying list of numbers untouched while returning a shuffled list (since random.shuffle() shuffles the input in place).

Keeping this list untouched allows the reset() method to work.

Community
  • 1
  • 1
johnsyweb
  • 136,902
  • 23
  • 188
  • 247
0

ret = list(self.nums) creates a new list since shuffle does a in place shuffle. So ret holds a copy of the original list which gets shuffled and returned and self.nums holds the contents of the original list.

Raviteja
  • 3,399
  • 23
  • 42
  • 69
sujit
  • 113
  • 9