How to merge two sequences in single sequence in an alternate manner without using arrays?

Viewed 99
for eg if sequence 1 : <1,3,5> and sequence 2 : <2,6,8,11,12>
than the result should be <1,2,3,6,5,8,11,12>

I tried to solve it using loops but what I am getting is a repeated structure

4 Answers

I'd be surprised if there isn't a better way to do it, but one way to do it would be like this:

from itertools import zip_longest

seq_1 = [1,3,5]
seq_2 = [2,6,8,11,12]
seq_3 = []
for a, b in zip_longest(seq_1, seq_2): # -> (1, 2) (3, 6) (5, 8) (None, 11) (None, 12)
    if a:
        seq_3.append(a)
    if b:
        seq_3.append(b)
i=0
j=0
N=len(L1)
M=len(L2)
L=[]
turn=True
while(i<N and j<M):
    if turn:
        L.append(L1[i])
        i+=1
    else:
        L.append(L2[j])
        j+=1
    turn=!turn
while(i<N):
    L.append(L1[i])
    i+=1
while(j<M):
    L.append(L2[j])
    j+=1
print(L)

THis can do the trick for you What Is being done is That I am keeping a boolean Turn to Alternate turns to select from the two arrays If You have any doubt regarding the loop logic I can elaborate a little. simple turn= !turn => ALternates turns on each iteration

This should do the trick. Explanation:

a = [1,3,5]
b = [2,4]
zip_longest(a,b) -> (1,2), (3,4), (5, None)
chain.from_iterable(l) -> 1,2,3,4,5,None

Followed by list comprehension.

from itertools import chain, zip_longest

l = [i for i in chain.from_iterable(zip_longest(a,b)) if i]

This code gives you a list of sorted numbers based on input.

x1,x2=[1,3,5],[2,6,8,11,12]

print(sorted(x1+x2))
Related