Exemplo n.º 1
0
class Queue(object):
    """Will create a instance of Queue and allow enqueue(), dequeue(), peek(), size() and len() methods to work."""
    def __init__(self, iterable=None):
        """Will init a new instance of the Stack class."""
        from dll import DoubleLinkedList
        self._dll = DoubleLinkedList()
        self._counter = 0

    def enqueue(self, data):
        """Will push a new element into the Queue."""
        self._dll.append(data)
        self._counter += 1

    def dequeue(self):
        """Will remove the first element in the Queue."""
        if self._dll.head:
            self._counter -= 1
        return self._dll.pop()

    def peek(self):
        """Will return the next value in the Queue."""
        return self._dll.head.data

    def __len__(self):
        """Will return the length of the stack using len()."""
        return self._counter
Exemplo n.º 2
0
class Queue(object):
    """Class Queue for enqueue and dequeue data structure."""
    def __init__(self):
        """Init for Queue."""
        self._new_dll = DoubleLinkedList()

    def enqueue(self, val):
        """Enqueue function for queue pushes value to head."""
        return self._new_dll.push(val)

    def dequeue(self):
        """Dequeue function for queue removes val from tail and returns val."""
        return self._new_dll.shift()

    def peek(self):
        """Return a new value without dequeuing it."""
        print(self._new_dll.tail.data)

    def size(self):
        """Length function for the queue."""
        return self._new_dll.size()

    def __len__(self):
        """Length."""
        return self._new_dll.size()
Exemplo n.º 3
0
class Deque(object):
    """Class deque for deque composition."""

    def __init__(self):
        """Init for deque."""
        self._new_dll = DoubleLinkedList()

    def append(self, val):
        """Enqueue function for queue pushes value to head."""
        return self._new_dll.push(val)

    def appendleft(self, val):
        """Append vals to the front of deque."""
        return self._new_dll.append(val)

    def pop(self):
        """Pop from dll."""
        return self._new_dll.pop()

    def popleft(self):
        """Shift for popleft."""
        return self._new_dll.shift()

    def peek(self):  # pragma no cover
        """Return a new value without dequeuing it."""
        print(self._new_dll.head.data)

    def peekleft(self):  # pragma no cover
        """Return a new value from the left without dequeing it."""
        print(self._new_dll.tail.data)

    def __len__(self):
        """Length function for the queue."""
        return len(self._new_dll)
Exemplo n.º 4
0
	def test_4(self):
		"""check that head is still the first node added to list"""
		n1 = Node('A')
		n2 = Node('B')
		dl = DoubleLinkedList()
		dl.append(n1)
		dl.append(n2)
		self.assertEqual(dl.head._value, 'A')
Exemplo n.º 5
0
	def test_3(self):
		"""add two nodes. test that 2nd append makes changes tail to new node"""
		n1 = Node('A')
		n2 = Node('B')
		dl = DoubleLinkedList()
		dl.append(n1)
		dl.append(n2)
		self.assertEqual(dl.tail._value, 'B')
Exemplo n.º 6
0
 def test_4(self):
     """ test that tail.next returns none """
     dl = DoubleLinkedList()
     n1 = Node(5)
     n2 = Node(3)
     dl.append(n1)
     dl.append(n2)
     self.assertEqual(dl.tail._next, None)
Exemplo n.º 7
0
 def __init__(self, num_buckets=256):
     """Initializes a Map with the given number of buckets."""
     # the map is a DLL
     self.map = DoubleLinkedList()
     # we add a DLL for every bucket so now we have
     # a big DLL containing other tiny DLLs - containers        # for the key -value tuples
     for i in range(0, num_buckets):
         self.map.push(DoubleLinkedList())
Exemplo n.º 8
0
 def test_5(self):
     """ added node is now head """
     dl = DoubleLinkedList()
     n1 = Node(5)
     n2 = Node(3)
     dl.push(n1)
     dl.push(n2)
     self.assertEqual(dl.head._value, 3)
Exemplo n.º 9
0
 def test_6(self):
     """ prev of prior head is now node 2 (n1 here) """
     dl = DoubleLinkedList()
     n1 = Node(5)
     n2 = Node(3)
     dl.push(n1)
     dl.push(n2)
     self.assertEqual(n1._prev._value, 3)
