Cannot assign to property: 'self' is immutableというエラーメッセージはSwiftで見られるもので、これはオブジェクトのプロパティや自身の値を変更しようとした際に、そのオブジェクトが不変(immutable)であることを示しています。具体的には、以下のような状況でこのエラーが発生することが一般的です:
def permutation(list, start, end):
if (start == end):
print list
else:
for i in range(start, end + 1):
list[start], list[i] = list[i], list[start] # The swapping
permutation(list, start + 1, end)
list[start], list[i] = list[i], list[start] # Backtracking
permutation([1, 2, 3], 0, 2) # The first index of a list is zero
import copy
_stack=[]
def permutation(list, start, end,count):
if (start == end):
print(list)
else:
for i in range(start, end + 1):
_backup=copy.copy(list);
list[start], list[i] = list[i], list[start] # The swapping
_stack.append(_backup[i])
print("swapped",_backup[start],"->",_backup[i],"then",list,_stack)
permutation(list, start + 1, end,count)
_backup=copy.copy(list);
list[start], list[i] = list[i], list[start] # Backtracking
_stack.pop()
print(" backte",_backup[i],"<-",_backup[start],"then",list,_stack)
permutation(['a', 'b','c'], 0, 2,0) # The first index of a list is zero
結果はこんな感じで推移する
swapped a -> a then ['a', 'b', 'c'] ['a']
swapped b -> b then ['a', 'b', 'c'] ['a', 'b']
['a', 'b', 'c']
backte b <- b then ['a', 'b', 'c'] ['a']
swapped b -> c then ['a', 'c', 'b'] ['a', 'c']
['a', 'c', 'b']
backte b <- c then ['a', 'b', 'c'] ['a']
backte a <- a then ['a', 'b', 'c'] []
swapped a -> b then ['b', 'a', 'c'] ['b']
swapped a -> a then ['b', 'a', 'c'] ['b', 'a']
['b', 'a', 'c']
backte a <- a then ['b', 'a', 'c'] ['b']
swapped a -> c then ['b', 'c', 'a'] ['b', 'c']
['b', 'c', 'a']
backte a <- c then ['b', 'a', 'c'] ['b']
backte a <- b then ['a', 'b', 'c'] []
swapped a -> c then ['c', 'b', 'a'] ['c']
swapped b -> b then ['c', 'b', 'a'] ['c', 'b']
['c', 'b', 'a']
backte b <- b then ['c', 'b', 'a'] ['c']
swapped b -> a then ['c', 'a', 'b'] ['c', 'a']
['c', 'a', 'b']
backte b <- a then ['c', 'b', 'a'] ['c']
backte a <- c then ['a', 'b', 'c'] []