Write a function
merge(tup1, tup2)that accepts two sorted tuples as parameters, and returns the merged tuple in which all integers appear in ascending order.You may assume that:
tup1andtup2each contain distinct integers sorted in ascending order.- Integers in
tup1are different from those intup2.- Length of tuples may also vary.
I can’t use python’s sorting function.
I’ve tried something like this, but failed public test cases such as
merge((-1, 1, 3, 5), (-2, 4, 6, 7))→(-2, -1, 1, 3, 4, 5, 6, 7)merge((-3, 8, 67, 100, 207), (-10, 20, 30, 40, 65, 80, 90))→(-10, -3, 8, 20, 30, 40, 65, 67, 80, 90, 100, 207)merge((-1, 1, 3, 5, 7, 9, 11), (-2, 0, 2, 4, 6))→(-2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 9, 11)
def merge(tup1, tup2):
size_1 = len(tup1)
size_2 = len(tup2)
res = ()
i, j = 0, 0
while i < size_1 and j < size_2:
if tup1(i) < tup2(j):
res.append(tup1(i))
i += 1
else:
res.append(tup2(j))
j += 1
return res = res + tup1(i:) + tup2(j:)
>Solution :
Your code (algorithm) is fine just full of syntax errors:
- tuples don’t have
append– you can concatenate them by using addition. - Indexing is done with
[..], not(...) - You can either
returnor assign – not both.
Your code with the above fixes seems to work fine:
def merge(tup1, tup2):
size_1 = len(tup1)
size_2 = len(tup2)
res = ()
i, j = 0, 0
while i < size_1 and j < size_2:
if tup1[i] < tup2[j]:
res += (tup1[i],)
i += 1
else:
res += (tup2[j],)
j += 1
return res + tup1[i:] + tup2[j:]