Exemplo n.º 10
0
 def test_3(self):
     """ test append by tail """
     dl = DoubleLinkedList()
     n1 = Node(5)
     n2 = Node(3)
     dl.append(n1)
     dl.append(n2)
     self.assertEqual(dl.tail._value, 3)
Exemplo n.º 11
0
 def test_2(self):
     """ test append by head """
     dl = DoubleLinkedList()
     n1 = Node(5)
     n2 = Node(3)
     dl.append(n1)
     dl.append(n2)
     self.assertEqual(dl.head._next._value, 3)
Exemplo n.º 12
0
 def test_10(self):
     """ remove by value, return an exception if doesn't exist """
     dl = DoubleLinkedList()
     n1 = Node(5)
     n2 = Node(3)
     n3 = Node(6)
     dl.append(n1)
     dl.append(n2)
     dl.append(n3)
     dl.remove(7)
     self.assertEqual(dl.remove(7), "Node does not exist!")
Exemplo n.º 13
0
def find_components(g: Graph):
    """
    Breadth First Search Alg. Which also:
    tests if the graph is connected,
    computes the distance from s to the other edges
    labels the vertices in the order they are visited
    :param g: Graph
    :return: (isConnected, {dict of components})
    """
    visited = set()
    components = dict()
    count = 1

    while len(visited) < len(g.vertices):
        for o in g.vertices:
            if o not in visited:
                v = o
                break
        queue = DoubleLinkedList()  # queue
        queue.append(v)
        visited.add(v)
        components[count] = [v]

        while len(queue) > 0:
            w = queue.pop()  # BFS so FIFO
            for n in w.neighbours:
                # If w not visited
                if n not in visited:
                    visited.add(n)
                    queue.append(n)
                    components[count].append(n)
        count += 1

    is_connected = len(components) == 1
    return is_connected, components
Exemplo n.º 14
0
 def test_9(self):
     """ remove by value, removed node's next now next of removed node's prev """
     dl = DoubleLinkedList()
     n1 = Node(5)
     n2 = Node(3)
     n3 = Node(6)
     dl.append(n1)
     dl.append(n2)
     dl.append(n3)
     dl.remove(3)
     self.assertEqual(dl.head._next._value, 6)
Exemplo n.º 15
0
	def test_7(self):
		"""check that shift removes last node"""
		n1 = Node('A')
		n2 = Node('B')
		n3 = Node('C')
		dl = DoubleLinkedList()
		dl.append(n1)
		dl.append(n2)
		dl.append(n3)
		dl.shift()
		self.assertEqual(dl.tail._value, 'B')
Exemplo n.º 16
0
	def test_6(self):
		"""check that pop removes head"""
		n1 = Node('A')
		n2 = Node('B')
		dl = DoubleLinkedList()
		dl.append(n1) #head and tail at this point
		dl.append(n2) # A is head and B is now tail
		dl.pop() # removes A so head value should be B
		self.assertEqual(dl.head._value, 'B') 
Exemplo n.º 17
0
 def test_8(self):
     """ prev of prior tail is now tail """
     dl = DoubleLinkedList()
     n1 = Node(5)
     n2 = Node(3)
     dl.push(n1)
     dl.push(n2)
     dl.shift()
     self.assertEqual(dl.tail._value, 3)
Exemplo n.º 18
0
 def test_7(self):
     """ next of prior head is now head """
     dl = DoubleLinkedList()
     n1 = Node(5)
     n2 = Node(3)
     dl.push(n1)
     dl.push(n2)
     dl.pop()
     self.assertEqual(dl.head._value, 5)
Exemplo n.º 19
0
	def test_5(self):
		"""check that push adds to front"""
		n1 = Node('A')
		n2 = Node('B')
		dl = DoubleLinkedList()
		dl.append(n1)
		dl.append(n2)
		n3 = Node('C')  #will push C to front(head)
		dl.push(n3)
		self.assertEqual(dl.head._value, 'C')
