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.

Stef
  • 13,242
  • 2
  • 17
  • 28
  • 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. – user19077881 Jun 23 '23 at 06:56

1 Answers1

-1

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
Clifford
  • 88,407
  • 13
  • 85
  • 165