def test_delete_elem(self): ol = OrderedList(True) ol.add(0) ol.add(1) ol.add(2) ol.delete(2) assert ol.len() == 2 ol_elements = ol.get_all() assert 2 not in ol_elements
def test_add_descending(self): ol = OrderedList(False) ol.add(-1) ol.add(-1) ol.add(13) ol.add(15) ol.add(-16) ol_elements = ol.get_all() assert ol_elements[0] == 15 assert ol_elements[1] == 13 assert ol_elements[2] == -1 assert ol_elements[3] == -1 assert ol_elements[4] == -16 assert ol.len() == 5
def test_find_elem(self): ol = OrderedList(True) ol.add(0) ol.add(1) ol.add(2) assert ol.find(3) is None assert ol.find(2).value == 2
def test_mixed(self): lst = OrderedList() cases = list(range(10)) random.shuffle(cases) results = cases.copy() for i, c in enumerate(cases): with self.subTest(case=c):
def test_compare(self): lst = OrderedList(True) lst_desc = OrderedList(False) cases = [ (0, 0), (0, 1), (1, 0), ] results = [ (0, 0), (1, -1), (-1, 1), ] for i, c in enumerate(cases): with self.subTest(case=c): res = lst.compare(c[0], c[1])
def test_find(self): lst = OrderedList() cases = list(range(-1, 3)) cases_to_find = [(0, 1), (0, 1), (1, ), (0, 1, 2, -1, 3)] results = [(False, False), (True, False), (True, True), (True, True, True, False, False)] for i, c in enumerate(cases): with self.subTest(case=c):
def __init__(self): # db init self.keycache = OrderedList() self.db = connDB() window = tk.Tk() window.title("关键词搜索") frame1 = Frame(window) frame1.pack() header = Message(frame1, text="检索") header.grid(row=1, column=3) frame2 = Frame(window) frame2.pack() self.v2 = IntVar() rbRed = Radiobutton(frame2, text="显示搜索结果链接", bg="red", variable=self.v2, value=1, command=self.processRadiobutton) rbYellow = Radiobutton(frame2, text="显示关联关键词", bg="yellow", variable=self.v2, value=2, command=self.processRadiobutton) label = Label(frame2, text="Enter the keyword: ") self.name = StringVar() entryName = Entry(frame2, textvariable=self.name) btGetName = Button(frame2, text="Search", command=self.processButton) # grid layout label.grid(row=1, column=1) entryName.grid(row=1, column=2) btGetName.grid(row=1, column=3) # grid rbRed.grid(row=2, column=2) rbYellow.grid(row=2, column=3) # display text self.text = Text(window) self.text.pack() window.mainloop()
def worker(num): """thread worker function""" print('Searcher: %s' % num) db = initDB() keycache = OrderedList() while True: keyword = input('Input the keywords to search:') if keyword == 'quit': break getresult(db, keycache, n, keyword) return
def aStar(self, from_, where, start_at=1): """ Executes the aStar algorithm. Fins a way from 'from_' to 'where' and returns it or raises NotFoundException if no way has been found. @from_: index of the item we are going from @where: index of the item we desire to get as destination @start_at: which is the first number in the enumeration? """ # fer funció que from i where existeixi (fora d'aquesta classe) # Move from and where values to start from zero from_, where = from_ - start_at, where - start_at self.parcial_cost_table = {} self.way_list = OrderedList() self.way_list.add([from_], 0) # n = 1 while self.way_list[0][0] != where and self.way_list: # print(n) # n+=1 head = self.way_list[0] expanded = self.expand(head) expanded = self.cleanCycles(expanded) father_cost = self.way_list.get(0)[1] # get cost # Remove head as we already explored it self.way_list.remove(head) # Remove all the ways that aren't optimized self.removeRedundantWays(expanded, father_cost) # Add all the ways that we found out in this iteration for way in expanded: cost = self.findCost(way, father_cost) self.way_list.add(way, cost) if self.way_list: return self.way_list[0] else: raise NotFoundException()
def test_desc_direction(self): d = OrderedList("desc") fill([1,5,0,4,23,4,6], d) self.assertEqual(str([23, 6, 5, 4, 4, 1, 0]), str(d))
return urlList # add to cache cache.add(question) url = "http://www.baidu.com/s?wd=" + quote( question.encode('utf-8')) + "&rn=" + str(num) html_doc = get_html(url) return get_news(db, question, html_doc, num) def worker(num, keys, n, keycache): """thread worker function""" print('Searcher thread: [%s]' % num) db = initDB() getresult(db, keycache, n, keys) def start_search(keys, num, keycache): t = threading.Thread(target=worker, args=(0, keys, num, keycache)) t.start() if __name__ == '__main__': q = "google" # for example keywords keycache = OrderedList() n = 20 # default links number start_search(q, n, keycache)
from OrderedList import OrderedList import random o_list = OrderedList() for i in range(10): rand_num = random.randrange(0,10) while o_list.search(rand_num): rand_num = random.randrange(0,10) o_list.add(rand_num) print("After insertion:") for item in o_list: print(item,end=" ") print() for i in range(10): rand_num = random.randrange(0,10) while not(o_list.search(rand_num)): rand_num = random.randrange(0,10) o_list.remove(rand_num) print("After deletion:") for item in o_list: print(item,end=" ") print()
def test_tail(self): lst = OrderedList() cases = [i for i in range(10)] results = cases.copy() for i, c in enumerate(cases): with self.subTest(case=c):
def test_compare(self): ol = OrderedList(True) assert ol.compare(0, 1) == -1 assert ol.compare(1, 0) == 1 assert ol.compare(1, 1) == 0
def test_asc_direction(self): a = OrderedList("asc") fill([1,5,0,4,23,4,6], a) self.assertEqual(str([0, 1, 4, 4, 5, 6, 23]), str(a))
def Astartprocessing(self,initalnode,goalnode,freeNodes,ax): #inital point g = plt.Rectangle((initalnode[0].x, initalnode[0].y), initalnode[0].width, initalnode[0].height, facecolor='red') ax.add_patch(g) #goal point g = plt.Rectangle((goalnode[0].x, goalnode[0].y), goalnode[0].width, goalnode[0].height, facecolor='green') ax.add_patch(g) unvisitedlist = OrderedList() stop = False #check meet goal foundpath = False visitedlist = OrderedList() unvisitedlist.add(initalnode[0]) k = 1 while(stop == False and foundpath == False): currnode = unvisitedlist.pop().getData() cost = self.findactualcost(currnode) visitedlist.add(currnode) #check close to goal if(currnode.x <= goalnode[0].x <= currnode.x+currnode.width and currnode.y <= goalnode[0].y <= currnode.y+currnode.height): foundpath = True #find 8 direction's node if(stop == False): nearnodes = self.findAround(currnode,freeNodes) #change actual cost in nearnodes for node in nearnodes: prex = node.x + node.width/2 prey = node.y + node.height/2 currx = currnode.x +currnode.width/2 curry = currnode.x+currnode.height/2 node.gValue = cost + self.getdistance(prex,prey,currx,curry) found = unvisitedlist.search(node) if(found != None): if(found.gValue > node.gValue): found.gValue = node.gValue found.father = currnode else: if(visitedlist.search(node) == None): node.father = currnode unvisitedlist.add(node) if(unvisitedlist == None): stop = True print("there is no path") if(foundpath == True): while (currnode.father!= None): #print("currx = ", currnode.x, "curry = ", currnode.y, "goalx = ", goalnode[0].x, "goaly = ", #goalnode[0].y) g = plt.Rectangle((currnode.x, currnode.y), currnode.width, currnode.height, facecolor='gray') ax.add_patch(g) currnode = currnode.father
from OrderedList import OrderedList, Node ol = OrderedList() ol.add(1) ol.add(23) print(ol.index(1)) print(ol.length()) ol.add(17) ol.add(58) ol.pop(0) ol.display()
def testOrderedList(): ol = OrderedList() while True: print("Choose operation: ") print( " 1 - Add(data)\n", "2 - Pop()\n", "3 - Search(key)\n", "4 - Remove(data)\n", "5 - Size()\n", "6 - Pop(pos)\n", "7 - exit()\n", ) choice = input() if choice == '1': ol = add(ol) ol.__str__() elif choice == '2': ol = pop(ol) ol.__str__() elif choice == '3': search(ol) ol.__str__() elif choice == '4': ol = remove(ol) ol.__str__() elif choice == '5': print("Size of list: %d" % ol.size()) ol.__str__() elif choice == '6': ol = popPos(ol) ol.__str__() elif choice == '7': break else: print("Bad Choice - choose from valid options")
def test_front(self): lst = OrderedList() cases = [i for i in range(9, -1, -1)] results = [i for i in range(10)] for i, c in enumerate(cases): with self.subTest(case=c):
from OrderedList import OrderedList import random o_list = OrderedList() for i in range(10): rand_num = random.randrange(0, 10) while o_list.search(rand_num): rand_num = random.randrange(0, 10) o_list.add(rand_num) print("After insertion:") for item in o_list: print(item, end=" ") print() for i in range(10): rand_num = random.randrange(0, 10) while not (o_list.search(rand_num)): rand_num = random.randrange(0, 10) o_list.remove(rand_num) print("After deletion:") for item in o_list: print(item, end=" ") print()
def __init__(self): self.costs = None self.heuristic = None self.ignore = None self.way_list = OrderedList() self.parcial_cost_table = {}
class SearchStrategies: """ Provides a way to run various search strategies. AStar usage: create instance: search = SearchStrategies() set the costs matrix: search.setCosts() set the euristics matrix: search.setHeuristic() (optional) set the ignore value: search.setIgnore(value) run algorithm: search.run(from, where) BFS usage: create instance: search = SearchStrategies() set cost matrix: search.setCosts (optional) set the ignore value: search.setIgnore(value) run algorithm: search.BFS(from, where) """ def __init__(self): self.costs = None self.heuristic = None self.ignore = None self.way_list = OrderedList() self.parcial_cost_table = {} def setCosts(self, costs): """ @costs: 2x2 matrix consisting in a list of lists """ self.costs = costs def setHeuristic(self, heuristic): """ @heuristic: 2x2 matrix consisting in a list of lists """ self.heuristic = heuristic def setIgnore(self, value): """ Value which represents 'unpassable' or 'invalid' ways. Will be compared against each value in the cost matrix and if the comparison is True, that cost will be ignored. """ self.ignore = value def aStar(self, from_, where, start_at=1): """ Executes the aStar algorithm. Fins a way from 'from_' to 'where' and returns it or raises NotFoundException if no way has been found. @from_: index of the item we are going from @where: index of the item we desire to get as destination @start_at: which is the first number in the enumeration? """ # fer funció que from i where existeixi (fora d'aquesta classe) # Move from and where values to start from zero from_, where = from_ - start_at, where - start_at self.parcial_cost_table = {} self.way_list = OrderedList() self.way_list.add([from_], 0) # n = 1 while self.way_list[0][0] != where and self.way_list: # print(n) # n+=1 head = self.way_list[0] expanded = self.expand(head) expanded = self.cleanCycles(expanded) father_cost = self.way_list.get(0)[1] # get cost # Remove head as we already explored it self.way_list.remove(head) # Remove all the ways that aren't optimized self.removeRedundantWays(expanded, father_cost) # Add all the ways that we found out in this iteration for way in expanded: cost = self.findCost(way, father_cost) self.way_list.add(way, cost) if self.way_list: return self.way_list[0] else: raise NotFoundException() def BFS(self, from_, where, start_at=1): """ Executes the Breath First Search algorithm. Fins a way from 'from_' to 'where' and returns it or raises NotFoundException if no way has been found. @from_: index of the item we are going from @where: index of the item we desire to get as destination @start_at: which is the first number in the enumeration? """ from_, where = from_ - start_at, where - start_at self.way_list = [] self.way_list.append([from_]) while self.way_list[0][0] != where and self.way_list: head = self.way_list[0] expanded = self.expand(head) expanded = self.cleanCycles(expanded) # Remove head as we already explored it self.way_list.remove(head) # Add all the ways that we found out in this iteration for way in expanded: self.way_list.append(way) if self.way_list: return self.way_list[0] else: raise NotFoundException() def expand(self, way): """ Returns a list of all the possible ways that we can produce from the given way. @way: list containing a way (list of nodes). """ head = way[0] # CARE return_list = [] # Traverse the matrix by row for i, cost in enumerate(self.costs[head]): if cost != self.ignore: copied_list = copy.copy(way) copied_list.insert(0, i) return_list.append(copied_list) return_list.append(copied_list) # Traverse the matrix by column (this way we can give only half the table # when we make the costs). i, j = head, head length = len(self.costs) while j < length: cost = self.costs[j][i] assert isinstance(cost, int) or isinstance(cost, float) if cost != self.ignore: copied_list = copy.copy(way) copied_list.insert(0, j) return_list.append(copied_list) j += 1 return return_list def cleanCycles(self, ways): """ Checks the given ways and returns a list of those ways that have no cycles. @ways: list of lists consisting of ways. """ return_list = [] for way in ways: if way[0] in way[1:]: continue return_list.append(way) return return_list def findCost(self, way, father_cost): """ Returns the cost of the given way. @way: list containing a way (list of nodes). @father_cost: acumulated cost in previous steps. Example: [10,9,7,6,4] cost [9,7,6,4] = father_cost return cost[9->10] + father_cost """ # Get indexes which will be used for searching the cost i = way[0] j = way[1] # If j is bigger than i, we just invert them, that way we can make sure # that the program will work even if we just provide half the # cost table (which can save a lot of space). if i > j: i, j = j, i cost = self.costs[j][i] return cost + father_cost def removeRedundantWays(self, expanded, father_cost): """ Checks every way in the expanded list against the value in the parcial cost table. If that way isn't optimum, we remove it in order to make the algorithm faster. @expanded: 2x2 matrix of possible ways we can go from the actual head. @father_cost: cost of the way from origin to the previous father node. """ # Traverse list from last to first as we may need to remove items # as we are iterating through it. for i in range(len(expanded) - 1, -1, -1): way = expanded[i] head = way[0] parcial_cost = self.parcial_cost_table.get(way[0], "NotFound") way_cost = self.findCost(way, father_cost) if way_cost < parcial_cost or parcial_cost == "NotFound": # Update the table with the new cost self.parcial_cost_table[head] = way_cost # Remove ways in the way_list that have the same cost as the parcial cost to_remove = [] for item, cost in self.way_list.iterWithValues(): if cost == parcial_cost and item[0] == head: to_remove.append(item) for removable in to_remove: self.way_list.remove(removable) else: expanded.pop(i)
def __init__(self): path = OrderedList()
def test_find_item(self): a = OrderedList("asc") fill([1,5,0,4,23,4,6], a) self.assertEqual("Item not found, interrupt", a.find(Node2(2)))
def testOrderedList(): ol = OrderedList() while True: print ("Choose operation: ") print (" 1 - Add(data)\n", "2 - Pop()\n", "3 - Search(key)\n", "4 - Remove(data)\n", "5 - Size()\n", "6 - Pop(pos)\n", "7 - exit()\n", ) choice = input() if choice == '1': ol = add(ol) ol.__str__() elif choice == '2': ol = pop(ol) ol.__str__() elif choice == '3': search(ol) ol.__str__() elif choice == '4': ol = remove(ol) ol.__str__() elif choice == '5': print ("Size of list: %d" % ol.size()) ol.__str__() elif choice == '6': ol = popPos(ol) ol.__str__() elif choice == '7': break else: print ("Bad Choice - choose from valid options")
def test_find_item(self): a = OrderedList("asc") fill(["a bta", "bc", "poiuy", "ceda", "eczxc", "zsasasd"], a) self.assertEqual("Item not found, interrupt", a.find(Node2("c")))
from UnorderedList import UnorderedList from OrderedList import OrderedList name_list = ["Gill", "Tom", "Eduardo", "Raffaele", "Serena", "Bella"] my_unorderedlist = UnorderedList() for name in name_list: my_unorderedlist.add(name) for item in my_unorderedlist: print(item, end=" ") print() my_orderedlist = OrderedList() for name in name_list: my_orderedlist.add(name) for item in my_orderedlist: print(item, end=" ") print()
from OrderedList import OrderedList newList = OrderedList() newList.add(5) newList.add(8) newList.add(10) newList.add(9) newList.add(4) print(newList) print(newList.index(-5)) print(newList)
from OrderedList import OrderedList def print_list(ol): current = ol.head while current != None: print(current.get_data(), end=" ") current = current.get_next() print() ol = OrderedList() for i in range(10, 0, -1): ol.add(i) ol.add(0) print_list(ol) print('Size of the list: %d' % ol.size()) print('Removing 5 from the list: %s' % ol.remove(5)) print_list(ol) for i in range(-1, 12): print('Is %d in the list? %s' % (i, ol.search(i))) print('Is 300 in the list? %s' % ol.search(300))