Exemplo n.º 1
0
def maxSlidingWindow3(nums: List[int], k: int) -> List[int]:
    '''
    法三
    :param nums:
    :param k:
    :return:
    '''
    from collections import deque
    # deque 是一个单调递减的队列,队首元素始终是当前窗口的最大值
    if not nums or k == 0: return []
    deque = deque()
    res = []
    n = len(nums)
    # 窗口未形成前
    for i in range(k):
        while deque and nums[i] >= deque[-1]:
            deque.pop()
        deque.append(nums[i])
    res.append(deque[0])

    # 窗口形成后
    for i in range(k, n):
        if deque[0] == nums[i - k]:
            deque.popleft()
        while deque and nums[i] >= deque[-1]:
            deque.pop()
        deque.append(nums[i])
        res.append(deque[0])
    return res
 def maxSlidingWindow(self, nums, k):
     # write your code here
     from collections import deque
     
     if k == 0 or len(nums) < k:
         return []
         
     res = []
     deque = deque([])
     
     for i in range(k):
         while deque and nums[i] > nums[deque[-1]]:
             deque.pop()
         deque.append(i)
             
     for i in range(k, len(nums)):
         res.append(nums[deque[0]])
         if i - deque[0] == k: 
             deque.popleft()
         while deque and nums[i] > nums[deque[-1]]:
             deque.pop()
         deque.append(i)
     res.append(nums[deque[0]])    
     
     return res
 def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
     """
     思路:
     1. 暴力方法:一重循环遍历左侧起始位置,然后向右遍历k个位置,期间更新最大值
                 时间复杂度O(n * k)
     2. 高效思路:由于滑动窗口,右侧添加元素,左侧弹出元素,所以可以使用队列模拟
                 如果窗口内出现[a, b] b < a 的情况,那么向右滑动时a总是无效的
                 因此需要弹出a,添加b,由此形成了类似于单调递减栈的结构
                 由于左侧只有弹出,由于存在弹出和添加两种情况,因此使用双端队列
                 并且队列保存单调递减,左侧总是max
     """
     from collections import deque
     ret, deque = list(), deque()
     for i in range(len(nums)):
         # 维护队列的单调递减特性
         while deque and nums[deque[-1]] < nums[i]:
             deque.pop()
         # 添加当前元素
         deque.append(i)
         # 弹出头部元素
         if i - deque[0] >= k:
             deque.popleft()
         # 添加到结果中
         if i >= k - 1:
             ret.append(nums[deque[0]])
     return ret
def check(deque):
    for _ in range(len(deque) - 1):
        if deque[0]>=deque[1]:
            deque.popleft()
        elif deque[-1]>=deque[-2]:
            deque.pop()
        else:
            return "No"
    return "Yes"
Exemplo n.º 5
0
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
    # 维持从大到小的队列,保证deque[0]为窗口内最大值的索引
    from collections import deque
    deque, res = deque(), []
    for index, value in enumerate(nums):
        if deque and deque[0] <= index - k:
            deque.popleft()
        while deque and nums[deque[-1]] < value:
            deque.pop()
        deque.append(index)
        if index >= k - 1:
            res.append(nums[deque[0]])
    return res
Exemplo n.º 6
0
 def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
     if not nums: return []  # 好的编程习惯
     from collections import deque  #双向队列
     deque = deque()  # 储存窗口中元素的索引值,对应【左值,小值。。。】:左值需要维护,新加入元素与小值对比,确保左值总是最大值
     res = []  #储存最终结果
     for i in range(len(nums)):
         if deque and k - 1 < i - deque[0]:  # 窗口左值索引到i步的距离大于等于k,窗口左边弹出左值
             deque.popleft()
         while deque and nums[i] > nums[
                 deque[-1]]:  # 新加入元素与小值对比,大于窗口右值,就弹出右值
             deque.pop()
         deque.append(i)  # 加入新的右值的索引
         if i >= k - 1:  #确保len(nums)-k+1个元素在res中
             res.append(nums[deque[0]])
     return res
 def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
     import collections
     if not nums or k == 0: return []
     deque = collections.deque()
     for i in range(k):  # 未形成窗口
         while deque and deque[-1] < nums[i]:
             deque.pop()
         deque.append(nums[i])
     res = [deque[0]]
     for i in range(k, len(nums)):  # 形成窗口后
         if deque[0] == nums[i - k]: deque.popleft()
         while deque and deque[-1] < nums[i]:
             deque.pop()
         deque.append(nums[i])
         res.append(deque[0])
     return res
