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)yxy + [x]
添加回答
举报
