def add(self, key, value): """Adds the key value pair to the hash table""" hash = self.hashFunction(key, self.capacity) value = [key, value] try: liList = self.table[hash] index = self.__containsKey(liList, key) if index >= 0: self.__removeFromLinkedList(liList, index) liList.add(value) except ValueError: self.table[hash] = None liList = LinkedList() liList.add(value) self.table[hash] = liList self.size += 1 if self.size / self.capacity > self.LOAD_FACTOR: self.__resizing() return True
def test_delete_middle_element(): linked_list = LinkedList() linked_list.add(10) linked_list.add(20) linked_list.add(30) linked_list.delete(1) assert linked_list.to_list() == [10, 30]
def test_delete_invalid_index(): linked_list = LinkedList() linked_list.add(10) linked_list.add(20) linked_list.add(30) linked_list.delete(4) assert linked_list.to_list() == [10, 20, 30]
def test_delete_end_element(): linked_list = LinkedList() linked_list.add(10) linked_list.add(20) linked_list.add(30) linked_list.delete(2) assert linked_list.to_list() == [10, 20]
def merge(left, right): """ Merges two linked lists, sorting by data in nodes Returns a new, merged list Takes O(n) space Runs in O(n) time """ # Create a new linked list that contains nodes from # merging left and right merged = LinkedList() # Add a fake head that is discarded later merged.add(0) # Set current to the head of the linked list current = merged.head # Obtain head nodes for left and right linked lists left_head = left.head right_head = right.head # Iterate over left and right until we reach the tail node # or either while left_head or right_head: # If the head node of left is None, we're past the tail # Add the node from right to merged linked list if left_head is None: current.next_node = right_head # Call next on right to set loop condition to False right_head = right_head.next_node # If the head node of right is None, we're past the tail # Add the tail node from left to merged linked list elif right_head is None: current.next_node = left_head # Call next on left to set loop condition to False left_head = left_head.next_node else: # Not at either tail node # Obtain node data to perform comparison operations left_data = left_head.data right_data = right_head.data # If data on left is less than right, set current to left node if left_data < right_data: current.next_node = left_head # Move left head to next node left_head = left_head.next_node # If data on left is greater than right, set current to right node else: current.next_node = right_head # Move right head to next node right_head = right_head.next_node # Move current to next node current = current.next_node # Discard fake head and set first merged node as head head = merged.head.next_node merged.head = head return merged
def boolean_OR(op1, op2): p1 = op1.getHead() p2 = op2.getHead() result = LinkedList() while p1 is not None or p2 is not None: if p1 is not None and p2 is None: result.add(p1.getData()) p1 = p1.getNext() elif p2 is not None and p1 is None: result.add(p2.getData()) p2 = p2.getNext() else: if p1.getData() == p2.getData(): result.add(p1.getData()) p1 = p1.getNext() p2 = p2.getNext() elif p1.getData() < p2.getData(): result.add(p1.getData()) p1 = p1.getNext() else: result.add(p2.getData()) p2 = p2.getNext() return result
def main(): list1 = LinkedList() list1.add_to_front(2) list1.add_to_front(3) list1.add_to_back(4) list1.add(1) list1.add(5) print list1 #for value in list1.enumerate(): #print value # 1) 3=>2=>4=>1=>5=>None remove(4) 3=>2=>1=>5=>None list1.remove(4) print list1 list1.remove(5) print list1 # 2) 3=>2=>4=>1=>5=>None remove(5) 3=>2=>4=>1=>None list1.remove_front() # print list1 # 3) 3=>2=>4=>1=>5=>None remove(3) 2=>4=>1=>5=>None # list1.remove_back() # print list1 list1.clear() print list1
def test_add_adds_to_end(self): llist = LinkedList() node = Node(1) node2 = Node(2) llist.add(node) llist.add(node2) self.assertEqual(llist.head, node)
def test_add(self): ll = LinkedList() ll.add(1) self.assertEqual(1, ll.get(0)) ll.add(4) self.assertEqual(1, ll.get(0)) self.assertEqual(4, ll.get(1))
def merge(left, right): merged = LinkedList() merged.add(0) current = merged.head left_head = left.head right_head = right.head while left_head or right_head: if left_head is None: current.next_node = right_head right_head = right_head.next_node elif right_head is None: current.next_node = left_head left_head = left_head.next_node else: left_data = left_head.data right_data = right_head.data if left_data < right_data: current.next_node = left_head left_head = left_head.next_node else: current.next_node = right_head right_head = right_head.next_node current = current.next_node head = merged.head.next_node merged.head = head return merged
def test_delete_first_element(): linked_list = LinkedList() linked_list.add(10) linked_list.add(20) linked_list.add(30) linked_list.delete(0) assert linked_list.to_list() == [20, 30]
def test_double_1_duplicate(self): test_list = LinkedList(Node(1)) test_list.add(Node(1)) actual_list = remove_dups(test_list) self.assertEqual(1, actual_list.length)
def partition(ll, v): new_ll = LinkedList() for val in ll: if val < v: new_ll.push(val) else: new_ll.add(val) ll.head = new_ll.head
def merge_list(left, right): """ Merges a two linked lists, sorting by data of the nodes Returns a new, merged list """ # Creating a new LinkedList to store # left and right merged list merged = LinkedList() # Add a fake head which will be replaced with # node at zero index merged.add(0) # Set current to the fake head current = merged.head # Get head node of left and right list left_head = left.head right_head = right.head # Iterate over left and right until we reach tail node # of either lists while left_head or right_head: # If left_head is None then we're past the tail # Add node from right_head to merge list if left_head is None: current.next_node = right_head # Call next_node on right to exit loop i.e. right_head is None right_head = right_head.next_node # If right_head is None then we're past the tail # Add node from left_head to merge list elif right_head is None: current.next_node = left_head # Call next_node on left to exit loop i.e. left_head is None left_head = left_head.next_node else: # not a tail node of either, perform comparison operation left_data = left_head.data right_data = right_head.data # if left_data < right_data, set current.next_node to left node if left_data < right_data: current.next_node = left_head # Move left head to next node left_head = left_head.next_node else: # right_data < left_data, set current.next_node to right node current.next_node = right_head # Move right head to next node right_head = right_head.next_node # Move current to next node current = current.next_node # Discard fake head and set it to fake head's next_node merged.head = merged.head.next_node return merged
def reverse_linked_list(list): current_node = list.head.next reversed_list = LinkedList(list.head.data) while current_node != None: reversed_list.add(current_node.data) current_node = current_node.next return reversed_list
class Game: def __init__(self, file): with open(file, 'r') as f: self.cash, self.height, self.width = [ int(x) for x in f.readline().split(' ') ] self.waves = LinkedList() self.waves_num = 0 for line in iter(f.readline, ''): self.waves.add(Wave(*[int(x) for x in line.split(' ')])) self.waves_num += 1 self.board = Queue( ) #Incomplete, supposed to create Queue of width and height of read-in file addme = {} for row in range(self.height): for column in range(self.width): addme.update({(row, column): None}) self.board.enqueue(addme) self.gameover = False self.turn = 0 self.nonplants_amt = 0 self.deck = Stack( ) #Completish, please bugtest, supposed to initialize powerup card deck for i in range(100): self.deck.push(random.randint(0, 5)) def draw(self): print("Cash: $", self.cash, "\nWaves: ", self.waves_num, sep='') s = ' '.join([str(i) for i in range(self.width - 1)]) print(' ', s) for row in range(self.height): s = [] for col in range(self.width): if self.is_plant(row, col): char = 'P' elif self.is_nonplant(row, col): size = self.board[row][col].size() char = str(size) if size < 10 else "#" else: char = '.' s.append(char) print(row, ' ', ' '.join(s), '\n', sep='') def is_nonplant(self, row, col): dict1 = self.board[0] if isinstance(dict1[(row, col)], Non_Plant): return True else: return False def is_plant(self, row, col): dict1 = self.board[0] if isinstance(dict1[(row, col)], Plant): return True else: return False
def add_all(self): ''' Put all tweets that were collected at computer by TweetResearcher to TweetAnalyser. Works only path to metadata was specified to TweetAnalyser (with initiation or add_path() method) ''' res = LinkedList() for tweet in self.iter_by_files(): res.add(tweet) self._collected_tweets = res
def setup(): values = [ 4, 8, 15, 16, 23, 42, 15, 32, 23, 56, 2 ] linked_list = LinkedList() for value in values: linked_list.add(value) print(linked_list) print(remove_duplicates(linked_list))
def partition(ll, ref_node): res = LinkedList() for node in ll: if node.value < ref_node.value: res.add_to_beginning(node.value) else: res.add(node.value) return res
def boolean_NOT(op, doc_list): result = LinkedList() p = op.getHead() for doc in doc_list: if p is not None and doc == p.getData(): p = p.getNext() else: result.add(doc) return result
def generate_dict_and_postings(input_directory): dictionary = {} postings = [] term_count = 0 stemmer = PorterStemmer() #Get list of all files in the input directory files = os.listdir(input_directory) files = map(int, files) files.sort() with open("docID.txt", 'w') as f: for docID in files: f.write(str(docID)) f.write(" ") for i in files: #Concat file name to directory file = os.path.join(input_directory, str(i)) with open(file, 'r') as f: #Tokenise and stem data = f.read() words = word_tokenize(data) words = [ stemmer.stem(word.translate(None, string.punctuation)) for word in words ] #Removes punctuation for words with puncuation as last character # for index, word in enumerate(words): # if word [-1] in string.punctuation and len(word) > 1: # words[index] = stemmer.stem(word[:-1].lower()) # else: # words[index] = stemmer.stem(word.lower()) #List(Set(words)) gets rid of duplicates for word in list(set(words)): if word not in string.punctuation: if word not in dictionary: #Add to dictionary, set doc freq to 1 #term_count is used as a reference to the corresponding index of the postings list dictionary[word] = [1, term_count, 0] #Add doc ID to as first element in linked list tempLinkedList = LinkedList() tempLinkedList.add(i) #Append linked list to postings list postings.append(tempLinkedList) term_count = term_count + 1 else: #Incremet doc frequency dictionary[word][0] = dictionary[word][0] + 1 #Append doc ID to posting list postings[dictionary[word][1]].add(i) return dictionary, postings
def test_iteration(self): ll = LinkedList() test_vals = [1, 2, 3] for v in test_vals: ll.add(v) for test_val, val in zip(test_vals, ll): self.assertEqual(test_val, val) ll.insert(0, 0) for test_val, val in zip([0] + test_vals, ll): self.assertEqual(test_val, val)
def test_delete_from_head(): # Given - A list with one item lst = LinkedList() lst.add(324) assert lst.size() == 1 # When - Deleting object that exist in list lst.delete(324) # Then - List size is reduced to 0 assert lst.size() == 0
class Game: def __init__(self, file): with open(file, 'r') as f: self.cash, self.height, self.width = [ int(x) for x in f.readline().split(' ') ] self.waves = LinkedList() self.waves_num = 0 for line in iter(f.readline, ''): self.waves.add(Wave(*[int(x) for x in line.split(' ')])) self.waves_num += 1
def setup_ver2(): print("Setup2-------------------------------\n") values = [ 4, 8, 15, 16, 23, 42, 15, 32, 23, 56, 2 ] linked_list = LinkedList() for value in values: linked_list.add(value) print(linked_list) print(remove_duplicates_without_ds(linked_list))
def ll_partition(node,val): smaller = LinkedList() larger = LinkedList() while node: nxt = node.nxt if node.val >= val: larger.add(node) elif node.val < val: smaller.add(node) node = nxt return (smaller,larger)
def test_add_one_item(): # Given - An empty list lst = LinkedList() # When - Adding one item lst.add(5) # Then - Item is added to list assert lst.size() == 1 head_node = lst.head assert head_node.value == 5 assert head_node.next is None
def test_update(self): ll = LinkedList() ll.add(1) ll.update(4, 0) self.assertEqual(4, ll.get(0)) ll.add(2) ll.add(3) ll.update(5, 1) self.assertEqual(5, ll.get(1)) self.assertEqual(3, ll.get(2)) ll.update(5, 2) self.assertEqual(5, ll.get(2))
def test_remove(self): ll = LinkedList() ll.add(1) ll.add(2) ll.add(3) ll.remove(1) self.assertEqual(3, ll.get(1)) self.assertEqual(None, ll.get(2)) ll.remove(0) self.assertEqual(3, ll.get(0)) self.assertEqual(None, ll.get(1)) ll.remove(0) self.assertEqual(None, ll.get(0))
def test_delete_existing_from_end(): # Given - A list with one item lst = LinkedList() lst.add("zig") lst.add(453) lst.add(324) assert lst.size() == 3 # When - Deleting object that exist in list lst.delete(324) # Then - List size is reduced to 2 assert lst.size() == 2
def partition(linked_list, n): before_list = LinkedList() after_list = LinkedList() node = linked_list.head while node: if node.value < n: before_list.add(node.value) else: after_list.add(node.value) node = node.next before_list.tail.next = after_list.head return before_list
def test_one_item_of_multiple_duplicates(): # Given - A list with multiple duplicate items lst = LinkedList() lst.add(123) lst.add(123) lst.add(123) assert lst.size() == 3 # When - Deleting object that exist in list lst.delete(123) # Then - List size is reduced to 2 assert lst.size() == 2
def test_basics(): stuff = [ 'foo', 'bar', 'quux', 'baz', 'bat' ] my_list = LinkedList() for item in stuff: my_list.add(item) for a,b in zip(stuff, my_list): assert a == b my_list.remove('quux') stuff.remove('quux') for a,b in zip(stuff, my_list): assert a == b
def merge(left, right): """ Merges two linked lists, sorting by data in nodes¨ Returns a new, merged list runs in linear time """ # crate a new linked list containing nodes from merging left and right merged = LinkedList() # Add a fake head that is discarded later merged.add(0) # setcurrent to tohe head of the linked list current = merged.head # obtain head nodes for left and right linked lists left_head = left.head right_head = right.head # iterate over left and right until we reach the tail node of either while left_head or right_head: # if the head node of left is None, we're past the tail # Add the node from right to merged linked list if left_head is None: current.next_node = right_head # Call next on right to set loop condition to False right_head = right_head.next_node # if the head node of right is None, we're past the tail # Add the node from left to merged linked list elif right_head is None: current.next_node = left_head # Call next on left to set loop condition to False left_head = left_head.next_node else: # not at either tail node # #obtain node data to perform comparison operations left_data = left_head.data right_data = right_head.data if left_data < right_data: current.next_node = left_head # move left head to the next node left_head = left_head.next_node else: current.next_node = right_head right_head = right_head.next_node # move current to next node current = current.next_node head = merged.head.next_node merged.head = head return merged
def linkedList(): mList = LinkedList() mList.add(34) mList.add(4) mList.add(93) mList.add(7) mList.display()
def test_remove(self): ll = LinkedList() ll.add('first') ll.add('second') ll.add('third') ll.add('fourth') assert ll.length() == 4 print ll ll.remove(0) assert ll.length() == 3 print ll.retrieve(0) assert ll.retrieve(0) == 'second' assert ll.retrieve(1) == 'third' assert ll.retrieve(2) == 'fourth' print ll ll.remove(1) assert ll.length() == 2 assert ll.retrieve(0) == 'second' assert ll.retrieve(1) == 'fourth' print ll
def test_add_and_retrieve(self): ll = LinkedList() ll.add('first') assert ll.length() == 1 assert ll.retrieve(0) == 'first' ll.add('second') assert ll.length() == 2 assert ll.retrieve(0) == 'first' assert ll.retrieve(1) == 'second' ll.add('third') assert ll.length() == 3 assert ll.retrieve(0) == 'first' assert ll.retrieve(1) == 'second' assert ll.retrieve(2) == 'third'
def test_add_length_incremented(self): llist = LinkedList() node = Node(1) llist.add(node) self.assertEqual(1, llist.length)
a[:,cols] = 0 return a # 1.8 def rotated_substring(s1,s2): return s2 in s1+s1 # 2 from linked_list import Node, LinkedList # 2.1 ll = LinkedList() ll.add(Node(5),Node(20),Node(10),Node(5),Node(2),Node(10),Node(17)) def ll_remove_duplicates(node): d = {} d[node.val] = True while node and node.nxt: if node.nxt.val in d: node.nxt = node.nxt.nxt else: d[node.nxt.val] = True node = node.nxt def ll_remove_duplicates_followup(node): c = node while c: f = c
class Queue: """Basic queue (FIFO) implementation using a singly linked list""" def __init__(self): """Queue constructor""" self.__list = LinkedList() def peek(self): """Returns the node at front of the queue without removing it""" return self.__list.get(0) if not self.is_empty() else None def dequeue(self): """Removes an item of the front of the queue (head) Time complexity: O(1) """ return self.__list.remove(0) if not self.is_empty() else None def enqueue(self, data): """Pushes an item onto the back of the queue (tail) Time complexity: O(1) """ return self.__list.add(data) def size(self): """Determines the size of the queue Time complexity: O(1) """ return self.__list.size def is_empty(self): """Determines if the queue is empty or not Time complexity: O(1) """ return self.__list.is_empty() def clear(self): """Clears out (empties) the queue. Time complexity: O(1) """ # Deallocate memory del self.__list # Create new linked list self.__list = LinkedList() def pretty_print(self): """Pretty prints the queue in the following format: (head) -> ... -> (tail) """ self.__list.pretty_print()
if node.data < x: data = node.data lst.delete(node.data) lst.add(data) node = node.next #test n = lst.root line = "" while n: line += str(n.data) + "," n = n.next print(line) if __name__ == "__main__": l = LinkedList(1) l.add(4) l.add(2) l.add(7) l.add(5) partition_list(l,4) #shold return #4,2,1,5,7