Beispiel #1
0
def test_pop_non_empty():
    """Assert first node gets removed and returned."""
    from dll import DoublyLinkedList
    my_list = DoublyLinkedList()
    my_list.insert(4)
    my_list.insert(5)
    assert my_list.pop() == 5
Beispiel #2
0
def sample_dll():
    """Create testing dlls."""
    from dll import DoublyLinkedList
    one_dll = DoublyLinkedList([1])
    empty_dll = DoublyLinkedList()
    new_dll = DoublyLinkedList([1, 2, 3, 4, 5])
    return one_dll, empty_dll, new_dll
Beispiel #3
0
 def breadth_first(self, starting_point=None):
     """
     This internal method is a generator that will output breadth first
     traversal of a binary tree(left child, right child, parent),
     one value at a time.
     """
     if self.length == 0:
         raise IndexError("You can't breadth-first traverse an empty Tree.")
     from dll import DoublyLinkedList
     unvisited = DoublyLinkedList()
     if starting_point is None:
         starting_point = self.root
     elif self.contains(starting_point) is False:
         raise IndexError('Starting point is not in the Tree.')
     unvisited.push(starting_point)
     visited = []
     while unvisited.size() > 0:
         current = unvisited.shift()
         if current not in visited:
             visited.append(current)
             if current.left:
                 unvisited.push(current.left)
             if current.right:
                 unvisited.push(current.right)
             yield current.val
Beispiel #4
0
def test_DLL_shift(mk_dll):
    zeroth = DoublyLinkedList()
    with pytest.raises(IndexError):
        zeroth.shift()
    populated = mk_dll
    for x in range(19, -1, -1):
        assert populated.shift() == x
Beispiel #5
0
class Queue(object):
    """Class implementation of queue.

    1.  Enqueue: Add new head node.
    2.  Dequeue: Remove and return tail node value.
    3.  Peek: Display tail node,
    4.  Size: Display queue length.

    """
    def __init__(self, iterable=None):
        """Instatiate Queue."""
        self.dll = DoublyLinkedList(iterable)

    def enqueue(self, contents):
        """Add new head node."""
        self.dll.push(contents)

    def dequeue(self):
        """Remove and return last node value."""
        try:
            old_tail_node_contents = self.dll.shift()
            return old_tail_node_contents
        except IndexError:
            raise IndexError('Queue is already empty.')

    def peek(self):
        """Display but don't remove the contents of tail node."""
        try:
            return self.dll.tail_node.contents
        except AttributeError:
            return None

    def size(self):
        """Return Queue length."""
        return self.dll.length
Beispiel #6
0
class Queue(object):
    """Creates a Queue class."""

    def __init__(self):
        """Initialization of the queue."""
        self._dll = DoublyLinkedList()
        self._counter = self._dll._counter
        self.head = self._dll.head
        self.tail = self._dll.tail

    def __len__(self):
        """Overwrite Python built in len function."""
        return self._counter

    def length(self):
        """Will use DLL counter for length."""
        return self._dll._counter

    def enqueue(self, data):
        """Add node to queue at head."""
        self._dll.push(data)

    def dequeue(self):
        """Remove node from queue at tail."""
        return self._dll.shift()

    def peek(self):
        """Display a value without removing it."""
        if self.length == 0:
            return None
        return self._dll.tail.data
class Queue:
    def __init__(self):
        self.size = 0
        # Why is our DLL a good choice to store our elements?
        # it has directional pointers so we know
        # where something is in the 'queue'
        self.storage = DoublyLinkedList()

    def enqueue(self, value):
        # take the dll
        # run add to tail and pass it value
        self.storage.add_to_head(value)
        self.size += 1

    def dequeue(self):
        # check if size > 0
        # if yes, dequeue
            # take the dll
            # run add remove from tail
            # decrement size by 1
        # if not, return None
        if self.size > 0:
            self.size -= 1
            return self.storage.remove_from_tail()
        else:
            return None

    def len(self):
        # return size of queue
        return self.size
