class Buffer: def __init__(self, name: str): self.name = name self.file = None self.buffer = DoublyLinkedList(2) self.cursorX = 0 self.cursorY = 0 def newLine(self, contents: str = ""): nl = DoublyLinkedList(2) for char in contents: nl.append(char) self.buffer.append(nl) def getLine(self, lineno: int): line = "" for char in self.buffer.getIndex(lineno).Traverse(): line += char return line def getBuffer(self): ret = [] for lineno in range(self.buffer.totalCount): ret.append(self.getLine(lineno)) return ret
def __init__(self, name: str): self.name = name self.file = None self.buffer = DoublyLinkedList(2) self.cursorX = 0 self.cursorY = 0
class AnimalShelter(object): def __init__(self): self.cats_ll = DoublyLinkedList() self.dogs_ll = DoublyLinkedList() def enqueue(self, animal): if animal.endswith("_c"): self.cats_ll.add(animal) else: self.dogs_ll.add(animal) def dequeueAny(self): num = random.randint(0, 1) if num == 0: return self.dequeueCat() return self.dequeueDog() def dequeueCat(self): cat = self.cats_ll.head self.cats_ll.head = cat.next return cat.value def dequeueDog(self): dog = self.dogs_ll.head self.dogs_ll.head = dog.next return dog.value
def test_items(self): dll = DoublyLinkedList() assert dll.items() == [] dll.append('A') assert dll.items() == ['A'] dll.append('B') assert dll.items() == ['A', 'B']
def test_length(self): dll = DoublyLinkedList() assert dll.length() == 0 dll.append('A') assert dll.length() == 1 dll.append('B') assert dll.length() == 2
class LRUCache: "A Least-Recently Used Cache" def __init__(self, size=100) -> None: self._items = DoublyLinkedList() self._map = {} self.maxsize = size self._capacity = size def __len__(self): return len(self._items) def put(self, value): # add the element to the front of the cache self._items.append_head(value) self._capacity -= 1 # set a reference to the node self._map[value] = self._items.head # if over capacity, evict from the back of the cache if self._capacity < 0: evicted = self._items.popright() del self._map[evicted] self._capacity += 1 def get(self, value): # check if value is in the cache node = self._map.get(value) if node is None: return False # move value to the front of the cache if node is not self._items.head: self._items._remove(node) self._items.append_head(value) return True
class test(unittest.TestCase): test_cases = [ (DoublyLinkedList("racecar"), True), (DoublyLinkedList("nolemonsnomelon"), True), (DoublyLinkedList("reviver"), True), (DoublyLinkedList("d"), True), (DoublyLinkedList("raceear"), False), (DoublyLinkedList("eeereeee"), False) ] test_functions = [ is_palindrome_stringify, is_palindrome_direct ] def test_is_palindrome(self): num_runs = 1000 function_runtimes = defaultdict(float) for _ in range(num_runs): for ll, expected in self.test_cases: for is_palindrome in self.test_functions: start = time.process_time() assert( is_palindrome(ll) == expected ), f"{is_palindrome.__name__} failed at {(e for e in ll)}" function_runtimes[is_palindrome.__name__] += ( time.process_time() - start) * 1000 print(f"{num_runs} runs") for function_name, runtime in function_runtimes.items(): print(f"{function_name:<20s}: {runtime:.1f}ms")
class LDeque: #CONSTRUCTOR def __init__(self): self.data = DoublyLinkedList() #CONSTRUCTOR #METHODS def pushFront(self, value): self.data.insertAtHead(value) def pushBack(self, value): self.data.insertAtTail(value) def popFront(self, count=1): for _ in range(count): self.data.removeHead() def popBack(self, count=1): for _ in range(count): self.data.removeTail() def isEmpty(self, value): return self.data.isEmpty() def peekFront(self, value): return self.data.head.value def peekBack(self, value): return self.data.tail.value def pushFrontAll(self, values): for value in values: self.pushFront(value) def pushBackAll(self, values): for value in values: self.pushBack(value) def getSize(self): return self.data.length
def partition(ll, div_node): temp_ll = DoublyLinkedList() if ll.head is not None: curr_node = ll.head else: return ll while curr_node.value is not None: curr_node_next = curr_node.next curr_node_prev = curr_node.prev if curr_node.value >= div_node.value: temp_ll.append(DoublyNode(value=curr_node.value)) if curr_node_prev: curr_node_prev.next = curr_node_next curr_node_next.prev = curr_node_prev curr_node = curr_node_next ll.append(temp_ll.head) return ll
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
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'
if curr_node.value >= div_node.value: temp_ll.append(DoublyNode(value=curr_node.value)) if curr_node_prev: curr_node_prev.next = curr_node_next curr_node_next.prev = curr_node_prev curr_node = curr_node_next ll.append(temp_ll.head) return ll if __name__ == '__main__': # tests ll = DoublyLinkedList() origin_node_values = [3, 5, 8, 5, 10, 2, 1] partition_value = 5 for node_value in origin_node_values: node = DoublyNode(value=node_value) ll.append(node) after_partition_value = False after_partition = partition(ll, DoublyNode(value=partition_value)) curr_node = after_partition.head while curr_node.value: if node.value >= partition_value: after_partition_value = True if after_partition_value:
def __init__(self, items: Iterable = None): self.queue_list = DoublyLinkedList(items)
def test_init_with_list(self): dll = DoublyLinkedList(['B', 'C', 'D']) assert dll.head.data == 'B' assert dll.tail.data == 'D' assert dll.size == 3
def test_init(self): dll = DoublyLinkedList() assert dll.head is None assert dll.tail is None assert dll.size == 0
import numpy as np tests = [([1, 2, 1], True), (["A", "B", "B", "A"], True), ([5, 6, 5, 1, 2, 2, 3, 2, 2, 1, 5, 6, 5], True), ([0, 0], True), ([1, 6, 5, 3, 2], False), ([1, 3, 5, 7, 6, 4, 7, 5, 3, 1], False), (["A", "A", "A", "B"], False), ([0, 1], False)] results = np.array( [palindrome(tests[i][0]) == tests[i][1] for i in range(len(tests))]) print("Test palindrome") if results.all() == True: print("All tests passed") else: print("All tests did not pass") results = np.array([ palindrome_2(DoublyLinkedList(tests[i][0])) == tests[i][1] for i in range(len(tests)) ]) print("Test palindrome_2") if results.all() == True: print("All tests passed") else: print("All tests did not pass") results = np.array([ palindrome_3(DoublyLinkedList(tests[i][0])) == tests[i][1] for i in range(len(tests)) ]) print("Test palindrome_3") if results.all() == True: print("All tests passed")
def __init__(self, size=100) -> None: self._items = DoublyLinkedList() self._map = {} self.maxsize = size self._capacity = size
curr_forwards = ll.head curr_backwards = ll.tail is_palindrome = True while curr_forwards and curr_backwards and curr_backwards != curr_forwards and is_palindrome: if curr_forwards.value != curr_backwards.value: is_palindrome = False curr_forwards = curr_forwards.next curr_backwards = curr_backwards.prev return is_palindrome if __name__ == '__main__': # tests palidrome = [1, 2, 3, 4, 5, 4, 3, 2, 1] palidrome_ll = DoublyLinkedList() for p in palidrome: palidrome_ll.append(DoublyNode(value=p)) assert is_palindrome(palidrome_ll) == True palidrome = [1, 2, 3, 4, 4, 3, 2, 1] palidrome_ll = DoublyLinkedList() for p in palidrome: palidrome_ll.append(DoublyNode(value=p)) assert is_palindrome(palidrome_ll) == True not_palidrome = [1, 2, 3, 4, 5, 3, 2, 1] not_palidrome_ll = DoublyLinkedList() for p in not_palidrome: not_palidrome_ll.append(DoublyNode(value=p)) assert is_palindrome(not_palidrome_ll) == False
class Queue(Sequence): "A Queue is a First-In-First-Out sequence of items." def __init__(self, items: Iterable = None): self.queue_list = DoublyLinkedList(items) @property def is_empty(self): return self.queue_list.is_empty def front(self): if self.is_empty: return None return self.queue_list.head.data def back(self): if self.is_empty: return None return self.queue_list.tail.data def size(self): return len(self.queue_list) def enqueue(self, item): self.queue_list.append_tail(item) def dequeue(self): if self.is_empty: raise ValueError("Cannot remove element from empty queue") front = self.front() self.queue_list.remove(front) return front # abc.Collection def __contains__(self, value): return value in self.queue_list # abc.Collection def __iter__(self): return iter(self.queue_list) # abc.Collection def __len__(self): return len(self.queue_list) # abc.Sequence def __getitem__(self, index): if self.is_empty: raise IndexError("index out of range") return self.queue_list[index] # abc.Sequence def __reversed__(self): return reversed(self.queue_list) def reverse(self, k: int = None): "Reverse the first k (default all) elements in queue" if self.is_empty: return self # Copy the elements to a stack tmp = deque() if k is None: while not self.is_empty: front = self.dequeue() tmp.append(front) else: for i in range(k): front = self.dequeue() tmp.append(front) # Move from the stack to the queue while len(tmp) > 0: top = tmp.pop() self.enqueue(top) # Shift the rest of the elements to the back of queue if k is not None: rest = self.size() - k for i in range(rest): front = self.dequeue() self.enqueue(front) return self
def setUp(self): self.ll = DoublyLinkedList(2)
def main2(): dl = DoublyLinkedList() dl.insert_at_end(22) dl.insert_at_end(56) dl.insert_at_end(190) dl.insert_at_start(200) dl.insert_after_value(56,'raj') dl.insert_after_value(190,2000) dl.traverse() dl.delete_by_value(2000) print("after deleting") dl.traverse() dl.reverse() print('after reversing') dl.traverse()
ilist1.append_head(15) ilist2.append_head(21) ilist2.append_head(14) ilist2.append_head(15) lst = ilist1 & ilist2 assert len(lst) == 2 print(">>> Intersect list1 & list2") print(lst) ########################################## ## DoublyLinkedList Tests ########################################## print(">>> Doubly Linked Lists") lst = DoublyLinkedList() lst.append_tail(1) lst.append_tail(2) lst.append_tail(3) lst.append_tail(4) lst.append_tail(5) print(lst) print("Deleting 4") lst.remove(4) assert 4 not in lst print(lst) print("List size:", len(lst)) ########################################## ## Reverse LinkedList ##########################################
def test_insert_at_index(self): dll = DoublyLinkedList() dll.insert_at_index(0, 'S') assert dll.get_at_index(0) == 'S' assert dll.head.data == 'S' assert dll.tail.data == 'S' assert dll.size == 1 dll.insert_at_index(1, 'O') assert dll.get_at_index(1) == 'O' assert dll.head.data == 'S' assert dll.tail.data == 'O' assert dll.size == 2 dll.insert_at_index(1, 'X') assert dll.get_at_index(1) == 'X' assert dll.head.data == 'S' assert dll.tail.data == 'O' assert dll.size == 3 dll.insert_at_index(3, 'SSS') assert dll.get_at_index(3) == 'SSS' assert dll.head.data == 'S' assert dll.tail.data == 'SSS' assert dll.size == 4
def __init__(self): self.data = DoublyLinkedList()
def __init__(self): self.cats_ll = DoublyLinkedList() self.dogs_ll = DoublyLinkedList()
class TestDLLMethods(unittest.TestCase): def setUp(self): self.ll = DoublyLinkedList(2) def getData(self) -> list: return [x.getData() for x in self.ll.Traverse()] def getSeeks(self) -> list: return [x.getData() for x in self.ll.seeks] def testGet(self): # Bit of a chicken-and-egg: # Relies on append functioning as intended, yet seeing that append # functions as intended requires the get parametres to work properly. self.ll.append("node1") self.ll.append("node2") self.ll.append("node3") self.assertEqual(self.getData(), ["node1", "node2", "node3"]) self.assertEqual([x.data for x in self.ll.revTraverse()], ["node3", "node2", "node1"]) self.assertEqual(self.ll.getIndex().data, "node3") self.assertEqual(self.ll.getIndex(1).data, "node2") def test_append(self): # Case 1: Append to an empty list with index supplied # Shows that isEmpty is functional, therefore no need to test other indicies. self.ll.append("node1", -1) self.assertEqual(self.getData(), ["node1"]) self.assertEqual(self.getSeeks(), ["node1"]) # Case 2: Append to the start of the list self.ll.append("node2", 0) self.assertEqual(self.getData(), ["node2", "node1"]) self.assertEqual(self.getSeeks(), ["node2"]) # Case 3: Append somewhere in between # Also tests if a new seek is added when conditions are satisfied. self.ll.append("node3", 1) self.assertEqual(self.getData(), ["node2", "node3", "node1"]) self.assertEqual(self.getSeeks(), ["node2", "node1"]) # Case 4: Append to the end # Also tests if the seek system handles the addition correctly. self.ll.append("node4", -1) self.assertEqual(self.getData(), ["node2", "node3", "node1", "node4"]) self.assertEqual(self.getSeeks(), ["node2", "node1"]) # Cases 5, 6: Appends to invalid indicies # Makes sure that nothing happens when an invalid index is passed. self.ll.append("node5", -2) self.assertEqual(self.getData(), ["node2", "node3", "node1", "node4"]) self.assertEqual(self.getSeeks(), ["node2", "node1"]) self.ll.append("node6", 100) self.assertEqual(self.getData(), ["node2", "node3", "node1", "node4"]) self.assertEqual(self.getSeeks(), ["node2", "node1"]) def test_delete(self): # Setup: creates the same list as in the prior test for convenience self.ll.append("node1", -1) self.ll.append("node2", 0) self.ll.append("node3", 1) self.ll.append("node4", -1) # Case 1, 2: Delete from invalid indicies # Makes sure that nothing happens when an invalid index is passed el = self.ll.delete(-2) self.assertEqual(self.getData(), ["node2", "node3", "node1", "node4"]) self.assertEqual(self.getSeeks(), ["node2", "node1"]) self.assertIsNone(el) el = self.ll.delete(100) self.assertEqual(self.getData(), ["node2", "node3", "node1", "node4"]) self.assertEqual(self.getSeeks(), ["node2", "node1"]) self.assertIsNone(el) # Case 3: Delete from end # Also tests if seek system handles the removal correctly. el = self.ll.delete(-1) self.assertEqual(self.getData(), ["node2", "node3", "node1"]) self.assertEqual(self.getSeeks(), ["node2", "node1"]) self.assertEqual(el.getData(), "node4") # Case 4: Delete from somewhere in between # Also tests if a seek is removed when conditions are satisfied el = self.ll.delete(1) self.assertEqual(self.getData(), ["node2", "node1"]) self.assertEqual(self.getSeeks(), ["node2"]) self.assertEqual(el.getData(),"node3") # Case 5: Delete from the start of the list. el = self.ll.delete(0) self.assertEqual(self.getData(), ["node1"]) self.assertEqual(self.getSeeks(), ["node1"]) self.assertEqual(el.getData(), "node2") # Case 6: Delete final element el = self.ll.delete(-1) self.assertEqual(self.getData(), []) self.assertEqual(self.getSeeks(), []) self.assertEqual(el.getData(), "node1")
import sys sys.path.append('./linkedlist') from linkedlist import DoublyLinkedList, DoublyNode from get_kth_to_last import get_ll_size def delete_mid_node(node): node.prev.next = node.next node.next.prev = node.prev if __name__ == '__main__': # tests ll = DoublyLinkedList() dnode1 = DoublyNode(value=1) dnode2 = DoublyNode(value=2) dnode3 = DoublyNode(value=3) ll.append(dnode1) ll.append(dnode2) ll.append(dnode3) assert get_ll_size(ll) == 3 assert ll.head.next == dnode2 delete_mid_node(dnode2, ) assert get_ll_size(ll) == 2 assert ll.head.next != dnode2
first_it = False runner1 = runner1.next runner2 = runner2.next and runner2.next.next return double_ref if double_ref is not None else False if __name__ == '__main__': # tests n1 = DoublyNode(value=1) n2 = DoublyNode(value=2) n3 = DoublyNode(value=3) n4 = DoublyNode(value=4) n5 = DoublyNode(value=5) n6 = DoublyNode(value=6) n1.next = n2 n2.next = n3 n3.next = n6 n6.next = n4 n4.next = n5 n5.next = n6 ll = DoublyLinkedList(head=n1) assert has_loop(ll) is not False or not None assert has_loop(ll) == n6
def newLine(self, contents: str = ""): nl = DoublyLinkedList(2) for char in contents: nl.append(char) self.buffer.append(nl)