使用帮助迭代器合并排序

时间:2014-10-22 18:35:04

标签: python-3.x iterator generator mergesort

我开发了合并排序,它只能使用迭代器(它是问题的陈述)。我的函数输出是生成器。

我写合并排序功能:

def merge_sort(data):
    data1, data2 = itertools.tee(data)

    counter = 0
    for i in data1:
        counter += 1

    if counter < 2:
        return data2

    middle = int(counter / 2)

    y = itertools.islice(data2, 0, middle)
    z = itertools.islice(data2, middle, counter)

    sorted_y = merge_sort(y)
    sorted_z = merge_sort(z)

    return heapq.merge(sorted_y, sorted_z)

我测试我的功能:

def main():
    unsorted_list = [10, 3, 5, 0, 1, -5, 6, 2]

    result = merge_sort(iter(unsorted_list))

    for i in result:
        print(i)

但它不起作用。我只得到了数字10.我在哪里犯了错误?

1 个答案:

答案 0 :(得分:1)

这是一项正确的功能:

def merge_sort(data):
    data1, data2, data3 = itertools.tee(data, 3)

    counter = 0
    for i in data1:
        counter += 1

    if counter < 2:
        return data3

    middle = int(counter / 2)

    y = itertools.islice(data2, 0, middle)
    z = itertools.islice(data3, middle, counter)

    sorted_y = merge_sort(y)
    sorted_z = merge_sort(z)

    return merge(sorted_y, sorted_z)