class RingBuffer:
    def __init__(self, capacity):
        self.capacity = capacity
        self.storage = DoublyLinkedList()
        self.marker = None

    def append(self, item):

        print(f'Marker: {self.marker}')
        # check if there is enough room to store item
        if len(self.storage) < self.capacity:
            self.storage.add_to_tail(item)
            print(f'Buffer Size: {len(self.storage)}/{self.capacity}')

            # set marker marker to first node input to list
            if len(self.storage) == 1:
                self.marker = self.storage.head
        # reached max capacity
        else:
            print(
                f'Overwriting Marker: {self.marker.value} with New Item: {item}'
            )
            # overwrite marker value with input item
            self.marker.value = item
            # change marker to next node if exists
            if self.marker.next:
                self.marker = self.marker.next
            # loops back to the head of list if next is null/reached tail
            else:
                self.marker = self.storage.head
            print(f'Next Marker: {self.marker}')

    def get(self):
        print(self.storage.get_all())
        return self.storage.get_all()
class RingBuffer:
    def __init__(self, capacity):
        self.capacity = capacity
        self.storage = DoublyLinkedList()
        self.oldest = None

    def append(self, item):
        if sef.storage.length == 0:
            self.storage.add_to_head(item)
            self.oldest = self.storage.head
            return
        
        elif self.storage.length < self.capacity:
            self.storage.add_to_tail(item)
            
        elif self.storage.length == self.capacity:
            if self.oldest = self.storage.head:
                self.oldest.value = item
                self.oldest = self.oldest.next
                
            elif self.oldest == self.storage.tail:
                self.oldest.value = item
                self.oldest = self.storage.head
                
            else:
                self.oldest.value = item
                self.oldest = self.storage.head
class RingBuffer:
    def __init__(self, capacity):
        '''Because every class needs an "init"'''
        self.capacity = capacity  # It's the capacity
        self.current_node = None  # Gotta start somewhere
        self.storage = DoublyLinkedList()  # Use a DLL to store them in

    def append(self, item):
        if len(self.storage) < self.capacity:  # If there's room in the DLL
            self.storage.add_to_tail(item)  # Insert the newest node at the end
        else:
            if self.current_node == None:  # If cur is empty
                self.storage.head.value = item  # Assign it
                self.current_node = self.storage.head.next  # Update
            else:
                self.current_node.value = item  # Assign it
                self.current_node = self.current_node.next  # Update

    def get(self):
        my_list = []  # Make an empty list for the return
        current_node = self.storage.head  # Get a starting place at the head
        while current_node:
            my_list.append(current_node.value)  # Append
            current_node = current_node.next  # Move on
        return my_list
class RingBuffer:
    def __init__(self, capacity):
        self.capacity = capacity
        self.node = None
        self.storage = DoublyLinkedList()  #will be stored in

    def append(self, item):
        if self.storage.length < self.capacity:  #check capacity: if space: add item
            self.storage.add_to_tail(item)  #put item in back
            self.node = self.storage.head  #make mself head
        elif self.storage.length == self.capacity:  #if capacity is full need:
            self.node.value = item  #get the new item
            if self.node == self.storage.tail:  #if at tail
                self.node = self.storage.head  #add to dll head
            else:
                self.node = self.node.next  #move nodes down a spot when adaded

    def get(self):
        storage = []  #list to add nodes to after getting
        node = self.storage.head  #desingate head
        #check for nodes to add, then add nodes to lsit
        # while the exist
        while node is not None:
            storage.append(node.value)
            #get next node, then repeat add
            node = node.next
        #return ist of nodes
        return storage
Beispiel #12
0
class Queue(object):
    """Queue class. Startrek. Nerds."""

    def __init__(self):
        """Init the Queue."""
        self.container = DoublyLinkedList()

    def enqueue(self, val):
        """Insert into front position."""
        self.container.insert(val)

    def dequeue(self, val):
        """Remove item in the list."""
        self.container.remove(val)

    def peek(self):
        """Check the next node in the queue."""
        if self.container.tail is None:
            return None
        return self.container.tail.previous.val

    def size(self):
        """Return size of container."""
        current = self.container.head
        counter = 1
        if current is None:
            return 0
        while current.next is not None:
            counter += 1
            current = current.next
        return counter
Beispiel #13
0
class Stack:
    def __init__(self):
        self.size = 0
        # Why is our DLL a good choice to store our elements?
        # we will be adding and subtracting based on LIFO
        self.storage = DoublyLinkedList()

    def push(self, value):
        # add to the top of the stack, aka the tail
        # increment size by 1
        self.size += 1
        self.storage.add_to_tail(value)

    def pop(self):
        # check if size > 0
        # if true:
        # remove from the top of the stack, aka the tail
        # decrement size by 1
        # else return None
        if self.size > 0:
            self.size -= 1
            return self.storage.remove_from_tail()
        else:
            return None

    def len(self):
        return self.size