Exemplo n.º 20
0
class Deque(object):
    """Will create a instance of Deque."""
    def __init__(self, iterable=None):
        """Will init a new instance of the Stack class."""
        from dll import DoubleLinkedList
        self._dll = DoubleLinkedList()
        self._counter = 0

    def append(self, data):
        """Will push a new element into the Deque."""
        self._dll.append(data)
        self._counter += 1

    def pop_left(self):
        """Will remove the head value."""
        if self._dll.head:
            self._counter -= 1
        else:
            raise ValueError('no value left to pop')
        return self._dll.pop()

    def append_left(self, data):
        """Append a value to the head."""
        self._dll.push(data)
        self._counter += 1

    def pop(self):
        """Pop a value from the end."""
        if self._dll.tail:
            self._counter -= 1
        else:
            raise ValueError('no value left to pop')
        return self._dll.shift()

    def peek_left(self):
        """Will return the value that pop_left would return."""
        if self._dll.head:
            return self._dll.head.data
        else:
            raise ValueError('no value in the deque to peek')

    def peek(self):
        """Will return the value that pop would return."""
        if self._dll.head:
            return self._dll.tail.data
        else:
            raise ValueError('no value in the deof correct typeque to peek')

    def size(self):
        """Return the size of the deque."""
        return self._counter

    def __len__(self):
        """Will return the length of the deque using len()."""
        return self._counter
Exemplo n.º 21
0
	def test_8(self):
		"""test to remove tail by using remove method"""
		n1 = Node('A')
		n2 = Node('B')
		n3 = Node('C')
		dl = DoubleLinkedList()
		dl.append(n1)
		dl.append(n2)
		dl.append(n3)
		dl.remove('C')  #this removes C so tail should become BaseException
		self.assertEqual(dl.tail._value, 'B')
		
		
		
		
		
	
		
Exemplo n.º 22
0
    def set(self, vertex: Vertex, color: int):
        """
        Adds the given vertex to the given color class

        Add the given vertex to the color class. If the color class does not yet exist, a new color class is created to
        which the vertex is added.
        :param color: the name of the color class
        :param vertex: the `Vertex` to add to the color class
        :raises KeyError when vertex already belongs to the coloring
        """

        if vertex in self._vertex_dict:
            raise KeyError('Vertex {} already in coloring, color: {}. '
                           'Use recolor instead'.format(
                               str(vertex), str(self.color(vertex))))

        self._dict.setdefault(color, DoubleLinkedList()).append(vertex)
        self._vertex_dict[vertex] = color
Exemplo n.º 23
0
class Deque(object):
    """Deque data structure, can add and remove from both ends."""
    def __init__(self):
        """Initialize the deque."""
        self.deque = DoubleLinkedList()

    def append(self, value):
        """Add an item to the back of the deque."""
        self.deque.append(value)

    def append_left(self, value):
        """Add an item to the front of the deque."""
        self.deque.push(value)

    def pop(self):
        """Pop a value off of the back of the deque and return it."""
        return self.deque.shift()

    def pop_left(self):
        """Pop a value off of the front of the deque and return it."""
        return self.deque.pop()

    def peek(self):
        """Return the next value that would be poped at the end of deque."""
        try:
            return self.deque.tail.data
        except AttributeError:
            return None

    def peek_left(self):
        """Return the next value to pop in the deque."""
        try:
            return self.deque.head.data
        except AttributeError:
            return None

    def size(self):
        """Return the number of nodes in the deque."""
        return self.deque.__len__()
Exemplo n.º 24
0
class Dictionary(object):
    def __init__(self, num_buckets=256):
        """Initializes a Map with the given number of buckets."""
        # the map is a DLL
        self.map = DoubleLinkedList()
        # we add a DLL for every bucket so now we have
        # a big DLL containing other tiny DLLs - containers        # for the key -value tuples
        for i in range(0, num_buckets):
            self.map.push(DoubleLinkedList())

    def hash_key(self, key):
        """Given a key this will create a number and then convert it to an index for the Map's buckets."""
        # returns the modulus of hash number of the key
        # and the number of items in the map
        return hash(key) % self.map.count()

    def get_bucket(self, key):
        """Given a key, find the bucket where it would go."""
        # set the bucket_id to the hash value of the key
        bucket_id = self.hash_key(key)
        # get the bucket_id and return it
        return self.map.get(bucket_id)

    def get_slot(self, key, default=None):
        """Return either the bucket and node for a slot, or None, None"""
        # set bucket to the bucket_id
        bucket = self.get_bucket(key)

        # if there's a bucket
        # set node to bucket.begin
        if bucket:
            node = bucket.begin
            i = 0

            # while there is a node
            while node:
                # return the bucket and the node
                # if the key = node.value[0]
                if key == node.value[0]:
                    return bucket, node
                # else set the node to node.next
                else:
                    node = node.next
                    i += 1

        # fall through for both if and while above
        return bucket, None

    def get(self, key, default=None):
        """Gets the value in a bucket for the given key, or the default."""
        bucket, node = self.get_slot(key, default=default)
        return node and node.value[1] or node

    def set(self, key, value):
        """Sets the key to the value, replacing any existing value."""
        bucket, slot = self.get_slot(key)

        if slot:
            # the key exists, replace it
            slot.value = (key, value)
        else:
            # the key does not, append to create it
            bucket.push((key, value))

    def delete(self, key):
        """Deletes the given key from the Map."""
        bucket = self.get_bucket(key)
        node = bucket.begin

        while node:
            k, v = node.value
            if key == k:
                bucket.detach.node(node)
                break

    def list(self):
        """Prints out what's in the Map."""
        bucket_node = self.map.begin
        while bucket_node:
            slot_node = bucket_node.value.begin
            while slot_node:
                print(slot_node.value)
                slot_node = slot_node.next
            bucket_node = bucket_node.next
Exemplo n.º 25
0
 def __init__(self, num_buckets=256):
     """Initializes a Map with the given number of buckets."""
     self.map = DoubleLinkedList()
     for i in range(0, num_buckets):
         self.map.push(DoubleLinkedList())
Exemplo n.º 26
0
 def __init__(self):
     """Init for Queue."""
     self._new_dll = DoubleLinkedList()
Exemplo n.º 27
0
 def __init__(self):
     """Initialize the deque."""
     self.deque = DoubleLinkedList()
Exemplo n.º 28
0
def random_list(count):
    numbers = DoubleLinkedList()
    for i in range(count, 0, -1):
        numbers.shift(randint(0, 10000))
    return numbers
Exemplo n.º 29
0
def dll():
    """Instantiate a dll for testing."""
    from dll import DoubleLinkedList
    double_link = DoubleLinkedList()
    return double_link
Exemplo n.º 30
0
class Dictionary(object):
    def __init__(self, num_buckets=256):
        """Initializes a Map with the given number of buckets."""
        self.map = DoubleLinkedList()
        for i in range(0, num_buckets):
            self.map.push(DoubleLinkedList())

    def hash_key(self, key):
        """Given a key this will create a number and then convert it to 
        an index for the aMap's buckets."""
        return hash(key) % self.map.count()

    def get_bucket(self, key):
        """Given a key, find the bucket where it would go."""
        bucket_id = self.hash_key(key)
        return self.map.get(bucket_id)

    def get_slot(self, key, default=None):
        """Return either the bucket and node for a slot, or None, None"""
        bucket = self.get_bucket(key)

        if bucket:
            node = bucket.begin
            i = 0

            while node:
                if key == node.value[0]:
                    return bucket, node
                else:
                    node = node.next
                    i += 1

        # fall through for both if and while above
        return bucket, None

    def get(self, key, default=None):
        """Gets the value in a bucket for the given key, or the default."""
        bucket, node = self.get_slot(key, default=default)
        return node and node.value[1] or node

    def set(self, key, value):
        """Sets the key to the value, replacing any existing value."""
        bucket, slot = self.get_slot(key)

        if slot:
            # the key exists, replace it
            slot.value = (key, value)
        else:
            # the key does not, append to create it
            bucket.push((key, value))

    def delete(self, key):
        """Deletes the given key from the Map."""
        bucket = self.get_bucket(key)
        node = bucket.begin

        while node:
            k, v = node.value
            if key == k:
                bucket.detach.node(node)
                break

    def list(self):
        """Prints out what's in the Map."""
        bucket_node = self.map.begin
        while bucket_node:
            slot_node = bucket_node.value.begin
            while slot_node:
                print(slot_node.value)
                slot_node = slot_node.next
            bucket_node = bucket_node.next