Question 1. Int and list are different

 

> > > a = 1 > > > = a > b > > a + = 1 > > > a, b (2, 1) > > > a = [1, 2, 3, 4] > > > = a > b > > a + = [5] > > > a, b ([1, 2, 3, 4, 5], [1, 2, 3, 4, 5])Copy the code

 

In layman’s terms, a and b are “different” when the type is int; When the type is list, a and B are “the same”. The terms are called immutable and mutable, and the exact principles need not be explored at this point. Question 1.1. When we run the statement b=a, we intuitively assume that B and A are different.

>>> a=[[1],[2],[3],[4]] >>> b+=a[0:2] >>> b [1, 2, 3, 4, [1], [2]] >>> a=[[1],[2],[3],[4]] >>> b=[] >>> b+=a[0:2] >>> a,b ([[1], [2], [3], [4]], [[1], [2]]) >>> b[0] [1] >>> b[0][0]='changed! ' >>> # You don't expect a to change >>> # However >>> a, b ([['changed!'], [2], [3], [4]], [['changed!'], [2]])Copy the code

It can be seen that the [1] of a[0] is “the same” as the [1] of B [0], since changing B [0] changes A [0]. A +b =a+b =a+b =a+b =a+b

> > > a = [1, 2, 3, 4] > > > = a > b > > a + = [5] > > > a, b ([1, 2, 3, 4, 5], [1, 2, 3, 4, 5]) > > > a = [1, 2, 3, 4] > > > = a > b > > a = a + [5] > > > a, b ([1, 2, 3, 4, 5], [1, 2, 3, 4])Copy the code

In the same colloquial way, in the case of +=, a is the same as B; In the case of +, A is no longer the same as B. Question 3. What should be done if += and + behave the same?

> > > import copy > > > a = [1, 2, 3, 4] > > > b = copy. Deepcopy (a) > > > a + = [5] > > > a, b ([1, 2, 3, 4, 5], [1, 2, 3, 4])Copy the code

This is consistent with the case where a=a+b in problem 2. When b=a is applied to a list, you are actually “referencing” it; Only using b= copy.deepCopy (a) is the “copy” operation that we would normally expect. Question 4. Back to the code in question, when k=1, the following code:

subset += (elements[0:size])
Copy the code

According to Question 1.1, subset and Elements are “the same”, so future operations that change elements of a subset may change elements of Elements.

When you get to this line of code, note that set is a subset passed recursively:

#set[j] +=  (elements[i])  #Why Elements change here?
set[j]  = set[j] +  (elements[i]) 
Copy the code

[j] = set[j] = set[j] = set[j] so

set[j] += elements[i]
Copy the code

It might be equivalent to

elements[*] += elements[i]
Copy the code

Once you change the elements of elements, the result is wrong. How to solve this problem? According to question 3, it is logical for the program to ensure that set and Elements are “different.” So will

subset += (elements[0:size])
Copy the code

Change to (remember import copy)

subset += copy.deepcopy(elements[0:size])
Copy the code

I’m going to be able to work with +=. B =copy. Deepcopy (a); b=copy. Deepcopy (a); (The difference between copy. Copy and copy. Deepcopy is beyond the question.