【问题标题】:Keep tracking number of calls and comparison in a recursive merge sort在递归合并排序中跟踪调用次数和比较
【发布时间】:2021-09-02 16:40:43
【问题描述】:

我试图在不使用全局变量的情况下跟踪对 merge_sort() 的调用次数和 merge() 期间的总比较。我下面的代码正确计算了调用次数和比较。不使用全局变量怎么办?

import numpy as np

call = 0
compare = 0


def merge_sort(array):
    global call   # update global
    call += 1
    
    n = len(array)
    if n <= 1:
        return array

    arr1 = merge_sort(array[0:n // 2])
    arr2 = merge_sort(array[n // 2:n])

    
    new_arr = merge(arr1, arr2)

    return new_arr


def merge(arr1, arr2):
    new_arr = np.empty(len(arr1) + len(arr2), dtype=int)
    ind = 0
    i = 0
    j = 0
    com_num = 0   # Count comparisons in this call
    while i < len(arr1) and j < len(arr2):
        if arr1[i] < arr2[j]:
            com_num += 1   # +1
            new_arr[ind] = arr1[i]
            i += 1
            ind += 1
        else:
            com_num += 1   # +1
            new_arr[ind] = arr2[j]
            j += 1
            ind += 1

    while i < len(arr1):
        new_arr[ind] = arr1[i]
        i += 1
        ind += 1

    while j < len(arr2):
        new_arr[ind] = arr2[j]
        j += 1
        ind += 1

    global compare    # update global
    compare += com_num

    return new_arr

【问题讨论】:

  • 试试 decorator,也许?
  • 这是否意味着使用另一个函数来扭曲这两个并在其中进行计数和比较?我认为这仍然使用全局变量?
  • 作为额外变量merge_sort(array, call, compare) 和return result, call, compare 发送和接收值。或转换为类,您将拥有类变量而不是全局变量。

标签: python sorting recursion parameters


【解决方案1】:

我会这样做:

def merge_sort(array):
    '''Performs merge sort on a given array, and outputs number of
       calls and comparisons.'''

    sorted_array, calls, comps = _merge_sort(array, 0, 0)
    print("Made %d calls and %d comparisons." % (calls, comps))
    return(sorted_array)


def _merge_sort(array, calls, comps):
    calls += 1
    n = len(array)

    # Empty or singleton arrays are sorted by definition.
    if n <= 1:
        return (array, calls, comps)
    # Otherwise we recursively merge sort.
    else:
        left_array, calls, comps  = _merge_sort(array[:n//2], calls, comps)
        right_array, calls, comps = _merge_sort(array[n//2:], calls, comps)
        sorted_array, comps = _merge(left_array, right_array, comps)

    return (sorted_array, calls, comps)


def _merge(arr1, arr2, comps):
    '''Merges two sorted lists into a bigger sorted list.'''
    # NOTE: You can do this with bisect.insort, but I'm assuming you want to
    # write your own "first-principles" algorithm, so I didn't use that.

    output_array = []
    arr1_len = len(arr1)
    arr2_len = len(arr2)

    # Merge the lists by comparing elements.
    i = 0
    j = 0
    while i < arr1_len and j < arr2_len:
        comps += 1
        if arr1[i] < arr2[j]:
            output_array.append(arr1[i])
            i += 1
        else:
            output_array.append(arr2[j])
            j += 1

    # One of the lists will now have been exhausted, so we can append
    # whatever remains.
    output_array += arr1[i:] + arr2[j:]

    return (output_array, comps)

这里我使用两个以下划线开头的“私有”方法。当使用需要在调用之间跟踪内部变量的递归时,这是非常标准的,因此要避免让函数的用户提供这些。

我在这里也没有使用 NumPy,只是为了使其尽可能通用。你可以进去,把它放在你认为合适的地方。此外,我做了一些一般性的代码清理。特别是,请参阅_merge 函数开头的注释。

【讨论】:

    猜你喜欢
    • 2021-11-03
    • 2010-12-03
    • 2020-04-21
    • 1970-01-01
    • 1970-01-01
    • 2016-10-02
    • 2022-01-23
    • 2022-01-24
    • 1970-01-01
    相关资源
    最近更新 更多