def search(node, v, queue):
    global detect_bipartite
    for w in v.adj:
        if node[w].layer == None:
            node[w].layer = v.layer + 1
            queue.append(w)
        if node[w].layer !=  None and abs(v.layer - node[w].layer) % 2 == 0:
            detect_bipartite = 0
예제 #2
0
def next_fit(mem, plist):
    mem = list(mem)
    t = 0
    print("time " + str(t) + "ms: Simulator started (Contiguous -- Next-Fit)")
    done = 0
    count = 0
    queue = []
    for p in plist:
        count += p.times
    pos = 0
    while done < count:
        for p in plist:
            for time in p.depart:
                if t == time and p.id in queue:
                    remove(mem, p)
                    done += 1
                    queue.remove(p.id)
                    print("time " + str(t) + "ms: Process " + p.id +
                          " removed:")
                    printmem(mem)
        for p in plist:
            for time in p.arrival:
                if t == time:
                    print("time " + str(t) + "ms: Process " + p.id +
                          " arrived (requires " + str(p.size) + " frames)")
                    if (room(mem) < p.size):
                        print("time " + str(t) + "ms: Cannot place process " +
                              p.id + " -- skipped!")
                        done += 1
                    else:
                        pos = search_first_place(mem, p, pos)
                        if (pos == -1):
                            print("time " + str(t) +
                                  "ms: Cannot place process " + p.id +
                                  " -- starting defragmentation")
                            defrag_time, moved, movedlist = defragmentation(
                                mem)
                            update_time(plist, t, defrag_time)
                            t += defrag_time
                            print("time " + str(t) +
                                  "ms: Defragmentation complete (moved " +
                                  str(moved) + " frames: " +
                                  print_movedlist(movedlist) + ")")
                            printmem(mem)
                            pos = search_first_place(mem, p, pos)
                        queue.append(p.id)
                        add(mem, p, pos)
                        print("time " + str(t) + "ms: Placed process " + p.id +
                              ":")
                        pos += p.size
                        if (pos >= 256):
                            pos -= 256
                        printmem(mem)
        t += 1
    print("time " + str(t - 1) +
          "ms: Simulator ended (Contiguous -- Next-Fit)\n")
예제 #3
0
def create_map(goal, grid_map): #Because we start planning the path from the goal
    queue = [goal]
    while len(queue) != 0:
        cell = queue.pop(0)
        neighbors = generate_neighbouring_cells(cell, grid_map)
        for neighbor in neighbors:
            if(get_value(neighbor, grid_map) < 0 and get_value(neighbor, grid_map) != 1):
                grid_map[neighbor[0]][neighbor[1]] = get_value(cell, grid_map) + abs(get_value(neighbor,grid_map))
                queue.append(neighbor)
    return grid_map
예제 #4
0
    def bellman(self, source, target):
        previous = {}
        distance = {}
        queue = []
        visited = {}
        count = {}

        cost_dict = self.__cost

        # we initialize the dictionaries
        for node in self.V:
            distance[node] = math.inf
            previous[node] = None
            count[node] = 0
            # no node is visited at the beginning
            visited[node] = False

        # the distance is 0 at the beginning
        distance[source] = 0

        # push the source in the queue
        queue.append(source)

        # the source vertex is marked as visited
        visited[source] = True

        # while the queue is not empty
        while queue:
            vertex = queue[0]
            queue.pop(0)
            visited[vertex] = False  # the vertex is marked as not visited
            for child in self._outbound:  # search through all its neighbours
                if distance[child] > distance[vertex] + cost_dict[
                    (vertex, child)]:
                    distance[child] = distance[vertex] + cost_dict[
                        (vertex, child)]  # update the distance
                    previous[child] = vertex

                    if visited[child] is False:
                        visited[child] = True  # child is marked as true
                        count[child] += 1
                        queue.append(child)  # push the child in the queue

                        # if the number of vertices is greater than the maximum number of vertices,
                        # we have negative cost cycle
                        # if count[child] >= len(self.graph.get_out()):
                        #     print("Negative cost cycle!")
                        #     return None

        # returns a pair distance, path
        msg = "no path"
        if distance[target] == math.inf:
            print("no path")
            return msg
        return (distance[target], self.get_path(source, target, previous))
예제 #5
0
def bfs(url) -> set:
    queue = []
    queue.append(url)
    queue[url] = True
    while queue:
        social_links = find_social_links(url)
        if (len(social_links) > 0):
            return social_links
        else:
            response = requests.get(url)
            links = page_links(response)
def distance(adj, s, t):
    dist = [-1] * (len(adj))
    queue = [s]
    dist[s] = 0
    while queue:
        cur = queue.pop(0)
        for vertex in adj[cur]:
            if dist[vertex] == -1:
                queue.append(vertex)
                dist[vertex] = dist[cur] + 1
    return dist[t]
예제 #7
0
 def getBFSearch(self):
     nodes = []
     queue = [self]
     while queue:
         cur_node = queue[0]
         queue = queue[1:]
         if cur_node.data is not None:
             nodes.append((cur_node.data.mcopy(), cur_node.support))
         for child in cur_node.children:
             queue.append(child)
     return nodes
예제 #8
0
def dfs():
    station_check = True
    start_complete = False
    end_complete = False

    while station_check == True:
        start_station = input('Enter Your Start Station\n')
        end_station = input('Enter Your End Station\n')
        start_station = start_station.lower()
        end_station = end_station.lower()

        if start_station == 'q':
            quit()
        for key in stations:
            if start_station == stations[key].lower():
                start_station_key = key
                start_complete = True

            if end_station == stations[key].lower():
                target = key
                end_complete = True

        if (start_complete == True) and (end_complete == True):
            break

        if station_check == True:
            print('Station(s) Not Found - Enter Start Station Again')

    visited = []
    t_visited = []
    queue = []
    t_queue = []
    queue.append(start_station_key)

    target_reached = False

    while target_reached != True:
        search_station = queue.pop(-1)

        visited.append(search_station)
        t_visited.append(stations[search_station])

        if search_station == target:
            print(stations[target], 'has been reached')
            target_reached = True
            break

        for value in connections[search_station]:
            if value not in visited and value not in queue:
                queue.append(value)
                try:
                    t_queue.append(stations[value])
                except:
                    pass
예제 #9
0
 async def add_to_queue(self, ctx, source):
     """Plays the specified source"""
     if ctx.voice_client is None:
         if ctx.author.voice:
             await ctx.author.voice.channel.connect()
         else:
             raise RuntimeError("Author not connected to a voice channel")
     info = self.get_info(ctx)
     queue = info["queue"]
     queue.append({"ty": "raw", "query": source})
     if info["current"] is None:
         self.schedule(ctx)
예제 #10
0
 def bfs(self, myGraph, start, end):
     queue = [(start, [start])]
     while queue:
         (vertex, path) = queue.pop(0)
         try:
             for next in myGraph[vertex]:
                 if next[0] == end:
                     return path + [next]
                 else:
                     queue.append((next, path + [next]))
         except KeyError:
             continue
예제 #11
0
 def run_bfs():
     queue = deque([])
     queue.append(s)
     distances[s] = 0
     while (len(queue) > 0):
         current = queue.popleft()
         for neighbor in adj[current]:
             if distances[neighbor] == -1:
                 queue.append(neighbor)
                 distances[neighbor] = distances[current] + 1
                 if neighbor == t:
                     return
예제 #12
0
파일: Search.py 프로젝트: TBry13/AIProject1
 def bfs (self, myGraph, start, end):
     queue = [(start, [start])]
     while queue:
         (vertex, path) = queue.pop(0)
         try: 
             for next in myGraph[vertex]:
                 if next[0] == end:
                     return path + [next]
                 else:
                     queue.append((next, path +[next]))
         except KeyError:
             continue
예제 #13
0
def bfs(graph,start,end):
    queue = [(start,[start])]
    result = []

    while queue:
        n, path = queue.pop(0)
        if n == end:
            result.queue(path)
        else:
            for m in graph[n] -set(path):
                queue.append((m,path+[m]))
    return result
예제 #14
0
def bfs(g,N):

visited=[False]*N
queue=[]
queue.append(0)
visited[0]=True
while queue:
    s=queue.pop(0)
    print(s,end=" ")
    for i in g[s]:
        if visited[i]==False:
            queue.append(i)
            visited[i]=True
예제 #15
0
파일: bfs.py 프로젝트: fagan2888/review
def distance(adj, s, t):
    #write your code here
    queue = []
    dist = [-1] * len(adj)
    dist[s] = 0
    queue.append(s)
    while len(queue) > 0:
        curr = queue.pop(0)
        for nbrs in adj[curr]:
            if dist[nbrs] == -1:
                dist[nbrs] = dist[curr] + 1
                queue.append(nbrs)
    return dist[t]
def bipartite(adj):
    colors = [-1] * len(adj)
    colors[0] = 0
    queue = [0]
    while queue:
        u = queue.pop(0)
        for v in adj[u]:
            if colors[v] == -1:
                colors[v] = 1 - colors[u]
                queue.append(v)
            elif colors[v] == colors[u]:
                return 0
    return 1
예제 #17
0
 def bfs(self, begin, end):
     queue = [(begin, [begin])]
     while queue:
         (v, path) = queue.pop(0)
         here = [x for x in self.graph[v] if x not in path]
         for nxt in here:
             if nxt == end:
                 if len(path) > self.distance:
                     self.distance = len(path)
                 return path
             else:
                 queue.append((nxt, path + [nxt]))
     return []
예제 #18
0
def BFS(graph, start):
    visited = []  # this contains all visited vertices
    queue = [start]  # what we want to search for

    while queue:
        node = queue.pop(0)  # initial starting point
        if node not in visited:
            visited.append(node)
            neighbours = graph[
                node]  # finding the neigbours of the initial node
            for neighbour in neighbours:
                queue.append(neighbour)
    return visited
예제 #19
0
 def run(self):
     while True:
         if con.acquire():
             if len(queue) > 10:
                 con.wait()
             else:
                 elem = random.randrange(100)
                 queue.append(elem)
                 print("Producer a elem {}, Now size is {}".format(
                     elem, len(queue)))
                 time.sleep(random.random())
                 con.notify()
             con.release()
예제 #20
0
    def bfs_undirect(self, graph, root):
        visited = [root]
        queue = [root]

        while queue:
            looking_vertex = queue.pop(0)
            vertex_neighbours = sorted(graph[looking_vertex])
            #print('current vertex: ', looking_vertex, ' and its neighbours: ', vertex_neighbours)
            for neighbour in vertex_neighbours:
                if neighbour not in visited:
                    queue.append(neighbour)
                    visited.append(neighbour)
        print('->'.join(visited))
예제 #21
0
 def on_message(self, ws, message):
     parsed_message = json.loads(message)
     message_type = parsed_message.get('method', 'unknown')
     if message_type not in self.messages:
         self.messages[message_type] = []
     queue = self.messages[message_type]
     if len(queue) == self.max_size:
         queue.pop(0)
     queue.append(parsed_message)
     try:
         self.handle_messages(parsed_message)
     except Exception as e:
         logger.exception(e)
예제 #22
0
 async def play_os(self, ctx, *, url):
     """Plays an Online Sequencer sequence"""
     if len(url) > 100:
         raise ValueError("url too long (length over 100)")
     if not url.isprintable():
         raise ValueError(f"url not printable: {url!r}")
     print(ctx.message.author.name, "queued", repr(url))
     info = self.get_info(ctx)
     queue = info["queue"]
     queue.append({"ty": "os", "query": url})
     if info["current"] is None:
         self.schedule(ctx)
     await ctx.send(f"Added to queue: os {url}")
예제 #23
0
def distance(adj, s, t):
    n = len(adj)
    dist = [n] * n
    dist[s] = 0
    queue = []
    queue.append(s)
    while queue:
        v = queue.pop(0)
        for u in adj[v]:
            if dist[u] == n:
                queue.append(u)
                dist[u] = dist[v] + 1
    return -1 if dist[t] == n else dist[t]
예제 #24
0
파일: utils.py 프로젝트: SNWK/DivideTree
def bfs_distance(start, adj_list, is_dense=False):
    distances = {}
    visited = set()
    queue = deque([(start, 0)])
    visited.add(start)
    while len(queue) != 0:
        current, d = queue.popleft()
        for neighbor, edge_type in adj_list[current]:
            if neighbor not in visited:
                distances[neighbor] = d + 1
                visited.add(neighbor)
                queue.append((neighbor, d + 1))
    return [(start, node, d) for node, d in distances.items()]
def distance(adj, s, t):
    dist = [len(adj)] * len(adj)
    dist[s] = 0
    queue = [s]
    while queue:
        u = queue.pop(0)
        for v in adj[u]:
            if dist[v] == len(adj):
                queue.append(v)
                dist[v] = dist[u] + 1
    if dist[t] != len(adj):
        return dist[t]
    return -1
예제 #26
0
def MinString(DFA, startstate, labels):
    queue = []

    # array of indexes, 0 = not discovered, 1 = discovered.
    discovered = [0] * len(DFA)
    discovered[startstate] = 1

    #index of parent node
    parent = [0] * len(DFA)

    #number of node
    label = [""] * len(DFA)

    queue.append(startstate)

    next = 0
    found = 0
    while (len(queue) != 0 and found == 0):
        curr = queue.pop(0)
        count = 0
        for transition in DFA[curr]:

            next = transition
            if next == -1:

                continue

            if next == 0:
                parent[next] = curr
                label[next] = str(labels[count])
                found = 1
                break
            elif discovered[next] == 0:
                discovered[next] = 1
                parent[next] = curr

                queue.append(next)
                label[next] = str(labels[count])
                #What does this do? its in the pseudocode

            count += 1

    if (next != 0):
        print("no valid solution")
        return parent
    else:
        output = ""
        while (next != len(DFA) - 1):
            output += label[next]
            next = parent[next]
        print(''.join(reversed(output)))
예제 #27
0
    def runnerbfs(self, agent_pos, c_map, c_agent_list):
        # Keep track of each coordinate the agent looks at
        visited = []

        # Keep track of the order we see coordinates so we can iterate through them
        queue = []
        path_map = {}

        # Go through the list of agents and find where this agent is located on the map
        current_pos = (agent_pos[0], agent_pos[1])

        for agent in self.agent_list:
            pos_form = agent.getPos()
            if (pos_form[0] == current_pos[0]) and (pos_form[1]
                                                    == current_pos[1]):
                current_agent = agent

        path_map[(current_pos, 0)] = 'END'

        # Add the agents current position to the list of visited and directions
        visited.append(current_pos)
        queue.append((current_pos, 0))

        while queue:
            # Grab the next coordinate in the queue
            current_pos = queue.pop(0)

            # Returns all moves that are immediately possible for the current position
            possible_moves = self.c_map.get_next(current_pos[0])

            # Iterate through each move possible
            for move, direction in possible_moves:
                # Check if move is a goal state and if it is, then return list of
                # instructions
                if current_agent.isGoal(move):
                    #print('GOAL')
                    # Go through path map and create a list of instructions
                    path_map[(move, direction)] = (current_pos)
                    com = path_map[current_pos]
                    return_list = [(move, direction)]
                    while com is not 'END':
                        return_list.append(com)
                        com = path_map[com]
                    return_list.reverse()
                    return return_list

                # If not goal state, then add to list of visited states, and continue looking
                elif move not in visited:
                    path_map[(move, direction)] = (current_pos)
                    visited.append(move)
                    queue.append((move, direction))
