Esempio n. 1
0
def runTest(fp):
    '''
    :param fp: file pointer to read in values
    :return: number of right and the length of the linked list

    creates linked lists and runs merge sort, then checks for correct result
    '''
    s_list = llist.LinkedList()
    count = AddValues(s_list,fp)
    s_list.head = student.MergeSort(s_list.head)


    a_list = llist.LinkedList()
    fp.seek(0,0)
    AddValues(a_list,fp)
    a_list.head = answer.MergeSort(a_list.head)

    right = check(s_list, a_list)


   # right = 0

   # while s_list.head.next:
   #     if s_list.head <= s_list.head.next:
   #         right +=1
   #     s_list.head = s_list.head.next




    return right, count
Esempio n. 2
0
def rev_order_rec(LL1, LL2, carry):
    if (LL1 == None or LL1.head == None) and (LL2 == None or LL2.head == None):
        return LinkedList()
    value = 0
    if LL1 == None or LL1.head == None:
        value = LL2.head.data
    elif LL2 == None or LL2.head == None:
        value = LL1.head.data
    else:
        value = LL1.head.data + LL2.head.data
    value += carry
    tmp = value

    if value >= 10:
        carry = 1
        value = value % 10
    else:
        carry = 0

    if LL1 == None or LL1.head == None:
        res = rev_order_rec(None, LinkedList(LL2.head.next), carry)
    elif LL2 == None or LL2.head == None:
        res = rev_order_rec(LinkedList(LL1.head.next), None, carry)
    else:
        res = rev_order_rec(LinkedList(LL1.head.next),
                            LinkedList(LL2.head.next), carry)

    n = Node(value)
    print("curr value:", n.data)
    if res.head == None and tmp >= 10:
        m = Node(1)
        res.append(m)
    res.append(n)
    return res
Esempio n. 3
0
def sum_list(ll1: LinkedList, ll2: LinkedList) -> LinkedList:
    """
    >>> sum_list(LinkedList(7, 1, 6), LinkedList(5, 9, 2))
    [2, 1, 9]
    >>> sum_list(LinkedList(7, 1, 6), LinkedList(5, 9, 2, 1))
    [2, 1, 9, 1]
    >>> sum_list(LinkedList(5, 9, 2, 1), LinkedList(7, 1, 6))
    [2, 1, 9, 1]
    >>> sum_list(LinkedList(5), LinkedList(1))
    [6]
    """

    carry = 0
    curr1, curr2 = ll1.head, ll2.head
    while (curr1.next if curr1 else None) or \
            (curr2.next if curr2 else None):
        s = (curr1.val if curr1 else 0) + (curr2.val if curr2 else 0) + carry
        carry = int(s / 10)
        curr1 = append_to_node(s % 10, curr1)
        curr2 = append_to_node(s % 10, curr2)
    s = (curr1.val if curr1 else 0) + (curr2.val if curr2 else 0) + carry
    carry = int(s / 10)
    if curr1:
        curr1 = append_to_node(LinkedList.Node(carry), curr1, val=s % 10)
        return ll1
    if curr2:
        curr2 = append_to_node(LinkedList.Node(carry), curr2, val=s % 10)
        return ll2
Esempio n. 4
0
 def test_linked_list_del_single(self):
     test_llist = ll.LinkedList()
     test_llist.add_in_tail(ll.Node(99))
     item_del = 99
     test_llist.delete(item_del, all=False)
     self.assertEqual(None, test_llist.head)
     self.assertEqual(None, test_llist.tail)
Esempio n. 5
0
def add(LL1, LL2):

    global carry
    print("carry: ", carry)
    if LL1.head == None and LL2.head == None:
        return LinkedList()

    res = add(LinkedList(LL1.head.next), LinkedList(LL2.head.next))
    value = LL1.head.data + LL2.head.data

    if carry == 0:
        print(LL1.head.data, LL2.head.data)
        value += has_carry(LL1, LL2)
    else:
        value += carry

    if value >= 10:
        value = value % 10
        carry = 1
    else:
        carry = 0

    n = Node(value)
    res.prepend(n)
    return res
Esempio n. 6
0
def has_intersection(list1, list2):
    shorter = LinkedList()
    longer = LinkedList()
    list1_size = list_size(list1)
    list2_size = list_size(list2)
    if list1_size > list2_size:
        longer = list1
        shorter = list2
    else:
        longer = list2
        shorter = list1

    ptr_shorter = shorter._head
    ptr_longer = longer._head

    difference_in_size = abs(list1_size - list2_size)
    for i in range(difference_in_size):
        ptr_longer = ptr_longer.next

    while ptr_longer is not None:
        if ptr_shorter == ptr_longer:
            return True, str(ptr_shorter.data.value)
        ptr_shorter = ptr_shorter.next
        ptr_longer = ptr_longer.next
    return False, None
    def bidirectional(self, start, start2):
        moves, moves2 = [], []

        stack = LinkedList.DoublyLinkedList()
        stackCopy = LinkedList.DoublyLinkedList()
        stack.insertEnd(start, None, None)
        stackCopy.insertEnd(start, None, None)
        visited = [start]

        stack2 = LinkedList.DoublyLinkedList()
        stackc2 = LinkedList.DoublyLinkedList()
        stack2.insertEnd(start2, None, None)
        stackc2.insertEnd(start2, None, None)
        visited2 = [start2]

        while stack.empty() is not None and stack2.empty() is not None:
            currentMove = stack.removeStart()
            currentMove2 = stack2.removeStart()

            nextMoves = Expansion.getNextMoves(currentMove.data)
            for i in range(len(nextMoves)):
                newMove = nextMoves[i]
                if newMove not in visited:
                    stack.insertEnd(newMove, currentMove, None)
                    stackCopy.insertEnd(newMove, currentMove, None)
                    visited.append(newMove)
                    if newMove in visited2:
                        while currentMove2.prevPointer is not None:
                            currentMove2 = currentMove2.prevPointer
                        while currentMove2.data != newMove:
                            currentMove2 = currentMove2.nextPointer
                        if currentMove2.parent is None:
                            moves2.append(currentMove.data)
                        while currentMove2.parent is not None:
                            currentMove2 = currentMove2.parent
                            moves2.append(currentMove2.data)
                        moves1 = stackCopy.tree()
                        return "Bidirecional solution: " + str(
                            list(moves1[::-1]) + moves2)

            nextMoves = Expansion.getNextMoves(currentMove2.data)
            for i in range(len(nextMoves)):
                newMove = nextMoves[i]
                if newMove not in visited2:
                    stack2.insertEnd(newMove, currentMove2, None)
                    stackc2.insertEnd(newMove, currentMove2, None)
                    visited2.append(newMove)
                    if newMove in visited:
                        while currentMove.prevPointer is not None:
                            currentMove = currentMove.prevPointer
                        while currentMove.nextPointer is not None and currentMove.data != newMove:
                            currentMove = currentMove.nextPointer
                        if currentMove.parent is None:
                            moves2.append(currentMove.data)
                        while currentMove.parent is not None:
                            currentMove = currentMove.parent
                            moves2.append(currentMove.data)
                        moves1 = stackc2.tree()
                        return "Bidirecional solution: " + str(
                            list(moves2[::-1]) + moves1)
Esempio n. 8
0
class Queue:
    def __init__(self):
        self.items = LinkedList()

    def __len__(self):
        return len(self.items)

    def enqueue(self, new_val):
        self.items.append(new_val)

    def dequeue(self):
        if len(self.items) == 0:
            return
        item = self.items.head.val
        self.items.remove_at(0)
        return item

    def peek(self):
        if self.is_empty():
            return
        return self.items.head.val

    def is_empty(self):
        return len(self.items) <= 0

    def __str__(self):
        if len(self) == 0:
            return "Empty Queue"
        return str(self.items)
Esempio n. 9
0
def test_reverse_up_to():
    _print_test_start("test_reverse_up_to")
    passed = True

    # Test #1
    l = _create_increasing_ordered_list(20)
    l.printList()
    actual = l.reverseUpTo(10)
    print("Original ll: ")
    l.printList()
    expected = _create_decreasing_ordered_list(10)
    actual_ll = LinkedList(actual)
    actual_ll.printList()

    actualNode = actual_ll.head
    expectedNode = expected.head

    while expectedNode != None and expectedNode.next != None:
        if expectedNode.value != actualNode.value:
            passed = False
            _print_test_result(1, expectedNode.value, actualNode.value)

        expectedNode = expectedNode.next
        actualNode = actualNode.next

    _print_test_status(passed, "test_reverse_up_to")
