2 回答

TA貢獻1864條經驗 獲得超6個贊
你的第一個函數 listPairs() 是可以的,但是第二個函數中的邏輯有一些問題。將每次迭代中的當前列表存儲在臨時變量中將有助于:
def listTriples(A):
B = listPairs(A)
C = []
for y in B:
for x in A:
if ((x not in y) and (x > y[len(y) - 1])):
temp = y.copy()
C.append(temp)
y.remove(x)
if x in y:
continue
return C
如果要打印每次迭代的結果,代碼應如下所示:
def listTriples(A):
B = listPairs(A)
C = []
for y in B:
for x in A:
if ((x not in y) and (x > y[len(y) - 1])):
print("x not in y")
print("Y: ",y)
print("X: ",x)
print("y.append(x): ", y.append(x))
print("new Y (temp):", y)
print("------")
temp = y.copy()
C.append(temp)
print("C: ", C)
y.remove(x)
print("Y:", y)
print("------\n\n")
if x in y:
continue
return C
最終結果:
x not in y
Y: [1, 2]
X: 3
y.append(x): None
new Y (temp): [1, 2, 3]
------
C: [[1, 2, 3]]
Y: [1, 2]
------
x not in y
Y: [1, 2]
X: 4
y.append(x): None
new Y (temp): [1, 2, 4]
------
C: [[1, 2, 3], [1, 2, 4]]
Y: [1, 2]
------
x not in y
Y: [1, 2]
X: 5
y.append(x): None
new Y (temp): [1, 2, 5]
------
C: [[1, 2, 3], [1, 2, 4], [1, 2, 5]]
Y: [1, 2]
------
x not in y
Y: [1, 3]
X: 4
y.append(x): None
new Y (temp): [1, 3, 4]
------
C: [[1, 2, 3], [1, 2, 4], [1, 2, 5], [1, 3, 4]]
Y: [1, 3]
------
x not in y
Y: [1, 3]
X: 5
y.append(x): None
new Y (temp): [1, 3, 5]
------
C: [[1, 2, 3], [1, 2, 4], [1, 2, 5], [1, 3, 4], [1, 3, 5]]
Y: [1, 3]
------
x not in y
Y: [1, 4]
X: 5
y.append(x): None
new Y (temp): [1, 4, 5]
------
C: [[1, 2, 3], [1, 2, 4], [1, 2, 5], [1, 3, 4], [1, 3, 5], [1, 4, 5]]
Y: [1, 4]
------
x not in y
Y: [2, 3]
X: 4
y.append(x): None
new Y (temp): [2, 3, 4]
------
C: [[1, 2, 3], [1, 2, 4], [1, 2, 5], [1, 3, 4], [1, 3, 5], [1, 4, 5], [2, 3, 4]]
Y: [2, 3]
------
x not in y
Y: [2, 3]
X: 5
y.append(x): None
new Y (temp): [2, 3, 5]
------
C: [[1, 2, 3], [1, 2, 4], [1, 2, 5], [1, 3, 4], [1, 3, 5], [1, 4, 5], [2, 3, 4], [2, 3, 5]]
Y: [2, 3]
------
x not in y
Y: [2, 4]
X: 5
y.append(x): None
new Y (temp): [2, 4, 5]
------
C: [[1, 2, 3], [1, 2, 4], [1, 2, 5], [1, 3, 4], [1, 3, 5], [1, 4, 5], [2, 3, 4], [2, 3, 5], [2, 4, 5]]
Y: [2, 4]
------
x not in y
Y: [3, 4]
X: 5
y.append(x): None
new Y (temp): [3, 4, 5]
------
C: [[1, 2, 3], [1, 2, 4], [1, 2, 5], [1, 3, 4], [1, 3, 5], [1, 4, 5], [2, 3, 4], [2, 3, 5], [2, 4, 5], [3, 4, 5]]
Y: [3, 4]
------
[[1, 2, 3], [1, 2, 4], [1, 2, 5], [1, 3, 4], [1, 3, 5], [1, 4, 5], [2, 3, 4], [2, 3, 5], [2, 4, 5], [3, 4, 5]]
|| Expected [[1, 2, 3], [1, 2, 4], [1, 2, 5], [1, 3, 4], [1, 3, 5], [1, 4, 5], ...]

TA貢獻1841條經驗 獲得超3個贊
問題出在 。的返回值為 none - 它通過附加值而不返回值進行修改。您將需要改用。C.append(y.append(x))
y.append(x)
y
x
y + [x]
添加回答
舉報