Iは、Pythonのメソッドのペアを作成した:これらのエントリをリストに追加するにはどうすればよいですか?
3つの数字リスト内のすべての値が異なることを確認checkAllValuesAreDifferent()
のすべての可能な組み合わせを取得
number_combinations()
-
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]
(単独で印刷したものである).However、tempが、私はこれで問題を把握することはできません[[2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2]]
であることが判明しました。誰も私に、一時リストに生成されている正しいリストをどのようにして正常に追加するかについて考えてください。
を(http://docs.python.org/library/itertools.html#itertools.permutations ) –
@ IgnacioVazquez-Abrams - stdlibに存在するので、その方法を使うのが望ましいでしょうが、自分で書くのは良い練習です。 Pythonでは、可変かつ不変の型について、ここで学ぶべき非常に貴重な教訓もあります。 – AKX