def get_children(self, node): category = node.getCategory() children = [] if category in ("player", "root"): moves = node.getGrid().getAvailableMoves() curr_backup = self.clone(node.getGrid()) for move in moves: curr_backup.move(move) children.append( Node(False, curr_backup, "computer", node, move)) curr_backup = self.clone(node.getGrid()) elif category == "computer": cells = node.getGrid().getAvailableCells() curr_backup = self.clone(node.getGrid()) for cell in cells: curr_backup.setCellValue(cell, 2) children.append(Node(False, curr_backup, "player", node)) curr_backup = self.clone(node.getGrid()) curr_backup.setCellValue(cell, 4) children.append(Node(False, curr_backup, "player", node)) return children
def add_node(output, operator): ''' add a Node into output queue, and add previous Node as operands ''' if operator != '~': right, left = output.pop(), output.pop() output.append(Node(left, right, operator)) else: output.append(Node(output.pop(), None, operator))
def lexical_analysis(s, values): tokens = [] i = 0 while i < len(s): c = s[i] if c in mappings: token_type = mappings[c] token = Node(token_type, value=c) elif re.match(r'[a-z]', c): val = values.get(c) token = Node( TokenType.T_NUM, value=BigNumber(val) ) # convert str to list of integers list(map(int, list(val))) elif re.match(r'[\d]+', c): current_string = "" while i < len(s) and re.match(r'[\d]+', s[i]): current_string += s[i] i += 1 i -= 1 token = Node( TokenType.T_NUM, value=BigNumber(current_string) ) # convert str to list of integers list(map(int, list(val))) else: raise Exception('Invalid syntax: {}'.format(c)) tokens.append(token) i += 1 tokens.append(Node(TokenType.T_END)) return tokens
def rrt_star(start, goal, obstacles): nodes = [] nodes.append(Node(start, None)) i = 0 while i < MAX_ITERATIONS: i = i + 1 if i % 10 == 0: rand = [goal[0], goal[1]] else: rand = world.random_position() if utils.is_in_obstacle(rand, obstacles): continue # Search nearest node to the rand point nearest = nodes[0] for node in nodes: if node.pos == rand: nearest = None break if utils.dist(node, rand) < utils.dist(nearest, rand): nearest = node if not nearest: continue # Search the neighbors of the nearest node neighbors = [] for node in nodes: if utils.dist(node, nearest ) < REROUTING_RADIUS and not utils.line_in_obstacles( node.pos, rand, obstacles): neighbors.append(node) # Select best possible neighbor nearest = None min_cost = math.inf for node in neighbors: if node.cost < min_cost: nearest = node min_cost = node.cost if not nearest: continue rand = Node(rand, nearest) nodes.append(rand) # Rewiring of the tree for node in neighbors: if rand.cost + utils.dist(rand, node) < node.cost: node.parent = rand node.cost = rand.cost + utils.dist(rand, node) center = [goal[0] + goal[2] / 2, goal[1] + goal[3] / 2] if utils.dist(rand, center, sqrt=True) < END_RADIUS: path, path_len = build_path(Node(center, rand)) return (path, nodes, i, path_len) raise ValueError('No Path Found')
def travel(dist_mat, startcity=0): optimal_tour = [] u = Node() pq = PriorityQueue() opt_len = 0 v = Node(level=0, path=[0]) min_len = sys.maxsize v.bound = bound(dist_mat, v) pq.put(v) while not pq.empty(): v = pq.get() if v.bound < min_len: u.level = v.level + 1 for i in filter(lambda x: x not in v.path, range(1, num_cities)): u.path = v.path[:] u.path.append(i) if u.level == num_cities - 2: l = set(range(1, num_cities)) - set(u.path) u.path.append(list(l)[0]) u.path.append(0) _len = length(dist_mat, u) if _len < min_len: min_len = _len opt_len = _len optimal_tour = u.path[:] else: u.bound = bound(dist_mat, u) if u.bound < min_len: pq.put(u) # make a new node at each iteration! u = Node(level=u.level) return optimal_tour, opt_len
def test_set_parent(self): """ Test setting of a parent for a node. """ new_node = Node('test_set_parent') new_node.set_parent(self.root_node) assert (new_node in self.root_node.children) assert (new_node.parent is self.root_node)
def p_assignment(p): '''Assignment : ExpressionList assign_op ExpressionList''' # TODO restriction on LHS expressions p[0] = Node() if len(p[1].exprlist) != len(p[3].exprlist): print "error: at line", p.lineno(0), "Unequal number of arguments" else: for i in range(len(p[1].exprlist)): if not inScope(p[1].exprlist[i].expr.value): print "error: at line", p.lineno(0), "variable not in scope" else: if p[1].exprlist[i].expr.type != p[3].exprlist[i].expr.type: print "error: at line", p.lineno( 0), "type mismatch is assighment" return exprtype = p[1].exprlist[i].expr.type p[0].expr.type = exprtype if p[2] == '=': p[0].code += p[1].exprlist[i].code + p[3].exprlist[ i].code + [ p[1].exprlist[i].place + ' := ' + p[3].exprlist[i].place ] ops = ['+=', '-=', '*=', '/=', '%='] if p[2] in ops: new_temp = newTemp(exprtype) p[0].code = p[1].exprlist[i].code + p[3].exprlist[ i].code + [ new_temp + ' := ' + p[1].exprlist[i].place + ' ' + exprtype + p[2][0] + ' ' + p[3].exprlist[i].place ] p[0].code += [ p[1].exprlist[i].expr.value + ' := ' + new_temp ]
def sum_lists(head1, head2): dummy = tmp = Node(-1) c = 0 while head1 and head2: s = head1.val + head2.val + c d = s % 10 c = s / 10 tmp.next = Node(d) tmp = tmp.next head1 = head1.next head2 = head2.next while head1: s = head1.val + c d = s % 10 c = s / 10 tmp.next = Node(d) tmp = tmp.next head1 = head1.next while head2: s = head2.val + c d = s % 10 c = s / 10 tmp.next = Node(d) tmp = tmp.next head2 = head2.next if c: tmp.next = Node(c) return dummy.next
def winning_score(players, highest_marble): cdll = CircularDoublyLinkedList() current = Node(0) cdll.append(current) scores = defaultdict(int) for key in range(1, highest_marble + 1): # if key is a multiple of 23 if key % 23 == 0: scores[key % players] += key # we go 7 marbles counter-clockwise mb = current.prev.prev.prev.prev.prev.prev.prev scores[key % players] += mb.data # now remove mb from our LL current = mb.next cdll.remove(mb) else: # get the current marble mb = Node(key) # insert marble after marble after this one cdll.insert(current.next, mb) current = mb return max(list(scores.values()))
def test_simple_case_loop(self): head = Node(1, Node(2)) loop_node = Node(3, Node(4)) head.next.next = loop_node head.next.next.next.next = loop_node assert loop_detection(head) is loop_node
def merge(): # Takes every child in merge list, adds a new node with # these children as children to the new node inner = Node(node.str_length + 1, "inner") for cm in current_merg: inner.add_child(cm) children_list.append(inner)
def __init__(self, iterable=[]): """ attributes: length--> length of the doubly linked list head--> starting node of the doubly linked list """ self.head = None self.end = None self.length = 0 self.iter = None #Checking if argument is iterable or not try: iter(iterable) except TypeError: error.error_message( "TypeError", "__init__(): Argument passed is not an iterable. Empty DLL created" ) return for iterator in iterable: if isinstance(iterable, doublyLinkedList): iterator = iterator.data if self.length == 0: self.head = Node.Node(iterator) self.end = self.head else: self.end.next = Node.Node(iterator) self.end.next.prev = self.end self.end = self.end.next self.length += 1
def insert(self, ele, index=0): """ Inserts ele at specified index. Float value of index will be floored. If index is not specified, inserts at the head. Indexing starts from 0. Returns NoneType """ try: index = int(index) except ValueError: error.error_message( "ValueError", "insert(ele,index): Index should be of type int or float") return if self.head is None: self.head = Node.Node(ele) self.end = self.head self.length += 1 else: index = min(index, self.length) index = index + self.length if index < 0 else index index = max(0, index) node = Node.Node(ele) iter = self.head while index > 0: iter = iter.next index -= 1 self._insert_before_node(iter, node) return
def Astar(self): search = [] # Set current node to start and add start node to the node list and node search dictionary CurrentNode = Node(self.start, self.start, self.goal, self.stepSize) NodeList = [CurrentNode] NodeDict = {tuple(CurrentNode.env)} search.append(CurrentNode) # Check if the current node is the goal node while sqrt((CurrentNode.env[0] - self.goal[0]) ** 2 + (CurrentNode.env[1] - self.goal[1]) ** 2) > 1.5: # Keep checking if there are nodes in list if len(NodeList) > 0: # Set current node to the first node in the list and then delete from list CurrentNode = NodeList.pop() Course = Environment(CurrentNode.env, self.clearance) # Check all of the possible actions for action in Course.possibleMoves(self.start, CurrentNode, self.stepSize): # Search dictonary and add node to list and dictionary if it hasn't been explored yet if tuple((int(action.env[0]), int(action.env[1]), action.env[2])) not in NodeDict: NodeList.append(action) search.append(action) NodeDict.add(tuple((int(action.env[0]), int(action.env[1]), action.env[2]))) # Sort list of nodes based on cost NodeList.sort(key=lambda x: x.weight, reverse=True) else: return -1, CurrentNode.path(), search # solve for path x = CurrentNode.path() path = [] for node in x: path.append(node) return path, search
def p_int_literal(p): '''IntLiteral : INTEGER''' p[0] = Node() p[0].expr.value = p[1] p[0].expr.type = 'int' p[0].expr.is_constant = True p[0].place = str(p[0].expr.value)
def p_for(p): '''ForStmt : FOR ConditionBlockOpt Block''' p[0] = Node() if p[2] is not None: p[0].begin = [newLabel()] p[3].forclause.next[0] = p[0].next if p[2].forclause.isClause: cond = p[2].forclause.condition cond.expr.true_label[0] = newLabel() cond.expr.false_label[0] = p[0].next p[3].next[0] = p[0].begin # TODO TODO TODO check confirtm update_label = [newLabel()] p[3].forclause.begin[0] = update_label # p[3].next[0] = p[0].next p[3].begin[0] = p[0].begin p[0].code += p[2].forclause.initialise p[0].code += [[p[0].begin, ":"] ] + cond.code + [cond.expr.true_label[0] + ":"] p[0].code += p[3].code + [[ update_label, ":" ]] + p[2].forclause.update + [['goto: ', p[0].begin]] else: p[2].expr.true_label[0] = newLabel() p[2].expr.false_label[0] = p[0].next p[3].forclause.begin[0] = p[0].begin p[3].next[0] = p[0].begin # TODO TODO TODO check confirtm # p[3].next[0] = p[0].next p[3].begin[0] = p[0].begin p[0].code += [[p[0].begin, ":"]] + p[2].code + [ p[2].expr.true_label[0] + ":" ] + p[3].code + [['goto: ', p[0].begin]] p[0].next[0] = newLabel()
def greedy_best_first(board, heuristic): """ an implementation of the greedy best first search algorithm. it uses a heuristic function to find the quickest way to the destination :param board: (Board) the board you start at :param heuristic: (function) the heuristic function :return: (list) path to solution, (int) number of explored boards """ frontier = PriorityQueue() node = Node(board) frontier.add(node, heuristic(node.data)) explored = [] while frontier.has_next(): node = frontier.pop() if node.data.is_solved(): return node.path(), len(explored) + 1 for move in node.data.legal_moves(): child = Node(node.data.forecast(move), node) if (not frontier.has(child)) and (child.data not in explored): frontier.add(child, heuristic(child.data)) explored.append(node.data) return None, len(explored)
def best_first_graph_search(problem, f): """Пребарувај низ следбениците на даден проблем за да најдеш цел. Користи функција за евалуација за да се одлучи кој е сосед најмногу ветува и потоа да се истражи. Ако до дадена состојба стигнат два пата, употреби го најдобриот пат. :param problem: даден проблем :param f: дадена функција за евристика :return: Node or None """ f = memoize(f, 'f') node = Node(problem.initial) if problem.goal_test(node.state): return node frontier = PriorityQueue(min, f) frontier.append(node) explored = set() while frontier: node = frontier.pop() if problem.goal_test(node.state): return node explored.add(node.state) for child in node.expand(problem): if child.state not in explored and child not in frontier: frontier.append(child) elif child in frontier: incumbent = frontier[child] if f(child) < f(incumbent): del frontier[incumbent] frontier.append(child) return None
def p_rune_literal(p): '''RuneLiteral : RUNE''' p[0] = Node() p[0].expr.value = p[1] p[0].expr.type = 'rune' p[0].expr.is_constant = True p[0].place = str(p[0].expr.value)
def enqueue(self, item): if self._last: new = Node(item, None, self._last) self._last.next, self._last = new, new else: self._first = self._last = Node(item) self._size += 1
def p_string_literal(p): '''StringLiteral : STRING''' p[0] = Node() p[0].expr.value = p[1] p[0].expr.type = 'string' p[0].expr.is_constant = True p[0].place = str(p[0].expr.value)
def p_img_literal(p): '''ImgLiteral : IMAGINARY''' p[0] = Node() p[0].expr.value = p[1] p[0].expr.type = 'imaginary' p[0].expr.is_constant = True p[0].place = str(p[0].expr.value)
def p_float_literal(p): '''FloatLiteral : FLOAT''' p[0] = Node() p[0].expr.value = p[1] p[0].expr.type = 'float' p[0].expr.is_constant = True p[0].place = str(p[0].expr.value)
def createMinimal(self, l, left, right): if right < left: return None mid = int((left + right) / 2) node = Node(l[mid]) node.left = self.createMinimal(l, left, mid - 1) node.right = self.createMinimal(l, mid + 1, right) return node
def sum_lists2(head1, head2): head1, head2 = padding_zero(head1, head2) c, head = dfs_helper(head1, head2) if c: new_node = Node(c) new_node.next = head head = new_node return head
def test_get_descendants(self): """ Test that all descendants can be retrieved """ child = Node('test_get_descendants_child') grand_child = Node('test_get_descendants_grand_child') child.add_child(grand_child) self.root_node.add_child(child) result = self.root_node.get_descendants() assert (all(c in result for c in [child, grand_child]))
def _construct_dags(prev_nodes, activations, func_names, num_blocks): """Constructs a set of DAGs based on the actions, i.e., previous nodes and activation functions, sampled from the controller/policy pi. Args: prev_nodes: Previous node actions from the policy. activations: Activations sampled from the policy. func_names: Mapping from activation function names to functions. num_blocks: Number of blocks in the target RNN cell. Returns: A list of DAGs defined by the inputs. RNN cell DAGs are represented in the following way: 1. Each element (node) in a DAG is a list of `Node`s. 2. The `Node`s in the list dag[i] correspond to the subsequent nodes that take the output from node i as their own input. 3. dag[-1] is the node that takes input from x^{(t)} and h^{(t - 1)}. dag[-1] always feeds dag[0]. dag[-1] acts as if `w_xc`, `w_hc`, `w_xh` and `w_hh` are its weights. 4. dag[N - 1] is the node that produces the hidden state passed to the next timestep. dag[N - 1] is also always a leaf node, and therefore is always averaged with the other leaf nodes and fed to the output decoder. """ dags = [] for nodes, func_ids in zip(prev_nodes, activations): dag = collections.defaultdict(list) # add first node dag[-1] = [Node(0, func_names[func_ids[0]])] dag[-2] = [Node(0, func_names[func_ids[0]])] # add following nodes for jdx, (idx, func_id) in enumerate(zip(nodes, func_ids[1:])): dag[utils.to_item(idx)].append(Node(jdx + 1, func_names[func_id])) leaf_nodes = set(range(num_blocks)) - dag.keys() # merge with avg for idx in leaf_nodes: dag[idx] = [Node(num_blocks, 'avg')] # TODO(brendan): This is actually y^{(t)}. h^{(t)} is node N - 1 in # the graph, where N Is the number of nodes. I.e., h^{(t)} takes # only one other node as its input. # last h[t] node last_node = Node(num_blocks + 1, 'h[t]') dag[num_blocks] = [last_node] dags.append(dag) return dags
def __init__(self, version: float, send_queue: Queue, gui_queue: Queue) -> None: super(DDosChain, self).__init__(version, send_queue, gui_queue) self.tree = Node('Root') self.tree.add_child( Node( str("ab2a248087095ef9e84a900337fac41cf2d588e9017b345f1c90a4bb0844ed28" .encode('utf-8')))) self.blocked_ips: Dict[str, Node] = {}
def expand_node(node: Node, to_play: Player, actions: List[Action], network_output: NetworkOutput): node.to_play = to_play node.hidden_state = network_output.hidden_state node.reward = network_output.reward policy = {a: math.exp(network_output.policy_logits[a]) for a in actions} policy_sum = sum(policy.values()) for action, p in policy.items(): node.children[action] = Node(p / policy_sum)
def delete_middle_node(node: Node) -> None: """ Assumptions: Given a node that is not the first or last node. Purpose: Deletes given node. """ node.data = node.next.data node.next = node.next.next