【发布时间】:2013-07-09 00:20:01
【问题描述】:
我在 Python 3.2 中有一段代码,我想在 Python 2.7 中运行它。我确实转换了它(在两个版本中都放入了missing_elements 的代码),但我不确定这是否是最有效的方法。基本上如果在missing_element 函数的上半部分和下半部分有两个yield from 调用,会发生什么情况?两半(上半和下半)的条目是否在一个列表中相互附加,以便父递归函数与 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] == L[end] - (end - index)
if not consecutive_high:
yield from missing_elements(L, index, end)
def main():
L = [10, 11, 13, 14, 15, 16, 17, 18, 20]
print(list(missing_elements(L, 0, len(L)-1)))
L = range(10, 21)
print(list(missing_elements(L, 0, len(L)-1)))
def missing_elements(L, start, end): # Python 2.7
return_list = []
if end - start <= 1:
if L[end] - L[start] > 1:
return range(L[start] + 1, L[end])
index = start + (end - start) // 2
# is the lower half consecutive?
consecutive_low = L[index] == L[start] + (index - start)
if not consecutive_low:
return_list.append(missing_elements(L, start, index))
# is the upper part consecutive?
consecutive_high = L[index] == L[end] - (end - index)
if not consecutive_high:
return_list.append(missing_elements(L, index, end))
return return_list
【问题讨论】:
-
下面的大多数实现在某些方面都缺乏支持(用于向生成器发送值、处理嵌套的 yield-from 等)。我在 PyPI 中发布了一个包,试图在行为上做到全面:amir.rachum.com/yieldfrom
标签: python generator python-2.x yield yield-from