-1
def merge(a1,a2):
    if len(a1)<1:
        return a2
    if len(a2)<1:
        return a1
    a1item=a1[0]
    a2item=a2[0]
    i=1
    j=1
    merge=[]
    while(a1item or a2item):
        print(a1item,a2item)
        if a1item<a2item:
            merge.append(a1item)
            a1item=a1[i]
            i+=1
        else:
            merge.append(a2item)
            a2item=a2[j]
            j+=1
        print(merge)


merge([1,2,3],[3,54,100])

I got error in a1item=a1[i] how to stop when the loop is pointing to last element. Suggest me without using inbuilt function

  • You need to check inside the loop. Every time `i` increases, you need to see if it's gone past end of one of the lists. If so, don't index into that list after that. – Tom Karzes Mar 28 '20 at 08:00
  • @eric your statement is correct .. but nothing at all to do with the error or the question? – Patrick Artner Mar 28 '20 at 09:15
  • Unlike some other programming languages, python will not let you access an element that does not exist. Meaning that something like [1,2,3][3] will give you an error message. That being said, `while(a1item or a2item):` does not work like how you are expecting it to, since you are trying to catch when `a1item` or `a2item` becomes undefined, which will never happen in python. Additionally, that condition will become `False` when either `a1item` or `a2item` is 0 – Kenta Nomoto Mar 28 '20 at 09:16

1 Answers1

1

You need to check your bounds yourself - beside that you got another error bound to happen if you merge [0,1,2,3] and [0,4,8] :

while(0 or 0):

is falsy and your function will not enter the while loop.

Fixes with comments:

def merge(a1,a2):
    if len(a1)<1:
        return a2
    if len(a2)<1:
        return a1
    i=0
    j=0
    # store result once - micro-optimization
    la1 = len(a1)
    la2 = len(a2)  

    m=[] # do not call variables the same as the function, in case you want to recurse

    # I removed the variables to hold the current values in favor 
    # of directly indexing them
    while True: # beware of (0 or 0) which is falsy
        print(a1[i],a2[j],end=" -> ")
        if a1[i] <= a2[j]:  # one more "true" value in first if branch
            m.append(a1[i]) # if both are same, we take from the 1st list
            i+=1            # no need to branch into the else part
        else:
            m.append(a2[j])
            j+=1
        print(m)

        # stop conditions: if one list is done, add the other to the end of m
        if i == la1:
            m.extend(a2[j:])
            break
        if j == la2:
            m.extend(a1[i:])
            break
    return m


print("----",merge([1,6,9],[0,7,8,11]))

Output:

1 0 -> [0]
1 7 -> [0, 1]
6 7 -> [0, 1, 6]
9 7 -> [0, 1, 6, 7]
9 8 -> [0, 1, 6, 7, 8]
9 11 -> [0, 1, 6, 7, 8, 9]
---- [0, 1, 6, 7, 8, 9, 11]

You can read more about list slicing here: Understanding slice notation

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69