Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
324 views
in Technique[技术] by (71.8m points)

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

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

question from:https://stackoverflow.com/questions/66058562/how-to-merge-two-sequences-in-single-sequence-in-an-alternate-manner-without-usi

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...