简体   繁体   中英

Error in Merge Sort function in yield

I received a merge sort function from someone else, here's the code:

def mergesort(lst):
    l = len(lst)
    if l <= 1:
        return lst
    return mergesorted(mergesort(lst[:l//2]), mergesort(lst[l//2:]))

def mergesorted(a, b):
    i, j = 0, 0
    la, lb = len(a), len(b)
    while i < la or j < lb:
        if i == la or (j != lb and a[i] > b[j]):
            yield b[j]
            j += 1
        else:
            yield a[i]
            i += 1

I'm still trying to understand how yield works, so when I was trying to print the result to test the function, I used

m = mergesort([4, 2, 5, 1, 6, 3])

for i in m :
    print(i)

It gave me this error:

Traceback (most recent call last):
    for i in m :
    la, lb = len(a), len(b)
TypeError: object of type 'generator' has no len()

Am I using the print statement wrong?

The fact that mergesorted has the yield keyword in it means that it's a generator. And like the error message says, generators don't have a len method.
The reason that generators don't have a len method is because generators don't actually know what values they're going to yield, until it's time to yield them. Unlike objects like list s or tuple s.
In this case, I don't see any advantage to using yield instead of return .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM