I get [-7,-4,-2], but I want to add the remaining numbers to my accumulator but I keep going out of range in my second if statement. How would I continue to add the remaining list? input: interleaved( [-7, -2, -1], [-4, 0, 4, 8])
def interleaved(seq1,seq2):
i = 0
j = 0
res = []
while i <len(seq1) and j <len(seq2):
if seq1[i] < seq2[j]:
res.append(seq1[i])
i+=1
if seq2[j] <= seq1[i]:
res.append(seq2[j])
j+=1
return res
Added an if
statement to check whether we "finished" exploring seq1
or not (same if
"check" can be applied on seq2
in case it had more negative values than seq1
)
def interleaved(seq1, seq2):
i = 0
j = 0
res = []
while i < len(seq1) and j < len(seq2):
if seq1[i] < seq2[j]:
res.append(seq1[i])
i += 1
if i == len(seq1): # If we explored all of seq1 (reached the end)
for num in seq2[j:]: # Explore the rest of seq2
res.append(num) # Append the rest
break # Break the while loop and go to "return"
if seq2[j] <= seq1[i]:
res.append(seq2[j])
j += 1
return res
print(interleaved())