Write a python function to merge two sorted lists into one sorted list.
- User
Write a python function to merge two sorted lists into one sorted list.
Assistant
Here is a python function to merge two sorted lists into one sorted list:
def merge_sorted_lists(list1, list2): merged_list = [] i, j = 0, 0 while i < len(list1) and j < len(list2): if list1[i] < list2[j]: merged_list.append(list1[i]) i += 1 else: merged_list.append(list2[j]) j += 1 merged_list += list1[i:] merged_list += list2[j:] return merged_listTo explain, it iterates through both lists simultaneously comparing the current elements. At each step, it appends the smaller element to the merged list and advances the index. Once one list is fully traversed, it appends the remaining elements of the other list.
Some examples:
list1 = [1,3,5,7] list2 = [2,4,6,8] merge_sorted_lists(list1, list2) Returns: [1,2,3,4,5,6,7,8]
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.