Guest User

gpt-4-0314 - simple python test

a guest
Dec 14th, 2023
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. #gpt-4-0314
  2. - Max Tokens 4096
  3. - Temp 1
  4.  
  5. #Prompt (empty system prompt)
  6. >write a python script that will perform a binary merge sort
  7.  
  8. ----
  9.  
  10. #Output
  11.  
  12. Here's an implementation of merge sort algorithm in Python:
  13.  
  14. ```python
  15. def merge_sort(arr):
  16. if len(arr) <= 1:
  17. return arr
  18.  
  19. # Split the list in half
  20. middle = len(arr) // 2
  21. left = arr[:middle]
  22. right = arr[middle:]
  23.  
  24. # Recursively sort both halves
  25. left_sorted = merge_sort(left)
  26. right_sorted = merge_sort(right)
  27.  
  28. # Merge the two sorted halves
  29. return binary_merge(left_sorted, right_sorted)
  30.  
  31.  
  32. def binary_merge(left, right):
  33. result = []
  34. left_index = 0
  35. right_index = 0
  36.  
  37. while left_index < len(left) and right_index < len(right):
  38. if left[left_index] < right[right_index]:
  39. result.append(left[left_index])
  40. left_index += 1
  41. else:
  42. result.append(right[right_index])
  43. right_index += 1
  44.  
  45. # Add the remaining elements from the left and right sublists
  46. result.extend(left[left_index:])
  47. result.extend(right[right_index:])
  48.  
  49. return result
  50.  
  51.  
  52. # Test the merge_sort function
  53. arr = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
  54. print("Original list:", arr)
  55. sorted_arr = merge_sort(arr)
  56. print("Sorted list:", sorted_arr)
  57. ```
  58.  
  59. This script defines a `merge_sort` function that takes a list as input and returns a new list containing the same elements sorted in ascending order using the merge sort algorithm. The `binary_merge` function is a helper function that takes in two sorted lists (`left` and `right`) and merges them into a single sorted list.
  60.  
  61. ----
  62.  
  63. # Test Output
  64.  
  65. Original list: [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
  66. Sorted list: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
  67.  
  68. PASS
  69.  
Advertisement
Add Comment
Please, Sign In to add comment