我在Python 3.2中有一个代码,我想在Python 2.7中运行它.我确实转换了它(已经把missing_elements两个版本的代码都放了)但我不确定这是否是最有效的方法.基本上如果yield from在missing_element功能的上半部分和下半部分有两个如下所示的调用会发生什么?两个部分(上部和下部)中的条目是否在一个列表中相互附加,以便父级递归函数与yield from调用一起使用并将两个部分一起使用?
def missing_elements(L, start, end): # Python 3.2
if end - start <= 1:
if L[end] - L[start] > 1:
yield from range(L[start] + 1, L[end])
return
index = start + (end - start) // 2
# is the lower half consecutive?
consecutive_low = L[index] == L[start] + (index - start)
if not consecutive_low:
yield from missing_elements(L, start, index)
# is the upper part consecutive?
consecutive_high = L[index] …Run Code Online (Sandbox Code Playgroud) 在这段代码中,为什么使用'for'会导致没有'StopIteration'或'for'循环捕获所有异常然后以静默方式退出?在这种情况下,为什么我们有无关的"回归"?或者是
for由:StopIteration?
#!/usr/bin/python3.1
def countdown(n):
print("counting down")
while n >= 9:
yield n
n -= 1
return
for x in countdown(10):
print(x)
c = countdown(10)
next(c)
next(c)
next(c)
Run Code Online (Sandbox Code Playgroud)
假设for是由以下方式触发:return.GeneratorExit何时生成?
def countdown(n):
print("Counting down from %d" % n)
try:
while n > 0:
yield n
n = n - 1
except GeneratorExit:
print("Only made it to %d" % n)
Run Code Online (Sandbox Code Playgroud)
如果我手动执行:
c = countdown(10)
c.close() #generates GeneratorExit??
Run Code Online (Sandbox Code Playgroud)
在哪种情况下,为什么我看不到追溯?
我一直致力于为生物学问题生成所有可能的子模型.我有一个工作递归,用于生成我想要的所有子模型的大列表.但是,列表的速度非常快(N = 12只能在下面的示例中使用,N> 12使用太多内存).所以我想用yield来转换为生成器函数,但是我被卡住了.
我的工作递归函数如下所示:
def submodel_list(result, pat, current, maxn):
''' result is a list to append to
pat is the current pattern (starts as empty list)
current is the current number of the pattern
maxn is the number of items in the pattern
'''
if pat:
curmax = max(pat)
else:
curmax = 0
for i in range(current):
if i-1 <= curmax:
newpat = pat[:]
newpat.append(i)
if current == maxn:
result.append(newpat)
else:
submodel_generator(result, newpat, current+1, maxn)
result = []
submodel_list(result, …Run Code Online (Sandbox Code Playgroud)