Esempio n. 10
0
def sumlists(num1, num2):
    carry = 0
    n1 = num1.head
    n2 = num2.head
    result = LinkedList()
    while n1.next != None and n2.next != None:
        result.addnode((carry + n1.data + n2.data) % 10)
        carry = (carry + n1.data + n2.data) / 10
        n1 = n1.next
        n2 = n2.next

    result.addnode((carry + n1.data + n2.data) % 10)
    carry = (carry + n1.data + n2.data) / 10

    if n1.next == None:
        n = n2.next
    else:
        n = n1.next

    while n != None:
        result.addnode((carry + n.data) % 10)
        carry = (carry + n.data) / 10
        n = n.next

    if carry != 0:
        result.addnode(carry)

    return result
Esempio n. 11
0
class StackList(object):
    __slots__ = ['__llista']
    def __init__(self):
        super(StackList, self).__init__() # inicializacion
        self.__llista=LinkedList()
        
    def push(self, data):
        self.__llista.insertBefore(data) # insertamos al principio de la pila
        
    def pop(self):
        aux=self.__llista.getHead() # creamos un auxiliar el cual es la cabeza que es donde esta el actual
        self.__llista.remove() # Eliminamos el nodo actual que es el primero de la cola
        return aux # Devolvemos el dato del elemento borrado
        
    def head(self):
        aux=self.__llista.getHead() # auxiliar es la cabeza que es donde esta el actual
        return aux # devolvemos el dato del actual
        
    def purge(self):
        self.__llista.clear() # Borramos toda la pila
        
    def __len__(self):
        return self.__llista.size() # devuelve la longitud de la pila
    
    def __str__(self):
        return self.__llista.__str__() # devuelve la pila convertida en una cadena de caracteres
Esempio n. 12
0
class Stack:

    # Constructor of Linked List
    def __init__(self):
        self._theStack = LinkedList()

    def isEmpty(self):
        return self._theStack.length() == 0

    def push(self, theValue):
        self._theStack.headInsert(theValue)

    def pop(self):
        if self.isEmpty():
            raise IndexError("Stack is empty!")
        else:
            return self._theStack.removeFromHead()

    def peek(self):
        if self.isEmpty():
            raise IndexError("Stack is empty!")
        else:
            return self._theStack.getHead().GetValue()

    def __str__(self):
        print '--The Stack--'
        stackList = list()
        while not self.isEmpty():
            stackList.append(self.pop())
        for i in reversed(stackList):
            self.push(i)

        return str(stackList)
Esempio n. 13
0
def sample_linkedlist_function():
    linked_list = LinkedList()
    init_linkedlist(linked_list)
    print(linked_list.to_list_forward())
    print(linked_list._head.data.value)
    print(type(linked_list._head))
    return recursive_linkedlist_to_list_forward(linked_list._head)
