def test_Queue_NonThreadSafe(self):
        queue = deque()
        queue.append('a')
        queue.append('b')
        queue.append('c')

        print(queue.popleft())
        print(queue.popleft())
        print(queue.popleft())
Beispiel #2
0
 def wrapper_method(*args, **kwargs):
     func(*args, **kwargs)
     queue = args[1]
     message = args[0]
     if len(queue) <= 4:
         queue.append(message)
     else:
         queue.popleft()
         queue.append(message)
Beispiel #3
0
    def level_order_successor(self, root, key):
        if root is None:
            return None
        queue = deque([])
        queue.append(self.root)
        while len(queue) != 0:
            current_node = queue.popleft()

            if current_node.left is not None:
                queue.append(current_node.left)
            if current_node.right is not None:
                queue.append(current_node.right)
            if current_node.data == key:
                break
        return queue.popleft().data
Beispiel #4
0
    def findCheapestPrice(self, n, flights, src, dst, K):
        """
        :type n: int
        :type flights: List[List[int]]
        :type src: int
        :type dst: int
        :type K: int
        :rtype: int
        """
        min_cost = sys.maxsize

        graph = collections.defaultdict(list)
        for u, v, cost in flights:
            graph[u].append((v, cost))
        queue = collections.deque([(src, 0, 0)])

        while queue:
            node, stops, cost = queue.popleft()
            if node == dst:
                min_cost = min(min_cost, cost)

            if stops <= K:
                for child, price in graph[node]:
                    if cost + price < min_cost:
                        queue.append((child, stops + 1, cost + price))

        return min_cost if min_cost != sys.maxsize else -1
Beispiel #5
0
def bfs(maze):
    num_states_explored = 0
    start_position = maze.getStart()
    end_position = maze.getObjectives()
    visited, queue = [], collections.deque([start_position])
    parent_map = {start_position: start_position}
    not_found = True
    while queue and not_found:
        num_states_explored += 1
        vertex = queue.popleft()
        visited.append((vertex[0], vertex[1]))
        if (vertex[0], vertex[1]) == end_position[0]:
            not_found = False
            break
        for neighbour in maze.getNeighbors(vertex[0], vertex[1]):
            if neighbour not in queue and neighbour not in visited:
                queue.append(neighbour)
                parent_map[neighbour] = (vertex[0], vertex[1])

    parent_list = []
    current = end_position[0]
    while current != start_position:
        parent_list.append(current)
        current = parent_map[current]
    parent_list.append(current)
    parent_list.reverse()
    return parent_list, num_states_explored
    def binaryTreeToLists(self, root):
        result = []
        if root is None: return result

        import collections
        queue = collections.deque()
        queue.append(root)

        dummy = ListNode(0)

        while queue:
            p = dummy
            size = len(queue)
            for i in range(size):
                head = queue.popleft()
                p.next = ListNode(head.val)
                p = p.next

                if head.left is not None:
                    queue.append(head.left)
                if head.right is not None:
                    queue.append(head.right)

            result.append(dummy.next)

        return result
Beispiel #7
0
def level_order_null_delim(root):
    if root is None:
        return

    queue = deque([root])
    queue.append(None)

    #or queue = deque([root, None])

    while len(queue) > 0:
        current = queue.popleft()

        if current is not None:
            visit_node(current)

            if current.left is not None:
                queue.append(current.left)

            if current.right is not None:
                queue.append(current.right)
        else:
            if len(queue) != 0:
                queue.append(None)

            # Any operation that needs to be done at level end
            print('Level end')
Beispiel #8
0
def all_positions(monster_pos, level_data, monster_type, other_monsters):
	positions = []
	queue = deque([monster_pos])
	visited = [monster_pos]

	while queue:
		v = queue.popleft()
		if(v[0] < len(level_data) - 1 and level_data[v[0] + 1][v[1]] == monster_type and [v[0] + 1, v[1]] not in visited and [v[0] + 1, v[1]] not in other_monsters):
			queue.append([v[0] + 1, v[1]])
			visited.append([v[0] + 1, v[1]])
			positions.append([v[0] + 1, v[1]])
		
		if(v[0] > 0 and level_data[v[0] - 1][v[1]] == monster_type and [v[0] - 1, v[1]] and [v[0] - 1, v[1]] not in visited):
			queue.append([v[0] - 1, v[1]])
			visited.append([v[0] - 1, v[1]])
			positions.append([v[0] - 1, v[1]])

		
		if(v[1] < len(level_data[0]) - 1 and level_data[v[0]][v[1] + 1] == monster_type and [v[0], v[1]+1] not in visited and [v[0], v[1]+1] not in other_monsters):
			queue.append([v[0], v[1]+1])
			visited.append([v[0], v[1] + 1])
			positions.append([v[0], v[1] + 1])

		
		if(v[1] > 0 and level_data[v[0]][v[1] - 1] == monster_type and [v[0], v[1] - 1] not in visited and [v[0], v[1]-1]not in other_monsters):
			queue.append([v[0], v[1]-1])
			visited.append([v[0], v[1]-1])
			positions.append([v[0], v[1] - 1])
	positions.append(monster_pos)
	return positions
Beispiel #9
0
    def bfs(self):
        """
        Do BFS
        :return: Answer and total cost. Empty list and 0 for no solution
        """
        visited = set()
        queue = deque()
        parent = {}

        # If entrance/goal grid not in graph, I should return FAIL
        if self.start_grid not in self.graph or self.goal_grid not in self.graph:
            return [], 0  # Empty list means FAIL

        queue.append(self.start_grid)
        visited.add(self.start_grid)
        while queue:
            s = queue.popleft()
            # Goal test
            if s == self.goal_grid:
                path = self.backtrack(parent)
                result_cost, total_cost = self.compute_cost(path)
                return result_cost, total_cost

            for t in self.graph[s]:
                if t not in visited:
                    queue.append(t)
                    visited.add(t)
                    parent[t] = s

        return [], 0
Beispiel #10
0
 def ladderLength(self, start, end, dict1):
  # write your code here
     def isOneDiff(a,b):
         if len(a)!=len(b): return False
         k = 0
         for i in range(len(a)):
             if a[i]!=b[i]:
                 k +=1 
                 if k>1: return False
         return k == 1
     if start == end: return 1
     if len(dict1) == 0 or len(start)!=len(end): return 0
     
     
     queue = collections.deque()
     queue.append(start)
     
     reached = set()
     level = 2
     while queue:
         p = collections.deque()
         while queue:
             fromstr = queue.popleft()
             if isOneDiff(fromstr,end): return level
             for d in dict1:
                 if (d not in reached) and isOneDiff(d,fromstr):
                     p.append(d)
                     reached.add(d)
         level+=1 
         queue = p
Beispiel #11
0
 def minCutTimeout(self, s):
     if s == None or len(s)==0 :return -1
     if len(s)==1 : return 0
     def isPalindrome(s,start,end):
         while start<=end:
             if s[start] != s[end]:
                 return False
             start += 1 
             end -= 1
         return True
     # write your code here
     biggestp = collections.defaultdict(list)
     for i in range(len(s)):
         for k in range(i,len(s)):
             if isPalindrome(s,i,k):
                 biggestp[i].append(k+1)
     print(biggestp)
     queue = collections.deque()
     queue.append(0)
     level = 0
     jumped = set()
     while queue:
         nextq = collections.deque()
         while queue:
             node = queue.popleft()
             for n in biggestp[node]:
                 if n == len(s): return level
                 if not n in jumped:
                     nextq.append(n)
                     jumped.add(n)
         queue = nextq
         level += 1
     return level
Beispiel #12
0
 def canFinish(self, numCourses, prerequisites):
     if not prerequisites and numCourses>=0:
         return True
     # write your code here
     depends = {}
     for i in range(numCourses):
         depends[i] = set()
     for course, precourse in prerequisites:
         depends.setdefault(course, set()).add(precourse)
         
     
     queue = collections.deque()
     for course, precourses in depends.items():
         if len(precourses) == 0:
             queue.append(course)
     
     processedcnt = 0
     while queue:
         #print(queue)
         nodevalue = queue.popleft()
         processedcnt += 1
         for course, precourses in depends.items():
             if nodevalue in precourses:
                 precourses.remove(nodevalue)
                 if len(precourses) == 0:
                     queue.append(course)
     #print(processedcnt)
     return numCourses == processedcnt
