sorting - Implementing Merging of List in Python -


I am writing a simple program in Python, which has two lists to be merged. I have taken the following pseudocode from Introduction to the analysis of algorithm .

algorithm to merge two lists

I now The following program is written in Python.

  def merge_list (a, b): a, b = sorted (a), sorted (b) p1, p2, i = 0,0,0 # scripton index 0 Starts with c = [0 in range (lane (a) + lane (b))] while i & lt; (Lane) + Len (b): If a [P1]  = B [p2]: c [i] = a [p1] p1 = p1 + 1 and: c [i] = b [p1] p2 = p2 + 1 i + = 1 return c res = merge_list ([1,3 , 5], [2,4,6])  

Now I'm getting the error with the IndexError: list index outside the limit Please correct me What am I doing wrong here?

As others have said, you can P1 and P2 . But you also have to check the empty list, and you also have the possibility that the input does not have the same length. This algorithm is not a list of all the pre-conditions, i.e., n must be less than or equal to m to work in writing. So we will take care of it.

  & gt; & Gt; & Gt; Def merge_list (a, b): a, b = sorted (a), sorted (b) if lenan (a)> gt; Lane (B): A, B = B, AP1, P2, I = 0,0,0 # begin with SPETHON INDEX 0, [0 in range for boundary (lane (A) + lane (B ))] While I & lt; (Lane (a) + lane (b)): If P1 and lieutenant (A) and P2 and lieutenant (B) and one [P1] & lt; = B [p2]: c [ii] = a [p1] p1 = p1 + 1 elif p2 & lt; Len (b): c [i] = b [p2] p2 = p2 + 1i + = 1 return c & gt; & Gt; & Gt; Merge_list ([1,3,5,7,9], [2,4,6,8]) [1, 2, 3, 4, 5, 6, 7, 8, 9] & gt; & Gt; & Gt; Merge-list ([1,3,5], [2,4,6,7]) [1, 2, 3, 4, 5, 6, 7]  

The first three Rows are not strictly with the modified pseudocode, but otherwise it is a 1-to-1 coupling, which is with a pseudocode.

Note that the answer to Sabisachi is too much dragon and it is generally preferred.


Comments