Esempio n. 14
0
def pal(lis):
    size = lis.size()
    new_list = LinkedList()
    cur = lis.head
    for i in range(size // 2 - 1):
        cur = cur.get_next()
    tem = cur
    cur = cur.get_next()
    tem.set_next(None)
    if size % 2 == 1:
        cur = cur.get_next()
    new_list.head = cur
    cur = cur.get_next()
    while (cur != None):
        new_list.insert(cur.get_data())
        cur = cur.get_next()

    par1 = lis.head
    par2 = new_list.head
    while (par1 != None):
        if (par1.get_data() != par2.get_data()):
            return False
        par1 = par1.get_next()
        par2 = par2.get_next()
    return True
Esempio n. 15
0
    def test_linked_list2_del_all(self):
        test_llist = ll.LinkedList2()
        self.assertEqual(None, test_llist.delete(1, all=True))

        temp_list = [
            11, 11, 11, 11, 12, 23, 11, 11, 34, 45, 56, 67, 11, 78, 11, 89, 11,
            11, 11
        ]
        for i in temp_list:
            test_llist.add_in_tail(ll.Node(i))
        del_item = 11
        test_llist.delete(del_item, all=True)
        # test_llist.print_all_nodes_both_row()
        temp_list = [i for i in temp_list if i != del_item]
        self.common_tests(temp_list, test_llist)

        # delete all same node:
        test_llist.clean()
        for i in range(10):
            test_llist.add_in_tail(ll.Node(del_item))
        test_llist.delete(del_item, all=True)
        self.assertEqual(None, test_llist.head)
        self.assertEqual(None, test_llist.tail)
        self.assertEqual(0, test_llist.len())
        self.assertEqual(0, test_llist.len_reverse())
Esempio n. 16
0
def pivot(ll, k):
    lower_head = LL.Node('dummy')
    equal_head = LL.Node('dummy')
    higher_head = LL.Node('dummy')
    lower = lower_head
    equal = equal_head
    higher = higher_head

    cur = ll.head
    while (cur):
        if cur.data < k:
            lower.nextNode = cur
            lower = lower.nextNode
        elif cur.data == k:
            equal.nextNode = cur
            equal = equal.nextNode
        else:
            higher.nextNode = cur
            higher = higher.nextNode
        cur = cur.nextNode
    higher.nextNode = None
    lower.nextNode = equal_head.nextNode
    equal.nextNode = higher_head.nextNode
    ll.head = lower_head.nextNode
    return repr(ll)
Esempio n. 17
0
def get_levels(t: Tree) -> [LinkedList]:
    """
    Complexity: O(2^depth) or O(nodes) on space and time
    Doing recursive w DFS would be same time but O(d) space!!!
    >>> t = Tree()
    >>> t.bst_from([1, 2, 3])
    >>> get_levels(t)
    [[2], [1, 3]]
    >>> t.bst_from([1, 2, 3, 4, 5, 6, 7, 8, 9])
    >>> get_levels(t)
    [[5], [3, 8], [2, 4, 7, 9], [1, 6]]
    """

    if not t.root:
        return []
    n = t.root
    n.level = 0
    q = deque([n])
    levels = [LinkedList()]
    while q:
        n = q.popleft()
        if n.left:
            n.left.level = n.level + 1
            q.append(n.left)
        if n.right:
            n.right.level = n.level + 1
            q.append(n.right)

        levels[n.level].append_to_tail(n.data)
        if q and n.level != q[0].level:
            levels.append(LinkedList())
    return levels
Esempio n. 18
0
def rec_intersect(LL1, LL2):
    print(LL1.head.data, LL2.head.data)

    if LL1 == None and LL2 == None:
        return None

    elif LL1 == None:
        res = intersect(LL1, LinkedList(LL2.head.next))

    elif LL2 == None:
        res = intersect(LinkedList(LL1.head.next), LL2)

    else:
        res = intersect(LinkedList(LL1.head.next), LinkedList(LL2.head.next))

    if res != None:
        return res

    if LL1.head == LL2.head:
        return None

    else:
        if LL1.head.next == LL2.head.next and LL1.head.next != None:
            return LL1.head.next

    return None
Esempio n. 19
0
class Queue:
    def __init__(self):
        self.queue = LinkedList()

    def __str__(self):
        return str(self.queue)

    def front(self):
        return self.queue.first()

    def deQueue(self):
        return self.queue.removeHead()

    def enQueue(self, item):
        if not isinstance(item, Node):
            item = Node(item, None)
        self.queue.appendItem(item)

    def size(self):
        return self.queue.size()

    def isEmpty(self):
        if self.size() == 0:
            return True
        return False
Esempio n. 20
0
def setup_for_read_numbers():
    l1 = LL.Node(3)
    l1.add(1)
    l1.add(5)
    l2 = LL.Node(5)
    l2.add(9)
    l2.add(2)
    return l1, l2
    def test_reversed_linked_list(self) -> None:
        """Test algorithm on a reversed list"""
        test_list = LinkedList([10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0])

        actual = self.algorithm(test_list).to_list()
        expected = sorted(test_list.to_list())

        assert actual == expected
    def test_key_reverse_linked_list(self) -> None:
        """Test algorithm on a list, sort with a reversing key."""
        test_list = LinkedList([10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0])

        actual = self.algorithm(test_list, (lambda x: -x)).to_list()
        expected = sorted(test_list.to_list(), key=(lambda x: -x))

        assert actual == expected
Esempio n. 23
0
 def __init__(self, data):
     """
     Builder of class Node, intializes each node with the parametre data
     and creates and empty list for childs
     :param data: what wants to be stored in the node
     """
     self.data = data
     self.childs = LinkedList()
    def test_unsorted_linked_list(self) -> None:
        """Test algorithm on an unsorted list"""
        test_list = LinkedList([9, 7, 5, 2, 4, 5, 3, 3, 2, 1, 10, 200])

        actual = self.algorithm(test_list).to_list()
        expected = sorted(test_list.to_list())

        assert actual == expected
    def test_sorted_linked_list(self) -> None:
        """Test algorithm on a sorted list"""
        test_list = LinkedList([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

        actual = self.algorithm(test_list).to_list()
        expected = sorted(test_list.to_list())

        assert actual == expected
Esempio n. 26
0
def test_delete_node_in_middle():
    assert LL.delete_node_in_middle(linkedlist.next) == 2
    assert linkedlist.data == 1
    assert linkedlist.next.data == 3
    try:
        assert LL.delete_node_in_middle(
            linkedlist.next) == "should throw error"
    except ValueError:
        pass
 def removeElements(self, head, val):
     """
     :type head: ListNode
     :type val: int
     :rtype: ListNode
     """
     list = LinkedList(head)
     list.remove(val)
     return list.head()
Esempio n. 28
0
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        list = LinkedList(head)
        list.reverse()

        return list.head()
Esempio n. 29
0
    def test_when_there_are_two_items_added_to_list_that_point_to_each_other_should_report_it_as_a_cycle(self):
        linked_list = LinkedList()
        linked_list.add('test item 0')
        linked_list.add('test item 1')
        node0 = linked_list.get(0)
        node1 = linked_list.get(1)
        node1.next_node = node0

        self.assertTrue(linked_list.has_loop())
Esempio n. 30
0
 def test_linked_list2_add_in_head(self):
     temp_list = [12, 23, 34, 45, 56, 67, 78, 89]
     test_llist2 = ll.LinkedList2()
     for i in temp_list:
         test_llist2.add_in_tail(ll.Node(i))
     item_head = 10
     temp_list.insert(0, item_head)
     test_llist2.add_in_head(ll.Node(item_head))
     # test_llist2.print_all_nodes_both_row()
     self.common_tests(temp_list, test_llist2)
Esempio n. 31
0
 def test_linked_list_del_last(self):
     temp_list = [12, 23, 11, 11, 34, 45, 56, 67, 11, 78, 11, 89, 11, 99]
     test_llist = ll.LinkedList()
     for i in temp_list:
         test_llist.add_in_tail(ll.Node(i))
     del_item = 99
     test_llist.delete(del_item, all=False)
     temp_list.remove(del_item)
     self.compare_list_llist(temp_list, test_llist)
     self.assertEqual(temp_list[-1], test_llist.tail.value)
Esempio n. 32
0
 def test_when_3_items_have_been_added_and_then_first_item_removed_3_times_count_should_be_0(
         self):
     linked_list = LinkedList()
     linked_list.add('test item 0')
     linked_list.add('test item 1')
     linked_list.add('test item 2')
     linked_list.remove(0)
     linked_list.remove(0)
     linked_list.remove(0)
     self.assertEqual(linked_list.count, 0)
Esempio n. 33
0
 def test_linked_list_clean(self):
     temp_list = [
         12, 23, 11, 11, 34, 45, 56, 67, 11, 78, 11, 89, 11, 11, 99
     ]
     test_llist = ll.LinkedList()
     for i in temp_list:
         test_llist.add_in_tail(ll.Node(i))
     test_llist.clean()
     self.assertEqual(None, test_llist.head)
     self.assertEqual(None, test_llist.tail)
def Test():
	l = LinkedList(0)
	for i in range (1,5):
		l.AddNode(i)

	last = l.last()
	last.next = l.root.next.next
	n = Detectcircle(l.root)
	print n
	m = FindFirstInloop(l.root)
	print m
Esempio n. 35
0
def partition(linkedList, x):
    small, large = LinkedList(), LinkedList();
    node = linkedList.head
    while node:
        if node.value < x:
            small.addNode(node.value)
        else:
            large.addNode(node.value)
        node = node.next
    small.tail.next = large.head
    return small
Esempio n. 36
0
class Stack(IReadOnlyCollection):
    """ Represents a generic stack. """
    # Remarks:
    # T is the type of item on the stack.

    def __init__(self, dataContainer = None):
        """ Creates a new stack instance that uses the specified list to store its data. """
        if dataContainer is None:
            self.data_container = None
            self.data_container = LinkedList()
            return
        self.data_container = dataContainer

    def push(self, Item):
        """ Pushes an item on the stack. """
        self.data_container.insert(0, Item)

    def pop(self):
        """ Pops the item at the top of the stack. """
        # Pre:
        # The stack may not be empty.
        # Post:
        # If the stack was empty, the stack's state will not change, and None will be returned.
        if self.is_empty:
            return None
        value = self.data_container[0]
        self.data_container.remove_at(0)
        return value

    def __iter__(self):
        """ Creates an iterator that iterates over every element in the collection. """
        return self.data_container.__iter__()

    @property
    def is_empty(self):
        """ Gets a boolean value that indicates whether the stack is empty or not. """
        return self.count == 0

    @property
    def count(self):
        """ Gets the number of items on the stack. """
        return self.data_container.count

    @property
    def top(self):
        """ Peeks at the item at the top of the stack, without removing it. """
        # Pre:
        # The stack may not be empty.
        # Post:
        # If the stack was empty, None will be returned.
        if self.is_empty:
            return None
        else:
            return self.data_container[0]
Esempio n. 37
0
class StackList(object):
    """
    StackList
    """
    def __init__(self):
        self.llista=LinkedList() # Initialize value
    """
    Introdueix un element a la llista utilitzant el metode de la LinkedList.
    :param:data, dada a introduir
    :return: None
    """
    def push(self, data):
        # Type code here
        self.llista.insertAfter(data)
    """
    Extreu un element a la llista utilitzant el metode de la LinkedList.
    :return: data Conte l'informació del node
    """
    def pop(self):
        # Type code here
        data=self.llista.getTail()
        self.llista.remove();
        return data;
    """
    Retorna l'element el primer element de la pila.
    :return: data
    """
    def head(self):
        # Type code here
        return self.llista.getTail()
    
    """
    Esborra el contingut de tota la pila.
    :return: None
    """
    def purge(self):
        self.llista.clear()
        
    """
    Metode que s'utilitza per implementar la funcio len(). .
    :param:data, dada a introduir
    :return: int Longitud de la pila
    """
    def __len__(self):
        # Type code here
        return self.llista.getSize()
    """
    Metode que s'utilitza per implementar la funcio print().
    :return string Retorna una cadena amb tots els elements de la pila.
    """    
    def __str__(self):
        # Type code here
        return self.llista.__str__()
Esempio n. 38
0
 def test_when_3_items_have_been_added_and_then_first_item_removed_3_times_count_should_be_0(self):
     linked_list = LinkedList()
     linked_list.add('test item 0')
     linked_list.add('test item 1')
     linked_list.add('test item 2')
     linked_list.remove(0)
     linked_list.remove(0)
     linked_list.remove(0)
     self.assertEqual(linked_list.count, 0)
def find_nth_to_last(head, n):
    dummy = LinkedList()
    dummy.next = head
    p = dummy
    while n > 0 and p.next:
        p = p.next
        n -= 1

    pp = dummy
    while pp.next and p.next:
        pp = pp.next
        p = p.next
    return pp.next
Esempio n. 40
0
class HashTable():
	buckets = 0
	hash_func = None
	match_func = None
	destroy_fun = None
	size = 0
	table = None

	def __init__(self,bucks, hasher, matcher,destroy):
		self.buckets 	= bucks
		self.hash_func	= hasher
		self.match_func	= matcher
		self.destroy_func	= destroy
		self.table = LinkedList();
		for i in range(0, self.buckets):
			self.table.attach(LinkedList())
		
		return

	def Table_destroy(self):
		for i in range(0,self.buckets):
			self.destroy(self.table.getElement())
		self.table = None
		return

	def Table_insert(self, value):
		to_insert = value
		x = self.Table_lookup(to_insert)
		if x == 0:
			return 1
		bucket = self.hash_func(value) % self.buckets

		self.table.get(bucket).attach(value)
		return

	def Table_remove(self, value):
		bucket = self.hash_func(value) % self.buckets
		self.table.get(bucket).delete(value)
		return

	def Table_lookup(self, value):
		bucket = self.hash_func(value) % self.buckets
		print "Bucket", bucket
		if not (self.table.get(bucket).isEmpty()):
			x = self.table.get(bucket).getvalue()
		else:
			return 1
		return 1

	def Table_size(self):
		return self.table.size()
Esempio n. 41
0
class Stack:
    def __init__(self):
        self.stack = LinkedList()

    def push(self,item):
        self.stack.addToHead(Node(item,None))

    def pop(self):
        return self.stack.removeFromHead().data

    def size(self):
        return self.stack.size

    def list(self):
        return self.stack.list()
Esempio n. 42
0
 def put(self, key, value):
     llist = self.links[self.hash(key)]
     if llist == None:
         node = Link(key = key, value = value)
         llist = LinkedList(head=node)
         self.links[self.hash(key)] = llist
         return
     cur_node = llist.head
     while cur_node != None:
         if cur_node.key == key:
             cur_node.value = value
             return
         else:
             cur_node = cur_node.next
     llist.push(Link(key = key, value = value))
Esempio n. 43
0
 def __init__(self, dataContainer = None):
     """ Creates a new stack instance that uses the specified list to store its data. """
     if dataContainer is None:
         self.data_container = None
         self.data_container = LinkedList()
         return
     self.data_container = dataContainer
Esempio n. 44
0
 def __init__(self, data):
     """
     Initialize node.
     :param data: Data of new node.
     """
     self.data = data
     self.childs = LinkedList()
Esempio n. 45
0
def main():
	# make the nodes from the .csv file and put them into a linked list
	with open('output.csv', 'r') as csvFile:
		lists = LinkedList.linkedList()
		for row in csvFile:
			diseaseText = repr(row.strip())
			lists.newNode(diseaseText)

	# print the list to the console (currently prints in reverse order of addition to the list)
	currentNode = lists.head
	while currentNode.next != None:
		print currentNode.cargo
		currentNode = currentNode.next

	# print only the diseases beginning with user inputted letter
	hasDiseases = False
	print " "
	searchFor = raw_input("Enter a letter to narrow search (A-G): ")
	print " "
	currentNode = lists.head
	while currentNode.next != None:
		if currentNode.cargo[1] == searchFor:
			print currentNode.cargo
			hasDiseases = True
		currentNode = currentNode.next
	if hasDiseases == False:
		print "List not extensive enough, no diseases found."
	print " "
Esempio n. 46
0
	def parseList(self, index, s):
		li=LinkedList();
		i=0;
		for i in range (index, len(s)):
			# If it is a list
			if s[i] =='(' or s[i] == '\'':
				if i != index:
					index, tmp=self.parseList(i+1, s);
					li.prepend(tmp);
				else:
					continue;
			elif s[i] == ')':
				break;
			else:
				li.prepend(s[i]);
		return i, li;
Esempio n. 47
0
    def test_when_3_items_have_been_added_and_then_middle_item_removed_then_first_item_should_point_to_third_one(self):
        linked_list = LinkedList()
        linked_list.add('test item 0')
        linked_list.add('test item 1')
        linked_list.add('test item 2')
        linked_list.remove(1)

        first_node = linked_list.get_first()
        self.assertEqual(first_node.next_node.value, 'test item 2')
Esempio n. 48
0
 def test_when_3_items_have_been_added_and_last_one_removed_then__get_last__should_return_second_item_with_no_next_node(self):
     linked_list = LinkedList()
     linked_list.add('test item 0')
     linked_list.add('test item 1')
     linked_list.add('test item 2')
     linked_list.remove(2)
     last_node = linked_list.get_last()
     self.assertEqual(last_node.value, 'test item 1')
     self.assertIsNone(last_node.next_node)
Esempio n. 49
0
    def test_when_there_is_a_loop_in_the_middle_of_the_list_should_be_able_to_report_it(self):
        linked_list = LinkedList()
        linked_list.add('test item 0')
        linked_list.add('test item 1')
        linked_list.add('test item 2')
        linked_list.add('test item 3')
        linked_list.add('test item 4')

        node1 = linked_list.get(1)
        node3 = linked_list.get(3)
        node3.next_node = node1

        self.assertTrue(linked_list.has_loop())
Esempio n. 50
0
 def __init__(self, data):
     """
     Builder of class Node, intializes each node with the parametre data
     and creates and empty list for childs
     :param data: what wants to be stored in the node
     """
     self.data = data
     self.childs = LinkedList()
Esempio n. 51
0
 def __init__(self, term, year):
     self._term = term
     self._year = year
     # each quarter has own list of courses
     self.courses = LinkedList.myLL()
     self.units = 0
     self.GTU = 0
     self.GPA = 0
     self.DefUnits = 0
Esempio n. 52
0
    def test_when_adding_second_element_previous_one_should_point_to_it(self):
        linked_list = LinkedList()
        linked_list.add('test item 0')
        first_node = linked_list.get(0)

        linked_list.add('test item 1')

        self.assertEqual(first_node.next_node, linked_list.get_last())
Esempio n. 53
0
	def __init__(self,bucks, hasher, matcher,destroy):
		self.buckets 	= bucks
		self.hash_func	= hasher
		self.match_func	= matcher
		self.destroy_func	= destroy
		self.table = LinkedList();
		for i in range(0, self.buckets):
			self.table.attach(LinkedList())
		
		return
Esempio n. 54
0
 def test_when_adding_several_items_should_be_able_to_get_last_node_by_index(self):
     linked_list = LinkedList()
     linked_list.add('test item 0')
     linked_list.add('test item 1')
     linked_list.add('test item 2')
     linked_list.add('test item 3')
     last_node = linked_list.get(3)
     self.assertEqual(last_node.value, 'test item 3')
Esempio n. 55
0
def evaluateCycleDetection(sizeOfList, cycleDetectionAlgorithm, locationOfCycle):
    '''
    Evaluates the specified Linked List cycle detection algorithm by creating lists with cycles from size 2 up to the
    specified size and returning a (python) list specifying the number of iterations it took to find the cycle.
    '''
    numberOfIterations = [] #y-axis
    
    for i in range (2, sizeOfList):
        list = LinkedList.createLinkedList(i, True, int(i * locationOfCycle))
        containsCycle, iterationsForList = cycleDetectionAlgorithm(list)
        
        assert containsCycle # all of the generated lists should contain cycles.
        
        numberOfIterations.append(iterationsForList)

    return numberOfIterations
Esempio n. 56
0
def addList(list1, list2):
    a, b = list1.head, list2.head
    result = LinkedList()
    temp = 0
    while a and b:
        num = (a.value + b.value + temp) % 10
        result.addNode(num)
        temp = (a.value + b.value + temp) / 10
        a, b = a.next, b.next
    if a:
        result.addNode(a.value + temp)
        reuslt.tail.next = a.next
    elif b:
        result.addNode(b.value + temp)
        result.tail.next = b.next
    return result
Esempio n. 57
0
from LinkedList import *

def delete_middle_node(node):
    node.value = node.next.value
    node.next = node.next.next

ll = LinkedList()
ll.add_multiple([1, 2, 3, 4])
middle_node = ll.add(5)
ll.add_multiple([7, 8, 9])

print(ll)
delete_middle_node(middle_node)
print(ll)
            else:
                smallEnd.next = node
                smallEnd = smallEnd.next
        else:
            if not largeStart:
                largeStart = largeEnd = node
            else:
                largeEnd.next = node
                largeEnd = largeEnd.next
        node = node.next

    if smallEnd is None:
        return linkedlist(largeStart)

    smallEnd.next = largeStart

    return LinkedList(smallStart)


if __name__ == "__main__":
    nodes = [Node(i) for i in range(10)]
    nodes.extend([Node(3), Node(5)])
    nodes.insert(1, Node(8))

    linkedlist = LinkedList()
    for node in nodes:
        linkedlist.addNode(node)
    print linkedlist

    print partitionList(linkedlist, 5)
Esempio n. 59
0
from LinkedList import *

def loopBegin(linkedList):
    slow, fast, start = linkedList.head, linkedList.head, linkedList.head
    while slow and fast:
        slow, fast = slow.next, fast.next.next
        if slow == fast: break
    while start and slow:
        start, slow = start.next, slow.next
        if start == slow: break
    return start

test = LinkedList()
test.generate(20, 0, 9)
print(test)
test.tail.next = test.head.next.next.next
print(loopBegin(test).value)

Esempio n. 60
0
import SetupQuarter
import LinkedList
import Quarter
import Course
import re

SetupQtr = SetupQuarter.SetupQuarter()
quarters = LinkedList.myLL()
originalGPA = 0

def getUnits():
    units = 0
    for i in range (0, quarters.size()):
        qtr = quarters.get(i)
        units += qtr.getUnits()
        return units

def getUnitsTaken():
    defUnits = 0
    for i in range (0, quarters.size()):
        qtr = quarters.get(i)
        defUnits += qtr.defUnits()
        return defUnits


def printGPA(currQtr, diffGPA, newGPA):
    if diffGPA > 0:
        print("\t>\tYour " + currQtr.getName() + " GPA went UP by " + str(diffGPA) + ":", newGPA)
    elif diffGPA < 0:
        print("\t>\tYour " + currQtr.getName() + " GPA went DOWN by " + str(abs(diffGPA)) + ":", newGPA)
    else: