简体   繁体   中英

python merge sort within a class

I am trying to make merge sort work within a class "Sorter for a python project, using the first code. The problem is that whenever I initialize the code, it calls the error "merge_sort' is not defined", and if I remove the "merge_sort" and use "left = lst[:mid]", it only cuts the list into half & reorganizes, but doesn't complete the script with the whole list. Is there a way to get around this issue? Thanks!!

from sorter import Sorter
unsorted_list = [5, -3, 4, 10, -14, 2, 4, -5]
my_sorter = Sorter()
my_sorter.unsorted_tuple = tuple(unsorted_list)
sorted_list = my_sorter._merge_sort()
print(sorted_list)

My code:

class Sorter():

    def __init__(self):
        self.unsorted_tuple = tuple([])
        self.algorithm = 'default'

    def generate_new_tuple(self, n):

        new_list = []
        for x in range (0, n):
            new_list.append(random.randint(0, maxsize))
        tuple(new_list)
        self.unsorted_tuple = new_list
        return None

    def _merge_sort(self, reverse=False):

        lst = list(self.unsorted_tuple)
        result = []
        i,j = 0,0

        if(len(lst)<= 1): 
            return lst
        mid = int(len(lst)/2)
        left = _merge_sort(lst[:mid])
        right = _merge_sort(lst[mid:])

        while i<len(left) and j<len(right):
            if left[i] <= right[j]:
                result.append(left[i]) 
                i+=1
            else:
                result.append(right[j])
                j+=1
        result += left[i:]
        result += right[j:]
        return result

You're confused about how classes and methods work.

The compiler is correct (by definition...): there is no function _merge_sort . That name applies to a method, and must be called with a Sorter object. You have gone to a lot of trouble to set up this class, but then you've ignored those encapsulation protections when you try to recur on the halves of your list:

    left = _merge_sort(lst[:mid])
    right = _merge_sort(lst[mid:])

You're trying to invoke your method as if it were a common function. Instead, you have to instantiate Sorter objects for each half of the list, set their unsorted attributes to those half-lists, and then you can invoke the method on each of those. Something like:

left_half = Sorter()
left_half.unsorted_tuple = lst[:mid]
left = left_half._merge_sort()
right_half = Sorter()
right_half.unsorted_tuple = lst[mid:]
right = right_half._merge_sort()

Please consider the "weight" of this code; perhaps you can reconfigure your class to better support your needs. For starters, give __init__ another parameter for the initial value of the list/tuple.

Does that get you moving?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM