我正在研究stuy编码问题中的一个问题,并遇到了这个问题。
因此,给定两个生成器,每个生成器以递增顺序输出数字,请将两个生成器合并为一个生成器,以按递增顺序输出数字。如果出现重复,请输出多次。
我的尝试:由于我对使用列表,元组,字典等更加熟悉,所以我认为我只是帮忙在生成器中创建项目列表。然后,我将两个列表合并并排序
def list_maker(gener):
l1 = []
for item in gener:
l1.append(item)
return l1
def merge_gens(first_gen, second_gen):
first_list = list_maker(first_gen)
second_list = list_maker(second_gen)
first_list.extend(second_list)
final_list = first_list
final_list.sort()
yield from final_list
尽管此方法似乎适用于有限生成器,但不适用于无限生成器(我忘记考虑了)。我显然无法列出无限的商品。我可以在不导入python库的情况下获得帮助吗?
最佳答案
你可以试试 :
def merge(first, second):
a = next(first)
b = next(second)
while(True):
# yield the smaller one
yield a if a < b else b
# get the next number from the
# generator that yielded the smaller one
if a < b:
a = next(first)
elif a==b:
# when the numbers are equal
# yield second number a second time
yield a
# get the next numbers from both the generators.
a = next(first)
b = next(second)
else:
b = next(second)
很抱歉缺少评论和解释。我还没有测试过边缘情况。我希望您能大致了解该方法,并能帮助您获得进一步执行任务的指示。
假设条件
-StopIteration异常将由被调用方处理