I have written a pair of methods in python:
number_combinations()which obtains all possible combinations of 3 numberscheckAllValuesAreDifferent()which checks that all the values in the list are different
–
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
When I just try printing the listOfElements, I get the right answer i.e all sets of 3 digits with each distinct. However, when I try appending to the list temp, I end up getting duplicate entries. So temp should be : [0,1,2],[0,2,1][1,0,2][1,2,0][2,0,1][2,1,0]
(which is the result of printing alone).However,temp turns out to be [[2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2]]
I cannot figure out the problem with this. Could anyone give me some idea as to how to successfully append the right lists being generated to the temp list.
Because you are passing the same
listOfElementsback to the function, and it will be modified in place.You can use the
[:]idiom to shallow-copy a list: