3
def merge_lists(all_lst):
    def merge(left,right):
        results = []
        while left and right:
            if min(left) < min(right):
                results.append(min(left))
                left.remove(min(left))
            else:
                results.append(min(right))
                right.remove(min(right))
        results.extend(left)
        results.extend(right)
        return results
    if all_lst == []:
        return []
    elif len(all_lst) == 1:
        return merge(all_lst[0],[])
    else:
        return merge_lists([merge(all_lst[0],all_lst[1])] + all_lst[2:])

all_lst = [[2, 7, 10], [0, 4, 6], [3, 11],[123,88,7],[12,32,4,6,7],[34,22,1],[3]]
print(merge_lists(all_lst))
>>> [0, 1, 2, 3, 3, 4, 4, 6, 6, 7, 7, 7, 10, 11, 12, 22, 32, 34, 123, 88]

My code sorts the numbers in increasing order. But why is 88 not in the correct place? Is there anything wrong with my code?

1
  • 1
    Is this some kind of homework, where you can't use built-in functions ? Seems you are not the only one working on it stackoverflow.com/questions/22440361/… Commented Mar 17, 2014 at 13:26

4 Answers 4

4

The problem is in your merge function. Consider this input:

[0, 2, 3, 4, 6, 7, 10, 11] [123, 88, 7]

After some time, result is [0, 2, 3, 4, 6, 7, 7, 10, 11], left is [] and right is [123, 88] -- and now you exit the while loop and just extend result with all the rest of right, which is not sorted!

To fix this, you could sort both left and right, then you don't need to use min anymore, either, as the first element will then always be the smallest. Or, if you can't use builtin sort functions, continue picking the minimum element from left and right until both are exhausted.

Sign up to request clarification or add additional context in comments.

Comments

2

You need to sort the list with a sort function, Python sort() works

all_lst = [0, 1, 2, 3, 3, 4, 4, 6, 6, 7, 7, 7, 10, 11, 12, 22, 32, 34, 123, 88]

sorted_ls = sorted(all_lst)
print sorted_ls

output: [0, 1, 2, 3, 3, 4, 4, 6, 6, 7, 7, 7, 10, 11, 12, 22, 32, 34, 88, 123]

Comments

0

please sort the list after adding all values.

all_lst.sort()

Comments

0

you should change your code to this

def merge(left,right):
    results = []
    left = sorted(left)
    right = sorted(right)
    while left and right:
        if min(left) < min(right):
            results.append(min(left))
            left.remove(min(left))
        else:
            results.append(min(right))
            right.remove(min(right))
    results.extend(left)
    results.extend(right)
    return results

when you do merge, you should keep left and right list are ordered.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.