Exemplo n.º 8
0
def gcd(a_, b_):
    deque = [(a_, b_)]

    while deque:
        item = deque[-1]
        X = MEMO

        if item in MEMO:
            result = MEMO[item]
            while deque:
                item = deque.pop()
                MEMO[item] = result
            return result

        a, b = item
        if a == 0 or b == 0:
            MEMO[(a, b)] = 0

        if a == b:
            MEMO[(a, b)] = a
            continue

        # a is greater
        if a > b:
            deque.append((a - b, b))
            continue

        deque.append((a, b - a))

    return MEMO[(a_, b_)]
Exemplo n.º 9
0
 def CMD_rpop(self, key):
     try:
         deque = self.dictionary[key]  # type: collections.deque
     except KeyError:
         return b"$-1\r\n"
     value = deque.pop()
     return b"$%d\r\n%s\r\n" % (len(value), value)
Exemplo n.º 10
0
def bfs (flow,source,target):
    """Pre: El flujo por el cual estoy pasando en ese momento, lo dequeue dequeuiere decir
    es no perder la ruta y no visitar rutas no adecuadas
    Pos: si en caso no encontre un camino hasta el fin del grafo, retorna false
    si en cado caso SI llego al target, pues existe un camino seguro para llegar
    """
    
    global rta, n, m
    p = [[]for i in range(m+n+2)];deque = [];deque.append(source)
    visitados = [0 for i in range(m+n+2)]
    while deque:
        vertex = deque.pop(0)
        for v in range(m+n+2):
            #pilas con el flujo, tiene que ser mayor a 0 y no haberlo visitado nunca
            if not visitados[v] and (rta[vertex][v]-flow[vertex][v] > 0) :
                lineadeataque = p[vertex][:]
                lineadeataque.append((vertex,v))
                p[v] = lineadeataque
                visitados[v] = 1
                
                if v == target: return p[v]
                #agregar la v a la cola
                deque.append(v)
                
    return False
Exemplo n.º 11
0
def palindrome2(s):
    from collections import deque
    deque = deque(s)
    while len(deque) > 1:
        if deque.popleft() != deque.pop():
            return False
    return True
 def levelOrder(self, root: TreeNode) -> List[List[int]]:
     if not root: return []
     res, deque = [], collections.deque()
     deque.append(root)
     while deque:
         tmp = []
         # 打印奇数层
         for _ in range(len(deque)):
             # 从左向右打印
             node = deque.popleft()
             tmp.append(node.val)
             # 先左后右加入下层节点
             if node.left: deque.append(node.left)
             if node.right: deque.append(node.right)
         res.append(tmp)
         if not deque: break
         # 打印偶数层
         tmp = []
         for _ in range(len(deque)):
             # 从右向左打印
             node = deque.pop()
             tmp.append(node.val)
             # 先右后左加入下层节点
             if node.right: deque.appendleft(node.right)
             if node.left: deque.appendleft(node.left)
         res.append(tmp)
     return res
def solution(s):

    x = deque()

    # 스택을 이용해서 값을 넣을 때마다 계속 스택을 갱신했다.
    # 짝이 맞으면 pop을 한다.
    for el in s:
        deque.append(x,el)
        if len(x) >= 2:
            while x[len(x)-1] == x[len(x)-2] and len(x) >= 2:
                deque.pop(x)
                deque.pop(x)
                if len(x) == 0: break

    if len(x) == 0: return 1
    else: return 0
