def generate_data(self, data: LinkedList, pos, filename) -> None: with open(filename, "r") as infile: for line in infile: for x in line.split(): data.insert(int(x), pos) pos += 1 infile.close()
def test_remove(self): lk = LinkedList() for i in range(0, 10): lk.add_first(i) lk.remove_first() assert lk.get_first() == 8 lk.remove_last() assert lk.get_last() == 1
class TestLinkedListAddNode(unittest.TestCase): def setUp(self): head_node = LinkedList.create_node() self.list_without_head = LinkedList() self.list_with_head_node = LinkedList(head_node=head_node) def test_can_add_node_without_head_node(self): self.list_without_head.add_node() self.assertEqual(type(self.list_without_head.head_node), Node) def test_can_add_node_with_head_node(self): #other test cases ensure that add works however leaving this in #case by throwing an exception it helps track down something else self.list_with_head_node.add_node()
def add_vertex(self, item: any) -> None: """ Add a new vertex with no edges Precondition: the item does not exist in the graph :param item: the value of the vertex to insert """ self.adjacency_list[item] = LinkedList()
class LinkedListStack(StackInterface): def __init__(self): self.__data = LinkedList() #链表对象 # 获取栈内元素个数 def getSize(self): return self.__data.getSize() # 判断栈是否为空 def isEmpty(self): return self.__data.isEmpty() # 入栈,在链表头插入 def push(self, e): self.__data.addFirst(e) #出栈,删除链表头元素 def pop(self): self.__data.deleteFirst() #取栈顶元素 def peek(self): return self.__data.getFirst() #打印输出链栈 def __str__(self): return str(self.__data) def __repr__(self): return self.__str__()
def dfs_visit(graph: Graph, u: Any, time: int, status: dict, topological_list: LinkedList) -> None: """ Completely explores each vertex connected to the source vertex u, starting from lowest depth :param graph: the graph to perform dfs_visit on :param u: the vertex to recurse down :param time: the time called :return: the time after dfs_visit() completes on the source vertex """ status[u] = 1 # update u to grey time += 1 for v in graph.adjacency_list[u]: if status[v] == 0: dfs_visit(graph, v, time, status, topological_list) status[u] = 2 time += 1 topological_list.insert_first(u)
class TestLinkedListGetLastNode(unittest.TestCase): def setUp(self): self.head_node = Node() self.list_without_head = LinkedList() self.list_with_head_node = LinkedList(head_node=self.head_node) def test_list_without_head_node_returns_none(self): self.assertIsNone(self.list_without_head.get_last_node()) def test_list_with_only_head_node_returns_head_node(self): self.assertEqual(self.list_with_head_node.get_last_node(), self.head_node) def test_list_with_more_than_one_node_returns_last_node(self): guid1 = str(uuid4()) guid2 = str(uuid4()) self.list_with_head_node.add_node(guid1) self.list_with_head_node.add_node(guid2) self.assertEqual(self.list_with_head_node.get_last_node().data, guid2) def tearDown(self): self.head_node = None self.list_without_head = None self.list_with_head_node = None
def checkPalindrome(ll): ll_len = len(ll) half_count = floor(ll_len / 2) len_is_even = ll_len % 2 == 0 half_reverse_ll = LinkedList() current = ll.head for i, value in enumerate(ll): if half_count < i + 1: break half_reverse_ll.add_to_beginning(str(value)) current = current.next if not len_is_even: current = current.next current_from_half = half_reverse_ll.head while current: if str(current_from_half.value) != str(current.value): return False current_from_half = current_from_half.next current = current.next return True
def topological_sort(graph: Graph) -> LinkedList: """ :param graph: the graph to sort :return: LinkedList such that if the graph contains edge (u, v), then u appears before v in the list """ topological_list = LinkedList() time = 0 vertices = graph.adjacency_list.keys() status = {} # synonymous to colours, initialized at white (unvisited) for vertex in vertices: status[vertex] = 0 for vertex in vertices: if status[vertex] == 0: dfs_visit(graph, vertex, time, status, topological_list) return topological_list
class TestCountNodesInList(unittest.TestCase): def setUp(self): self.linked_list_without_head = LinkedList() self.linked_list_with_head = LinkedList(head_node=Node()) def test_linked_list_without_head_has_size_zero(self): self.assertEqual(self.linked_list_without_head.get_size(), 0) def test_linked_list_with_head_only_has_size_one(self): self.assertEqual(self.linked_list_with_head.get_size(), 1) def test_linked_list_with_added_values_reports_size_correctly(self): self.linked_list_with_head.add_node("some data") self.linked_list_with_head.add_node("another node") self.assertEqual(self.linked_list_with_head.get_size(), 3) def tearDown(self): self.linked_list_without_head = None self.linked_list_with_head = None
def __init__(self, initial_node: Node): self.rank = 0 self.items = LinkedList() self.items.insert_node(initial_node)
# 'M': 100 # } # for i in range(len(s)): # t = s[i] # # tmp = 0 # for t in keyVal: # tmp = 0 # if t == 'I': # tmp = tmp + keyVal[t] # return tmp # romanToInt('II') # This section is to learn how to import classes from a different directory # %% # import sys # sys.path.append('../') from LinkedList.LinkedList import LinkedList # %% llist = LinkedList() llist.append('I') llist.prepend('L') llist.append('O') llist.append('N') llist.print_list() # %%
def test_set_elememt(self): lk = LinkedList() for i in range(0, 10): lk.add_first(i) assert lk.get_first() == 9 lk.set(9, 99) assert lk.get_last() == 99 lk.set(5, 788) assert lk.contains(788) is True
def solver(input): if input == None: return False # just swap the value of the current node with the value of the next node next = input.next input.value = next.value input.next = next.next return True if __name__ == "__main__": values = [1, 2, 3, 4, 5, 6, 7, 8, 9] ll = LinkedList() ll2 = LinkedList() for x in values: ll.addToTail(x) if x != 5: ll2.addToTail(x) curr = ll.head while curr.value != 5: curr = curr.next # now that we have 5, pass that value into the function solver(curr) ll.printList() ll2.printList()
def test_add_first(self): lk = LinkedList() for i in range(0, 10): lk.add_first(i) assert lk.get_first() == 9
def setUp(self): self.head_node = Node() self.list_without_head = LinkedList() self.list_with_head_node = LinkedList(head_node=self.head_node)
longer_node = ll1.head if ll1_len >= ll2_len else ll2.head shortter_node = ll2.head if ll2_len <= ll1_len else ll1.head len_diff = abs(ll1_len - ll2_len) if len_diff != 0: while len_diff != 0: longer_node = longer_node.next len_diff -= 1 while longer_node.next != None: if longer_node == shortter_node: return longer_node longer_node = longer_node.next shortter_node = shortter_node.next ll1 = LinkedList([3, 1, 5, 9, 7, 2, 1]) ll2 = LinkedList([4, 6]) ll2.tail.next = ll1.head.next.next.next.next ll2.tail = ll1.tail print(Intersection(ll1, ll2)) ll11 = LinkedList([3, 1, 5, 9, 7, 2, 1]) ll22 = LinkedList([5, 1, 5, 9, 7, 2, 1]) print(Intersection(ll11, ll22))
len_is_even = ll_len % 2 == 0 half_reverse_ll = LinkedList() current = ll.head for i, value in enumerate(ll): if half_count < i + 1: break half_reverse_ll.add_to_beginning(str(value)) current = current.next if not len_is_even: current = current.next current_from_half = half_reverse_ll.head while current: if str(current_from_half.value) != str(current.value): return False current_from_half = current_from_half.next current = current.next return True ll = LinkedList(['l', 'e', 'v', 'e', 'l']) print(checkPalindrome(ll)) ll = LinkedList(['l', 'e', 'e', 'l']) print(checkPalindrome(ll)) ll = LinkedList(['l', 'e', 'v', 'a', 'l']) print(checkPalindrome(ll))
else: seen.remove(p2.value) p1 = p1.next p2 = p2.next # p2 should be at the end, but if the current value there has been seen, then we have to remove this node if p2.value not in seen: p1.next = None # return the new linked list return input if __name__ == "__main__": # Create unsorted Linked list l1 = LinkedList() toAdd = [5, 6, 5, 1, 2, 1, 2] for x in toAdd: l1.addToTail(x) # do the problem print("========== RESULT ==========") solver(l1) l1.printList() # Create unsorted Linked list print("========== ANSWER ==========") s1 = LinkedList() ans = [5, 6, 1, 2] for x in ans: s1.addToTail(x)
def __init__(self): self.__data = LinkedList() #链表对象
#!/usr/bin/python3 from LinkedList.LinkedList import LinkedList linked_list = LinkedList() linked_list.insert_start(23) linked_list.insert_start(33) linked_list.insert_start(36) linked_list.traverse() print('\n\n ==== ') linked_list.remove(23) print(linked_list.size()) linked_list.traverse() print('\n\n ==== ') linked_list.insert_start('mbido') linked_list.insert_end('nkwusi') linked_list.traverse() print(linked_list.size())
def test_node_creation_with_next_node(self): test_next_node = LinkedList.create_node() test_node = LinkedList.create_node(next_node=test_next_node) self.assertEqual(test_node.next_node, test_next_node)
def test_node_creation_with_data(self): test_node = LinkedList.create_node(data="hello") self.assertEqual(test_node.data, "hello")
def test_node_creation_with_defaults(self): test_node = LinkedList.create_node() self.assertEqual(type(test_node), Node)
def generate_data(self, data: LinkedList, pos, n) -> None: for c in Coprime_pairs_iter(3, n, 2): data.insert(c[0], pos) data.insert(c[1], pos + 1) pos += 2
while True: if slower_node is faster_node: return faster_node # Collision Node slower_node = slower_node.next if faster_node.next is None or faster_node.next.next is None: return False faster_node = faster_node.next.next def detectLoop(ll): collision_node = hasLoop(ll) if not collision_node: return False start_node = ll.head start_node_2 = collision_node while True: if start_node.next is start_node_2.next: return start_node_2 start_node = start_node.next start_node_2 = start_node_2.next ll1 = LinkedList(['A', 'B', 'C', 'D', 'E', 'Q', 'W', 'E', 'R', 'T', 'Y']) ll1.tail.next = ll1.head.next.next.next ll1.tail = None print(detectLoop(ll1))
from LinkedList.LinkedList import LinkedList LinkedList = LinkedList() LinkedList.insert(22) LinkedList.insert(12) LinkedList.insert(134) LinkedList.insert(245) LinkedList.traverseList() LinkedList.remove(22) LinkedList.traverseList()
print( "Length Mismatch: size of outputs ({}) doesn't match expected ({})" .format(len(outputs, len(expected)))) return # Run through all the solutions, and see what's up counter = 0 for ans, exp, inp in zip(outputs, expected, inputs): if ans == exp: counter += 1 else: print("======================================================") print("Wrong Answer: {} should equal {}".format(ans, exp)) print("Input: {}".format(inp)) print("======================================================\n") # print the final score print("FINAL SCORE: {}/{}".format(counter, len(inputs))) if __name__ == "__main__": # create a random list of integers, so that we can create some random tests values = [random.randint(0, 1000) for x in range(10000)] ll = LinkedList() for x in values: ll.addToTail(x) toGet = 0 print("Value Returned from function: {}".format(solver(ll, toGet))) print("Correct Value: {}".format(values[len(values) - toGet - 1]))
def setUp(self): head_node = LinkedList.create_node() self.list_without_head = LinkedList() self.list_with_head_node = LinkedList(head_node=head_node)
def __init__(self, vertices): self.vertices = vertices self.edges = [LinkedList() for _ in range(vertices)]