def triangulations(p):
result = []
n = len(p)
if n == 2:
result.append([])
elif n == 3:
result.append([p])
else:
for k in range(1, n - 1):
for u, v in product(triangulations(p[:k + 1]), triangulations(p[k:])):
result.append(u + [(p[0], p[k], p[-1])] + v)
return result
for i in triangulations([1, 2, 3]):
print(i)
更多說明:
def triangulations(p):
result = []
n = len(p)
print ("execute triangulations")
if n == 2:
result.append([])
elif n == 3:
result.append([p])
else:
for k in range(1, n - 1):
for u, v in product(triangulations(p[:k + 1]), triangulations(p[k:])):
result.append(u + [(p[0], p[k], p[-1])] + v)
return result
triangulationsResult = triangulations([1, 2, 3])
for i in triangulationsResult:
print(i)
for i in triangulationsResult:
print(i)
def triangulationsYield(p):
n = len(p)
print ("execute triangulationsYield")
if n == 2:
yield []
elif n == 3:
yield [p]
else:
for k in range(1, n - 1):
for u, v in product(triangulations(p[:k + 1]), triangulations(p[k:])):
yield u + [(p[0], p[k], p[-1])] + v
triangulationsResultYield = triangulationsYield(["a", "b", "c"])
for i in triangulationsResultYield:
print(i)
for i in triangulationsResultYield:
print(i)
輸出:
execute triangulations
[[1, 2, 3]]
[[1, 2, 3]]
execute triangulationsYield
[['a', 'b', 'c']]
這取決於如何發生器(三角)在代碼別處調用。你能發佈那部分代碼嗎? – perigon
print(list(triangulations(tuple(「abcde」)))) – RamsesXVII
首先,你應該看看這個輝煌的anwser,以確保你理解生成器:https://stackoverflow.com/questions/231767/what- do-the-yield-keyword-do-in-python – maestromusica