我在Python 3.2中有一個代碼,我想在Python 2.7中運行它。我確實轉換了它(已將missing_elements
的代碼放在兩個版本中),但我不確定這是否是最有效的方法。基本上如果在missing_element
函數中有兩個yield from
調用如上半部分和下半部分會發生什麼情況?來自兩個半部分(上部和下部)的條目是否在一個列表中相互追加,以便與yield from
調用的父遞歸函數一起使用這兩個半部分?將「yield from」語句轉換爲Python 2.7代碼
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
你可能想獲得'bar',不'foo'。 – ovgolovin
@ovgolovin:謝謝;固定。 – abarnert
遞歸調用如何工作?父母功能的「收益」是否結合了孩子中的兩個「收益」陳述?如果不是連續的低: 收益missing_elements(L,開始,索引) #是上部連續? consecutive_high = L [index] == L [end] - (end - index) if not consecutive_high: 從missing_elements(L,index,end)得到 – vkaul11