def __init__(self, capacity): """ :type capacity: int """ self.capacity = capacity self.map = { } # map from key to a double linked list node, whose value is a list [key, value, frequency node in self.freqlist] self.freqlist = DoubleLinkedList( ) # a double linked list with each node holding a list [frequency, double linked list with nodes (self.map's values) of this frequency]
def test_unshift(): colors = DoubleLinkedList() colors.shift("Viridian") colors.shift("Sap Green") colors.shift("Van Dyke") assert colors.unshift() == "Van Dyke" assert colors.unshift() == "Sap Green" assert colors.unshift() == "Viridian" assert colors.unshift() == None
def test_push(): colors = DoubleLinkedList() for i in range(1000): colors.push("Pthalo Blue") colors._invariant() #assert colors.count() == 1 colors.push("Ultramarine Blue") #assert colors.count() == 2 colors._invariant()
def random_list(count): numbers = DoubleLinkedList() # numbers.shift(2) # numbers.shift(1) # numbers.push(3) node = numbers.head for i in range(count, 0, -1): numbers.push(randint(0, 1000)) #numbers.shift(2) return numbers
def set(self, key, value): deleted = self.cache.delete_tail_if_full() if deleted: del self.dict[deleted.key] node = DoubleLinkedList.Node(key, value) self.dict[key] = node self.cache.add_to_head(node)
def test_pop(self): colors = sll.DoubleLinkedList() colors.push("Magenta") colors.push("Alizarin") assert colors.pop() == "Alizarin" assert colors.pop() == "Magenta" assert colors.pop() == None
def DLLsample(array): print( '=================================== EJEMPLO DE LISTAS DOBLEMENTE ENLAZADAS ===================================' ) DLList = DoubleLinkedList.DLinkedList() print('¿La Lista esta vacia? R/', DLList.isEmpty()) for i in array: DLList.add(i) print('¿La Lista esta vacia? R/', DLList.isEmpty()) print('El tamaño de la lista es:', len(DLList)) print('¿Esta la nota "F" en la lista? R/', DLList.search('F')) print('¿Esta la nota "A+" en la lista? R/', DLList.search('A+')) print('Veamos la lista entera') DLList.printList() print('Eliminemos la nota "B"') print(DLList.remove('B')) DLList.printList() print('Intento de eliminar otra nota que no debe estar') print(DLList.remove('B')) print('Asi queda la lista') DLList.printList() print('Probemos la devolucion') print( 'La cabeza es:', DLList.head().getValue(), "'El siguiente es:',DLList.head().getNext().getValue(),'Y el anterior es:', DLList.head().getPrev" ) print( '================================= FIN EJEMPLO DE LISTAS DOBLEMENTE ENLAZADAS =================================' )
def test_last(self): colors = sll.DoubleLinkedList() colors.push("Cadmium Red Light") assert colors.last() == "Cadmium Red Light" colors.push("Hansa Yellow") assert colors.last() == "Hansa Yellow" colors.shift("Pthalo Green") assert colors.last() == "Hansa Yellow"
def politicaLRU(self, file): location = DoubleLinkedList() pageFaults = 0 indice = 0 llena = False hashTable = HashTable(self.M) totalLineas = 0 for line in file: totalLineas += 1 line = line.rstrip('\n') if llena: sMH = StringMH(line) value = hashTable.getValue(sMH) if value is None: pageFaults = pageFaults + 1 firstNodeData = location.removeFirstNode() hashTable.deleteKey(firstNodeData) refNode = location.append(sMH) hashTable.putKeyValue(sMH, refNode) else: location.remove(value) refNode = location.append(sMH) hashTable.updateValue(sMH, refNode) else: sMH = StringMH(line) value = hashTable.getValue(sMH) if value is None: pageFaults = pageFaults + 1 refNode = location.append(sMH) hashTable.putKeyValue(sMH, refNode) indice = indice + 1 if indice >= self.N: llena = True else: location.remove(value) refNode = location.append(sMH) hashTable.updateValue(sMH, refNode) missRate = 100*(float(pageFaults)/totalLineas) missWarm = 100*(float(pageFaults - self.N)/(totalLineas-self.N)) mW = pageFaults - self.N print "Evaluando una cache LRU con " + str(self.N) + " entradas" print "Resultados:" print "Miss rate: %0.2f" %missRate + "%% (%d" %pageFaults + " misses out of %d" %totalLineas + " references)" print "Miss rate (warm cache): %0.2f" %missWarm + "%% (%d" %mW + " misses out of %d" %totalLineas + "-%d" %self.N + " references)"
def test_unshift(self): colors = sll.DoubleLinkedList() colors.push("Viridian") colors.push("Sap Green") colors.push("Van Dyke") assert colors.unshift() == "Viridian" assert colors.unshift() == "Sap Green" assert colors.unshift() == "Van Dyke" assert colors.unshift() == None
def test_shift(self): colors = sll.DoubleLinkedList() colors.shift("Cadmium Orange") assert colors.count() == 1 colors.shift("Carbazole Violet") assert colors.count() == 2 assert colors.pop() == "Cadmium Orange" assert colors.count() == 1 assert colors.pop() == "Carbazole Violet" assert colors.count() == 0
def test_remove(self): colors = sll.DoubleLinkedList() colors.push("Cobalt") colors.push("Zinc White") colors.push("Nickle Yellow") colors.push("Perinone") assert colors.remove("Cobalt") == 0 #colors.dump("before perinone") assert colors.remove("Perinone") == 2 #colors.dump("after perinone") assert colors.remove("Nickle Yellow") == 1 assert colors.remove("Zinc White") == 0
def merge(left, right): # print("merge") result = DoubleLinkedList() while left != None and right != None: if first(left) <= first(right): result.push(left.data) # print("result:---", result.head) left = rest(left) else: result.push(right.data) # print("result:---", result.head) right = rest(right) while left != None: result.push(left.data) # print("result:---", result.head) left = rest(left) while right != None: result.push(right.data) #print("result:---", result.head) right = rest(right) return result.head
def test_get(self): colors = sll.DoubleLinkedList() colors.push("Vermillion") assert colors.get(0) == "Vermillion" colors.push("Sap Green") assert colors.get(0) == "Vermillion" assert colors.get(1) == "Sap Green" colors.push("Cadmium Yellow Light") assert colors.get(0) == "Vermillion" assert colors.get(1) == "Sap Green" assert colors.get(2) == "Cadmium Yellow Light" assert colors.pop() == "Cadmium Yellow Light" assert colors.get(0) == "Vermillion" assert colors.get(1) == "Sap Green" assert colors.get(2) == None colors.pop() assert colors.get(0) == "Vermillion" colors.pop() assert colors.get(0) == None
def __init__(self): self.FIFO = DLL.DoubleLinkedList()
def test_push(self): colors = sll.DoubleLinkedList() colors.push("Pthalo Blue") assert colors.count() == 1 colors.push("Ultramarine Blue") assert colors.count() == 2
def test_add_to_head(self): ll = DoubleLinkedList(3) n = Node(3, 5) ll.add_to_head(n) self.assertEqual(ll.head.key, n.key) self.assertEqual(ll.head.value, n.value) self.assertEqual(ll.tail.key, n.key) self.assertEqual(ll.tail.value, n.value) n2 = Node('a', 1) ll.add_to_head(n2) self.assertEqual(ll.head.key, n2.key) self.assertEqual(ll.head.value, n2.value) self.assertEqual(ll.tail.key, n.key) self.assertEqual(ll.tail.value, n.value) # print(ll) ll.delete(n) self.assertEqual(ll.head.key, n2.key) self.assertEqual(ll.head.value, n2.value) self.assertEqual(ll.tail.key, n2.key) self.assertEqual(ll.tail.value, n2.value) n3 = Node('b', 2) ll.add_to_head(n3) self.assertEqual(ll.head.key, n3.key) self.assertEqual(ll.head.value, n3.value) self.assertEqual(ll.tail.key, n2.key) self.assertEqual(ll.tail.value, n2.value) print(ll) n4 = Node('c', 3) ll.add_to_head(n4) n5 = Node('d', 4) ll.add_to_head(n5) print(ll) self.assertEqual(ll.head.key, n4.key) self.assertEqual(ll.head.value, n4.value) self.assertEqual(ll.tail.key, n2.key) self.assertEqual(ll.tail.value, n2.value) self.assertEqual(ll.count, 3) ll.delete(n4) self.assertEqual(ll.head.key, n3.key) self.assertEqual(ll.head.value, n3.value) self.assertEqual(ll.tail.key, n2.key) self.assertEqual(ll.tail.value, n2.value) self.assertEqual(ll.count, 2)
_author_ = 'Nikita Karatsev' _project_ = 'Lab2' import DoubleLinkedList from notebook.notebookapp import raw_input d1 = DoubleLinkedList.DoubleLinkedList() d2 = DoubleLinkedList.DoubleLinkedList() ifs = '' '''a = {"0": d.fill_deque(), "1": d.sort1(), "2": d.sort2(), "3": d.sort3() } ''' while ifs is not '~': #"Welcome. 0 - add deque, 1-3 sort seque, ~ exit") print( "\nДобро пожаловать в консоль. Что будем делать?!(0 - заполнить массив, 1..3 - сортировка и вывод на экран)") ifs = raw_input() if ifs is '0': d1.fill_deque(d2) elif ifs is '1': d1.sort1(d2) elif ifs is '2': d1.sort2(d2) elif ifs is '3': d1.sort3(d2) elif ifs is '~': print("FBI OPEN DOOR!") else:
def test_pop(): colors = DoubleLinkedList() colors.push("Magenta") colors._invariant() colors.push("Alizarin") colors.push("Van Dyke") colors._invariant() assert colors.pop() == "Van Dyke" colors._invariant() assert colors.get(1) == "Alizarin" assert colors.pop() == "Alizarin" assert colors.pop() == "Magenta" colors._invariant() assert colors.pop() == None
def setUp(self): self.list = DoubleLinkedList.DoubleLinkedList()
def __init__(self): self.linked_list = DoubleLinkedList.DoubleLL()
def test_remove(): colors = DoubleLinkedList() colors.push("Cobalt") colors.push("Zinc White") colors.push("Nickle Yellow") colors.push("Perinone") assert colors.remove("Cobalt") == 0 colors._invariant() colors.dump("before perinone") assert colors.remove("Perinone") == 2 colors._invariant() colors.dump("after perinone") assert colors.remove("Nickle Yellow") == 1 colors._invariant() assert colors.remove("Zinc White") == 0 colors._invariant()
def random_list(self, count) -> 'DoubleLinkedList': numbers = DoubleLinkedList() for i in range(count, 0, -1): numbers.shift(randint( 0, 1000)) # adds nodes to the double linked list return numbers
import Node import SingleLinkedList as SingleList import DoubleLinkedList as DoubleList print("=======> Double Linked List <==========") dlist = DoubleList.DoubleLinkedList() # print(dlist.isEmpty()) dlist.push(22) dlist.push(45) # print(dlist.isExist(22)) # print(dlist.isExist(23)) dlist.append(23) # print(dlist.index(22)) # print(dlist.findByPos(3)) # print(dlist.findAfterPos(4)) # print(dlist.remove(23)) # print(dlist.pop()) # print(dlist.popByPos(1)) # print(dlist.insertBefore(3, 20)) print(dlist.insertAfter(2, 20)) print(*dlist.traverse(), sep='<-->')
def test_first(): colors = DoubleLinkedList() colors.push("Cadmium Red Light") assert colors.first() == "Cadmium Red Light" colors.push("Hansa Yellow") assert colors.first() == "Cadmium Red Light" colors.shift("Pthalo Green") assert colors.first() == "Pthalo Green"
class LFUCache: def __init__(self, capacity): """ :type capacity: int """ self.capacity = capacity self.map = { } # map from key to a double linked list node, whose value is a list [key, value, frequency node in self.freqlist] self.freqlist = DoubleLinkedList( ) # a double linked list with each node holding a list [frequency, double linked list with nodes (self.map's values) of this frequency] def get(self, key): """ :type key: int :rtype: int """ if key not in self.map: print('-1') return -1 else: # get the corresponding ListNode node = self.map[key] # update this node's frequency self._updatefreq(node) print(node.val[1]) return node.val[1] def put(self, key, value): """ :type key: int :type value: int :rtype: void """ if self.capacity < 1: #bug fixed: corner case when capacity is 0 return if key in self.map: # get the corresponding ListNode node = self.map[key] # update the value node.val[1] = value else: if len(self.map) == self.capacity: # evict the least used key self._evict() # create a new ListNode node = ListNode([key, value, None]) # add key and value into self.map self.map[key] = node # update this node's frequency self._updatefreq(node) def _evict(self): """ evict the least used node rtype: void """ # get the frequency ListNode with the least frequency least_freq_node = self.freqlist.tail # get the least frequency list least_freq_list = least_freq_node.val[1] # get the tail node in the least frequency list tail = least_freq_list.tail # get the key value key = tail.val[0] # remove tail node from the least frequency list least_freq_list.remove(tail) # remove the least frequency node, if its list is empty if least_freq_list.isempty(): self.freqlist.remove(least_freq_node) # remove key from self.map self.map.pop(key) def _updatefreq(self, node): """ update frequency of a node :type: node: ListNode :rtype: void """ if node is None: return # get key, value and corresponding frequency ListNode old_freq_node = node.val[2] if old_freq_node is None: # this is a new node if self.freqlist.tail is None or self.freqlist.tail.val[0] != 1: new_freq_node = ListNode([1, DoubleLinkedList()]) self.freqlist.append(new_freq_node) else: new_freq_node = self.freqlist.tail # get the new frequency list new_freq_list = new_freq_node.val[1] # append node to the head of new frequency list so it is the most recently used node new_freq_list.append_head(node) # update the node's frequency ListNode from old one to new one node.val[2] = new_freq_node return # get the current frequency and the linked list of nodes with the same frequency old_freq, old_freq_list = old_freq_node.val # remove node from the old frequency's list old_freq_list.remove(node) # increase frequency by 1 new_freq = old_freq + 1 # check if the higher frequency node exists and equal to new frequency if old_freq_node.prev is None or old_freq_node.prev.val[0] != new_freq: # frequency (freq + 1) node doesn't exist, create one new_freq_node = ListNode([new_freq, DoubleLinkedList()]) # insert the newly created frequency node into self.freqlist self.freqlist.insert_before(old_freq_node, new_freq_node) else: # frequency (freq + 1) node exists new_freq_node = old_freq_node.prev # get the new frequency list new_freq_list = new_freq_node.val[1] # append node to the head of new frequency list so it is the most recently used node new_freq_list.append_head(node) # update the node's frequency ListNode from old one to new one node.val[2] = new_freq_node # remove the old frequency node, if its list is empty if old_freq_list.isempty(): self.freqlist.remove(old_freq_node)
def __init__(self, capacity=5): self.cache = DoubleLinkedList.DoubleLinkedList(capacity) self.dict = {}
from listas from DoubleLinkedList ld = DoubleLinkedList() print ("Esta vacia?: " , ld.is_empty () ) ld.append(10) ld.append(20) ld.append(30) print(f"La lista tiene { ld.get_size()}elementos") ld.transversal() ld.reverse_trasnversal() ld.remove_from_head(20) ld.reverse_transversal()
def politicaLRU(self, file): location = DoubleLinkedList() pageFaults = 0 indice = 0 llena = False hashTable = HashTable(self.M) totalLineas = 0 for line in file: totalLineas += 1 line = line.rstrip('\n') if llena: sMH = StringMH(line) value = hashTable.getValue(sMH) if value is None: pageFaults = pageFaults + 1 firstNodeData = location.removeFirstNode() hashTable.deleteKey(firstNodeData) refNode = location.append(sMH) hashTable.putKeyValue(sMH, refNode) else: location.remove(value) refNode = location.append(sMH) hashTable.updateValue(sMH, refNode) else: sMH = StringMH(line) value = hashTable.getValue(sMH) if value is None: pageFaults = pageFaults + 1 refNode = location.append(sMH) hashTable.putKeyValue(sMH, refNode) indice = indice + 1 if indice >= self.N: llena = True else: location.remove(value) refNode = location.append(sMH) hashTable.updateValue(sMH, refNode) missRate = 100 * (float(pageFaults) / totalLineas) missWarm = 100 * (float(pageFaults - self.N) / (totalLineas - self.N)) mW = pageFaults - self.N print "Evaluando una cache LRU con " + str(self.N) + " entradas" print "Resultados:" print "Miss rate: %0.2f" % missRate + "%% (%d" % pageFaults + " misses out of %d" % totalLineas + " references)" print "Miss rate (warm cache): %0.2f" % missWarm + "%% (%d" % mW + " misses out of %d" % totalLineas + "-%d" % self.N + " references)"
def _updatefreq(self, node): """ update frequency of a node :type: node: ListNode :rtype: void """ if node is None: return # get key, value and corresponding frequency ListNode old_freq_node = node.val[2] if old_freq_node is None: # this is a new node if self.freqlist.tail is None or self.freqlist.tail.val[0] != 1: new_freq_node = ListNode([1, DoubleLinkedList()]) self.freqlist.append(new_freq_node) else: new_freq_node = self.freqlist.tail # get the new frequency list new_freq_list = new_freq_node.val[1] # append node to the head of new frequency list so it is the most recently used node new_freq_list.append_head(node) # update the node's frequency ListNode from old one to new one node.val[2] = new_freq_node return # get the current frequency and the linked list of nodes with the same frequency old_freq, old_freq_list = old_freq_node.val # remove node from the old frequency's list old_freq_list.remove(node) # increase frequency by 1 new_freq = old_freq + 1 # check if the higher frequency node exists and equal to new frequency if old_freq_node.prev is None or old_freq_node.prev.val[0] != new_freq: # frequency (freq + 1) node doesn't exist, create one new_freq_node = ListNode([new_freq, DoubleLinkedList()]) # insert the newly created frequency node into self.freqlist self.freqlist.insert_before(old_freq_node, new_freq_node) else: # frequency (freq + 1) node exists new_freq_node = old_freq_node.prev # get the new frequency list new_freq_list = new_freq_node.val[1] # append node to the head of new frequency list so it is the most recently used node new_freq_list.append_head(node) # update the node's frequency ListNode from old one to new one node.val[2] = new_freq_node # remove the old frequency node, if its list is empty if old_freq_list.isempty(): self.freqlist.remove(old_freq_node)
def Main(): DLL = DoubleLinkedList.DoubleLinkedList() try: fo = open("Cars.txt", "r") except IOError: print("No such file!") else: for line in fo.readlines(): info = line.split() Make = info[0] Model = info[1] Year = int(info[2]) Mileage = float(info[3]) Price = float(info[4]) newCar = Car.Car(Make, Model, Year, Mileage, Price) DLL.AppendToHead(newCar) fo.close() print("Cars information in the system are as follows:") DLL.PrintCars() s = menu() while s in range(1, 8): if s == 1: key = float(input("Enter car's price you want to search:")) foundNode = DLL.Search(key) if (foundNode != 0): print( "The car information you want to search are Make: %s, Model: %s, Year: %d, Mileage: %.0f, Price: %.0f" % (foundNode.data.Make, foundNode.data.Model, foundNode.data.Year, foundNode.data.Mileage, foundNode.data.Price)) else: print("There is no such car with price of ", key) if s == 2: key = float(input("Enter the car price you want to delete: ")) t = DLL.Delete(key) if t == 1: print("The car with the price has been deleted!") DLL.PrintCars() if s == 3: print( "Enter the information of the car you want to append to the head:" ) Make = input("Make: ") Model = input("Model: ") Year = int(input("Year: ")) Mileage = float(input("Mileage: ")) Price = float(input("Price: ")) newCar = Car.Car(Make, Model, Year, Mileage, Price) DLL.AppendToHead(newCar) print("Cars information in the system are as follows: ") DLL.PrintCars() if s == 4: print( "Enter the information of the car you want to append to the tail:" ) Make = input("Make: ") Model = input("Model: ") Year = int(input("Year: ")) Mileage = float(input("Mileage: ")) Price = float(input("Price: ")) newCar = Car.Car(Make, Model, Year, Mileage, Price) DLL.AppendToTail(newCar) print("Cars information in the system are as follows: ") DLL.PrintCars() if s == 5: oldCar = DLL.RemoveFromHead() if oldCar != 0: print( "Removed car information from Head are Make: %s, Model: %s, Year: %d, Mileage: %.0f, Price: %.0f" % (oldCar.data.Make, oldCar.data.Model, oldCar.data.Year, oldCar.data.Mileage, oldCar.data.Price)) if s == 6: oldCar = DLL.RemoveFromTail() if oldCar != 0: print( "Removed car information from Tail are Make: %s, Model: %s, Year: %d, Mileage: %.0f, Price: %.0f" % (oldCar.data.Make, oldCar.data.Model, oldCar.data.Year, oldCar.data.Mileage, oldCar.data.Price)) if s == 7: DLL.PrintCars() s = menu()