Преобразование оператора yield from в код Python 2.7
У меня был код ниже в 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:
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:
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