python编码转换语句_将“ 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:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值