Exemplo n.º 14
0
 def dijkstra():
     COST = [[1e4]*m for _ in range(n)]
     COST[0][0] = 0
     deque = [(0, 0)]
 
     while True:
         x, y = deque.pop(0) 
         if x == m-1 and y == n-1:
             return COST[n-1][m-1]
 
         cost = COST[y][x]
         for x, y in [(x, y-1), (x-1, y), (x+1, y), (x, y+1)]:
             if not (0 <= x < m and 0 <= y < n):
                 continue
 
             is_wall = status[y][x] == '1'
             new_cost = cost + (1 if is_wall else 0)
 
             if COST[y][x] <= new_cost:
                 continue
 
             COST[y][x] = new_cost
             if is_wall:
                 deque.append((x, y))
             else:
                 deque.insert(0, (x, y))
Exemplo n.º 15
0
def do_command(deque, command):
    parts = command.split()
    action = parts[0]

    if action == "append":
        item = parts[1]
        deque.append(item)

    elif action == "appendleft":
        item = parts[1]
        deque.appendleft(item)
    
    elif action == "pop":
        deque.pop()

    elif action == "popleft":
        deque.popleft()
Exemplo n.º 16
0
 def maxSlidingWindow(self, nums, k):
     if not nums or k == 0:
         return []
     deque = deque()
     for i in range(k):  # 未形成窗口
         while deque and deque[-1] < nums[i]:
             deque.pop()
         deque.append(nums[i])
     res = deque[0]
     for i in range(k, len(nums)):
         if deque[0] == nums[i - k]:
             deque.popleft()
         while deque and deque[-1] < nums[i]:
             deque.pop()
         deque.append(nums[i])
         res.append(deque[0])
     return res
Exemplo n.º 17
0
def pop(deque, command):
    if len(deque) == 0:
        return -1
    else:
        if command == "pop_front":
            return deque.popleft()
        else:
            return deque.pop()
    def findMaxValueOfEquation(self, points, k):
        # stack
        # stack #|xi - xj| <= k
        # xi < xj , yi + yj + |xi - xj| = yi + yj + xj - xi => find the max(xj - xi)
        from collections import deque
        deque = deque()
        res = -float("inf")
        for x, y in points:
            while deque and k < x - deque[0][1]:
                deque.popleft()
            if deque:
                res = max(res, deque[0][0] + x + y)
            while deque and deque[-1][0] <= y - x:
                deque.pop()
            deque.append([y - x, x])

        return res
Exemplo n.º 19
0
    def play_smart(self, screen):
        # self._update_screen(screen)
        # pygame.time.wait(5000)
        while not self.finished():
            from collections import deque

            list_of_moves = []
            deque = deque()

            if self._best_option() is not None:
                optimal_move_x = self._best_option()[0]
                optimal_move_y = self._best_option()[1]
                self.matrix[optimal_move_x][optimal_move_y].visited = True
                self.moves += 1
                self._update_screen(screen)
                list_of_moves.append(self.matrix[optimal_move_x][optimal_move_y])
            else:
                deque.clear()
                for element in self.list_of_hits:
                    self.add_neighbours_deque(deque, element.x, element.y)
                while not self.finished() and len(deque) != 0:
                    next_field = deque.pop()
                    if next_field.ship_placed and not next_field.visited:
                        self.hits += 1
                        self.list_of_hits.append(next_field)
                        next_field.visited = True
                    else:
                        element.visited = True
                    self._update_screen(screen)
                    if self.finished():
                        return self.moves

            while not self.matrix[optimal_move_x][optimal_move_y].ship_placed:
                if self._best_option() is not None:
                    optimal_move_x = self._best_option()[0]
                    optimal_move_y = self._best_option()[1]
                    list_of_moves.append(self.matrix[optimal_move_x][optimal_move_y])
                    self._update_screen(screen)
                    self.matrix[optimal_move_x][optimal_move_y].visited = True
                    self.moves += 1

            self._update_screen(screen)
            self.hits += 1
            self.add_neighbours_deque(deque, optimal_move_x, optimal_move_y)


            while not self.finished() and len(deque) != 0:
                next_field = deque.popleft()
                list_of_moves.append(next_field)
                if next_field.visited:
                    continue
                if next_field.ship_placed and not next_field.visited:
                    self.hits += 1
                    self.add_neighbours_deque(deque, next_field.x, next_field.y)
                self.moves += 1
                next_field.visited = True
                self._update_screen(screen)
        return self.moves
    def findMaxValueOfEquation(self, points, k):
        # deque/stack 
        # Time O(N)
        # Space O(N)
        # time o(n), space: o(n)
        # stack #|xi - xj| <= k
        # xi < xj , yi + yj + |xi - xj| = yi + yj + xj - xi =  xj + yj +yi - xi => find the max(yi-xi)
        from collections import deque
        deque = deque()
        res = -float("inf")
        for x, y in points:
            while deque and k < x - deque[0][1]:
                deque.popleft()
            if deque:
                res = max(res, deque[0][0] + x + y) # 
            while deque and deque[-1][0] <= y-x: # yj - xj >= yi - xi
                deque.pop()
            deque.append([y-x, x]) 

        return res
