[Python] Merge sorting algorithm in Python for two sorted lists - trouble constructing for-loop

Discussão em 'Python' iniciado por Stack, Março 18, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to create an algorithm to merge two ordered lists into a larger ordered list in Python. Essentially I began by trying to isolate the minimum elements in each list and then I compared them to see which was smallest, because that number would be smallest in the larger list as well. I then appended that element to the empty larger list, and then deleted it from the original list it came from. I then tried to loop through the original two lists doing the same thing. Inside the "if" statements, I've essentially tried to program the function to append the remainder of one list to the larger function if the other is/becomes empty, because there would be no point in asking which elements between the two lists are comparatively smaller then.

    def merge_cabs(cab1, cab2):
    for (i <= all(j) for j in cab1):
    for (k <= all(l) for l in cab2):
    if cab1 == []:
    newcab.append(cab2)
    if cab2 == []:
    newcab.append(cab1)
    else:
    k = min(min(cab1), min(cab2))
    newcab.append(k)
    if min(cab1) < min(cab2):
    cab1.remove(min(cab1))
    if min(cab2) < min(cab1):
    cab2.remove(min(cab2))
    print(newcab)


    cab1 = [1,2,5,6,8,9]
    cab2 = [3,4,7,10,11]
    newcab = []
    merge_cabs(cab1, cab2)


    I've had a bit of trouble constructing the for-loop unfortunately. One way I've tried to isolate the minimum values was as I wrote in the two "for" lines. Right now, Python is returning "SyntaxError: invalid syntax," pointing to the colon in the first "for" line. Another way I've tried to construct the for-loop was like this:

    def merge_cabs(cabs1, cabs2):
    for min(i) in cab1:
    for min(j) in cab2:



    I've also tried to write the expression all in one line like this:

    def merge_cabs(cab1, cab2):
    for min(i) in cabs1 and min(j) in cabs2:


    and to loop through a copy of the original lists rather than looping through the lists themselves, because searching through the site, I've found that it can sometimes be difficult to remove elements from a list you're looping through. I've also tried to protect the expressions after the "for" statements inside various configurations of parentheses. If someone sees where the problem(s) lies, it would really be great if you could point it out, or if you have any other observations that could help me better construct this function, I would really appreciate those too.

    Continue reading...

Compartilhe esta Página