'How to write a function that accepts two tuples, and returns the merged tuple in which all integers appears in ascending order?
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 1:[1]
Unpack both tuples into a list using *operator, sort and convert to tuple.
merge = lambda t1, t2: tuple(sorted([*t1, *t2]))
Solution 2:[2]
Since tuples are immutable in Python, I would loop over them to copy the items one by one into a list, sort that list with .sort(), and then convert it into a tuple.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | matszwecja |
| Solution 2 | Schnitte |
