Code Simplifier | Python

Refactored and Minified merge_sort Function

The input presents a refactored and minified version of the merge_sort function in Python, with a concise summary of the key transformation points, coding practices, and a provided test case with expected and actual outputs.


Empty image or helper icon

Prompt

def merge_sort(arr):
    if len(arr) > 1:
        mid = len(arr) // 2
        L = arr[:mid]
        R = arr[mid:]

        merge_sort(L)
        merge_sort(R)

        i = j = k = 0

        while i < len(L) and j < len(R):
            if L[i] < R[j]:
                arr[k] = L[i]
                i += 1
            else:
                arr[k] = R[j]
                j += 1
            k += 1

        while i < len(L):
            arr[k] = L[i]
            i += 1
            k += 1

        while j < len(R):
            arr[k] = R[j]
            j += 1
            k += 1

# Test the merge_sort function
arr = [12, 11, 13, 5, 6, 7]
merge_sort(arr)
print("Sorted array is:", arr)

Answer

# Refactored and Minified merge_sort function
def merge_sort(arr):
    if len(arr) > 1:
        mid = len(arr) // 2
        L, R = arr[:mid], arr[mid:]
        merge_sort(L)
        merge_sort(R)
        i = j = k = 0
        while i < len(L) and j < len(R):
            if L[i] < R[j]: arr[k] = L[i]; i += 1
            else: arr[k] = R[j]; j += 1
            k += 1
        while i < len(L): arr[k] = L[i]; i += 1; k += 1
        while j < len(R): arr[k] = R[j]; j += 1; k += 1

# Test the merge_sort function
arr = [12, 11, 13, 5, 6, 7]
merge_sort(arr)
print("Sorted array is:", arr)

The original merge_sort function is refactored and minified. Key points of transformation include:

  • Redundant variable assignments are condensed to multiple assignments in a single line.
  • Whitespace and unnecessary line breaks are removed to minimize code length.
  • The logic and functionality of the original code are preserved.

Test Case:

  • Input: arr = [12, 11, 13, 5, 6, 7]
  • Expected Output: Sorted array is: [5, 6, 7, 11, 12, 13]
  • Actual Output: Sorted array is: [5, 6, 7, 11, 12, 13]

Create your Thread using our flexible tools, share it with friends and colleagues.

Your current query will become the main foundation for the thread, which you can expand with other tools presented on our platform. We will help you choose tools so that your thread is structured and logically built.

Description

The input presents a refactored and minified version of the merge_sort function in Python, with a concise summary of the key transformation points, coding practices, and a provided test case with expected and actual outputs.