예제 #28
0
def bfs_search(root_node, search_value):
    visited = []
    queue = [root_node]

    while len(queue) > 0:
        current_node = queue.pop(0)
        queue.append(current_node)

        if current_node.value == search_value:
            return current_node

        for child in current_node.children:
            if child not in visited:
                queue.append(child)
예제 #29
0
 def bfs_traverse(self, start):
     queue = [start]
     res = []
     while queue:
         v_node = queue.pop(0)
         if not v_node.get_visited():
             v_node.set_visited()
             res.append(v_node.get_vertex_val())
             v_node_idx = self.get_vertex_idx(v_node.get_vertex_val())
             for target_idx in range(0, self.num_vertex):
                 if self.adj_matrix[v_node_idx][
                         target_idx] != -1 and v_node_idx != target_idx:
                     queue.append(self.get_vertex(target_idx))
     return res
예제 #30
0
def bfs_connected_component(graph,
                            start):  ##Method which returns States Expanded
    explored = []
    queue = [start]
    visited = [start]
    while queue:
        node = queue.pop(0)
        explored.append(node)
        neighbours = graph[node]
        for i in neighbours:
            if i not in visited:
                queue.append(i)
                visited.append(i)
    return explored
예제 #31
0
def buildTree(nums: list):
    head = TreeNode(nums.pop(0))
    queue = [head]
    while nums:
        v = queue.pop(0)
        l = nums.pop(0)
        r = nums.pop(0)
        if l:
            v.left = TreeNode(l)
            queue.append(v.left)
        if r:
            v.right = TreeNode(r)
            queue.append(v.right)
    return head
예제 #32
0
 async def stream(self, ctx, *, url):
     """Plays from a url (almost anything youtube_dl supports)"""
     if len(url) > 100:
         raise ValueError("url too long (length over 100)")
     if not url.isprintable():
         raise ValueError(f"url not printable: {url!r}")
     print(ctx.message.author.name, "queued", repr(url))
     info = self.get_info(ctx)
     queue = info["queue"]
     ty = "local" if url == "coco.mp4" else "stream"
     queue.append({"ty": ty, "query": url})
     if info["current"] is None:
         self.schedule(ctx)
     await ctx.send(f"Added to queue: {ty} {url}")
def distance(adj, s, t):
    queue = []
    distance = {k:-1 for k in range(0, len(adj))}

    #make s initial node
    distance[s] = 0
    queue.append(s)
    while len(queue):
        v = queue.pop(0)
        for edge in adj[v]:
            if distance[edge] == -1:
                distance[edge] = distance[v] + 1
                queue.append(edge)
                if edge == t:
                    return distance[edge]
    return -1
예제 #34
0
def bfs(graph, startnode, endnode):

    queue = []
    queue.append([startnode])
    while queue:

        path = queue.pop(0)

        node = path[-1]

        if node == endnode:
            return path
        for adjacent in graph.get(node, []):
            new_path = list(path)
            new_path.append(adjacent)
            queue.append(new_path)
예제 #35
0
def levelOrderWithLevel1(root):
    # Single queue with flags
    if root == None:
        return []
    result = []
    queue = [root]
    cur = 0
    end = 1
    while cur < len(queue):
        partialResult = []
        while cur < end:
            partialResult.append(queue[cur])
            if queue[cur].left != None:
                queue.append(queue[cur].left)
            if queue[cur].right != None:
                queue.append(queue[cur].right)
            cur += 1
        result.append(partialResult)
        end = len(queue)
    result.reverse()
	def buildSiteMapData(self) :
		# if the current project's URL state variables are not set, do so
		if (len(self.known_urls) == 0) :
			self.setCrawlVariables(True)

		# if the queue isn't empty, then this project hasn't been fully crawled
		# so bail out
		if (len(self.url_queue) != 0) :
			self.gui.showErrorMsgBox(title="Operation Failed", message="The currently opened project hasn't been completely crawled.\n\nPlease do so before generating a site map.")
			return

		# local variable used by the crawlers to control access to the queue
		queue_lock = threading.Lock()
		# local list variable used as the queue, built from the known_urls set
		queue = []
		for item in self.known_urls :
			queue.append(item)
		# sort the queue by URL asc
		queue.sort(key=str.lower, reverse=True)

		# reset the instance variable with the site map data
		self.site_map_items = []
		# reset the instance variable with the site map data's sorting
		# in the form [[col_alias, True/False], [col_alias, True/False]]
		# the default is to sort by url asc
		self.site_map_items_sorting = [["url", False]]

		# local variable used to store all the crawler objects created
		threads = []

		# local variable with the current system date as YYYY-MM-DD
		local_time_aux = time.localtime()
		local_time_str = "{0}-{1}-{2}".format(str(local_time_aux.tm_year), str(local_time_aux.tm_mon).zfill(2), str(local_time_aux.tm_mday).zfill(2))

		# disable all task buttons in the GUI
		self.gui.setTaskButtons("disable_all")
		# execute GUI changes for a building site map task
		self.gui.manageTaskSiteMapInputElems("working")
		# clear any site map data already drawn to the screen
		self.gui.redrawSiteMapItems(None)

		# set the MapGenerator's class variables, to keep all instances in sync
		MapGenerator.MapGenerator.terminate_thread_ = False
		MapGenerator.MapGenerator.queue_ = queue
		MapGenerator.MapGenerator.queue_lock_ = queue_lock
		MapGenerator.MapGenerator.root_url_ = self.root_url
		MapGenerator.MapGenerator.local_time_ = local_time_str
		MapGenerator.MapGenerator.site_map_items_ = self.site_map_items

		# local variables used to control the periodic update of the GUI with
		# the site map items
		last_time_call = time.monotonic()
		gui_update_cooldown = self.GUI_UPDATE_SECONDS_

		# grab the # of threads the user wants to have created
		self.getNumThreads()
		# get from the GUI class the use/nouse of robots.txt file value
		use_robots_file = self.gui.getRobotsUse()

		# instantiate each MapGenerator thread, start it and store the object reference
		for _ in range(self.num_threads) :
			thread = MapGenerator.MapGenerator(use_robots_file)
			thread.start()
			threads.append(thread)

		# loop until all items have been processed
		# (checked after updating UI to make sure it updates with last items processed)
		while True :
			# update the gui update timers
			gui_update_cooldown -= time.monotonic() - last_time_call
			last_time_call = time.monotonic()
			# check if it's time to update the GUI
			if (gui_update_cooldown <= 0) :
				# send the call for the GUI to update the site map items on the screen
				self.gui.updateSiteMapItems(self.site_map_items)

				# reset the gui update cooldown
				gui_update_cooldown = self.GUI_UPDATE_SECONDS_

			# check if all processing is done
			if (len(self.known_urls) == len(self.site_map_items)) :
				# all done
				# send the call for the GUI to update the site map items on the screen
				self.gui.updateSiteMapItems(self.site_map_items)

				# exit loop
				break

			# wait 1 second before checking again
			time.sleep(1)

		# signal all instances of MapGenerator to terminate
		MapGenerator.MapGenerator.terminate_thread_ = True

		# wait for all the MapGenerator instances to terminate
		for t in threads:
			t.join()

		# update the arrows in the table header of the GUI
		self.gui.updateSortArrows()

		# activate all task buttons in the GUI
		self.gui.setTaskButtons("activate_all")
		# execute GUI changes for a completed site map task
		self.gui.manageTaskSiteMapInputElems("continued")

		# show message to user to indicate that the process is complete
		self.gui.showInfoMsgBox(message="The list of webpages for this project has been compiled.\n\nThe values for \"last modified\", \"change frequency\" and \"priority\" have been given default values, based on the best guess of the application.\n\nYou should confirm and, if necessary, change them before requesting the creation of the Site Map file.", title="Operation Completed")
def search(node, v, queue):
    for w in v.adj:
        if node[w].layer == None:
            node[w].layer = v.layer + 1
            queue.append(w)