diff --git a/names/names.py b/names/names.py index ea158997f..e1d899286 100644 --- a/names/names.py +++ b/names/names.py @@ -1,22 +1,69 @@ import time +import os + +file_names_1 = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'names_1.txt') +file_names_2 = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'names_2.txt') start_time = time.time() -f = open('names_1.txt', 'r') +f = open(file_names_1, 'r') names_1 = f.read().split("\n") # List containing 10000 names f.close() -f = open('names_2.txt', 'r') +f = open(file_names_2, 'r') names_2 = f.read().split("\n") # List containing 10000 names f.close() duplicates = [] # Return the list of duplicates in this data structure +class BSTNode: + def __init__(self, value): + self.value = value + self.left = None + self.right = None + + # Insert the given value into the tree + def insert(self, value): + if value < self.value: + if self.left is None: + self.left = BSTNode(value) + else: + self.left.insert(value) + else: + if self.right is None: + self.right = BSTNode(value) + else: + self.right.insert(value) + + # Return True if the tree contains the value + # False if it does not + def contains(self, target): + if self.value == target: + return True + + if target < self.value: + if self.left is None: + return False + else: + return self.left.contains(target) + else: + if self.right is None: + return False + else: + return self.right.contains(target) # Replace the nested for loops below with your improvements -for name_1 in names_1: - for name_2 in names_2: - if name_1 == name_2: - duplicates.append(name_1) +# for name_1 in names_1: +# for name_2 in names_2: +# if name_1 == name_2: +# duplicates.append(name_1) + +bst = BSTNode(names_1[0]) +for names1 in names_1: + bst.insert(names1) +for names2 in names_2: + if bst.contains(names2): + duplicates.append(names2) + end_time = time.time() print (f"{len(duplicates)} duplicates:\n\n{', '.join(duplicates)}\n\n") diff --git a/reverse/reverse.py b/reverse/reverse.py index 6116252d1..f4f2bfbd1 100644 --- a/reverse/reverse.py +++ b/reverse/reverse.py @@ -39,4 +39,10 @@ def contains(self, value): return False def reverse_list(self, node, prev): - pass + while node: + reverse_node = node.get_next() + node.next_node = prev + prev = node + node = reverse_node + self.head = prev + return node diff --git a/ring_buffer/ring_buffer.py b/ring_buffer/ring_buffer.py index 37e9fb0dd..94b7b259b 100644 --- a/ring_buffer/ring_buffer.py +++ b/ring_buffer/ring_buffer.py @@ -1,9 +1,15 @@ class RingBuffer: def __init__(self, capacity): - pass + self.capacity = capacity + self.current = -1 + self.buffer_array = [] def append(self, item): - pass + if len(self.buffer_array) == self.capacity: + self.current = (self.current + 1) % self.capacity + self.buffer_array[self.current] = item + else: + self.buffer_array.append(item) def get(self): - pass \ No newline at end of file + return self.buffer_array