Beispiel #13
0
def ladder_length(beginWord, endWord, wordList):
    if endWord not in wordList or not endWord or not beginWord or not wordList:
        return 0

    L = len(beginWord)

    all_combo_dict = defaultdict(list)
    for word in wordList:
        for i in range(L):
            all_combo_dict[word[:i] + "*" + word[i + 1:]].append(word)

    # Queue for BFS
    queue = collections.deque([(beginWord, 1)])
    # Visited to make sure we don't repeat processing same word.
    visited = {beginWord: True}
    while queue:
        current_word, level = queue.popleft()
        for i in range(L):
            # Intermediate words for current word
            intermediate_word = current_word[:i] + "*" + current_word[i + 1:]

            # Next states are all the words which share the same intermediate state.
            for word in all_combo_dict[intermediate_word]:
                # If at any point if we find what we are looking for
                # i.e. the end word - we can return with the answer.
                if word == endWord:
                    return level + 1
                # Otherwise, add it to the BFS Queue. Also mark it visited
                if word not in visited:
                    visited[word] = True
                    queue.append((word, level + 1))

            all_combo_dict[intermediate_word] = []
    return 0
Beispiel #14
0
    def snakesAndLadders(self, board):
        """
        :type board: List[List[int]]
        :rtype: int
        """
        queue = collections.deque([(1, 0)])
        vis = set([1])
        n = len(board)

        while queue:
            cell, moves = queue.popleft()

            if cell == n * n:
                return moves

            for d in range(1, 7):
                next_cell = cell + d

                if next_cell <= n * n:
                    i, j = self.get_coord(next_cell, board)
                    if board[i][j] != -1:
                        next_cell = board[i][j]
                    if next_cell not in vis:
                        vis.add(next_cell)
                        queue.append((next_cell, moves + 1))

        return -1
Beispiel #15
0
    def distanceK(self, root, target, K):
        """
        :type root: TreeNode
        :type target: TreeNode
        :type K: int
        :rtype: List[int]
        """
        res = []

        graph = collections.defaultdict(set)
        self.build_graph(root, graph)

        queue = collections.deque([(target.val, 0)])
        vis = set([target.val])

        while queue:
            curr_node, moves = queue.popleft()

            if moves == K:
                res.append(curr_node)

            for node in graph[curr_node]:
                if node not in vis and moves < K:
                    queue.append((node, moves + 1))
                    vis.add(node)

        return res
Beispiel #16
0
    def updateBoard(self, board, click):
        """
        :type board: List[List[str]]
        :type click: List[int]
        :rtype: List[List[str]]
        """
        if board[click[0]][click[1]] == "M":
            board[click[0]][click[1]] = "X"
            return board

        queue = collections.deque([(click[0], click[1])])
        while queue:
            i, j = queue.popleft()

            if 0 <= i < len(board) and 0 <= j < len(board[0]) and\
            board[i][j] == "E":

                num_mines = self.get_mines(i, j, board)
                if num_mines > 0:
                    board[i][j] = str(num_mines)
                    continue

                board[i][j] = "B"
                for r, c in ((i - 1, j - 1), (i - 1, j), (i - 1, j + 1),
                             (i, j - 1), (i, j + 1), (i + 1, j - 1),
                             (i + 1, j), (i + 1, j + 1)):
                    queue.append((r, c))

        return board
Beispiel #17
0
 def bfs(self, start):
     queue, enqueued = deque([(None, start)]), set([start])
     while queue:
         parent, n = queue.popleft()
         yield parent, n
         new = set(self.parseOutboundNeighbours(n)) - enqueued
         enqueued |= new
         queue.extend([(n, child) for child in new])