Exemplo n.º 21
0
 def rotate(self, nums, k):
     """
     :type nums: List[int]
     :type k: int
     :rtype: None Do not return anything, modify nums in-place instead.
     """
     deque = deque(nums)
     k %= len(nums)
     for _ in range(k):
         deque.appendleft(deque.pop())
     nums[:] = list(deque)
Exemplo n.º 22
0
def determineStack(blocks):
    curr, dq = float("inf"), deque(blocks)
    while len(deque):
        if deque[0] > deque[-1] and deque[0] >= curr:
            curr = deque.popleft()
        elif deque[-1] >= curr:
            curr = deque.pop()
        else:
            print("NO")
            return
    print("YES")
Exemplo n.º 23
0
 def deckRevealedIncreasing1(self, deck):
     from collections import deque
     deque = deque()
     deck.sort(reverse=True)
     for num in deck:
         if deque:
             deque.appendleft(deque.pop())
             deque.appendleft(num)
         else:
             deque.appendleft(num)
     return list(deque)
Exemplo n.º 24
0
def update_path(next_point, deque):
    if len(deque) >= 2:
        # get the current point before the move
        first_pop = deque.pop()
        # get the previous point
        second_pop = deque.pop()
        # if the player backtracks (previous point == next point)
        if second_pop == next_point:
            # only append the previous point
            deque.append(second_pop)
        else:
            # add all the points back to the deque including the next point
            deque.append(second_pop)
            deque.append(first_pop)
            deque.append(next_point)
        # return the deque
        return deque
    else:
        # if the deque only has its initial point
        deque.append(next_point)
        # return the deque
        return deque
Exemplo n.º 25
0
    def rollback(self):
        node = deque.pop(self)
        self.executor.rolledback.append(node)
        self.counter -= 1
        cells = node[OBJ]

        graph = cells.model.tracegraph
        if graph.has_node(node):
            graph.remove_node(node)

        while self.refstack:
            if self.refstack[-1][0] == self.counter:
                _, ref = self.refstack.pop()
            else:
                break
Exemplo n.º 26
0
	def pushRight(kind): 
		# update score after window is extended 1 to the right by @kind
		assert len(window) >= 1

		if len(window) === 1:
			(num, item) = deque.pop()

			if item === 'i' and kind === 'i': 
				score += (num + 1)
				deque.append(num + 1, 'i')
			if item === 'i' and kind === 'd': 
				score -= 1
				deque.append(num, 'i')
				deque.append(1, 'd')
			if item === 'i' and kind === 's': 
Exemplo n.º 27
0
    def close(self):
        """Closes all currently opened connections.

        This operation is not thread safe and is only a best effort strategy
        to close active connections.

        All connections are guaranteed to be closed only if no other thread
        is accessing the client and no call is pending.
        """
        size = len(self.deque)
        for _ in range(0, size):
            try:
                connection = deque.pop()
                connection.close()
            except Exception:
                pass
Exemplo n.º 28
0
    def close(self):
        """Closes all currently opened connections.

        This operation is not thread safe and is only a best effort strategy
        to close active connections.

        All connections are guaranteed to be closed only if no other thread
        is accessing the client and no call is pending.
        """
        size = len(self.deque)
        for _ in range(0, size):
            try:
                connection = deque.pop()
                connection.close()
            except:
                pass
