0

The question is :

Write a function called merge that takes two already sorted lists of possibly different lengths, and merges them into a single sorted list.

(a) Do this without using the sort method

I tried the following :

list1=input("Enter the elements of list :").split()

list2=input("Enter the elements of list :").split()
    
def merge(list1,list2):
    merged_list,sorted_list=(list1+list2),[]

    while len(merged_list)>0 :

        sorted_list.append(min(merged_list))

        merged_list.remove(min(merged_list))

    return sorted_list

    print(merge(list1,list2))

This works well for alphabetic strings, but doesn't work for numbers. It treats numbers as strings too and hence sorting them in dictionary order instead of sorting based on their numeric value. What changes should I incorporate to make the above code universal? It has to work well for both strings and numbers.

1
  • Your answer DOES work for numbers (for example list1 = [1, 2, 5], list2 = [4, 6, 7] which anyway is a better way of providing test data. Your problem is that input always returns a string and hence you are getting ['1', '2', '5'] etc. hence treatment as strings. That said as commented you are not using the already sorted-ness. Commented Jun 23, 2023 at 6:56

1 Answer 1

-2

try this

def sort_list(lst):
    sorted_list = []
    while lst:
        min_value = min(lst)  # Find the minimum value in the list
        sorted_list.append(min_value)  # Append the minimum value to the sorted list
        lst.remove(min_value)  # Remove the minimum value from the original list
    return sorted_list
Sign up to request clarification or add additional context in comments.

4 Comments

Clearly the purpose of the exercise is not to generate a list that needs to be sorted, and exploit the fact that the input is already sorted.
This answer is logically just a re-written version of the OP answer and hence not an improvement in the sense of the question.
@user21623541 That isn't working too... take the following list as example : [08, 4, 123, 26]
Anyone please help me on this thing... quicker

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.