Beispiel #14
0
def test_DLL_pop(mk_dll):
    zeroth = DoublyLinkedList()
    with pytest.raises(IndexError):
        zeroth.pop()
    populated = mk_dll
    for twice in range(2):
        for x in range(20):
            assert populated.pop() == x
Beispiel #15
0
def test_remove():
    """Test if selected Node is removed from list."""
    from dll import DoublyLinkedList
    my_list = DoublyLinkedList()
    my_list.insert('last')
    my_list.insert('second')
    my_list.insert('head')
    my_list.remove('second')
    assert my_list.head.next.val == 'last'
 def __init__(self, initial_text=None):
     # the contents of our buffer are stored as a linked list
     self.contents = DoublyLinkedList()
     """  
      if we are passed in initial text as an argument
      loop through the string and make linked list nodes
      with every letter 
      """
     if initial_text:
         for char in initial_text:
             self.contents.add_to_tail(char)
Beispiel #17
0
def test_dll_remove():
    """Test for dll remove."""
    from dll import DoublyLinkedList
    one_dll, empty_dll, new_dll = sample_dll()
    new_dll.remove(3)
    assert new_dll.length == 4
    assert new_dll.head_node.next_node.next_node.contents == 2
    assert new_dll.head_node.next_node.next_node.previous_node.contents == 4
    try:
        new_dll.remove(10)
    except NameError:
        assert True
    new_dll.remove(5)
    assert new_dll.head_node.contents == 4
    new_dll.remove(1)
    assert new_dll.tail_node.contents == 2
    empty_dll = DoublyLinkedList()
    try:
        empty_dll.remove(100)
    except NameError:
        assert True
    one_dll = DoublyLinkedList([1])
    one_dll.remove(1)
    assert one_dll.head_node is None
    assert one_dll.tail_node is None
    assert one_dll.length == 0
Beispiel #18
0
class Queue(object):
    """First in first out queue structure."""
    def __init__(self, iterable=None):
        """Construct queue."""
        try:
            self._dll = DoublyLinkedList(iterable)
        except ValueError:
            raise ValueError("Queue optional parameter must be iterable.")

    def enqueue(self, val):
        """Add value to the queue."""
        self._dll.append(val)

    def dequeue(self):
        """Remove item from the queue and returns an error if queue empty."""
        try:
            return self._dll.pop()
        except:
            raise IndexError('Cannot dequeue from an empty queue.')

    def peek(self):
        """Return the next value in the queue without dequeueing it. If the."""
        """queue is empty, returns None."""
        return self.head.val if self.head else None

    def size(self):
        """Return the size of the queue, if empty return 0."""
        return self._dll._length

    def clear(self):
        """Empty queue."""
        self._dll.head = None
        self._dll.tail = None
        self._dll._length = 0

    def __len__(self):
        """Return length of queue."""
        return self.size()

    @property
    def head(self):
        """Read only head property."""
        return self._dll.head

    @property
    def tail(self):
        """Read only tail property."""
        return self._dll.tail
Beispiel #19
0
class Queue:
  def __init__(self):
    self.size = 0
    # using DLL for constant time enqueue and dequeue
    self.dll = DoublyLinkedList()

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

  def enqueue(self, item):
    self.dll.add_to_tail(item)
  
  def dequeue(self):
    return self.dll.remove_from_head()

  def len(self):
    return len(self)
Beispiel #20
0
class LRUCache:
    """
    Our LRUCache class keeps track of the max number of nodes it
    can hold, the current number of nodes it is holding, a doubly-
    linked list that holds the key-value entries in the correct
    order, as well as a storage dict that provides fast access
    to every node stored in the cache.
    """
    def __init__(self, limit=10):
        self.limit = limit
        self.size = 0
        self.order = DoublyLinkedList()
        # self.order = list()
        self.storage = dict()

    """
    Retrieves the value associated with the given key. Also
    needs to move the key-value pair to the end of the order
    such that the pair is considered most-recently used.
    Returns the value associated with the key or None if the
    key-value pair doesn't exist in the cache.
    """

    def get(self, key):
        if key not in self.storage:
            return None
        else:
            node = self.storage[key]
            self.order.move_to_end(node)
            return node.value[1]

    """
    Adds the given key-value pair to the cache. The newly-
    added pair should be considered the most-recently used
    entry in the cache. If the cache is already at max capacity
    before this entry is added, then the oldest entry in the
    cache needs to be removed to make room. Additionally, in the
    case that the key already exists in the cache, we simply
    want to overwrite the old value associated with the key with
    the newly-specified value.
    """

    def set(self, key, value):
        if key in self.storage:
            node = self.storage[key]
            node.value = (key, value)
            self.order.move_to_end(node)
            return
        if len(self.order) == self.limit:
            evicted = self.order.head.value[0]
            del self.storage[evicted]
            self.order.remove_from_head()
        self.order.add_to_tail((key, value))
        self.storage[key] = self.order.tail
Beispiel #21
0
def test_shift():
    """Assert shift works on non empty list."""
    from dll import DoublyLinkedList
    my_list = DoublyLinkedList()
    my_list.insert(1)
    my_list.insert(2)
    my_list.insert(3)
    assert my_list.shift() == 1
Beispiel #22
0
class Queue:
    def __init__(self):
        self.size = 0
        self.storage = DoublyLinkedList()

    def enqueue(self, value):
        self.size += 1
        self.storage.add_to_tail(value)

    def dequeue(self):
        value = self.storage.remove_from_head()

        if value is not None:
            self.size -= 1

        return value

    def len(self):
        return self.size
Beispiel #23
0
class LRUCache:
    def __init__(self, limit=10):
        self.limit = limit
        self.length = 0
        self.dll = DoublyLinkedList()

    """
  Retrieves the value associated with the given key. Also
  needs to move the key-value pair to the top of the order
  such that the pair is considered most-recently used.
  Returns the value associated with the key or None if the
  key-value pair doesn't exist in the cache. 
  """

    def get(self, key):
        found = self.dll.search(key)
        if found is None:
            return None
        self.dll.move_to_front(found)
        return found.value[key]

    """
  Adds the given key-value pair to the cache. The newly-
  added pair should be considered the most-recently used
  entry in the cache. If the cache is already at max capacity
  before this entry is added, then the oldest entry in the
  cache needs to be removed to make room. Additionally, in the
  case that the key already exists in the cache, we simply 
  want to overwrite the old value associated with the key with
  the newly-specified value.
  """

    def set(self, key, value):
        found = self.dll.search(key)
        if found is not None:
            found.value[key] = value
            self.dll.move_to_front(found)
        else:
            if self.length == self.limit:
                self.dll.remove_from_tail()
            else:
                self.length += 1
            self.dll.add_to_head({key: value})
Beispiel #24
0
def test_insert_on_non_emtpy_list():
    """Assert insert on non-empty list works."""
    from dll import DoublyLinkedList
    my_list = DoublyLinkedList()
    my_list.insert(4)
    my_list.insert('Diana')
    assert my_list.head.val == 'Diana'
Beispiel #25
0
def test_assert_previous():
    """Assert second node points to its previous."""
    from dll import DoublyLinkedList
    my_list = DoublyLinkedList()
    my_list.insert('Daniel')
    my_list.insert('Diana')
    assert my_list.head.val == 'Diana'
Beispiel #26
0
def test_pop_single_item_list():
    """Test pop on single item list."""
    from dll import DoublyLinkedList
    my_list = DoublyLinkedList()
    my_list.insert(4)
    my_list.pop()
    assert my_list.head is None
Beispiel #27
0
def test_append_non_empty():
    """Assert node gets appended to the end of the lsit."""
    from dll import DoublyLinkedList
    my_list = DoublyLinkedList()
    my_list.insert(4)
    my_list.append(8)
    assert my_list.tail.val == 8
Beispiel #28
0
def test_tail():
    """Assert the last node is the tail."""
    from dll import DoublyLinkedList
    my_list = DoublyLinkedList()
    my_list.insert(4)
    my_list.insert(5)
    my_list.insert(6)
    assert my_list.tail.val == 4