Beispiel #18
0
def BFS(graph, start):
    visited, queue = [start], collections.deque([start])
    while queue:
        vertex = queue.popleft()
        for ConnectedVertex in graph[vertex]:
            if ConnectedVertex not in visited:
                visited.append(ConnectedVertex)
                queue.append(ConnectedVertex)
    return visited
    def test_Stack_NonThreadSafe(self):
        stack = deque()
        stack.append('a')
        stack.append('b')
        stack.append('c')

        # dequeue from right
        print(stack.pop())
        print(stack.pop())
        print(stack.pop())

        queue = deque()
        queue.append('a')
        queue.append('b')
        queue.append('c')

        # dequeue from left
        print(queue.popleft())
        print(queue.popleft())
        print(queue.popleft())
Beispiel #20
0
 async def shuffle(self, ctx):
     """Shuffles the queue"""
     info = self.get_info(ctx)
     queue = info["queue"]
     temp = []
     while queue:
         temp.append(queue.popleft())
     random.shuffle(temp)
     while temp:
         queue.appendleft(temp.pop())
     await ctx.send("Queue shuffled")
Beispiel #21
0
    def get_data_to_push(self, node, successor):
        queue = self.queues[self.get_key(node, successor)]

        if node._state != node.STATE_CLOSED:
            size = successor.batch_size
        else:
            size = len(queue)

        if len(queue) >= size:
            return [queue.popleft() for x in range(size)]

        return None
    def print_tree(self):
        import queue
        temp = self.head
        if not temp: return
        queue = queue.deque()
        queue.append(temp)

        while queue:
            p = queue.popleft()
            print(p.val)
            if p.left: queue.append(p.left)
            if p.right: queue.append(p.right)
Beispiel #23
0
 async def remove(self, ctx, position: int):
     """Removes a song on queue"""
     info = self.get_info(ctx)
     queue = info["queue"]
     try:
         index = self.normalize_index(ctx, position, len(queue))
     except ValueError:
         raise commands.CommandError(f"Index out of range [{position}]")
     queue.rotate(-index)
     song = queue.popleft()
     queue.rotate(index)
     await ctx.send(f"Removed song [{position}]: {song['query']}")
 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
Beispiel #25
0
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 maxDepth(self, root: TreeNode) -> int:
     if root == None:
         return 0
     queue = collections.deque()  #双端队列
     queue.append(root)
     ans = 0
     while queue:
         ans += 1
         for i in range(len(queue)):
             node = queue.popleft()
             if node.left:
                 queue.append(node.left)
             if node.right:
                 queue.append(node.right)
     return ans
Beispiel #27
0
def level_order(root):
    if root is None:
        return
    
    queue = deque([root])

    while len(queue) > 0:
        current = queue.popleft()
        visit_node(current)

        if current.left is not None:
            queue.append(current.left)

        if current.right is not None:
            queue.append(current.right)
Beispiel #28
0
def BFS(graph, start):
    visited, queue = [start], collections.deque([start])
    distance = 1
    DisDict = []

    while queue:
        vertex = queue.popleft()
        for ConnectedVertex in graph[vertex]:
            if ConnectedVertex not in visited:
                visited.append(ConnectedVertex)
                queue.append(ConnectedVertex)
                d_ConnectedVertex = distance
                DisList.append(distance)
        distance += 1

    return max(DisList)
def isBipartite(n, adj):
    dist = [float('inf')] * (n + 1)
    queue = deque()
    queue.append(1)
    dist[1] = 0
    while queue:
        now = queue.popleft()
        for v in adj[now]:
            if dist[v] == float('inf'):
                queue.append(v)
                dist[v] = dist[now] + 1
            else:
                if (dist[now] - dist[v]) % 2 == 0:
                    # same color vertices
                    return 0
    return 1
Beispiel #30
0
 def ladderLength(self, beginWord: str, endWord: str,
                  wordList: List[str]) -> int:
     wordset = set(wordList)
     queue = deque()
     queue.append((beginWord, 1))
     word_length = len(beginWord)
     while queue:
         word, step = queue.popleft()
         if word == endWord: return step
         for i in range(word_length):
             for c in "abcdefghijklmnopqrstuvwxyz":
                 newWord = word[:i] + c + word[i + 1:]
                 if newWord in wordset:
                     wordset.remove(newWord)
                     queue.append((newWord, step + 1))
     return 0