def __init__(self, iterable=None): """Initialize this queue and enqueue the given items, if any""" # Initialize a new linked list to store the items self.list = DoublyLinkedList() if iterable: for item in iterable: self.enqueue(item)
def test_items_iterator(self): dl_list = DoublyLinkedList([1, 2, 3]) count = 0 for i in dl_list.items(): self.assertIsInstance(i, DoublyLinkedListNode) self.assertGreater(i.value, 0) count += 1 self.assertEqual(count, 3)
def __init__(self, iterable=None): """Initialize this stack and push the given items, if any.""" # Initialize a new linked list to store the items self.list = DoublyLinkedList() self.size = 0 if iterable is not None: for item in iterable: self.push(item)
class LinkedQueue(object): def __init__(self, iterable=None): """Initialize this queue and enqueue the given items, if any.""" # Initialize a new linked list to store the items self.list = DoublyLinkedList() self.size = 0 if iterable is not None: for item in iterable: self.enqueue(item) def __repr__(self): """Return a string representation of this queue.""" return 'Queue({} items, front={})'.format(self.length(), self.front()) def is_empty(self): """Return True if this queue is empty, or False otherwise.""" # TODO: Check if empty return self.list.is_empty() def length(self): """Return the number of items in this queue.""" # TODO: Count number of items return self.size def enqueue(self, item): """Insert the given item at the back of this queue. Running Time and why O(1) every case, because we keep track of the tail at all times, and enqueue appends at the tail""" # TODO: Insert given item self.list.append(item) # set tail to the Node(item), constant time self.size += 1 def front(self): """Return the item at the front of this queue without removing it, or None if this queue is empty.""" # TODO: Return front item, if any if self.is_empty(): return None return self.list.head.data def dequeue(self): """Remove and return the item at the front of this queue, or raise ValueError if this queue is empty. Running Time and why O(1), because we keep track of the head at all times and dequeue removes at the head""" # TODO: Remove and return front item, if any if self.is_empty(): raise ValueError("Head is empty, can't dequeue") head = self.front() self.list.head = self.list.head.next self.size -= 1 return head
class LinkedStack(object): def __init__(self, iterable=None): """Initialize this stack and push the given items, if any.""" # Initialize a new linked list to store the items self.list = DoublyLinkedList() self.size = 0 if iterable is not None: for item in iterable: self.push(item) def __repr__(self): """Return a string representation of this stack.""" return 'Stack({} items, top={})'.format(self.length(), self.peek()) def is_empty(self): """Return True if this stack is empty, or False otherwise.""" # TODO: Check if empty return self.peek() is None def length(self): """Return the number of items in this stack.""" # TODO: Count number of items return self.size def push(self, item): """Insert the given item on the top of this stack. O(1), we append an item to the tail, we always keep track of the tail""" # TODO: Push given item self.list.prepend(item) self.size += 1 def peek(self): """Return the item on the top of this stack without removing it, or None if this stack is empty.""" # TODO: Return top item, if any item = self.list.head if item is not None: return item.data return item def pop(self): """Remove and return the item on the top of this stack, or raise ValueError if this stack is empty. O(1), we remove an item from the tail, we always keep track of the tail and I also used a doubly linked list so we have the previous node pointer which helps with deleting the last item in the list without traversing it""" # TODO: Remove and return top item, if any if self.is_empty(): raise ValueError item = self.peek() self.list.head = self.list.head.next self.size -= 1 return item
def test_find(self): dll = DoublyLinkedList() dll.append('A') dll.append('B') dll.append('C') assert dll.find(lambda item: item == 'B') == 'B' assert dll.find(lambda item: item < 'B') == 'A' assert dll.find(lambda item: item > 'B') == 'C' assert dll.find(lambda item: item == 'D') is None
def __init__(self, items=None): """ initializes a Deque with items if any are given. If items are given they are populated into Deque with push_front method (loading in front by default) """ # initialize linked list for our deque to use self.list = DoublyLinkedList() # build are deque if items is not None: for item in items: self.push_front(item)
def test_get_at_index(self): dll = DoublyLinkedList(['A', 'B', 'C']) assert dll.get_at_index(0) == 'A' assert dll.get_at_index(1) == 'B' assert dll.get_at_index(2) == 'C' with self.assertRaises(ValueError): dll.get_at_index(3) dll.get_at_index(-1)
class Deque: def __init__(self, items=None): """ initializes a Deque with items if any are given. If items are given they are populated into Deque with push_front method (loading in front by default) """ # initialize linked list for our deque to use self.list = DoublyLinkedList() # build are deque if items is not None: for item in items: self.push_front(item) def push_front(item): """ Takes in given item and prepends it to the front of the deque """ # use linked list prepend method self.list.prepend(item) def push_back(item): """ Takes an item as parameter and appends it to the back of the deque """ # uses linked list append method self.list.append(item) def pop_front(): """ Removes the item at front of deque and returns it """ # grab item to be popped/returned popped_item = self.list.head # remove from left side of list using linkedlist delete method # note: this is still constant b/c popped_item is first item in linkedlist self.list.delete(popped_item) return popped_item # returning item that was just deleted def pop_back(): """ Removes the item at the end of deque and returns its value """ # grab item to be removed (tail of linked list) popped_item = self.list.tail # remove item from right side # currently O(n) self.list.delete(popped_item) return popped_item # return value of deleted item
def test_init_with_list(self): ll = DoublyLinkedList(['A', 'B', 'C']) assert ll.head.data == 'A' # first item assert ll.tail.data == 'C' # last item assert ll.head.prev is None # check prev assert ll.tail.prev.data == 'B' # check prev assert ll.size == 3
def _resize(self, new_size=None): """Resize this hash table's buckets and rehash all key-value entries. Should be called automatically when load factor exceeds a threshold such as 0.75 after an insertion (when set is called with a new key). Best and worst case running time: O(n) Best and worst case space usage: O(n)""" # If unspecified, choose new size dynamically based on current size if new_size is None: new_size = len(self.buckets) * 2 # Double size # Option to reduce size if buckets are sparsely filled (low load factor) elif new_size is 0: new_size = len(self.buckets) / 2 # Half size # Get a list to temporarily hold all current key-value entries temp_list = [] # itterate through the hashtable and append each item to temp_list for ll in self.buckets: if not ll.is_empty(): for item in ll: temp_list.append(item) # Create a new list of new_size total empty linked list buckets self.buckets = [DoublyLinkedList() for i in range(new_size)] self.size = 0 # reset the size to 0 # Insert each key-value entry into the new list of buckets, # which will rehash them into a new bucket index based on the new size for item in temp_list: self.set(*item.data) # item.data is a touple
def test_replace(self): ll = DoublyLinkedList(['A', 'B', 'C']) ll.replace('A', 'D') assert ll.head.data == 'D' # new head assert ll.tail.data == 'C' # unchanged assert ll.size == 3 ll.replace('B', 'E') assert ll.head.data == 'D' # unchanged assert ll.tail.data == 'C' # unchanged assert ll.size == 3 ll.replace('C', 'F') assert ll.head.data == 'D' # unchanged assert ll.tail.data == 'F' # new tail assert ll.size == 3 with self.assertRaises(ValueError): ll.replace('X', 'Y') # item not in list
def test_delete(self): ll = DoublyLinkedList(['A', 'B', 'C']) ll.delete('A') assert ll.head.data == 'B' # new head assert ll.tail.data == 'C' # unchanged assert ll.size == 2 ll.delete('C') assert ll.head.data == 'B' # unchanged assert ll.tail.data == 'B' # new tail assert ll.size == 1 ll.delete('B') assert ll.head is None # new head assert ll.tail is None # new head assert ll.size == 0 with self.assertRaises(ValueError): ll.delete('X') # item not in list
def cleanup(self): # merge all roots of same degree root_array = [None] * floor(log2(self.number_of_nodes)) for tree in self.roots: t = tree.value d = t.degree while root_array[d] is not None: u = root_array[d] root_array[d] = None t = self.merge(t,u) root_array[d] = t self.roots = DoublyLinkedList() for root in root_array: if root is not None: self.roots.push(root,root.key)
def test_size(self): ll = DoublyLinkedList() assert ll.size == 0 ll.append('A') assert ll.size == 1 ll.append('B') assert ll.size == 2 ll.append('C') assert ll.size == 3
def test_size(self): dll = DoublyLinkedList() assert dll.size == 0 dll.append('A') assert dll.size == 1 dll.append('B') assert dll.size == 2 dll.append('C') assert dll.size == 3
def test_get_at_index(self): ll = DoublyLinkedList(['A', 'B', 'C']) assert ll.get_at_index(0) == 'A' # head item assert ll.get_at_index(1) == 'B' # middle item assert ll.get_at_index(2) == 'C' # tail item with self.assertRaises(ValueError): ll.get_at_index(3) # index too high with self.assertRaises(ValueError): ll.get_at_index(-1) # index too low
def test_init_with_list(self): ll = DoublyLinkedList(['A', 'B', 'C']) assert ll.head.data == 'A' assert ll.head.previous == None assert ll.head.next.data == 'B' assert ll.tail.data == 'C' assert ll.tail.previous.data == 'B' assert ll.tail.next == None
def josephus(n, m): L = DoublyLinkedList() for i in range(1, n + 1): L.append(chr(ord('A') + i - 1)) p = L.first() for i in range(n - 1): print(L, p.el) for j in range(m): p = p.next if p.el is None: p = L.first() q = p p = p.next if p.el is None: p = L.first() L.remove(q) return L.first().el
def clear(self): """Empty the Linked List""" # Best: Omega(1) # Worst: O(n) (number of buckets) for i, bucket in enumerate(self.buckets): if bucket: self.buckets[i] = DoublyLinkedList()
class LinkedQueue(object): def __init__(self, iterable=None): """Initialize this queue and enqueue the given items, if any""" # Initialize a new linked list to store the items self.list = DoublyLinkedList() if iterable: for item in iterable: self.enqueue(item) def __repr__(self): """Return a string representation of this queue""" return 'Queue({} items, front={})'.format(self.length(), self.front()) def is_empty(self): """Return True if this queue is empty, or False otherwise""" # TODO: Check if empty return self.list.size is 0 def length(self): """Return the number of items in this queue""" # TODO: Count number of items return self.list.size def enqueue(self, item): """Insert the given item at the back of this queue""" # TODO: Insert given item self.list.append(item) def front(self): """Return the item at the front of this queue without removing it, or None if this queue is empty""" # TODO: Return front item, if any if self.is_empty(): return None return self.list.head.data def dequeue(self): """Remove and return the item at the front of this queue, or raise ValueError if this queue is empty""" # TODO: Remove and return front item, if any if self.is_empty(): raise ValueError('Queue is empty') item = self.list.head.data self.list.delete(item) return item
def __init__(self, init_size=8): """Initialize this hash table with the given initial size""" # Best: Omega(1) # Worst: O(n) (init size) self.buckets = [DoublyLinkedList() for i in range(init_size)] self.entries = 0 self.load = self.entries / len(self.buckets) self.max_load = 0.75
def test_prepend(self): ll = DoublyLinkedList() ll.prepend('C') assert ll.head.data == 'C' assert ll.tail.data == 'C' ll.prepend('B') assert ll.head.data == 'B' assert ll.tail.data == 'C' ll.prepend('A') assert ll.head.data == 'A' assert ll.tail.data == 'C'
def test_remove_all_in_between_empty(self): dl_list = DoublyLinkedList([1, 2, 3]) self.assertEqual(len([i for i in dl_list.items()]), 3) new_list = dl_list.removeAllInBetween(\ dl_list.firstnode(), dl_list.firstnode().next()) self.assertEqual(len([i for i in dl_list.items()]), 3) self.assertEqual(len([i for i in new_list.items()]), 0) self.assertEqual(new_list.firstnode(), None)
def test_remove_all_in_between_single_item(self): dl_list = DoublyLinkedList([1, 2, 3, 4, 5, 6]) self.assertEqual(len([i for i in dl_list.items()]), 6) new_list = dl_list.removeAllInBetween(\ dl_list.firstnode(), dl_list.firstnode().next().next()) self.assertEqual(len([i for i in dl_list.items()]), 5) self.assertEqual(len([i for i in new_list.items()]), 1) self.assertEqual(new_list.firstnode().value, 2)
class LinkedListStack: def __init__(self): self.data = DoublyLinkedList() def size(self): return self.data.getLength() def isEmpty(self): return self.size() == 0 def push(self, item): node = Node(item) self.data.insertAt(self.size() + 1, node) def pop(self): return self.data.popAt(self.size()) def peek(self): return self.data.getAt(self.size()).data
def test_append(self): dll = DoublyLinkedList() # Append should always update tail node dll.append('A') assert dll.head.data == 'A' # New head assert dll.tail.data == 'A' # New tail dll.append('B') assert dll.head.data == 'A' # Unchanged assert dll.tail.data == 'B' # New tail dll.append('C') assert dll.head.data == 'A' # Unchanged assert dll.tail.data == 'C' # New tail
def test_prepend(self): dll = DoublyLinkedList() # Prepend should always update head node dll.prepend('C') assert dll.head.data == 'C' # New head assert dll.tail.data == 'C' # New head dll.prepend('B') assert dll.head.data == 'B' # New head assert dll.tail.data == 'C' # Unchanged dll.prepend('A') assert dll.head.data == 'A' # New head assert dll.tail.data == 'C' # Unchanged
def test_prepend(self): ll = DoublyLinkedList() ll.prepend('C') assert ll.head.data == 'C' # new head assert ll.tail.data == 'C' # new head assert ll.size == 1 ll.prepend('B') assert ll.head.data == 'B' # new head assert ll.tail.data == 'C' # unchanged assert ll.size == 2 ll.prepend('A') assert ll.head.data == 'A' # new head assert ll.tail.data == 'C' # unchanged assert ll.size == 3
def test_append(self): dll = DoublyLinkedList() dll.append('A') assert dll.head.data == 'A' assert dll.tail.data == 'A' assert dll.size == 1 dll.append('B') assert dll.head.data == 'A' assert dll.tail.data == 'B' assert dll.size == 2 dll.append('C') assert dll.head.data == 'A' assert dll.tail.data == 'C' assert dll.size == 3