在以下代码中,yield命令用于生成返回值。我想避免使用它,用迭代操作替换它。我该怎么办?
def triangulations(p):
n = len(p)
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
print(list(triangulations(tuple("abcde"))))
答案 0 :(得分:4)
Constructor
更多解释:
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)