Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to write a function that 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:

  • tup1 and tup2 each contain distinct integers sorted in ascending order.
  • Integers in tup1 are different from those in tup2.
  • Length of tuples may also vary.

I can’t use python’s sorting function.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 return or 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:]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading