示例#1
0
 def __new__(cls, elements=None, heap_property="min", d=4):
     obj = Heap.__new__(cls)
     obj.heap_property = heap_property
     obj.d = d
     if heap_property == "min":
         obj._comp = lambda key_parent, key_child: key_parent <= key_child
     elif heap_property == "max":
         obj._comp = lambda key_parent, key_child: key_parent >= key_child
     else:
         raise ValueError("%s is invalid heap property" % (heap_property))
     if elements is None:
         elements = DynamicOneDimensionalArray(TreeNode, 0)
     elif _check_type(elements, (list, tuple)):
         elements = DynamicOneDimensionalArray(TreeNode, len(elements),
                                               elements)
     elif _check_type(elements, Array):
         elements = DynamicOneDimensionalArray(TreeNode, len(elements),
                                               elements._data)
     else:
         raise ValueError(
             f'Expected a list/tuple/Array of TreeNode got {type(elements)}'
         )
     obj.heap = elements
     obj._last_pos_filled = obj.heap._last_pos_filled
     obj._build()
     return obj
 def __new__(cls, key, data=None):
     from pydatastructs.linear_data_structures.arrays import DynamicOneDimensionalArray
     obj = Node.__new__(cls)
     obj.data, obj.key = data, key
     obj.children, obj.parent, obj.is_root = (DynamicOneDimensionalArray(
         BinomialTreeNode, 0), None, False)
     return obj
示例#3
0
 def __new__(cls, root_list=[]):
     if not all((_check_type(root, BinomialTree)) for root in root_list):
         raise TypeError("The root_list should contain "
                         "references to objects of BinomialTree.")
     obj = Heap.__new__(cls)
     obj.root_list = DynamicOneDimensionalArray(BinomialTree, root_list)
     return obj
 def __new__(cls, key, data=None):
     from pydatastructs.linear_data_structures.arrays import DynamicOneDimensionalArray
     obj = Node.__new__(cls)
     obj.data = data
     obj.key = key
     obj.is_root = False
     obj.children = DynamicOneDimensionalArray(int, 0)
     return obj
示例#5
0
 def __new__(cls, key, data=None, **kwargs):
     raise_if_backend_is_not_python(cls,
                                    kwargs.get('backend', Backend.PYTHON))
     from pydatastructs.linear_data_structures.arrays import DynamicOneDimensionalArray
     obj = Node.__new__(cls)
     obj.data, obj.key = data, key
     obj.children, obj.parent, obj.is_root = (DynamicOneDimensionalArray(
         BinomialTreeNode, 0), None, False)
     return obj
示例#6
0
def _do_match(string, query, kmp_table):
    j, k = 0, 0
    positions = DynamicOneDimensionalArray(int, 0)

    while j < len(string):
        if query[k] == string[j]:
            j = j + 1
            k = k + 1
            if k == len(query):
                positions.append(j - k)
                k = kmp_table[k]
        else:
            k = kmp_table[k]
            if k < 0:
                j = j + 1
                k = k + 1

    return positions
示例#7
0
 def __new__(cls, key, data=None, **kwargs):
     raise_if_backend_is_not_python(cls,
                                    kwargs.get('backend', Backend.PYTHON))
     from pydatastructs.linear_data_structures.arrays import DynamicOneDimensionalArray
     obj = Node.__new__(cls)
     obj.data = data
     obj.key = key
     obj.is_root = False
     obj.children = DynamicOneDimensionalArray(int, 0)
     return obj
示例#8
0
def _rabin_karp(text, query):
    t = len(text)
    q = len(query)
    positions = DynamicOneDimensionalArray(int, 0)
    if q == 0 or t == 0:
        return positions

    query_hash = _hash_str(query)
    text_hash = OneDimensionalArray(int, t + 1)
    text_hash.fill(0)
    p_pow = _p_pow(t)

    for i in range(t):
        text_hash[i + 1] = (text_hash[i] + ord(text[i]) * p_pow[i]) % MOD
    for i in range(t - q + 1):
        curr_hash = (text_hash[i + q] + MOD - text_hash[i]) % MOD
        if curr_hash == (query_hash * p_pow[i]) % MOD:
            positions.append(i)

    return positions
def test_TernaryHeap():
    max_heap = TernaryHeap(heap_property="max")
    assert raises(IndexError, lambda: max_heap.extract())
    max_heap.insert(100, 100)
    max_heap.insert(19, 19)
    max_heap.insert(36, 36)
    max_heap.insert(17, 17)
    max_heap.insert(3, 3)
    max_heap.insert(25, 25)
    max_heap.insert(1, 1)
    max_heap.insert(2, 2)
    max_heap.insert(7, 7)
    assert str(max_heap) == \
           ('[(100, 100, [1, 2, 3]), (25, 25, [4, 5, 6]), '
            '(36, 36, [7, 8]), (17, 17, []), '
            '(3, 3, []), (19, 19, []), (1, 1, []), '
            '(2, 2, []), (7, 7, [])]')

    assert max_heap.extract().key == 100

    expected_sorted_elements = [36, 25, 19, 17, 7, 3, 2, 1]
    sorted_elements = []
    for _ in range(8):
        sorted_elements.append(max_heap.extract().key)
    assert expected_sorted_elements == sorted_elements

    elements = [
        TreeNode(7, 7),
        TreeNode(25, 25),
        TreeNode(100, 100),
        TreeNode(1, 1),
        TreeNode(2, 2),
        TreeNode(3, 3),
        TreeNode(17, 17),
        TreeNode(19, 19),
        TreeNode(36, 36)
    ]
    min_heap = TernaryHeap(elements=DynamicOneDimensionalArray(
        TreeNode, 9, elements),
                           heap_property="min")
    expected_extracted_element = min_heap.heap[0].key
    assert min_heap.extract().key == expected_extracted_element

    expected_sorted_elements = [2, 3, 7, 17, 19, 25, 36, 100]
    sorted_elements = [min_heap.extract().key for _ in range(8)]
    assert expected_sorted_elements == sorted_elements
示例#10
0
def test_DHeap():
    assert raises(ValueError, lambda: DHeap(heap_property="none", d=4))
    max_heap = DHeap(heap_property="max", d=5)
    assert max_heap.extract() is None
    max_heap.insert(100, 100)
    max_heap.insert(19, 19)
    max_heap.insert(36, 36)
    max_heap.insert(17, 17)
    max_heap.insert(3, 3)
    max_heap.insert(25, 25)
    max_heap.insert(1, 1)
    max_heap = DHeap(max_heap.heap, heap_property="max", d=4)
    max_heap.insert(2, 2)
    max_heap.insert(7, 7)
    assert str(max_heap) == \
           ('[(100, 100, [1, 2, 3, 4]), (25, 25, [5, 6, 7, 8]), '
           '(36, 36, []), (17, 17, []), (3, 3, []), (19, 19, []), '
           '(1, 1, []), (2, 2, []), (7, 7, [])]')

    assert max_heap.extract().key == 100

    expected_sorted_elements = [36, 25, 19, 17, 7, 3, 2, 1]
    sorted_elements = []
    for _ in range(8):
        sorted_elements.append(max_heap.extract().key)
    assert expected_sorted_elements == sorted_elements

    elements = [
        TreeNode(7, 7),
        TreeNode(25, 25),
        TreeNode(100, 100),
        TreeNode(1, 1),
        TreeNode(2, 2),
        TreeNode(3, 3),
        TreeNode(17, 17),
        TreeNode(19, 19),
        TreeNode(36, 36)
    ]
    min_heap = DHeap(elements=DynamicOneDimensionalArray(
        TreeNode, 9, elements),
                     heap_property="min")
    assert min_heap.extract().key == 1

    expected_sorted_elements = [2, 3, 7, 17, 19, 25, 36, 100]
    sorted_elements = [min_heap.extract().key for _ in range(8)]
    assert expected_sorted_elements == sorted_elements
示例#11
0
    def merge(self, other_heap):
        """
        Merges current binomial heap with the given binomial heap.

        Parameters
        ==========

        other_heap: BinomialHeap
        """
        if not _check_type(other_heap, BinomialHeap):
            raise TypeError("Other heap is not of type BinomialHeap.")
        new_root_list = DynamicOneDimensionalArray(BinomialTree, 0)
        i, j = 0, 0
        while ((i <= self.root_list._last_pos_filled)
               and (j <= other_heap.root_list._last_pos_filled)):
            new_tree = None
            while self.root_list[i] is None:
                i += 1
            while other_heap.root_list[j] is None:
                j += 1
            if self.root_list[i].order == other_heap.root_list[j].order:
                new_tree = self.merge_tree(self.root_list[i],
                                           other_heap.root_list[j])
                i += 1
                j += 1
            else:
                if self.root_list[i].order < other_heap.root_list[j].order:
                    new_tree = self.root_list[i]
                    i += 1
                else:
                    new_tree = other_heap.root_list[j]
                    j += 1
            self._merge_heap_last_new_tree(new_root_list, new_tree)

        while i <= self.root_list._last_pos_filled:
            new_tree = self.root_list[i]
            self._merge_heap_last_new_tree(new_root_list, new_tree)
            i += 1
        while j <= other_heap.root_list._last_pos_filled:
            new_tree = other_heap.root_list[j]
            self._merge_heap_last_new_tree(new_root_list, new_tree)
            j += 1
        self.root_list = new_root_list
示例#12
0
 def __new__(cls, elements=None, heap_property="min", d=4):
     obj = Heap.__new__(cls)
     obj.heap_property = heap_property
     obj.d = d
     if heap_property == "min":
         obj._comp = lambda key_parent, key_child: key_parent <= key_child
     elif heap_property == "max":
         obj._comp = lambda key_parent, key_child: key_parent >= key_child
     else:
         raise ValueError("%s is invalid heap property" % (heap_property))
     if elements is None:
         elements = DynamicOneDimensionalArray(TreeNode, 0)
     else:
         if not all(map(lambda x: _check_type(x, TreeNode), elements)):
             raise ValueError("Expect a list/tuple of TreeNode got %s" %
                              (elements))
     obj.heap = elements
     obj._last_pos_filled = obj.heap._last_pos_filled
     obj._build()
     return obj
示例#13
0
def test_BinaryHeap():

    max_heap = BinaryHeap(heap_property="max")

    assert raises(IndexError, lambda: max_heap.extract())

    max_heap.insert(100, 100)
    max_heap.insert(19, 19)
    max_heap.insert(36, 36)
    max_heap.insert(17, 17)
    max_heap.insert(3, 3)
    max_heap.insert(25, 25)
    max_heap.insert(1, 1)
    max_heap.insert(2, 2)
    max_heap.insert(7, 7)
    assert str(max_heap) == \
        ("[(100, 100, [1, 2]), (19, 19, [3, 4]), "
        "(36, 36, [5, 6]), (17, 17, [7, 8]), "
        "(3, 3, []), (25, 25, []), (1, 1, []), "
        "(2, 2, []), (7, 7, [])]")

    assert max_heap.extract().key == 100

    expected_sorted_elements = [36, 25, 19, 17, 7, 3, 2, 1]
    l = max_heap.heap[0].left
    l = max_heap.heap[0].right
    sorted_elements = []
    for _ in range(8):
        sorted_elements.append(max_heap.extract().key)
    assert expected_sorted_elements == sorted_elements

    elements = [
        TreeNode(7, 7),
        TreeNode(25, 25),
        TreeNode(100, 100),
        TreeNode(1, 1),
        TreeNode(2, 2),
        TreeNode(3, 3),
        TreeNode(17, 17),
        TreeNode(19, 19),
        TreeNode(36, 36)
    ]
    min_heap = BinaryHeap(elements=DynamicOneDimensionalArray(
        TreeNode, 9, elements),
                          heap_property="min")
    assert min_heap.extract().key == 1

    expected_sorted_elements = [2, 3, 7, 17, 19, 25, 36, 100]
    sorted_elements = [min_heap.extract().key for _ in range(8)]
    assert expected_sorted_elements == sorted_elements

    non_TreeNode_elements = [(7, 7),
                             TreeNode(25, 25),
                             TreeNode(100, 100),
                             TreeNode(1, 1), (2, 2),
                             TreeNode(3, 3),
                             TreeNode(17, 17),
                             TreeNode(19, 19),
                             TreeNode(36, 36)]
    assert raises(
        ValueError, lambda: BinaryHeap(elements=non_TreeNode_elements,
                                       heap_property='min'))
