我在python中编写了一对方法:
number_combinations()
获取3个数字的所有可能组合checkAllValuesAreDifferent()
检查列表中的所有值是否不同-
temp = []
def number_combinations(listOfElements,index):
if index==3:
#if checkAllValuesAreDifferent(listOfElements):
#print "Going to append the following list to the sat tuple list "
print listOfElements
#print "Temp is ",temp
temp.append(listOfElements)
print "Temp is ",temp
print "exit from function "
return listOfElements
else:
for value in range(3):
listOfElements[index]=value
#print "LIST OF ELEMENTS IS ",listOfElements
if checkAllValuesAreDifferent(listOfElements,index,value)==True:
#print "RECURSIVE CALL "
(number_combinations(listOfElements,index+1))
#print "THE LIST IS ",temp
#print "APPENDING TO SAT TUPLES "
#print "BACKTRACK HAPPEND ",listOfElements
#print "AND INDEX IS ",index
#recursive call to next level
return #backtrack since no number found
def checkAllValuesAreDifferent(list_of,index,value):
if index==0:
return True
else:
for i in range(index):
#print "Entered loop with index ",index
if(list_of[i]==value):
return False
return True
当我只是尝试打印listOfElements时,我得到了正确的答案,即每个不同的所有3位数组。但是,当我尝试附加到列表temp时,我最终得到重复的条目。所以临时应该是:[0,1,2],[0,2,1][1,0,2][1,2,0][2,0,1][2,1,0]
(这是单独打印的结果)。但是,temp结果是[[2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2]]
我无法弄清楚这个问题。任何人都可以告诉我如何成功地将正在生成的列表附加到临时列表。
答案 0 :(得分:2)
因为您将相同的listOfElements
传递回函数,并且它将被修改。
您可以使用[:]
惯用法对列表进行浅层复制:
temp.append(listOfElements[:])