Exemplo n.º 29
0
def invoke(command, arg=0):
    if command == "push_front":
        deque.appendleft(arg)
    elif command == "push_back":
        deque.append(arg)
    elif command == "pop_front":
        print(deque.popleft() if deque else -1)
    elif command == "pop_back":
        print(deque.pop() if deque else -1)
    elif command == "size":
        print(len(deque))
    elif command == "empty":
        print(0 if deque else 1)
    elif command == "front":
        print(deque[0] if deque else -1)
    elif command == "back":
        print(deque[-1] if deque else -1)
Exemplo n.º 30
0
def f(p):
    from collections import deque

    if not p:
        return p

    deque.appendleft(p)

    while deque:
        q = deque.pop()
        q.left, q.right = q.right, q.left

        if q.right:
            deque.appendleft(q.right)
        if q.left:
            deque.appendleft(q.left)

    return p
def level_by_level(root):
    current_level = deque([root])
    next_level = deque()
    result = []
    level = 0
    while len(current_level) > 0:
        popped_node = deque.pop()
        result[level].append(popped_node)

        if popped_node.right:
            next_level.appendleft(popped_node.right)
        if popped_node.left:
            next_level.appendleft(popped_node.left)
        if len(current_level) == 0:
            current_level.extendleft(next_level)
            level += 1
            result.append([])
    return result
Exemplo n.º 32
0
    def pop(self):
        node = deque.pop(self)
        self.counter -= 1
        cells = node[OBJ]

        graph = cells.model.tracegraph
        if self:
            graph.add_edge(node, self[-1])
        else:
            graph.add_node(node)

        while self.refstack:
            if self.refstack[-1][0] == self.counter:
                _, ref = self.refstack.pop()
                cells.model.refgraph.add_edge(ref, node)
            else:
                break

        return node
Exemplo n.º 33
0
 def networkDelayTime(self, times: List[List[int]], N: int, K: int) -> int:
     visited = []
     taken_time = [0 for e in range(N)]
     deque = ([])
     for e in times:
         if e[0] == K:
             deque.append(e)
     while deque:
         source, target, time = deque.pop(0)
         if target in visited:
             if time < taken_time[target - 1]:
                 taken_time[target - 1] = time
             continue
         visited.append(target)
         taken_time[target - 1] = time
         for e in times:
             if e[0] == target:
                 deque.append((e[0], e[1], e[2] + time))
     if taken_time.count(0) > 1:
         return -1
     return max(taken_time)
Exemplo n.º 34
0
    def skipLoc(netloc):  # return True to continue, False to add to the todo list
        if netloc in blacklist:
            return True
        else:
            return False

if args.iterative:
    todo = deque()
    todo.append(args.url)
    matches = []
    seen = set()
    count = 0
 
    while 1: 
        try:
            link = deque.pop(todo)  # remove a link from todo and put it in link
        except IndexError:  # if there was an IndexError (probably because there are no more items in the deque
            print('looks like there is no more pages to proccess')
            break
        if args.count:  # if there should be a limit
            if count == args.count:  # if the limit is hit
                print("iteratitve matches:", matches)  # print matches
                break  # stop

        if link in seen:  # if the link has been seen before
            continue  # skip it
                
        page = pageDownloader(link)  # use pageDownloader to create a list of lines in the page
        for href in hrefParser(page):  # look through the page for hrefs
            (scheme, netloc, path, dumy, dumy, dumy) = urllib.parse.urlparse(href)           # split the found uri
Exemplo n.º 35
0
 def pop(self):
     self.__size_sema.acquire()
     return deque.pop(self)
Exemplo n.º 36
0
__author__ = 'cgiridhar'

from collections import deque

# Deques are a generalization of stacks and queues (the name is pronounced “deck” and is short for “double-ended queue”).
# Deques support thread-safe, memory efficient appends and pops from either side of the deque with approximately the same O(1)
# performance in either direction.

#Though list objects support similar operations, they are optimized for fast fixed-length operations and incur O(n)
# memory movement costs for pop(0) and insert(0, v) operations which change both the size and position of the underlying data representation.

deque = range(9)
deque.append("1")
print deque

deque.pop()
print deque