diff --git a/binary_search_tree/binary_search_tree.py b/binary_search_tree/binary_search_tree.py index d80d9f6282..7bd9144c15 100644 --- a/binary_search_tree/binary_search_tree.py +++ b/binary_search_tree/binary_search_tree.py @@ -1,3 +1,7 @@ +from collections import deque +from queue import Queue +from stack import Stack + """ Binary search trees are a data structure that enforce an ordering over the data they store. That ordering in turn makes it a lot more efficient @@ -9,6 +13,8 @@ 2. Implement the `in_order_print`, `bft_print`, and `dft_print` methods on the BSTNode class. """ + + class BSTNode: def __init__(self, value): self.value = value @@ -17,37 +23,157 @@ def __init__(self, value): # Insert the given value into the tree def insert(self, value): - pass + # left case? + # check if the value is less than the root value? + if value < self.value: + # move to the left and check if it is none? + if self.left == None: + # insert node here + new_node = BSTNode(value) + self.left = new_node + # otherwise + else: + # call insert on the root's left node + self.left.insert(value) + # right case? + if value >= self.value: + # otherwise + # move to the right and check if it is none? + if self.right == None: + # insert the node here + new_node = BSTNode(value) + self.right = new_node + # otherwise + else: + # call insert on the root's right node + self.right.insert(value) # Return True if the tree contains the value # False if it does not + def contains(self, target): - pass + # check if the node is == target + if self.value == target: + # if true return true + return True + # otherwise check if target is < node value + elif target < self.value: + # if left is None, target doesn't exist in tree, return false + if self.left == None: + return False + # if left value is = target return true + elif self.left.value == target: + return True + # otherwise move down left, call contains on left node + else: + self.left.contains(target) + # otherwise check if target is >= node value + elif target > self.value: + # if right is None, target doesn't exist in tree, return false + if self.right == None: + return False + # if right value is = target return true + elif self.right.value == target: + return True + # otherwise move down right, call contains on right node + else: + self.right.contains(target) # Return the maximum value found in the tree + def get_max(self): - pass + if self.right == None: + return self.value + else: + max_value = self.right.get_max() + return max_value # Call the function `fn` on the value of each node def for_each(self, fn): - pass + # run the function passing in the value of the node + fn(self.value) + + # if left is not none run for each on left + if self.left: + # call function on left + self.left.for_each(fn) + + # if right is not None run for each on right + if self.right: + # call function on right + self.right.for_each(fn) # Part 2 ----------------------- # Print all the values in order from low to high # Hint: Use a recursive, depth first traversal def in_order_print(self): - pass + # base case + # if there are no more nodes + if self == None: + # return + return self + + # if there is a node to the left + if self.left is not None: + # call in order print on the left + self.left.in_order_print() + # print the value of the current node (self.value) + print(self.value) + + # if there is a node to the right + if self.right is not None: + # call order print on the right + self.right.in_order_print() # Print the value of every node, starting with the given node, # in an iterative breadth first traversal - def bft_print(self): - pass + + def bft_print(self): # use a queue + # create a queue + values = Queue() + # eneque the first node(self) + values.enqueue(self) + + # while there is data on queue + while values.size > 0: + # dequeue from queue on to current_node + self = values.dequeue() + # print the current_node's value + print(self.value) + # if the current_node has a left child + if self.left: + # enqueue the left child + values.enqueue(self.left) + # if the current_node has a right child + if self.right: + # enqueue right child + values.enqueue(self.right) + # this increases our values.size + # continuing the loop until done # Print the value of every node, starting with the given node, # in an iterative depth first traversal - def dft_print(self): - pass + + def dft_print(self): # use a stack + # instantiate stack + values = Stack() + # push starting node + values.push(self) + # while stack is NOT empty: + while values.size > 0: + # pop the node + # print node.value + self = values.pop() + print(self.value) + # if node.left: + # push left node + if self.left: + values.push(self.left) + # if node.right: + # push right node + if self.right: + values.push(self.right) # Stretch Goals ------------------------- # Note: Research may be required @@ -60,6 +186,7 @@ def pre_order_dft(self): def post_order_dft(self): pass + """ This code is necessary for testing the `print` methods """ @@ -77,9 +204,9 @@ def post_order_dft(self): bst.dft_print() print("elegant methods") -print("pre order") -bst.pre_order_dft() +# print("pre order") +# bst.pre_order_dft() print("in order") -bst.in_order_dft() -print("post order") -bst.post_order_dft() +bst.in_order_print() +# print("post order") +# bst.post_order_dft() diff --git a/binary_search_tree/queue.py b/binary_search_tree/queue.py new file mode 100644 index 0000000000..d342b43662 --- /dev/null +++ b/binary_search_tree/queue.py @@ -0,0 +1,36 @@ +""" +A queue is a data structure whose primary purpose is to store and +return elements in First In First Out order. + +1. Implement the Queue class using an array as the underlying storage structure. + Make sure the Queue tests pass. +2. Re-implement the Queue class, this time using the linked list implementation + as the underlying storage structure. + Make sure the Queue tests pass. +3. What is the difference between using an array vs. a linked list when + implementing a Queue? + +Stretch: What if you could only use instances of your Stack class to implement the Queue? + What would that look like? How many Stacks would you need? Try it! +""" + + +class Queue: + def __init__(self): + self.size = 0 + # self.storage = [] + self.storage = [] # instead of LinkedList() + + def __len__(self): + return self.size + + def enqueue(self, value): + self.size += 1 + return self.storage.append(value) # intead of add_to_tail + + def dequeue(self): + if self.size == 0: + return None + self.size -= 1 + # return self.storage.pop(0) + return self.storage.pop(0) # intead of remove_tail diff --git a/binary_search_tree/stack.py b/binary_search_tree/stack.py new file mode 100644 index 0000000000..4e9930db92 --- /dev/null +++ b/binary_search_tree/stack.py @@ -0,0 +1,31 @@ +""" +A stack is a data structure whose primary purpose is to store and +return elements in Last In First Out order. + +1. Implement the Stack class using an array as the underlying storage structure. + Make sure the Stack tests pass. +2. Re-implement the Stack class, this time using the linked list implementation + as the underlying storage structure. + Make sure the Stack tests pass. +3. What is the difference between using an array vs. a linked list when + implementing a Stack? +""" + + +class Stack: + def __init__(self): + self.size = 0 + self.storage = [] + + def __len__(self): + return self.size + + def push(self, value): + self.size += 1 + self.storage.append(value) + + def pop(self): + if self.size == 0: + return None + self.size -= 1 + return self.storage.pop() diff --git a/binary_search_tree/test_binary_search_tree.py b/binary_search_tree/test_binary_search_tree.py index 0a0cee5911..6ebaab2bad 100644 --- a/binary_search_tree/test_binary_search_tree.py +++ b/binary_search_tree/test_binary_search_tree.py @@ -4,6 +4,7 @@ import io from binary_search_tree import BSTNode + class BinarySearchTreeTests(unittest.TestCase): def setUp(self): self.bst = BSTNode(5) @@ -15,7 +16,7 @@ def test_insert(self): self.bst.insert(6) self.assertEqual(self.bst.left.right.value, 3) self.assertEqual(self.bst.right.left.value, 6) - + def test_handle_dupe_insert(self): self.bst2 = BSTNode(1) self.bst2.insert(1) @@ -38,7 +39,7 @@ def test_get_max(self): def test_for_each(self): arr = [] - cb = lambda x: arr.append(x) + def cb(x): return arr.append(x) v1 = random.randint(1, 101) v2 = random.randint(1, 101) @@ -94,17 +95,18 @@ def test_print_traversals(self): self.assertTrue(output == "1\n8\n5\n7\n6\n3\n4\n2\n" or output == "1\n8\n5\n3\n2\n4\n7\n6\n") - sys.stdout = io.StringIO() - self.bst.pre_order_dft() - output = sys.stdout.getvalue() - self.assertEqual(output, "1\n8\n5\n3\n2\n4\n7\n6\n") + # sys.stdout = io.StringIO() + # self.bst.pre_order_dft() + # output = sys.stdout.getvalue() + # self.assertEqual(output, "1\n8\n5\n3\n2\n4\n7\n6\n") - sys.stdout = io.StringIO() - self.bst.post_order_dft() - output = sys.stdout.getvalue() - self.assertEqual(output, "2\n4\n3\n6\n7\n5\n8\n1\n") + # sys.stdout = io.StringIO() + # self.bst.post_order_dft() + # output = sys.stdout.getvalue() + # self.assertEqual(output, "2\n4\n3\n6\n7\n5\n8\n1\n") sys.stdout = stdout_ # Restore stdout + if __name__ == '__main__': unittest.main() diff --git a/doubly_linked_list/doubly_linked_list.py b/doubly_linked_list/doubly_linked_list.py index 6f91b43a9b..1a9ed97170 100644 --- a/doubly_linked_list/doubly_linked_list.py +++ b/doubly_linked_list/doubly_linked_list.py @@ -1,3 +1,4 @@ + """ Each ListNode holds a reference to its previous node as well as its next node in the List. @@ -27,7 +28,15 @@ def __len__(self): the old head node's previous pointer accordingly. """ def add_to_head(self, value): - pass + if self.length == 0: + newnode = ListNode(value) + self.head = newnode + self.tail = newnode + else: + newnode = ListNode(value, None, self.head) + self.head.prev = newnode + self.head = self.head.prev + self.length += 1 """ Removes the List's current head node, making the @@ -35,7 +44,19 @@ def add_to_head(self, value): Returns the value of the removed Node. """ def remove_from_head(self): - pass + if self.length == 1: + temp = self.head.value + self.head = None + self.tail = None + self.length = 0 + return temp + elif self.length == 0: + pass + else: + self.length -= 1 + self.head.next.prev = None + self.head = self.head.next + return self.head """ Wraps the given value in a ListNode and inserts it @@ -43,7 +64,15 @@ def remove_from_head(self): the old tail node's next pointer accordingly. """ def add_to_tail(self, value): - pass + if self.length == 0: + newnode = ListNode(value) + self.head = newnode + self.tail = newnode + else: + newnode = ListNode(value, self.tail, None) + self.tail.next = newnode + self.tail = self.tail.next + self.length += 1 """ Removes the List's current tail node, making the @@ -51,32 +80,82 @@ def add_to_tail(self, value): Returns the value of the removed Node. """ def remove_from_tail(self): - pass + if self.length == 1: + temp = self.tail.value + self.head = None + self.tail = None + self.length = 0 + return temp + elif self.length == 0: + pass + else: + self.length -= 1 + self.tail.prev.next = None + self.tail = self.tail.prev + return self.tail """ Removes the input node from its current spot in the List and inserts it as the new head node of the List. """ def move_to_front(self, node): - pass + temp = self.head + while temp is not None: + if node.value == temp.value: + break + temp = temp.next + self.delete(temp) + self.add_to_head(temp.value) """ Removes the input node from its current spot in the List and inserts it as the new tail node of the List. """ def move_to_end(self, node): - pass + temp = self.head + while temp is not None: + if node.value == temp.value: + break + temp = temp.next + self.delete(temp) + self.add_to_tail(temp.value) """ Deletes the input node from the List, preserving the order of the other elements of the List. """ def delete(self, node): - pass - + if self.head == self.tail: + self.head = None + self.tail = None + else: + temp = self.head + while temp is not None: + if node.value == temp.value: + break + temp = temp.next + if node.value == self.head.value: + if self.length == 2: + self.head = self.tail + else: + self.head = node.next + if node.value == self.tail.value: + self.tail = node.prev + if temp.next is not None: + temp.next.prev = node.prev + if temp.prev is not None: + temp.prev.next = node.next + self.length -= 1 + """ Finds and returns the maximum value of all the nodes in the List. """ def get_max(self): - pass \ No newline at end of file + max_val = self.head.value + temp = self.head + while temp is not None: + if temp.value > max_val: + max_val = temp.value + temp = temp.next + return max_val \ No newline at end of file diff --git a/queue/queue.py b/queue/queue.py index 0d2599ded7..99312d0a9a 100644 --- a/queue/queue.py +++ b/queue/queue.py @@ -13,16 +13,117 @@ Stretch: What if you could only use instances of your Stack class to implement the Queue? What would that look like? How many Stacks would you need? Try it! """ +class Node: + def __init__(self, value, next_node=None): + # the value that the node is holding + self.value = value + # reference to the next node in the linked list + self.next_node = next_node + + # method to get the value of the node + def get_value(self): + return self.value + + # method to get the node's `next_node` + def get_next(self): + return self.next_node + + # method to update the node's `next_node` to the input node + def set_next(self, new_next): + self.next_node = new_next + +class LinkedList: + def __init__(self): + self.head = None + self.tail = None + + def add_to_tail(self, value): + # wrap the value in a Node + new_node = Node(value) + # check if the Linked List is empty + if self.head is None and self.tail is None: + # set head and tail to the new node + self.head = new_node + self.tail = new_node + # otherwise, the list has at least one node + else: + # update the last node's `next_node` to the new node + self.tail.set_next(new_node) + # update `self.tail` to point the new node we just added + self.tail = new_node + + def remove_tail(self): + # check if the linked list is empty + if self.head is None and self.tail is None: + return None + + # check if the linked list has only one node + if self.head == self.tail: + # store the node we're going to remove's value + val = self.head.get_value() + self.head = None + self.tail = None + return val + + # otherwise, the linked list has more than one Node + else: + # store the last Node's value in a nother variable so we can return it + val = self.tail.get_value() + # we need to set `self.tail` to the second-to-last Node + # the only way we can do this, is by traversing the whole linked list + # from the beginning + + # starting from the head, we'll traverse down to the second-to-last Node + # init another reference to keep track of where we are in the linked + # list as we're iterating + current = self.head + + # keep iterating until the node after `current` is the tail + while current.get_next() != self.tail: + # keep iterating + current = current.get_next() + + # set `self.tail` to `current` + self.tail = current + # set the new tail's `next_node` to None + self.tail.set_next(None) + return val + + def remove_head(self): + # check if the linked list empty + if self.head is None and self.tail is None: + return None + # check if there is only one linked list node + if self.head == self.tail: + val = self.head.get_value() + self.head = None + self.tail = None + return val + else: + # store the old head's value that we need to return + val = self.head.get_value() + # set `self.head` to the old head's `next_node` + self.head = self.head.get_next() + # return the old_head's value + return val + class Queue: def __init__(self): self.size = 0 - # self.storage = ? + # self.storage = [] + self.storage = LinkedList() def __len__(self): - pass + return self.size def enqueue(self, value): - pass + self.size += 1 + # return self.storage.append(value) + return self.storage.add_to_tail(value) def dequeue(self): - pass + if self.size == 0: + return None + self.size -= 1 + # return self.storage.pop(0) + return self.storage.remove_head() \ No newline at end of file diff --git a/singly_linked_list/singly_linked_list.py b/singly_linked_list/singly_linked_list.py index e69de29bb2..ea31f48cc4 100644 --- a/singly_linked_list/singly_linked_list.py +++ b/singly_linked_list/singly_linked_list.py @@ -0,0 +1,115 @@ +class Node: + def __init__(self, value, next_node=None): + # the value that the node is holding + self.value = value + # reference to the next node in the linked list + self.next_node = next_node + + + def get_value(self): + """ + Method to get the value of a node + """ + return self.value + + def get_next(self): + """ + Method to get the node's "next_node" + """ + return self.next_node + + def set_next(self, new_next): + """ + Method to update the node's "next_node" to the new_next + """ + self.next_node = new_next + + +class LinkedList: + def __init__(self): + self.head = None + self.tail = None + + def add_to_tail(self, value): + #wrap the value in a new Node + new_node = Node(value) + #check if the linked list is empty + if self.head is None and self.tail is None: + #set the head and tail to the new node + self.head = new_node + self.tail = new_node + + #otherwise the list must have at least one item in there + else: + #update the last node's "next_node" to the new node + self.tail.set_next(new_node)#(last node in the chain).next_node = new_node + #update the self.tail to the point to the new node that we just added + self.tail = new_node + + def remove_tail(self): + #remove the last node in the chain and return its value + #check for empty list + if self.head is None and self.tail is None: + #return none + return None + + #check if there is only one node + if self.head == self.tail: + #store the value of the node that we are going to remove + value = self.head.get_value() + #remove the node + #set the head and the tail to None + self.head = None + self.tail = None + # return the stored value + return value + + #otherwise the link list has more than one node + else: + #store the value of the node that we are going to remove + value = self.tail.get_value() + # we need to set the "self.tail" to the second to last node + # we can only do this by traversing the whole list from beginning to end + + #starting from the head, we'll traverse down to the second to last node + #init another reference to keep track of where we are in the linked + #list as we're iterating. + current_node = self.head + + # keep iterating until the node after "current_node" is the tail + while current_node.get_next() != self.tail: + #keep looping + current_node = current_node.get_next() + + #at the end of the iteration set "self.tail" to the current_node + self.tail = current_node + #set the new tail's "next_node" to None + self.tail.set_next(None) + #return the value + return value + + def remove_head(self): + #check for empty list + if self.head is None and self.tail is None: + #return none + return None + #check if there is only one linked list node + if self.head == self.tail: + val = self.head.get_value() + self.head = None + self.tail = None + return val + else: + #store the old head's value that we need to return + val = self.head.get_value() + # set `self.head` to the old head's `next_node` + self.head = self.head.get_next() + # return the old_head's value + return val + + + + + + + diff --git a/stack/stack.py b/stack/stack.py index 6e6d660ac7..db1e62bbf3 100644 --- a/stack/stack.py +++ b/stack/stack.py @@ -13,13 +13,16 @@ class Stack: def __init__(self): self.size = 0 - # self.storage = ? + self.storage = [] def __len__(self): - pass + return self.size def push(self, value): - pass + self.size += 1 def pop(self): - pass + if self.size == 0 + return None + self.size -= 1 + return self.storage.pop()