If either i or j reach the end of their list range, how i copy the remainder of the other list to the merge list https://ibb.co/m9JzBYp go to link if not get the question
JavaScript
x
18
18
1
def list_merge (x, y):
2
merge = []
3
i = 0
4
j = 0
5
total = len (x) + len(y)
6
while != total :
7
if x[i] < y[j]:
8
merge.append(x[i])
9
i += 1
10
if i >= len (x):
11
#how i copy the reminder
12
else :
13
merge.append(y[j])
14
j += 1
15
if j >= len (y):
16
#how i copy the reminder
17
return merge
18
Advertisement
Answer
EDIT – OP wanted the code in some specific way.. Please see second snippet.
Don’t try to complicate your code.. just go with how you would do it manually and write the code.
JavaScript
1
30
30
1
def list_merge (x, y):
2
merged_list = []
3
i = 0
4
j = 0
5
6
# when one of them is empty, break out
7
while i < len(x) and j < len(y):
8
if x[i] <= y[j]:
9
merged_list.append(x[i])
10
i +=1
11
else:
12
merged_list.append(y[j])
13
j +=1
14
15
# if you are here, that means either one of the list is done
16
# so check the bounds of both lists and append the one which is not traversed
17
18
# x has some elements to add
19
# check how extend works... makes your code clean
20
if i != len(x):
21
merged_list.extend(x[i:])
22
else:
23
merged_list.extend(y[j:])
24
25
return merged_list
26
27
a = [1,3,5,7,10]
28
b = [2,4,6,8,100]
29
print(list_merge(a,b))
30
Output
JavaScript
1
2
1
[1, 2, 3, 4, 5, 6, 7, 8, 10, 100]
2
What OP needed
JavaScript
1
20
20
1
def list_merge (x, y):
2
merge = []
3
i = 0
4
j = 0
5
total = len (x) + len(y)
6
while len(merge) != total :
7
if x[i] < y[j]:
8
merge.append(x[i])
9
i += 1
10
if i >= len (x):
11
merge.extend(y[j:])
12
else:
13
merge.append(y[j])
14
j += 1
15
if j >= len (y):
16
merge.extend(x[i:])
17
18
return merge
19
20