Beispiel #29
0
def test_DLL_rm(mk_dll):
    zeroth = DoublyLinkedList()
    with pytest.raises(IndexError):
        zeroth.remove(3)
    populated = mk_dll
    # Remove from the head
    assert populated.head.data == 0
    populated.remove(0)
    assert populated.head.data == 1
    # Remove from the tail
    assert populated.tail.data == 19
    populated.remove(19)
    assert populated.tail.data == 18
    # Remove from the middle
    current = populated.head
    for a in range(5):
        current = current.next
    the_nexts_value = current.next.data
    populated.remove(the_nexts_value)
    assert the_nexts_value + 1 == current.next.data

    # Try to remove a value that isn't there
    with pytest.raises(ValueError):
        populated.remove('not there')
Beispiel #30
0
class Deque(object):
    """Deque implements a simple Python deque data structure."""
    def __init__(self, iterable=None):
        """Init deque, iterate through data if provided as an argument."""
        self.dll = DoublyLinkedList(iterable)

    def append(self, data):
        """Append a node containing data to the head(end) of the deque."""
        self.dll.push(data)

    def appendleft(self, data):
        """Append a node containing data to the tail(front) of the deque."""
        self.dll.append(data)

    def pop(self):
        """Remove a value from the head(end) of the deque and return it.

        Will raise an exception if the deque is empty."""
        try:
            return self.dll.pop()
        except AttributeError:
            raise IndexError("The deque is empty.")

    def popleft(self):
        """Remove a value from the tail(front) of the deque and return it.

        Will raise an exception if the deque is empty."""
        try:
            return self.dll.shift()
        except AttributeError:
            raise IndexError("The deque is empty.")

    def peek(self):
        """Returns the value of the head(end) of the deque.

        Returns None if the deque is empty."""
        if self.dll.head is None:
            return None
        return self.dll.head.data

    def peekleft(self):
        """Returns a value from the tail(front) of the deque.

        Returns None if the deque is empty."""
        if self.dll.tail is None:
            return None
        return self.dll.tail.data

    def size(self):
        """Returns the count of nodes in the queue, 0 if empty."""
        count = 0
        current = self.dll.head
        while current is not None:
            count += 1
            current = current._next
        return count
Beispiel #31
0
class Deque(object):
    """Deque class."""

    def __init__(self):
        """Initilizer of deque class."""
        self.container = DoublyLinkedList()

    def append_left(self, val):
        """Append val to the head of the list."""
        self.container.insert(val)

    def append(self, val):
        """Append val to the tail of the list."""
        self.container.append(val)

    def pop(self):
        """Return and remove head from the list."""
        self.container.shift()

    def pop_left(self):
        """Remove head of deque and return that value."""
        self.container.pop()

    def peek(self):
        """Check the next node in the deque."""
        if self.container.tail is None:
            return None
        return self.container.tail.val

    def peek_left(self):
        """Return the tail of the deque."""
        if self.container.head is None:
            return None
        return self.container.head.val

    def size(self):
        """Return the size of the deque."""
        current = self.container.head
        counter = 1
        if current is None:
            return 0
        while current.next is not None:
            counter += 1
            current = current.next
        return counter
Beispiel #32
0
def test_insert_on_empty_list():
    """Assert insert works."""
    from dll import DoublyLinkedList
    my_list = DoublyLinkedList()
    my_list.insert(4)
    assert my_list.head.val == 4
Beispiel #33
0
 def __init__(self):
     """Initilizer of deque class."""
     self.container = DoublyLinkedList()
Beispiel #34
0
def test_shift_empty():
    """Assert shift works on empty list."""
    from dll import DoublyLinkedList
    my_list = DoublyLinkedList()
    with pytest.raises(IndexError):
        my_list.shift()
Beispiel #35
0
def test_remove_empty():
    """Assert remove works on empty list."""
    from dll import DoublyLinkedList
    my_list = DoublyLinkedList()
    with pytest.raises(AttributeError):
        my_list.remove('chicken')
Beispiel #36
0
def test_pop_empty():
    from dll import DoublyLinkedList
    my_list = DoublyLinkedList()
    with pytest.raises(IndexError):
        my_list.pop()
Beispiel #37
0
def test_append_empty():
    """Assert node gets appended to empty list."""
    from dll import DoublyLinkedList
    my_list = DoublyLinkedList()
    my_list.append(4)
    assert my_list.tail.val == 4