def Update(self): directions = Empty position = prevPosition = self.Position # Check all posible directions if self.IsTraverseable(position.Up): directions = Node(position.Up, directions) if self.IsTraverseable(position.Down): directions = Node(position.Down, directions) if self.IsTraverseable(position.Left): directions = Node(position.Left, directions) if self.IsTraverseable(position.Right): directions = Node(position.Right, directions) # Do we have somewhere to go to? if directions is not Empty: position.Taken = False position = directions.random().Value position.Taken = True # Apply new position return self.__class__(position, self.CanRemove, self.Texture, prevPosition) # Stay stationary if there is nowhere to go return self.__class__(self.Position, self.CanRemove, self.Texture, self.PrevPosition)
def addToTree(elt, curTree): eltNode = Node(elt) if curTree: # Check whether the element is more general than the root of # the tree. If so, then we make it the new root. # TODO: We're also going to need to handle the case where # two things are at the same level of generality. if moreGeneral(elt, curTree.v): eltNode.addChild(curTree) return eltNode # Otherwise figure out if it should be inserted between the root # and any of the children. else: addedBetweenChildren = False for c in curTree.children: if moreGeneral(elt, c.v): tmp = c.v c.v = elt c.addChild(Node(tmp)) break # If not, it can simply be a child. if not addedBetweenChildren: curTree.addChild(eltNode) else: # If we don't have a current tree, make this the tree! return eltNode
def __init__(self, terminals=None, name=None, filePath=None): if name is None: name = "Flowchart" if terminals is None: terminals = {} self.filePath = filePath Node.__init__(self, name) ## create node without terminals; we'll add these later self.inputWasSet = False ## flag allows detection of changes in the absence of input change. self._nodes = {} self.nextZVal = 10 #self.connects = [] #self._chartGraphicsItem = FlowchartGraphicsItem(self) self._widget = None self._scene = None self.processing = False ## flag that prevents recursive node updates self.widget() self.inputNode = Node('Input', allowRemove=False) self.outputNode = Node('Output', allowRemove=False) self.addNode(self.inputNode, 'Input', [-150, 0]) self.addNode(self.outputNode, 'Output', [300, 0]) self.outputNode.sigOutputChanged.connect(self.outputChanged) self.outputNode.sigTerminalRenamed.connect(self.internalTerminalRenamed) self.inputNode.sigTerminalRenamed.connect(self.internalTerminalRenamed) self.viewBox.autoRange(padding = 0.04) for name, opts in terminals.iteritems(): self.addTerminal(name, **opts)
def construct_three_lan_model_token_graph(self, node): if len(node.next_nodes) == 0: return n = len(node.pre_nodes) if n == 1: node.pre_token = node.pre_nodes[0].current_token for next_node in node.next_nodes: self.construct_tree_lan_modle_token_graph(next_node) else: split_nodes = [] for pre_node in node.pre_nodes: has_node = False for split_new_node in split_nodes: if self.is_pre_node(split_new_node, pre_node): pre_node.next_nodes.remove(node) pre_node.next_nodes.append(split_new_node) has_node = True break if not has_node: new_node = Node(node.current_token, pre_node.current_token) new_node.pre_nodes.append(pre_node) new_node.next_nodes = node.next_nodes[:] pre_node.next_nodes.remove(node) pre_node.next_nodes.append(split_new_node) del node for new_node in split_nodes: for next_node in new_node.next_nodes: self.construct_tree_lan_modle_token_graph(next_node)
def loadNodeFromSumitChunk(self, sentence_node, parent, chunk, discourse): result = None ''' If the chunk is a non-atomic node ''' if chunk.attributes['span'].value.find('..') >= 0: result = Node(parent) ''' For child = each one of chunk's children ''' for child in getDirectChildElements(chunk): child_node = None child_node = self.loadNodeFromSumitChunk(sentence_node, result, child, discourse) if child_node != None: result.children.append(child_node) else: ''' If the chunk is an atomic node (i.e., a word itself) ''' ''' Look for the word in words list ''' for sen in discourse.sentences: for word in sen.words: if word.properties['id'] == chunk.attributes['span'].value: result = word result.parent = parent sentence_node.words.append(result) break if result != None: break if result != None: result.form = chunk.attributes['form'].value return result
def test_half_sib(tree,p1,p2,rel_dict,truth_rel,married_in): exists=False print "entering test_half_sib" tree_test=copy.deepcopy(tree) p1_node=tree_test[p1] p2_node=tree_test[p2] if len(p1_node.parents.intersection(p2_node.parents)) > 0: #relationship already exists! exists=True return tree,0,exists #add the minimum number of nodes needed to make the half-sib relationship work p1_parent=None p1_parent_candidates=[] for p1_parent in p1_node.parents: if p1_parent not in married_in: if p1_parent.__contains__('Unknown'): break p1_parent_candidates.append(p1_parent) if p1_parent==None and len(p1_parent_candidates)>0: p1_parent=p1_parent_candidates[0] if p1_parent!=None: p1_parent=tree_test[p1_parent] #p2 parent candidates: p2_parent=None p2_parent_candidates=[] for p2_parent in p2_node.parents: if p2_parent not in married_in: if p2_parent.__contains__('Unknown'): break p2_parent_candidates.append(p2_parent) if p2_parent==None and len(p2_parent_candidates)>0: p2_parent=p2_parent_candidates[0] if p2_parent!=None: p2_parent=tree_test[p2_parent] if p1_parent==None and p2_parent==None: both_parent=Node() index=1 while "Unknown"+str(index) in tree_test: index+=1 both_parent.name="Unknown"+str(index) tree_test[both_parent.name]=both_parent elif p1_parent!=None: both_parent=p1_parent else: both_parent=p2_parent both_parent.children.add(p2_node.name) both_parent.children.add(p1_node.name) for s in p2_node.siblings: tree_test[s].parents.add(both_parent.name) both_parent.children.add(s) for s in p1_node.siblings: tree_test[s].parents.add(both_parent.name) both_parent.children.add(s) p2_node.parents.add(both_parent.name) p1_node.parents.add(both_parent.name) errors=get_errors(truth_rel,tree_test,rel_dict) return tree_test,errors,exists
def insertFirst(self, num): # curr = Node.Node(num); curr = Node(num); curr.setNext(self.__head); self.__head = curr; self.__size += 1;
def runalltests(tests, expectedfailures=0): if expectedfailures > 0: print "WARNING: this module is currently failing some of the unit tests. Number of expected failures: %s" % expectedfailures # Create the event queue for this process: DoQ.doq = DoQ.DoQ() # Call `init()'. Node.init() numsuccessesh = [0] ts = [] for test in tests: finishedflag = threading.Event() ts.append((test, finishedflag,)) DoQ.doq.add_task(test, args=(finishedflag, numsuccessesh,)) timeout = 60 for (test, finishedflag,) in ts: tstart = timer.time() while not finishedflag.isSet(): if (timer.time() - tstart) < timeout: finishedflag.wait(1) else: print "test %s didn't finish within %s seconds" % (test, timeout,) break assert numsuccessesh[0] == len(tests), "not all tests passed: num successes: %s, num failures: %s" % (numsuccessesh[0], map(lambda x: x[0], filter(lambda x: not x[1].isSet(), ts)),)
def _build_tree_static(self, proc_mat, fraction, parent_id, idx_map): """ Recursive top-down (start at root) construction of a tree. This construction is static, i.e. it is built from the same processed pair-wise matrix, the relationships do not change based on the level of the tree. """ if fraction < 0: return c = Components(proc_mat) components = c.get_components(fraction, proc_mat)[0] for component in components: i_map = idx_map[component] b_mat = self.base_affinity_matrix[i_map,:][:,i_map] p_mat = self.proc_affinity_matrix[i_map,:][:,i_map] keys = self.key_list[i_map] n_id = len(self.nodes) n = Node(i_map, keys, b_mat, p_mat, n_id) n._parent = parent_id if parent_id is not None: self.nodes[parent_id]._children.append(n_id) self.nodes[n_id] = n fraction = fraction - 1/float(self.fixed_k) self._build_tree_static(p_mat, fraction, n_id, i_map)
def BST(array,start, end): if (start>end): return None mid = start + (end-start)/2 root = Node(array[mid]) root.left = BST(array,start,mid-1) root.right = BST(array,mid+1,end) return root
def main(): root =Node(1) root.left = Node(2,root) root.right = Node(3,root) root.left.left=Node(4,root.left) root.left.left.right=Node(5,root.left.left) node = first_ancestor4(root, root.left,root.right) print node.val
def regex(self): (first, accept_transitions) = self.alt() accepting_state = Node() accepting_state.accepting = True for x in accept_transitions: x.attach_destination(accepting_state) self.assert_match("<EOF>") return first
def run(self): if not self.recursive: self.doInit() self.createView() self.doTitle() if self.validateNodes: Node.validateAllNodes() # This made it look worse! #pal = pygame.image.load(r'c:\ned\nat\world\common.pal') #self.screen.set_palette(pal.get_palette()) # Enter the first node self.node = self.homeNode if type(self.node) == type(""): self.node = Node.findNode(self.node) self.enterNode(self.node) # Main event loop while 1: event = pygame.event.wait() #if self.debug: # print "Event: ", event # Quitting the game is always the same regardless of node. if event.type == QUIT: break newnode = self.doEvent(event) # What did the node ask us to do? if type(newnode) == type(""): newnode = Node.findNode(newnode) if newnode != None: # Changing nodes self.leaveNode(self.node) self.enterNode(newnode) # default handling if the node didn't want it. if newnode == None: if event.type == KEYDOWN and event.key == K_ESCAPE: # Quit the game break if self.debug and event.type == KEYDOWN and event.key == K_3: self.drawGrid() self.leaveNode(self.node) # Clean up self.doCredits() if not self.recursive: self.doTerm()
def create_new_connected_node(self, word, pre_node, next_node): node = Node(word, None) pre_node.add_next_node(node) node.add_pre_node(pre_node) next_node.add_pre_node(node) node.add_next_node(next_node) return node
def insertStart(self,data): newNode = Node(data); if not self.head : self.head = newNode; else: newNode.nextNode = self.head; self.head = newNode;
def remove(self, dataToRemove): if( self.rootNode ): if( self.rootNode.data == dataToRemove ): tempNode = Node(None); tempNode.leftChild = self.rootNode; self.rootNode.remove(dataToRemove,tempNode); self.rootNode = tempNode.leftChild; else: self.rootNode.remove(dataToRemove,None);
def main(): root = Node(1) root.left = Node(2) root.right = Node(2) node1 = root.left node2 = root.right node1.left = Node(3) node1.left.left = Node(3) val = IsBalanced(root) print val
def insertLast(self, num): if(self.isEmpty()): self.insertFirst(num); else: curr = self.__head; while(curr.getNext() != None): curr = curr.getNext(); newNode = Node(num); newNode.setNext(None); curr.setNext(newNode);
def quant(self): (first, transitions) = self.paren() # quant_tail res = self.match('+', '?', '*') if res: self.append_postfix(res) if res == '*': loop_node = Node() for n in transitions: n.attach_destination(loop_node) loop_node.add_epsilon_transition(first) transition = Transition(loop_node, None) return (loop_node, List(transition)) elif res == '+': loop_node = Node() for tr in transitions: tr.attach_destination(loop_node) loop_node.add_epsilon_transition(first) out_transition = Transition(loop_node, None) return (first, List(out_transition)) elif res == '?': skip_node = Node() skip_node.add_epsilon_transition(first) return (skip_node, transitions + List(Transition(skip_node, None))) return (first, transitions)
def setup_node(i): n = Node(name=("Node"+str(i))) n.setprefix(IPNetwork("10.0."+str(i)+"/24")) #cbgpcommands.append("net add node " + str(n.prefix[1])) cbgpcommands.append("net add node " + str(n.prefix[1])) #cbgpcommands.append("net add domain " + str(i)) #cbgpcommands.append("net node " + str(n.prefix[1]) + " domain "+str(i)) cbgpcommands.append("bgp add router " +str(i) + " "+ str(n.prefix[1])) cbgpcommands.append("bgp router " + str(n.prefix[1]) + " add network " + str(n.prefix)) return n
def main(): import getopt import sys def usage(): print "Options:" print "\t-d\tDebug mode" print "\t-f\tFull screen" try: opts, args = getopt.getopt(sys.argv[1:], "df") except getopt.GetoptError: # print help information and exit: usage() return debug = 0 fullscreen = 0 for o, a in opts: if o == "-d": debug = 1 if o == "-f": fullscreen = 1 if debug: print '%d nodes' % (Node.countNodes()) if debug: Node.setJumpNode('t', 'wash_t:n') Node.setJumpNode('a', 'arlington_t:0') Node.setJumpNode('u', 'broovill_t:n') Node.setJumpNode('0', 'hall:w') nw = WorldApp.WorldApp() nw.setTitle("Nat's World") nw.setScreenSize((800, 600)) nw.setFullScreen(fullscreen) nw.setDebug(debug) nw.setHomeNode('hall:w') nw.setCreditRoll([ ("Nat's World", (255,50,50)), "Conception: Ned", "Photography: Ned & Max", "Programming: Ned", "Direction: Nat", "Walking: Nat, Max & Ned", "Set Design: Sue", "Key Grip: Ben", "Catering: Sue", "Transportation: MBTA", "Music: R.E.M., Alanis Morrisette & Max" ]) #nw.setCreditSong('music\\maxneverhood.wav') nw.main()
def main(): root1 = Node(0) root1.left = Node(1) root1.right = Node(2) root1.left.left = Node(3) root1.left.right = Node(4) root2 = Node (3) # root2.left = Node(1) # root2.right = Node(4) check = Issubtree(root1,root2) print check
def parse_topology(generate_json): """"generate JSON file for visualization if generate_json == True""" tree = ET.parse("abilene-TM" + os.sep + "topo" + os.sep + "Abilene-Topo-10-04-2004.xml") root = tree.getroot() topology = root.find("topology") node_list = [] link_list = [] graph = Graph(node_list, link_list) if generate_json: f = open("data.json", "w") output = {"nodes":{}, "links":[]} for node in topology.iter("node"): new_node = Node(node.attrib["id"]) node_list.append(new_node) if generate_json: location = node.find("location") new_node.set_location(float(location.attrib["latitude"]), float(location.attrib["longitude"])) output["nodes"][new_node.node_id] =\ (float(location.attrib["latitude"]), float(location.attrib["longitude"])) for link in topology.iter("link"): link_id = link.attrib["id"] link_from = graph.find_node(link.find("from").attrib["node"]) link_to = graph.find_node(link.find("to").attrib["node"]) bw = int(link.find("bw").text) new_link = Link(link_id, link_from, link_to, bw) link_list.append(new_link) if generate_json: output["links"].append(\ ((link_from.lat, link_from.lng), (link_to.lat, link_to.lng))) igp = root.find("igp").find("links") for link in igp.iter("link"): link_id = link.attrib["id"] link_obj = graph.find_link_by_id(link_id) if link_obj != None: link_obj.metric = float(link.find("static").find("metric").text) if generate_json: json.dump(output, f) f.close() return graph
def insert(self,item,pos): if pos==0: self.add(item) return a=self.head p=a while pos>0: p=a a=a.next pos-=1 temp=Node(item) p.next=temp temp.next=a
def add(self, data): newNode = Node(data, None, None) # If list is empty, make new node the head if self.head == None: self.head = newNode # Otherwise, add to front else: temp = self.head.next self.head = newNode temp.prev = newNode newNode.next = temp
def get_dfa_node(self, nodeset): """Palauttaa sen DFA-tilan, joka vastaa kyseistä NFA-tilajoukkoa 'nodeset'""" if nodeset in self.cache: return self.cache[nodeset] node = Node() node.nfa_states = nodeset for n in nodeset: if n.accepting: node.accepting = True break self.cache[nodeset] = node return node
def construct_tree(n, al, nodes, tree) : """ Takes in a node and an adjacency list and sets a node's children and level. Also takes in a dictionary to store groupings of level nodes n is the current node al is an adjacency list (dictionary of lists) nodes is a dictionary of lists tree will be the entire collection of nodes, indexible by their ID """ child1 = Node() child2 = Node() parent = Node() node_data = al[n.ID] # [c1, c2, p] if node_data[0] != '' : # has left child child1.ID = node_data[0] child1.level = n.level + 1 child1.parent = n construct_tree(child1, al, nodes, tree) n.child1 = child1 if node_data[1] != '' : # has right child child2.ID = node_data[1] child2.level = n.level + 1 child2.parent = n construct_tree(child2, al, nodes, tree) n.child2 = child2 if n.level not in nodes : # has not been added to yet, hence not created nodes[n.level] = [] nodes[n.level].append(n) # add node to its level tree[n.ID] = n return n
def test_remove_all_children(self): node1 = Node(10) node2 = Node(11) to_test = Node(1) to_test.add_child(node1) to_test.add_child(node2) to_test.remove_all_children() self.assertEqual(len(to_test.get_children()), 0) self.assertIs(node1.get_parent(), None) self.assertIs(node2.get_parent(), None)
def getGraph(file, graph, height): index = 0 y = height-1 for line in file: if line: x = 0 lineSplit = line.split() for val in lineSplit: n = Node(val) n.setLoc(x,y) graph.addData(n, index) x += 1 y -= 1 index += 1
def readWorld(world, grp): yval= 7 #Because I start from the top for lines in world: col= 0 lines= lines.split() for char in lines: #char holds the value mahNo= Node(char) mahNo.x= col mahNo.y= yval col = col +1 grp.addNode(mahNo) yval= yval -1 return grp
def editYesChild(aCourse, aNode): print(aCourse.smallToString(aNode)) opt = input( "Do you want to edit a prereq of this course?(y/n): ").upper().strip() if opt != 'Y': return opt = input(''' Choose operation: 0.Change Type 1.Delete all Prereq 2.Edit items in prereq (for AND, OR, OF) 2.Exit input: ''').strip() if (opt not in ['0', '1', '2']): return elif (opt == '2'): if (aNode.child.type == 'NODE'): print('you cant add prereq with this type') return code = input('course code(or STOP to stop): ').upper().strip() while (code != 'STOP'): if not (code in allCourseList): raise FileExistsError('invalid course') course_dict = dict() try: filename = '../data/' + code + '.csv' csv_file = open(filename) csv_reader = csv.reader(csv_file, delimiter=',') line_count = 0 for row in csv_reader: if line_count != 0: course_dict[row[0]] = [ row[1].replace('$', ','), row[2].replace('$', ','), row[3].replace('$', ','), row[4].replace('$', ','), row[5].replace('$', ',') ] line_count += 1 # print(course_dict) except FileNotFoundError: raise FileNotFoundError('Cannot access course') num = input('enter code number: ').strip() if (num in course_dict): print('\nInfo\nCourse name: ' + course_dict[num][0] + '\nCourse code: ' + course_dict[num][1]) print('Course Prerequisite: ' + course_dict[num][2] + '\nCourse Antirequisite(s): ' + course_dict[num][3] + '\ncourse added\n') else: raise FileExistsError('invalid course') if (aCourse.findNode(course_dict[num][1]) == None): aNode.child.addItem([Node(course_dict[num][1])]) else: aNode.child.addItem([aCourse.findNode(course_dict[num][1])]) code = input('course code: ').upper().strip() elif (opt == '1'): aNode.setChild(None) elif (opt == '0'): opt = input(''' Choose operation: 0.AND 1.OR 2.number of (ie.2 of a,b,c) 3.only a course 4.Exit input: ''').strip() if (aNode.child.type == 'NODE'): prereq = [aNode.child] else: prereq = aNode.child.courses if (opt not in ['0', '1', '2', '3']): return elif opt == '3': if (len(prereq) > 1): print('undoable') else: aNode.setChild(None) aNode.setChild(prereq[0]) elif (opt == '0'): aNode.setChild(None) aCourse.setAndChild(aNode, prereq) elif (opt == '1'): aNode.setChild(None) aCourse.setOrChild(aNode, prereq) elif (opt == '2'): aNode.setChild(None) aCourse.setNofChild(aNode, 2, prereq)
def build(self, inst, grad, hns, rate, parameter): assert len(inst) == len(grad) == len(hns) cdr = 0 self.root = Node() self.root.build(inst, grad, hns, rate, cdr, parameter)
if __name__ == '__main__': try: csv_file = open(f'../data/courses.csv') csv_reader = csv.reader(csv_file, delimiter=',') line_count = 0 for row in csv_reader: if line_count != 0: allCourseList.append(row[0]) line_count += 1 except FileNotFoundError: print('cannot access database, abort') exit(1) # print(allCourseList) newCourse = course(Node('CPSC 313')) newCourse.setAndChild(newCourse.head, []) newCourse.head.child.addItem( [orNode([Node('MATH 271'), Node('MATH 273')])]) newCourse.head.child.addItem( [orNode([Node('PHIL 279'), Node('PHIL 377')])]) newCourse.head.child.addItem( [orNode([Node('CPSC 219'), Node('CPSC 233'), Node('CPSC 235')])]) userCourseList.append(newCourse) # print(newCourse.smallToString(newCourse.head)) # newCourse.nodeList = newCourse.parse(newCourse.head) newCourse.refresh()
def push(self, data): cur = Node(data) cur.set_next(self.head) self.head = cur
def id3(): data = [[]] f = open('Pokemon1.csv') for line in f: line = line.strip("\r\n") data.append(line.split(',')) data.remove([]) tree = { 'objectType': { 'pokemon': { 'rarity': { '<7': { 'type': { 'other': { 'catchable': { 'y': { 'ap': { '<30': { 'dp': { '<30': { 'hpOfPokemon': { '<50': { 'hpOfPlayer': { '<60': { 'shiny': { 'y': 'y', 'n': 'n' } }, '>60': { 'shiny': { 'y': 'y', 'n': 'n' } } } }, '>50': { 'hpOfPlayer': { '<60': 'y', '>60': 'n' } } } }, '>30': { 'hpOfPokemon': { '<50': { 'hpOfPlayer': { '<60': { 'shiny': { 'y': 'y', 'n': 'n' } }, '>60': { 'shiny': { 'y': 'y', 'n': 'n' } } } }, '>50': { 'hpOfPlayer': { '<60': 'y', '>60': { 'shiny': { 'y': 'y', 'n': 'n' } } } } } } } }, '>30': { 'dp': { '<30': { 'hpOfPokemon': { '<50': { 'hpOfPlayer': { '<60': { 'shiny': { 'y': 'y', 'n': 'n' } }, '>60': { 'shiny': { 'y': 'y', 'n': 'n' } } } }, '>50': { 'hpOfPlayer': { '<60': 'y', '>60': { 'shiny': { 'y': 'y', 'n': 'n' } } } } } }, '>30': 'y' } } } }, 'n': { 'ap': { '<30': { 'dp': { '<30': { 'hpOfPokemon': { '<50': 'n', '>50': { 'hpOfPlayer': { '<60': 'n', '>60': { 'shiny': { 'y': 'y', 'n': 'n' } } } } } }, '>30': 'n' } }, '>30': 'n' } } } }, 'normal': { 'catchable': { 'y': { 'ap': { '<30': { 'dp': { '<30': { 'hpOfPokemon': { '<50': { 'hpOfPlayer': { '<60': { 'shiny': { 'y': 'y', 'n': 'n' } }, '>60': { 'shiny': { 'y': 'y', 'n': 'n' } } } }, '>50': { 'hpOfPlayer': { '<60': 'y', '>60': { 'shiny': { 'y': 'y', 'n': 'n' } } } } } }, '>30': { 'hpOfPokemon': { '<50': { 'hpOfPlayer': { '<60': { 'shiny': { 'y': 'y', 'n': 'n' } }, '>60': { 'shiny': { 'y': 'y', 'n': 'n' } } } }, '>50': { 'hpOfPlayer': { '<60': 'y', '>60': { 'shiny': { 'y': 'y', 'n': 'n' } } } } } } } }, '>30': { 'dp': { '<30': { 'hpOfPokemon': { '<50': { 'hpOfPlayer': { '<60': { 'shiny': { 'y': 'y', 'n': 'n' } }, '>60': { 'shiny': { 'y': 'y', 'n': 'n' } } } }, '>50': { 'hpOfPlayer': { '<60': 'y', '>60': { 'shiny': { 'y': 'y', 'n': 'n' } } } } } }, '>30': { 'hpOfPokemon': { '<50': { 'hpOfPlayer': { '<60': { 'shiny': { 'y': 'y', 'n': 'n' } }, '>60': { 'shiny': { 'y': 'y', 'n': 'n' } } } }, '>50': { 'hpOfPlayer': { '<60': 'y', '>60': { 'shiny': { 'y': 'y', 'n': 'n' } } } } } } } } } }, 'n': 'n' } } } }, '>7': { 'type': { 'other': { 'catchable': { 'y': 'y', 'n': 'n' } }, 'normal': { 'catchable': { 'y': 'y', 'n': 'n' } } } } } }, 'item': 'y' } } attributes = [ 'objectType', 'rarity', 'type', 'catchable', 'ap', 'dp', 'hpOfPokemon', 'hpOfPlayer', 'shiny', 'catch' ] count = 0 for entry in data: count += 1 tempDict = tree.copy() result = "" while (isinstance(tempDict, dict)): root = Node.Node(list(tempDict)[0], tempDict[list(tempDict)[0]]) tempDict = tempDict[list(tempDict)[0]] index = attributes.index(root.value) value = entry[index] if (value in tempDict.keys()): child = Node.Node(value, tempDict[value]) result = tempDict[value] tempDict = tempDict[value] else: print(str("Info from pokedex: %s" % data)) return str(result) break print(str("Info from pokedex: %s" % data)) print("entry%s = %s" % (count, result)) return str(result)
# Black Bishops board[9, 0, 2] = 1 board[9, 0, 5] = 1 # Black Knights board[10, 0, 1] = 1 board[10, 0, 6] = 1 # Black Pawns board[11, 1, :] = 1 return board # Play Script board = initialBoard() game = Node.Node(board) network = 0 network = torch.load( r'D:\Machine Learning\DeepLearningChessAI\Networks\QualityControl.cnn') network = network.cuda() player = Player(game, network, "White", 4, 4) player.play() ############################################################################################################################################################# # # Debug Script # import DataAlteration # import PredictionVisualization
class CircularLinkedList(LinkedList): def __init__(self): LinkedList.__init__(self) self._tail = None ############################## #### Metodes sobreescrits #### ############################## def __str__(self): ''' Imprimeix tots els nodes de la llista circular ''' if (not (self._head)): return '' res = "" for item in self: res += str(item.getData()) + ", " return res def getTail(self): ''' Retorna el Node final''' return self._tail ####################################### ### Metodes per gestionar la classe ### ####################################### def initialize(self, until): ''' Crea un array predeterminat de nodes on els valors son numeros de 1 a n ''' for i in xrange(0, until): self.insertFirst(until - i) def insertFirst(self, data): ''' Inserta un Node al principi de la llista circular ''' if self._head == None: self._head = Node(data, self._head) self._tail = self._head self._head.setNext(self._head) else: self._head = Node(data, self._head.getNext()) self._tail.setNext(self._head) self._size += 1 def insertLast(self, data): ''' Inserta un node al final de la llista circular ''' self.inserti(len(self), data) def traverse(self): ''' Recorre la llista enllasada circular imprimint els valors i enllasos ''' probe = self._head i = 0 while (i < len(self)): print probe, " ----> ", probe.getNext() probe = probe.getNext() i += 1 def find(self, targetItem): ''' Busca item a la llista (per valor), per index ja tenim redefinit el __getitem__ ''' i = 0 probe = self._head while (i < len(self) and targetItem != probe.getData()): probe = probe.getNext() i += 1 return (False if (i >= len(self)) else True) def removeFirst(self): ''' Elimina el primer Node i el retorna ''' if (not (self._head)): return None res = self._head self._head = self._head.getNext() self._size -= 1 return res def removei(self, index): ''' Esborra el node de la iessima posicio i retorna el seu valor ''' if (index == 0): return self.removeFirst() if (not (self._head)): removedItem = None else: probe = self[index - 1] removedItem = probe.getNext().getData() probe.setNext(probe.getNext().getNext()) self._size -= 1 return removedItem def removeLast(self): ''' Esborra el Node de la ultima posicio i en retorna el valor ''' return self.removei(len(self) - 1) def replace(self, targetItem, newItem): ''' Remplasa un valor existent per un de nou (busca per valor no per index) i nomes la primera coincidencia ''' i = 0 probe = self._head while (i < len(self)): if (self[i].getData() == targetItem): self[i].setData(newItem) return True i += 1 return False def replaceAll(self, targetItem, newItem): ''' Remplasa totes les coincidencies existents per un nou valor ''' i = 0 probe = self._head while (i < len(self)): if (self[i].getData() == targetItem): self[i].setData(newItem) i += 1 def replace(self, index, newItem): ''' Remplasa un valor existent buscant per index ''' if (index < 0 or index > len(self) - 1): return False self[index].setData(newItem) return True # funcio de proves def test(self): print "{TEST DE CIRCULAR LINKED LIST}" print("Tenemos una lista enlazada con varios elementos.") self.inserti(0, "hola") self.inserti(1, [1, 2, 3, 4]) self.insertLast("pau") self.insertLast("pau") print("La lista enlazada tiene estos nodos:\n{}").format(self) print("La longitud de la lista es {}").format(len(self)) elem_name = "pau" print("Esta el elemento {} en la lista? {}").format( elem_name, self.find(elem_name)) print("Cual es el primer elemento? {}").format(self.getHead()) self.replacei(0, "nou") print("Ahora lo hemos cambiado por este: {}").format(self.getHead()) elem = [1, 2, 3, 4] self.replace(elem, "canviat") print("Ahora cambiamos el segundo elemento: {}").format(self[1]) elem1, elem2 = "pau", "albert" self.replaceAll(elem1, elem2) print( "Hemos remplazado {} por {} en todas sus apariciones.\nAhora la lista tiene este aspecto:" ).format(elem1, elem2) self.traverse() print("Recorremos la lista para remplazar todos los elementos:") for elemento in self: elemento.setData("remplazado") print self print( "Insertamos un elemento al principio, otro al final y otro en medio:" ) self.insertFirst("primero") self.inserti(len(self) / 2, "medio") self.insertLast("ultimo") print self
def test_preorder_both(self): tree = Node.Node(5, Node.Node(4, None, None), Node.Node(3, None, None)) self.assertEqual(TreeOperations.pre_order(tree), [5, 4, 3])
def test_max_depth_1(self): tree = Node.Node(5, None, None) self.assertEqual(1, TreeOperations.maximum_depth(tree))
from flask import Flask, request import requests from Blockchain import * from Node import * from main import createTransactionsIntial #transaction example #{"sender": 0, "receiver": 10, "timestamp": 1575457940.1777258, "amount": 20} #block example app = Flask(__name__) node = Node(Blockchain()) peers = set() transactionsIntial = createTransactionsIntial(15) transactionsNodeAddress = "" for t in transactionsIntial: node.blockchain.unconfirmed_transactions.append(t) # @app.route('/new-ttransaction') # def new_transaction_parameters(): # sender = request.args.get("sender") #if not exists returns None # receiver = request.args.get("receiver") # timestamp = request.args.get("timestamp") # amount = request.args.get("amount") # transaction = Transaction(sender, receiver, timestamp, amount) #http://127.0.0.1:8000/new-ttransaction?sender=0&receiver=1×tamp=1575419338.4732528&amount=15 # chain.addNewTransactions([transaction]) # # return "Got your transaction: " + str(transaction.__dict__)
import Node import argparse, pickle, threading from time import sleep parser = argparse.ArgumentParser(description='Node instance number (1-4)') parser.add_argument('nodeID', help='NodeID.', type=int) args = parser.parse_args() # start up the node node = Node.Node(4, args.nodeID) ## appointments for test purposes: choice5 = ("DMV", 3, 12.5, 13.5, [1, 2, 3]) choice6 = ("Skiing", 3, 6.0, 17.0, [3]) #### def check_refresh(): while True: if node.refresh_calendar: node.displayCalendar() print("What action would you like to perform? \n\t1. Insert " + "appointment \n\t2. Delete appointment \n\t3. Refresh " + "calendar \n\t4. Exit calendar application\n") node.refresh_calendar = False sleep(.5) threading.Thread(target=check_refresh, daemon=True).start() running_calendar = True
def UpdateNode(node): properties = Node(River, Node(Bridge, Empty)) node.DefaultTexture = pygame.image.load("Content\white_pixel.png").convert() node.UpdateProps(properties)
def main(test=0): if (test == 0): print("Execute main as usual") lvl0 = BitBoard(2) if (test == 1): print( "====================== This is the size comparison test ======================" ) lvl0 = BitBoard(2, True, True) lvl1 = BitBoard(4, True, True) lvl0.printObjectSizeStatistics() lvl1.printObjectSizeStatistics() elif (test == 2): print( "====================== This is the sparse matrix fill comparison test ======================" ) lvl0 = BitBoard(3, True, True) lvl1 = BitBoard(3, True, True) lvl1.fillSparseAdjacencyMatrix() lvl1.printObjectSizeStatistics(lvl0) lvl1.printObjectSizeStatistics() print("====================== Matrix Contents ======================") print(lvl0.getSparseAdjacencyMatrix().toarray()) print(lvl1.getSparseAdjacencyMatrix().toarray()) elif (test == 3): print( "====================== This is the board representation test ======================" ) lvl0 = BitBoard(5, False, False) lvl0.fillBoard() print("Board as a bool matrix : ") lvl0.representBoardAsMatrix() print("Board as a 1D bit vector : ") print(lvl0.getBitBoard()) elif (test == 4): print( "====================== This is a test for the board whacking function ======================" ) size = 3 lvl0 = BitBoard(size, False, False) lvl0.fillBoard(full=True) for i in range(0, size): for j in range(0, size): print("\n Whack at " + str((i, j)) + "\n") placeholder = copy.deepcopy(lvl0) placeholder.orthogonalWhack(i, j) print(placeholder.representBoardAsMatrix()) placeholder.representBoardAsMatrix() placeholder = copy.deepcopy(lvl0) # None should change placeholder.orthogonalWhack(4, 1) print("Used to show that it doesn't work out of bounds \n") print(placeholder.representBoardAsMatrix()) lvl0.orthogonalWhack(1, 1) print("Used to show that it doesn't act on a bit that is 0 \n") print(lvl0.representBoardAsMatrix()) lvl0.orthogonalWhack(1, 1) print("\n") print(lvl0.representBoardAsMatrix()) elif (test == 5): print( "====================== This is a test for finding all possible transitions ======================" ) size = 4 lvl0 = BitBoard(size, False, True) lvl0.findAllPossibleTransisitons() elif (test == 6): print( "====================== This is a test for the BFS function ======================" ) size = 3 lvl0 = BitBoard(size, False, True) lvl0.assignCritterOnBoard(0, 0) lvl0.assignCritterOnBoard(1, 0) lvl0.assignCritterOnBoard(0, 2) lvl0.assignCritterOnBoard(2, 1) print("Starting State : ") lvl0.representBoardAsMatrix() print("\n") lvl0.findAllPossibleTransisitons(diagonalWhack=False) search = SearchAlgorithm.SearchAlgorithm( lvl0.getSparseAdjacencyMatrix().tolil()) startNode = Node.Node(int(lvl0.getBitBoard())) endNode = Node.Node(0) fin = search.BFS(startNode, endNode) solution = fin[1] step = len(solution) - 1 if (len(solution) == 0): print("This has no solution") while (0 < step): print("Step: " + str(step)) lvl0.representBoardAsMatrix( biv.BitVector(intVal=solution[step].getNumber(), size=lvl0.getBoardSize()**2), printBoard=True) print("\n") step -= 1 elif (test == 7): print( "====================== This is a test for the reverse BFS function paired with orthogonal whacking ======================" ) size = 4 lvl0 = BitBoard(size, False, True) lvl0.assignCritterOnBoard(2, 2) lvl0.assignCritterOnBoard(1, 3) lvl0.assignCritterOnBoard(1, 1) lvl0.findAllPossibleTransisitons(diagonalWhack=False) search = SearchAlgorithm.SearchAlgorithm( lvl0.getSparseAdjacencyMatrix().tolil()) startNode = Node.Node(45019) # starting from node Node.Node(1) fails endNode = Node.Node(0) highlightNode = Node.Node(int(lvl0.getBitBoard())) allNodes = search.reverseBFS(endNode) path = search.BFS(startNode, endNode) if (size < 4): createGraph(lvl0, allNodes, highlightNode, True) if (len(path[1]) > 0): createGraph(lvl0, path[1], startNode, False, reverse=True) print("The number acceptable solutions is :" + str(len(allNodes)) + " out of the possible " + str(2**(lvl0.getBoardSize()**2))) elif (test == 8): print( "====================== This is a test for the reverse BFS function paired with diagonal whacking ======================" ) size = 3 lvl0 = BitBoard(size, False, True) lvl0.assignCritterOnBoard(2, 2) lvl0.assignCritterOnBoard(1, 3) lvl0.assignCritterOnBoard(1, 1) lvl0.findAllPossibleTransisitons(diagonalWhack=True) search = SearchAlgorithm.SearchAlgorithm( lvl0.getSparseAdjacencyMatrix().tolil()) endNode = Node.Node(0) highlightNode = Node.Node(int(lvl0.getBitBoard())) allNodes = search.reverseBFS(endNode) if (size < 4): createGraph(lvl0, allNodes, highlightNode, False) print("The number acceptable solutions is :" + str(len(allNodes)) + " out of the possible " + str(2**(lvl0.getBoardSize()**2))) elif (test == 9): size = 3 lvl0 = BitBoard(size, False, False) lvl0.assignCritterOnBoard(2, 2) lvl0.assignCritterOnBoard(1, 3) lvl0.assignCritterOnBoard(1, 1) search = SearchAlgorithm.SearchAlgorithm() currentNode = Node.Node(0) path = search.greedySearch(currentNode, lvl0, iterations=500) print(path)
def insert(self, data): if not self.rootNode: self.rootNode = Node.Node(data) else: self.rootNode.insert(data)
from Node import * from NodeFactory import * import DelayStrat import ConnStrat from Quorum import SCPQuorum import Utils if __name__ == '__main__': # Experiment parameters nodeCount = 4 factory = SimpleNodeFactory(time = 100, timeoutGap = 0) # Instantiate instances with parameters nodes = [] for nodeID in range(nodeCount): nodes.append(Node(factory, nodeID)) factory.createConn().initWithPeers(nodes, 1, 0.67) # Evaluate the NodeRank Utils.NodeRank(nodes[0].mConn.getQuorum(), nodeCount, draw=False) # run the instances for node in nodes: t = Thread(target=node.run) t.start()
def test_max_depth_2_right(self): tree = Node.Node(5, None, Node.Node(3, None, None)) self.assertEqual(2, TreeOperations.maximum_depth(tree))
def tests(): totalScore = 0 # Check Node aNode = Node() aNode.data = 0.1 bNode = Node(data=1.1, next=Node(data=2.21)) aNode.next = bNode # Testing Nodes totalScore += CheckOutput('0.1', str(aNode)) totalScore += CheckOutput('1.1', str(bNode)) totalScore += CheckOutput('2.21', str(bNode.next)) totalScore += CheckOutput(None, bNode.next.next) # Check List aList = OurLinkedList(aNode) bList = OurLinkedList(bNode) cList = aList.shallowCopy() dList = aList.deepCopy() aList.head.next.next.data = 55 # Check List totalScore += CheckOutput('[0.1,1.1,55]', str(aList)) totalScore += CheckOutput('[1.1,55]', str(bList)) totalScore += CheckOutput('[0.1,1.1,55]', str(cList)) totalScore += CheckOutput('[0.1,1.1,2.21]', str(dList)) # check equals if not (aList == bList): totalScore += 1 if (aList == cList): totalScore += 1 if not (aList == dList): totalScore += 1 # getitem totalScore += CheckOutput('0.1', str(aList[0])) try: aList[3] except IndexError: totalScore += 1 try: aList[-3] except IndexError: totalScore += 1 # appending aList.append(77) totalScore += CheckOutput('[0.1,1.1,55,77]', str(aList)) totalScore += CheckOutput('77', str(aList[3])) # prepend aList.prepend(45) totalScore += CheckOutput('[45,0.1,1.1,55,77]', str(aList)) totalScore += CheckOutput('45', str(aList[0])) # insertAt aList.insert(0, 100) aList.insert(len(aList), 101) aList.insert(3, 102) totalScore += CheckOutput('[100,45,0.1,102,1.1,55,77,101]', str(aList)) * 2 if len(aList) == 8: totalScore += 1 # empty/almost empty lists bList = OurLinkedList() bList.append(4) totalScore += CheckOutput('[4]', str(bList)) try: print(bList.pop(-1)) except IndexError: totalScore += 1 try: print(bList.pop(1)) except IndexError: totalScore += 1 totalScore += CheckOutput('4', str(bList.pop(0))) * 2 totalScore += CheckOutput('[]', str(bList)) totalScore += CheckOutput(None, bList.head) totalScore += CheckOutput(None, bList.tail) # Updating tail properly totalScore += CheckOutput('101', str(aList.pop(len(aList) - 1))) * 2 totalScore += CheckOutput('[100,45,0.1,102,1.1,55,77]', str(aList)) totalScore += CheckOutput(None, aList.tail.next) # remove aList.remove(100) aList.remove(77) totalScore += CheckOutput('[45,0.1,102,1.1,55]', str(aList)) if len(aList) == 5: totalScore += 1 try: aList.remove(800) except ValueError: totalScore += 1 # reverse aList.reverse() totalScore += CheckOutput('[55,1.1,102,0.1,45]', str(aList)) * 2 totalScore += CheckOutput('55', str(aList.head)) totalScore += CheckOutput('45', str(aList.tail)) return totalScore * 2
jobSite = Site.Site() return_tuple = runJob.argumentParser() tolog("argumentParser returned: %s" % str(return_tuple)) jobSite.setSiteInfo(return_tuple) # jobSite.setSiteInfo(argParser(sys.argv[1:])) # reassign workdir for this job jobSite.workdir = jobSite.wntmpdir if runJob.getPilotLogFilename() != "": pUtil.setPilotlogFilename(runJob.getPilotLogFilename()) # set node info node = Node.Node() node.setNodeName(os.uname()[1]) node.collectWNInfo(jobSite.workdir) # redirect stder sys.stderr = open("%s/runjob.stderr" % (jobSite.workdir), "w") tolog("Current job workdir is: %s" % os.getcwd()) tolog("Site workdir is: %s" % jobSite.workdir) # get the experiment object thisExperiment = getExperiment(runJob.getExperiment()) tolog("RunJob will serve experiment: %s" % (thisExperiment.getExperiment())) # set the cache (used e.g. by LSST)
def main(): data = [[]] f = open('bananas.csv') for line in f: line = line.strip("\r\n") data.append(line.split(',')) data.remove([]) tree = { 'color1R': { '3': { 'color1B': { '2': { 'color1G': { '1': { 'color2R': { '3': 'NOT RIPE', '5': 'RIPE' } }, '2': 'OVERRIPE' } }, '4': 'NOT RIPE' } }, '2': 'NOT RIPE', '5': { 'color1B': { '3': 'RIPE', '5': { 'color1G': { '3': { 'color2R': { '3': 'RIPE', '4': { 'color2B': { '3': { 'color2G': { '1': 'RIPE', '2': 'OVERRIPE' } }, '4': 'RIPE' } } } }, '2': { 'color2R': { '5': 'RIPE', '4': { 'color2B': { '3': 'RIPE', '4': 'NOT RIPE' } } } }, '4': 'RIPE' } }, '4': { 'color1G': { '1': 'RIPE', '3': { 'color2R': { '5': 'RIPE', '4': 'OVERRIPE' } }, '2': { 'color2R': { '3': 'RIPE', '5': 'RIPE', '4': { 'color2B': { '2': 'RIPE', '4': 'NOT RIPE' } } } } } } } }, '4': { 'color1B': { '3': 'OVERRIPE', '5': 'NOT RIPE', '4': { 'color1G': { '2': 'NOT RIPE', '5': 'RIPE' } } } } } } attributes = [ 'color1R', 'color1B', 'color1G', 'color2R', 'color2B', 'color2G', 'color3R', 'color3B', 'color3G', 'class' ] count = 0 for entry in data: count += 1 tempDict = tree.copy() result = "" while (isinstance(tempDict, dict)): root = Node.Node( list(tempDict.keys())[0], tempDict[list(tempDict.keys())[0]]) tempDict = tempDict[list(tempDict.keys())[0]] index = attributes.index(root.value) value = entry[index] if (value in tempDict.keys()): child = Node.Node(value, tempDict[value]) globalfile.resultRIPE = tempDict[value] tempDict = tempDict[value] else: print("can't process input %s" % (count)) result = "?" break print("entry%s = %s" % (count, globalfile.resultRIPE))
def test_preorder_left(self): tree = Node.Node(5, Node.Node(4, None, None), None) self.assertEqual(TreeOperations.pre_order(tree), [5, 4])
def decisionTree(parameters, types, counts, labels, X, y, algo): tree = Node(0, types, counts, labels, X, y, parameters) tree.createNode(algo) return tree
def main(): ################################################################################################# # NOTE ! You need a credentials.json https://developers.google.com/sheets/api/quickstart/python # ################################################################################################# # connect to the google sheet creds = None # The file token.pickle stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists('token.pickle'): with open('token.pickle', 'rb') as token: creds = pickle.load(token, encoding="latin1") # if there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_local_server(port=0) # save the credentials for the next run with open('token.pickle', 'wb') as token: pickle.dump(creds, token) service = build('sheets', 'v4', credentials=creds) # call the Sheets API sheet = service.spreadsheets() result = sheet.values().get(spreadsheetId=SPREADSHEET_ID, range=GET_RANGE).execute() values = result.get('values', []) map = [None] * len(values) grid = "" # print(len(map)) if not values: print('No data found.') else: for row in values: # rows on gSheets are [id, id_to_left, id_to_right, id_to_front, id_to_behind] for i in range(len(row)): # user didn't have a neighbor, reformat entry if row[i] is u'': row[i] = None else: row[i] = int(row[i]) if len(row) is 4: row.append(None) n = row[0] # create Node in map initialized to the student's id map[n] = Node(n) map[n].l = row[1] map[n].r = row[2] map[n].u = row[3] map[n].d = row[4] edge_map = [None] * len(values) # find the top left corner n = int(len(map) / 2) while map[n].u is not None or map[n].l is not None: if map[n].u is not None: n = map[n].u if map[n].l is not None: n = map[n].l # construct a grid moving from the top left corner cur_x = 0 cur_y = 0 while True: while map[n].r is not None: map[n].x = cur_x map[n].y = cur_y cur_x = cur_x + 1 grid = grid + str(n) + ' ' n = map[n].r map[n].x = cur_x map[n].y = cur_y cur_x = 0 cur_y = cur_y + 1 grid = grid + str(n) + '\n' if map[n].d is not None: n = map[n].d while map[n].l is not None: n = map[n].l else: break # construct coords for updating the google sheet coords = [None] * len(map) for i in range(len(map)): coords[i] = [i, map[i].x, map[i].y] # print(coords) # messages = encodeMessages(map) # update the google sheet to have the current positions of people body = {'range': SET_RANGE, 'values': coords} ret = sheet.values().update(spreadsheetId=SPREADSHEET_ID, range=SET_RANGE, body=body, valueInputOption='RAW').execute()
def opponentTurn(self, tree): board = copy.deepcopy(tree.getBoard()) tree.createChildren() legalMoves = tree.getChildren() print( "Make your move: select a square and then input an action. Input \"done\" to submit move." ) move = "" coordinates = [] isTurn = True while isTurn: move = input() # get user input if move == "done": # change turn if self.color == "White": board[12:14, :, :] = 0 else: board[12:14, :, :] = 1 print(Node.Node(board)) for line in legalMoves: if torch.equal(line.getBoard(), board): self.tree = line # change head of tree to match opponent's move isTurn = False print("Move submitted") break if isTurn: print("submitted move was not legal") else: break elif re.search( r'\d', move): # if has number -> indicates square selection coordinates = [] coordinates.append(8 - int(move[1])) coordinates.append(ord(move[0]) - 97) print("Selected: " + str(coordinates)) elif move == "clear": if coordinates: board[0:12, coordinates[0], coordinates[1]] = 0 print(Node.Node(board)) else: print("first, select a square") elif len(move) == 1: if move == "K": move = 0 elif move == "Q": move = 1 elif move == "R": move = 2 elif move == "B": move = 3 elif move == "N": move = 4 elif move == "P": move = 5 else: print("Piece not recognized") continue if coordinates: board[self.opponentColorChannels[move], coordinates[0], coordinates[1]] = 1 print(Node.Node(board)) else: print("first, select a square")
# Romel Pascua # 017167304 # CECS 328 Final # Dijkstra from Node import * from Dijkstra import * # all nodes start with dst = infinity a = Node('a') b = Node('b') c = Node('c') d = Node('d') e = Node('e') f = Node('f') g = Node('g') h = Node('h') # (node, weight) a.adj = {(b, 15), (c, 2), (d, 3)} b.adj = {(a, 15), (c, 8), (e, 2), (f, 1)} c.adj = {(a, 2), (b, 8), (f, 7), (g, 5)} d.adj = {(a, 3), (e, 1)} e.adj = {(b, 2), (d, 1)} f.adj = {(b, 1), (c, 7), (g, 2)} g.adj = {(c, 5), (f, 2), (h, 1)} h.adj = {(g, 1)} V = [a, b, c, d, e, f, g, h] Dijkstra(a, V) # fill V again since Dijkstra emptied it
def find_child(pyra): temp_heur = 999999999 nodes = [] #-----Check u/U/Uw u = node.Node(0,pyra) u.pyra = copy.deepcopy(pyra) u.pyra.u_swap() u.heuristic = u.find_heuristic() heapq.heappush(nodes,u) U = node.Node(0,pyra) U.pyra = copy.deepcopy(pyra) U.pyra.U_swap() U.heuristic = U.find_heuristic() #print("U heuristic is ", U.heuristic) heapq.heappush(nodes,U) Uw = node.Node(0,pyra) Uw.pyra = copy.deepcopy(pyra) Uw.pyra.Uw_swap() Uw.heuristic = Uw.find_heuristic() # print("Uw heuristic is ", Uw.heuristic) heapq.heappush(nodes, Uw) b = node.Node(0,pyra) b.pyra = copy.deepcopy(pyra) b.pyra.b_swap() b.heuristic = b.find_heuristic() #print("b heuristic is ", b.heuristic) heapq.heappush(nodes, b) B = node.Node(0,pyra) B.pyra = copy.deepcopy(pyra) B.pyra.B_swap() B.heuristic = B.find_heuristic() #print("B heuristic is ", B.heuristic) heapq.heappush(nodes, B) Bw = node.Node(0,pyra) Bw.pyra = copy.deepcopy(pyra) Bw.pyra.Bw_swap() Bw.heuristic = Bw.find_heuristic() #print("Bw heuristic is ", Bw.heuristic) heapq.heappush(nodes, Bw) L = node.Node(0,pyra) L.pyra = copy.deepcopy(pyra) L.pyra.L_swap() L.heuristic = L.find_heuristic() #print("L heuristic is ", L.heuristic) heapq.heappush(nodes, L) l = node.Node(0,pyra) l.pyra = copy.deepcopy(pyra) l.pyra.l_swap() l.heuristic = l.find_heuristic() #print("l heuristic is ", l.heuristic) heapq.heappush(nodes, l) Lw = node.Node(0,pyra) Lw.pyra = copy.deepcopy(pyra) Lw.pyra.Lw_swap() Lw.heuristic = Lw.find_heuristic() #print("Lw heuristic is ", Lw.heuristic) heapq.heappush(nodes, Lw) r = node.Node(0,pyra) r.pyra = copy.deepcopy(pyra) r.pyra.r_swap() r.heuristic = r.find_heuristic() #print("r heuristic is ", r.heuristic) heapq.heappush(nodes, r) R = node.Node(0,pyra) R.pyra = copy.deepcopy(pyra) R.pyra.R_swap() R.heuristic = R.find_heuristic() #print("R heuristic is ", R.heuristic) heapq.heappush(nodes, R) Rw = node.Node(0,pyra) Rw.pyra = copy.deepcopy(pyra) Rw.pyra.Rw_swap() Rw.heuristic = Rw.find_heuristic() #print("Rw heuristic is ", Rw.heuristic) heapq.heappush(nodes, Rw) return nodes
def __gen_tree(max_depth, num): if max_depth < 0 or (random.random() > 0.8 and random.random() > 0.8): return None else: return Node.Node(num.pop(), __gen_tree(max_depth - 1, num), __gen_tree(max_depth - 1, num))
def create_node(name): ''' Create new node from the given name, add to 'nodes' and return it''' node = Node(name) nodes[int(name)] = node return node
def test_bfs_root(self): tree = Node.Node(5, None, None) self.assertEqual(TreeOperations.breadth_first_search(tree), [5])
def build_scene (dimension, offset): def build_board(): entry_point = None above_line = None prev_node = None for row in range(dimension): for column in range(dimension): node = Tile(Vector2(column, row), "Content\white_pixel.png", offset, Empty) if row == 0 and column == 0: entry_point = node if (column == 0): prev_node = node else: prev_node.Right = node node.Left = prev_node prev_node = node if(row > 0): node.Up = above_line above_line.Down = node above_line = above_line.Right while prev_node.Left != None: prev_node = prev_node.Left above_line = prev_node return entry_point board = build_board() board_with_rivers = build_rivers(board) board_with_bridges = build_bridge(board_with_rivers, dimension) _board = board __board = _board all_tiles = Empty first = Node(board, Empty) rest = first while(__board != None): while(_board != None): rest.Tail = Node(_board, Empty) rest = rest.Tail _board = _board.Right __board = __board.Down _board = __board entry_rivers = Empty _first = first while not _first.IsEmpty: if _first.Value.River and _first.Value.Position.Y == 0: entry_rivers = Node(_first.Value, entry_rivers) _first = _first.Tail bridges = Empty _first = first while not _first.IsEmpty: if _first.Value.Bridge: bridges = Node(_first.Value, bridges) _first = _first.Tail build_buildings(first) return first, entry_rivers, bridges
def test_bfs_both(self): tree = Node.Node(5, Node.Node(4, None, None), Node.Node(3, None, None)) self.assertEqual(TreeOperations.breadth_first_search(tree), [5, 4, 3])