def sort(self): slash_counts = self.get_slash_counts() sorted_items = sorted(slash_counts.items(), key=lambda x: x[1]) new_ll = LinkedList() for (k, v) in sorted_items: new_ll.append(k) self.values = new_ll
class Stack: def __init__(self): self.size = 0 #self.storage = [] ##array code commented out self.storage = LinkedList() def __len__(self): #return len(self.storage) return self.size def push(self, value): #return self.storage.append(value) self.storage.add_to_end( value) ##from ll functions add to end of stack. LIFO self.size += 1 #size of in +1 def pop(self): #if len(self.storage) == 0: #return None #else: #return self.storage.pop() if not self.storage.head: return None else: self.size -= 1 #remove 1 from in return self.storage.remove_at_end( ) #rmeove last input from end of stack. LIFO
def __init__(self, *args, **kwargs): n1 = Node(12) n2 = Node(55) n3 = Node(12) n1.next = n2 n2.next = n3 self.linked_list = LinkedList() self.linked_list.head = n1 self.linked_list.tail = n3 super(TestLinkedListMethods, self).__init__(*args, **kwargs)
def test_remove(self): l = LinkedList(1) l.append(2) l.append(3) l.append(4) l.append(5) l.remove(3) self.assertEqual(l.value, 1) self.assertEqual(l.next.value, 2) self.assertEqual(l.next.next.value, 4) self.assertEqual(l.length(), 4)
def __init__(self, _type, size=-1): """ initializing for channels""" self.__buffer = LinkedList() self.__capacity = size self.__closed = False self.__cond = Condition() self.__type = _type self.__zero_value_map = { int: 0, float: 0.0, str: '', tuple: (), list: [], dict: {}, set: set() }
def main(): ll = LinkedList() ll.insert("t") ll.insert("a") ll.insert("t") ll.insert("b") ll.insert("a") isp = is_palindrome_ll(ll) print(isp)
def test_append(self): l = LinkedList(1) l.append(2) l.append(3) l.append(4) l.append(5) n = l.find(4) self.assertEqual(n.value, 4) self.assertEqual(l.length(), 5) self.assertEqual(n.next.value, 5) self.assertEqual(n.next.next, None)
def main(): ll = LinkedList() ll.insert(2) ll.insert(1) ll.insert(3) ll.insert(9) ll.insert(4) ll.insert(6) print_ll(ll.head) partition(ll, 6) print_ll(ll.head)
def test_one_odd_node(self): node = Node(3) one_odd_list = LinkedList() one_odd_list.add_node(node) one_odd_list.remove_odds() "it should produce and empty list has only one node, which is odd" self.assertTrue(one_odd_list.is_empty())
def test_findlast(self): l = LinkedList(1) l.append(2) l.append(3) l.append(4) l.append(5) n = l.find(5) self.assertEqual(n.value, 5) self.assertEqual(n.next, None)
def test_all_even(self): all_even = LinkedList() node_vals = [2, 4, 6] for node_val in node_vals: all_even.add_node(Node(node_val)) all_even.remove_odds() "It should not remove any nodes if all nodes are even" self.assertEqual(all_even.get_length(), 3)
def main(): ll = LinkedList() ll.insert("a") ll.insert("b") ll.insert("c") ll.insert("d") ll.insert("e") ll.insert("f") print_ll(ll.head) node = ll.head.next.next.next middle_node(node) print_ll(ll.head)
def test_tail_odd(self): odd_tail = LinkedList() node_vals = [2, 3, 4, 5] for node_val in node_vals: odd_tail.add_node(Node(node_val)) odd_tail.remove_odds() "it should remove the tail if the tail is odd and the head is even" self.assertEqual(odd_tail.tail.data, 4) self.assertEqual(odd_tail.get_length(), 2)
def test_tail_even(self): even_tail = LinkedList() node_vals = [2, 3, 4, 10] for node_val in node_vals: even_tail.add_node(Node(node_val)) even_tail.remove_odds() "it should remove odds if the tail is even and the head is even" self.assertEqual(even_tail.tail.data, 10) self.assertEqual(even_tail.get_length(), 3)
def test_find(self): l = LinkedList(1) l.insert(2) l.insert(3) l.insert(4) l.insert(5) n = l.find(3) self.assertEqual(n.value, 3) self.assertEqual(n.next.value, 2) self.assertEqual(n.next.next.value, 1)
def main(): l1 = LinkedList() l2 = LinkedList() for i in reversed(range(1, 4)): l1.add_node(i) for i in reversed(range(6, 9)): l2.add_node(i) print "l1:" print_nodes(l1.root) print "l2:" print_nodes(l2.root) print "sum:" sum_ll_root = add_numbers(l1.root, l2.root) print_nodes(sum_ll_root)
def reverse(lst: LinkedList): """ The business! Reverses the linked list. """ prev: Optional[Node] = None current: Node = lst.head while current is not None: next = current.next current.next = prev prev = current current = next lst.head = prev return lst
def test_head_odd(self): odd_head = LinkedList() node_vals = [3, 4, 5, 6] for node_val in node_vals: odd_head.add_node(Node(node_val)) odd_head.remove_odds() "it should remove odds when the head node is odd and the tail is even" self.assertEqual(odd_head.head.data, 4) self.assertEqual(odd_head.get_length(), 2) self.assertEqual(odd_head.tail.data, 6)
def test_all_odd(self): all_odd = LinkedList() node_vals = [1, 3, 5, 7] for node_val in node_vals: all_odd.add_node(Node(node_val)) all_odd.remove_odds() "it should remove all nodes if all nodes are odd" self.assertEqual(all_odd.get_length(), 0) self.assertEqual(all_odd.head, None) self.assertEqual(all_odd.tail, None)
def main(): l1 = LinkedList() for i in [100, 80, 60, 40, 20, 0]: l1.add_node(i) print "l1:" print_nodes(l1.root) l1_reversed = reverse_iterative(l1.root) print "l1_reversed:" print_nodes(l1_reversed) print "Reverse LinkedList from node no 2 to node 4" l1 = LinkedList() for i in [100, 80, 60, 40, 20, 0]: l1.add_node(i) l1_reversed = reverse_between(l1.root, 2, 4) print_nodes(l1_reversed)
def sum_lists2(l1, l2): l4 = LinkedList() node = l1.head temp = l2.head counter1 = 0 counter2 = 0 while node: node = node.next counter1 = counter1 + 1 while temp: temp = temp.next counter2 = counter2 + 1 node = l1.head temp = l2.head x = 0 y = 0 while node or temp: if node: counter1 = counter1 - 1 x = x + (node.data) * pow(10, counter1) node = node.next if temp: counter2 = counter2 - 1 y = y + (temp.data) * pow(10, counter2) temp = temp.next z = x + y n = z digit = 1 while n >= 10: n = n / 10 digit = digit + 1 for t in xrange(digit): digit = digit - 1 s = z / pow(10, digit) z = z - (s * pow(10, digit)) l4.insert_front(s) return l4
class Queue: def __init__(self): self.size = 0 #self.storage = [] ##array code commented out self.storage = LinkedList() def __len__(self): #return len(self.storage) return self.size def enqueue(self, value): #self.storage.append(value) self.storage.add_to_end(value) #adds to back of que self.size +=1 def dequeue(self): #if len(self.storage) != 0: #return self.storage.pop(0) if not self.storage.head: return None else: self.size -=1 return self.storage.remove_from_head() #takes from front of que
def test(): assert head(cons("a", nil)) == "a" lst = cons("a", cons("b", nil)) print(lst) assert len(nil) == 0 assert len(lst) == 2 lstlst = map(lambda x: x * 2, lst) assert head(lstlst) == "aa" assert list(lstlst) == ["aa", "bb"] assert "bb" in lstlst assert "(a b)" == repr(lst) assert nil == nil assert LinkedList.from_iter(["aa", "bb"]) == lstlst assert LinkedList.from_iter(["aa"]) == filter(lambda x: x.startswith("a"), lstlst) assert nil == filter(lambda x: x.startswith("c"), lstlst) assert "aabb" == ll.foldl(lambda a, b: a + b, "", lstlst)
def test_find_all(self): # поиск значения NODE_VAL = 12 nodes = self.linked_list.find_all(NODE_VAL) self.assertEqual(len(nodes), 2) for node in nodes: self.assertEqual(node.value, NODE_VAL) # поиск по "сложному" типу данных NODE_VAL = ['test', 12] self.linked_list.add_in_tail(Node(NODE_VAL)) nodes = self.linked_list.find_all(NODE_VAL) self.assertEqual(len(nodes), 1) for node in nodes: self.assertEqual(node.value, NODE_VAL) # поиск несуществующего значения NODE_VAL = 120 nodes = self.linked_list.find_all(NODE_VAL) self.assertEqual(len(nodes), 0) # получение всех узлов списка nodes = self.linked_list.find_all() self.assertEqual(len(nodes), 4) # поиск по None NODE_VAL = None nodes = self.linked_list.find_all(NODE_VAL) self.assertEqual(len(nodes), 4) # поиск по нулевому значению NODE_VAL = 0 self.linked_list.add_in_tail(Node(NODE_VAL)) nodes = self.linked_list.find_all(NODE_VAL) self.assertEqual(len(nodes), 1) # поиск в пустом списке linked_list = LinkedList() nodes = linked_list.find_all(12) self.assertEqual(len(nodes), 0) # поиск в списке из одного узла linked_list.add_in_tail(Node(12)) nodes = linked_list.find_all(12) self.assertEqual(len(nodes), 1) for node in nodes: self.assertEqual(node.value, 12) nodes = linked_list.find_all(10) self.assertEqual(len(nodes), 0)
def resize(self, new_capacity): """ Changes the capacity of the hash table and rehashes all key/value pairs. Implement this. """ # Your code here if self.get_load_factor() > 0.7: old_storage = self.storage self.storage = [LinkedList()] * new_capacity for item in old_storage: current = item.head while current: self.put(current.key, current.value) current = current.next self.capacity = new_capacity
def test_find(self): # поиск значения NODE_VAL = 12 node = self.linked_list.find(NODE_VAL) self.assertEqual(node.value, NODE_VAL) # поиск несуществующего значения NODE_VAL = 128 node = self.linked_list.find(NODE_VAL) self.assertIsNone(node) # поиск по None NODE_VAL = None self.linked_list.add_in_tail(Node(NODE_VAL)) node = self.linked_list.find(NODE_VAL) self.assertEqual(node.value, NODE_VAL) # поиск по "сложному" типу данных NODE_VAL = ['test', 12] self.linked_list.add_in_tail(Node(NODE_VAL)) node = self.linked_list.find(NODE_VAL) self.assertEqual(node.value, NODE_VAL) # поиск по нулевому значению NODE_VAL = 0 self.linked_list.add_in_tail(Node(NODE_VAL)) node = self.linked_list.find(NODE_VAL) self.assertEqual(node.value, NODE_VAL) # поиск в пустом списке linked_list = LinkedList() node = linked_list.find(12) self.assertIsNone(node) # поиск в списке из одного узла linked_list.add_in_tail(Node(12)) node = linked_list.find(12) self.assertEqual(node.value, 12) node = linked_list.find(10) self.assertIsNone(node)
class Queue(): def __init__(self): self.values = LinkedList() def add(self, newVal): self.values.append(newVal) def remove(self): self.values.remove_from_front() def itemAt(self, index): return self.values.itemAt(index) def indexOf(self, value): return self.values.indexOf(value) def __len__(self): return self.values.length def __str__(self): return str(self.values)
def sum_lists(l1, l2): l3 = LinkedList() node = l1.head temp = l2.head remainder = 0 while node or temp: if node: x = node.data node = node.next else: x = 0 if temp: y = temp.data temp = temp.next else: y = 0 z = x + y + remainder remainder = z / 10 l3.insert_front(z % 10) if remainder == 1: l3.insert_front(1) return l3
def add_numbers(l1, l2): """ Add two numbers represented by LinkedList :param l1: root of linked list :param l2: root of linked list :return: sum_ll_root: root of linked list """ l1 = reverse_iterative(l1) l2 = reverse_iterative(l2) sum_ll = LinkedList() carry = 0 while l1 is not None and l2 is not None: sum = l1.get_data() + l2.get_data() + carry s = sum % 10 carry = sum / 10 print carry, s, l1.get_data(), l2.get_data(), carry sum_ll.add_node(s) l1 = l1.get_next() l2 = l2.get_next() if carry: sum_ll.add_node(carry) sum_ll_root = reverse_iterative(sum_ll.root) return sum_ll_root
def sum_linked_lists(first: LinkedList, second: LinkedList): if not isinstance(first, LinkedList): raise Exception("The first argument must be of the LinkedList type.") if not isinstance(second, LinkedList): raise Exception("The second argument must be of the LinkedList type.") if first.len() != second.len(): raise Exception("Lists must be the same size.") result = LinkedList() node1 = first.head node2 = second.head while node1 is not None: if not isinstance(node1.value, int) or not isinstance( node2.value, int): del result raise Exception("The list should only have numeric values.") result.add_in_tail(Node(node1.value + node2.value)) node1 = node1.next node2 = node2.next return result
def test_insert(self): l = LinkedList(37) l.insert(45) self.assertEqual(45, l.value) self.assertEqual(37, l.next.value) self.assertEqual(2, l.length())
import argparse from ll import LinkedList if __name__ == "__main__": def replace(string): """ Search uses regex for searching with wildcards. The . (dot) is any char. """ return string.replace('*', '.', 25) parser = argparse.ArgumentParser(description="Linked list. Builds\ a list from a file containing a list of\ words. Then searches that list for the\ inputed word. Wildcards(*) are allowed.") parser.add_argument('file', type=str, help="File location") parser.add_argument('word', type=str, help="Word to search") args = parser.parse_args() search_value = replace(args.word) with open(args.file, 'r') as reader: print("Building linked list...") linked_list = LinkedList() for line in reader: linked_list.insert(line.rstrip()) query = str(linked_list.search(search_value)) print("The following words were matched: \n" + query)