示例#14
0
def longest_increasing_subsequence(array, **kwargs):
    """
    Returns the longest increasing subsequence (as a OneDimensionalArray) that
    can be obtained from a given OneDimensionalArray. A subsequence
    of an array is an ordered subset of the array's elements having the same
    sequential ordering as the original array. Here, an increasing
    sequence stands for a strictly increasing sequence of numbers.

    Parameters
    ==========

    array: OneDimensionalArray
        The given array in the form of a OneDimensionalArray
    backend: pydatastructs.Backend
        The backend to be used.
        Optional, by default, the best available
        backend is used.

    Returns
    =======

    output: OneDimensionalArray
        Returns the longest increasing subsequence that can be obtained
        from the given array

    Examples
    ========

    >>> from pydatastructs import lower_bound, OneDimensionalArray as ODA
    >>> from pydatastructs import longest_increasing_subsequence as LIS
    >>> array = ODA(int, [2, 5, 3, 7, 11, 8, 10, 13, 6])
    >>> longest_inc_subsequence = LIS(array)
    >>> str(longest_inc_subsequence)
    '[2, 3, 7, 8, 10, 13]'
    >>> array2 = ODA(int, [3, 4, -1, 5, 8, 2, 2 ,2, 3, 12, 7, 9, 10])
    >>> longest_inc_subsequence = LIS(array2)
    >>> str(longest_inc_subsequence)
    '[-1, 2, 3, 7, 9, 10]'
    """
    raise_if_backend_is_not_python(longest_increasing_subsequence,
                                   kwargs.get('backend', Backend.PYTHON))
    n = len(array)
    dp = OneDimensionalArray(int, n)
    dp.fill(0)
    parent = OneDimensionalArray(int, n)
    parent.fill(-1)
    length = 0
    for i in range(1, n):
        if array[i] <= array[dp[0]]:
            dp[0] = i
        elif array[dp[length]] < array[i]:
            length += 1
            dp[length] = i
            parent[i] = dp[length - 1]
        else:
            curr_array = [array[dp[i]] for i in range(length)]
            ceil = lower_bound(curr_array, array[i])
            dp[ceil] = i
            parent[i] = dp[ceil - 1]
    ans = DynamicOneDimensionalArray(int, 0)
    last_index = dp[length]
    while last_index != -1:
        ans.append(array[last_index])
        last_index = parent[last_index]
    n = ans._last_pos_filled + 1
    ans_ODA = OneDimensionalArray(int, n)
    for i in range(n):
        ans_ODA[n - 1 - i] = ans[i]
    return ans_ODA
示例#15
0
def _knuth_morris_pratt(text, query):
    if len(text) == 0 or len(query) == 0:
        return DynamicOneDimensionalArray(int, 0)
    kmp_table = _build_kmp_table(query)
    return _do_match(text, query, kmp_table)