usage of the append function of list in python -


class solution:         # @param num, list of integer     # @return list of lists of integers         def permute(self, num):             self.res = [];             self.dfs(num, 0)             return self.res          def dfs(self, num, level):             if level == len(num):                 self.res.append(num)                 print(num)                 return             in range(level, len(num)):                 num[i], num[level] = num[level], num[i]                 self.dfs(num, level+1)                 num[i], num[level] = num[level], num[i] 

the above code used generate permutations given collection of numbers. example, num = [1, 3] result be: [1 3], [3, 1]

but there bug above code don't understand, self.res.append(num). if change self.res.append(num[:]), code correct. can explain why?

using self.res.append(num), result is:

[1, 3], [1, 3]

using self.res.append(num[:]), result is:

[1, 3], [3, 1]

the elements of python list references other objects. when append using self.res.append(num), list grown 1 element, , last element set refer object pointed num.

now in first case, there 2 references same list object. self.res[0] , self.res[1] refer same object, changes performed through either visible through other.

in second case, using num[:], [:] operator makes new list copy of original.


for general algorithm creating permutations of given collection of elements, use itertools.permutations:

>>> itertools import permutations >>> print(list(permutations([1, 3]))) [(1, 3), (3, 1)] 

Comments

Popular posts from this blog

php - render data via PDO::FETCH_FUNC vs loop -

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

The canvas has been tainted by cross-origin data in chrome only -