def bfs(): global water_temp global beaver_temp while (beaver_temp): w_q = dq(water_temp) water_temp = [] while (w_q): wy, wx = w_q.popleft() for i in range(4): n_wy = wy + dy[i] n_wx = wx + dx[i] if (pos(n_wy, n_wx) and arr[n_wy][n_wx] != 'D'): water[n_wy][n_wx] = True water_temp.append((n_wy, n_wx)) b_q = dq(beaver_temp) beaver_temp = [] while (b_q): by, bx, cnt = b_q.popleft() if ((by, bx) == hole): return cnt for i in range(4): n_by = by + dy[i] n_bx = bx + dx[i] if (pos(n_by, n_bx) and not beaver[n_by][n_bx]): beaver[n_by][n_bx] = True beaver_temp.append((n_by, n_bx, cnt + 1)) return -1
def generate(pots, rules, gens, f): def getsum(pots, zero): s = 0 for i, p in zip(range(-zero, len(pots) - zero), pots): if p: s += i return s zeroPot = 0 pots.extendleft(it.repeat(0, 2)) for i in range(gens): # print(i) for p in pots: c = '#' if p else ' ' f.write(c) f.write('\n') newpots = dq([0, 0]) pots.extendleft([0, 0]) pots.extend([0, 0, 0, 0]) for i in range(len(pots) - 4): state = 0 for j in range(5): state = state << 1 state += pots[i + j] newpots.append(rules[state]) while newpots.pop() == 0: pass newpots.append(1) pots = dq(list(newpots)[2:]) return getsum(pots, zeroPot)
def __init__(self, turtle_gen, max_turtle=1, stack_like=False, helper_func=None): ''' 初始化装饰器对象 ''' # 线程池 self._sprouts = dq() self._sprout_stack = stack_like # 记录当前运行turtle self._running_turtles = 0 self._turtle_count = max_turtle self._qlock = Lock() # 用于调用的turtle队列 self._turtles = dq() for i in range(max_turtle): self._turtles.append(turtle_gen()) # 记录主循环线程是否已在运行 self._looping = False # 与主循环同时运行的伴随线程 self._helper_func = helper_func
def list_manipulator(list_of_num, *args): from collections import deque as dq list_of_num = dq(list_of_num) command = args[0] where = args[1] numbers = dq(args[2:]) if command == "add": if where == "beginning": list_of_num = numbers + list_of_num elif where == "end": list_of_num = list_of_num + numbers elif command == "remove": if where == "beginning": if numbers: for _ in range(int(numbers[0])): list_of_num.popleft() else: list_of_num.popleft() elif where == "end": if numbers: for _ in range(int(numbers[0])): list_of_num.pop() else: list_of_num.pop() return list(list_of_num)
def bfs(g, s): # Initialisation & marquage de sommets non parcourus(-1) d = {} p = {} marqued = {} for i in g.nodes(): d[i] = -1 marqued[i] = False marqued[s] = True d[s] = 0 Q = dq() Q.appendleft(s) # Liste FIFO # Iterations # tant que Q n'est pas vide while Q != dq([]): # u = defiler()Q u = Q.pop() # Retirer le premier sommet de la file vs = [i for i in g.successors(u)] # Pour tous les voisins non-marques de u : for v in reversed(vs): if marqued[v] == False: #d[v] == -1 : Q.appendleft(v) # Ajouter v a la fin de la file d[v] = d[u] + 1 p[v] = u marqued[v] = True return (d, p)
def solve(): s=dq([x for x in input()]) k=ii() m=dq([x for x in str(bin(k)).lstrip("0b")]) if len(m)>len(s): while(len(s)!=len(m)): s.appendleft("0") if len(m)<len(s): while(len(m)!=len(s)): m.appendleft("0") #print(s,m) ans=[] c=0 for x in range(len(m)-1,-1,-1): a,b=int(m[x]),int(s[x]) sm=a^b^c c=(a and b) or (b and c) or (a and c) ans.append(str(sm)) if c==1: ans.append("1") print("".join(ans[::-1])) #print(2*"x") print(len(1234))
def processQueries(self, a: List[int], b: int) -> List[int]: ret = list() l = dq([i for i in range(1, b + 1)]) for i in a: tmp = l.index(i) ret.append(tmp) l = dq(islice(l, 0, tmp)) + dq(islice(l, 1 + tmp, b)) # l.remove(i) l.appendleft(i) return ret
def popMiddle(self) -> int: if len(self.l): mid = len(self.l) // 2 if len(self.l) % 2: tmp = self.l[mid] else: mid -= 1 tmp = self.l[mid] x = dq(islice(self.l, 0, mid)) x += dq(islice(self.l, mid + 1, len(self.l))) self.l = x return tmp return -1
def solution(stock, dates, supplies, k): answer = 0 queue=[] dates=dq(dates) supplies=dq(supplies) while stock < k : #stock이 k보다 클때까지 while dates and stock >= dates[0] : #수입일자가 존재하고 stock이 수입일자[0]보다 크면 돌아감 dates.popleft() val=supplies.popleft() hq.heappush(queue,(-val,val)) # -val을 이용해서 최대heap 생성 stock+=hq.heappop(queue)[1] # val을 꺼내서 stock에 더해줌 answer+=1 return answer
def lastStoneWeight(self, stones: List[int]) -> int: a =dq(stones) while len(a)>1: a=dq(sorted(a,reverse=True)) if a[0]==a[1]: a.popleft() a.popleft() else: a[0] = a[0] - a[1] del a[1] if len(a)==1: return a[0] return 0
def solution(start, cur): global visit q = dq([start]) y, x, cnt = start arr[y][x] = 0 hq = [] visit = [[False] * n for _ in range(n)] visit[y][x] = True while (q): y, x, cnt = q.popleft() for i in range(4): ny = y + dy[i] nx = x + dx[i] if (pos(ny, nx)): if (arr[ny][nx] == 0 or arr[ny][nx] == cur): visit[ny][nx] = True q.append((ny, nx, cnt + 1)) elif (arr[ny][nx] < cur): heapq.heappush(hq, (cnt + 1, ny, nx)) if (hq): return hq[0] return None
def run(self): self.queue = dq(maxlen = 200) if(len(self.queue)): msg = self.queue[0] self.queue.popleft() self.change_value.emit(msg) delay(1)
def make_pathlist(self, fc, curLevel, vst_arr1, vst_arr2, cnts): tmp = dq([]) #lehcode = lc.lehmer_code(12,7) all_moves, all_corner_states, all_edge_states, all_edge1_states, all_edge2_states = rcm.move_with_cython( fc, self.transfer_matrix) for curf in range(18): ist = 48 * curf ied = ist + 48 statecode1 = all_edge1_states[curf] statecode2 = all_edge2_states[curf] #cur_config = str(statecode1) + str(statecode2) #tmpcode1 = self.getstate_edgesplit(np.array(all_moves[ist:ied]), lehcode, 0) #tmpcode2 = self.getstate_edgesplit(np.array(all_moves[ist:ied]), lehcode, 1) vst1 = vst_arr1[statecode1] vst2 = vst_arr2[statecode2] curfc = all_moves[ist:ied] tmp.append(curfc) if vst1 == 0: vst_arr1[statecode1] = curLevel cnts[0] = cnts[0] + 1 if vst2 == 0: vst_arr2[statecode2] = curLevel cnts[1] = cnts[1] + 1 if vst1 > 0 and curLevel < vst1: vst_arr1[statecode1] = curLevel if vst2 > 0 and curLevel < vst2: vst_arr2[statecode2] = curLevel return tmp, vst_arr1, vst_arr2, cnts
def solve(start): finish = "+" * len(start) queue = dq([start]) parent = {start: None} def swap(pancake): return '+' if pancake == '-' else '-' def lifts(state): l = len(state) for i in range(l): yield "".join("".join(map(swap, state[:l-i]))[::-1] + state[l-i:]) #print(list(lifts("-+++-"))) def numParentsOf(state): if state == start: print(state) return 0 else: ret = 1 + numParentsOf(parent[state]) print(state) return ret while True: crt = queue.popleft() if crt == finish: return numParentsOf(crt) for lift in lifts(crt): if not lift in parent: parent[lift] = crt queue.append(lift)
def bfs(y, x): q = dq([(y, x)]) visit[y][x] = True union = [(y, x)] while (q): y, x = q.popleft() for i in range(4): ny = y + dy[i] nx = x + dx[i] if (pos(ny, nx) and not visit[ny][nx] and l <= abs(arr[y][x] - arr[ny][nx]) <= r): union.append((ny, nx)) q.append((ny, nx)) visit[ny][nx] = True if (len(union) == 1): return 0 num = 0 for y, x in union: num += arr[y][x] num = int(num / len(union)) for y, x in union: arr[y][x] = num return 1
def isCousins(self, root: TreeNode, x: int, y: int) -> bool: from collections import deque as dq q = dq() q.append(root) while len(q) > 0: n = len(q) temp = [] for i in range(n): curr = q.popleft() temp.append(curr.val) if curr.left is not None: if curr.right is not None: if (x == curr.left.val or y == curr.left.val) and (x == curr.right.val or y == curr.right.val): return False q.append(curr.left) q.append(curr.right) else: q.append(curr.left) else: if curr.right is not None: q.append(curr.right) if x in temp and y in temp: return True return False
def connect(self, root: Node) -> Node: """ Approach: Level Order Traversal Time Complexity: O(N) Space Complexity: O(N) :param root: :return: """ if not root: return None from collections import deque as dq queue = dq([root]) while queue: size = len(queue) for i in range(size): node = queue.popleft() if i < size - 1: node.next = queue[0] if node.left: queue.append(node.left) if node.right: queue.append(node.right) return root
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: from collections import deque as dq course = list(0 for _ in range(numCourses)) need = dict() for i in range(numCourses): need[i] = [] for a, b in prerequisites: course[a] += 1 need[b].append(a) cnt = 0 point = dq([]) for i in range(numCourses): if course[i] == 0: point.append(i) cnt += 1 while point: a = point.popleft() for i in need[a]: course[i] -= 1 if course[i] == 0: point.append(i) cnt += 1 if cnt == numCourses: return True else: return False
def __init__(self, iterator): """ Initialize your data structure here. :type iterator: Iterator """ self.iter = iterator self.stack = dq()
def bfs(): queue = dq([]) result = 0 for i in range(h): for j in range(m): for k in range(n): if(tomato[i][j][k] == 1): queue.append((i,j,k,0)) while(queue): z,y,x,day = queue.popleft() result = max(result, day) for i in range(6): ny = y + dy[i] nx = x + dx[i] nz = z + dz[i] if(pos(nz,ny,nx)): tomato[nz][ny][nx] = 1 queue.append((nz,ny,nx,day+1)) for z in range(h): for y in range(m): for x in range(n): if(tomato[z][y][x] == 0): return -1 return result
def dbl_linear(n): h = 1 cnt = 0 a, b = dq([]), dq([]) while True: if (cnt >= n): return h a.append(2 * h + 1) b.append(3 * h + 1) h = min(a[0], b[0]) if h == a[0]: h = a.popleft() if h == b[0]: h = b.popleft() cnt += 1
def bfs(q): visit = [[[[0] * M for _ in range(N)] for _ in range(M)] for _ in range(N)] for step in range(1, 11): temp = dq([]) while q: (rr, rc), (br, bc) = q.popleft() visit[rr][rc][br][bc] = 1 for d in range(4): matrix[rr][rc], matrix[br][bc] = 'R', 'B' blue_ball = move(br, bc, d) red_ball = move(rr, rc, d) if blue_ball: nbr, nbc = blue_ball blue_ball = move(nbr, nbc, d) if blue_ball: if red_ball: nrr, nrc = red_ball matrix[nrr][nrc] = '.' nbr, nbc = blue_ball matrix[nbr][nbc] = '.' if visit[nrr][nrc][nbr][nbc] == 0: visit[nrr][nrc][nbr][nbc] = 1 temp.append((red_ball, blue_ball)) else: return step else: if red_ball: nr, nc = red_ball matrix[nr][nc] = '.' else: if red_ball: nr, nc = red_ball matrix[nr][nc] = '.' q = temp return -1
def bfs(a, b): q = dq([(a, b, 0)]) temp_visit = [[False] * m for _ in range(n)] temp_visit[a][b] = True while (q): y, x, cnt = q.popleft() node = Node((y, x)) for i in range(4): ny = y + dy[i] nx = x + dx[i] n_node = Node((ny, nx)) if (pos(ny, nx) and not temp_visit[ny][nx]): q.append((ny, nx, cnt + 1)) temp_visit[ny][nx] = True n_node.prev = node while (node.prev): y, x = node.data visit[y][x] = True node = node.prev return cnt
def solve(): n, k = mi() if k == 0: print(*[x for x in range(1, n + 1)]) return elif n % 2 == 0: if k > n // 2 - 1: print(-1) return elif n % 2 != 0: if k > n // 2: print(-1) return if n < 3: print(-1) return a = dq([x for x in range(1, n + 1)]) ans = [] cp = 0 for x in range(1, n + 1): if x % 2 == 0 and k > 0: ans.append(a.pop()) k -= 1 else: ans.append(a.popleft()) print(*ans)
def solution(maps): n, m = len(maps), len(maps[0]) visit = [[False]*m for _ in range(n)] dy = [1, -1, 0, 0] dx = [0, 0, 1, -1] def pos(y, x): if(0 <= y < n and 0 <= x < m and maps[y][x]): return True return False q = dq([(0, 0, 1)]) visit[0][0] = True while(q): y, x, cnt = q.popleft() if(y == n-1 and x == m-1): return cnt for i in range(4): ny = y + dy[i] nx = x + dx[i] if(pos(ny, nx) and not visit[ny][nx]): q.append((ny, nx, cnt+1)) visit[ny][nx] = True return -1
def multi_remove(list_object, *indices): # Inspired by: # <so>/497426/deleting-multiple-elements-from-a-list/7016104#7016104 # where <so> : stackoverflow.com/questions/ """ Removes objects from list at multiple indices. The list is modified in place and the removed items are returned. Example: >>> x = [1,4,6,7,8] >>> removed = multi_remove(x, 1, 3) >>> x [1, 6, 8] >>> removed [7, 4] Arguments --------- list_object : list The list from which to remove the objects indices : iterable An list of indices on which to remove Returns ------- list A list containing all the removed items """ return list(dq((list.pop(list_object, i) for i in sorted(indices, reverse=True)), maxlen = len(indices)))
def bfs2(): # 적록색약 q = dq([]) visit = [[False] * n for _ in range(n)] cnt = 0 for i in range(n): for j in range(n): if (color[i][j] == 'G'): color[i][j] = 'R' for i in range(n): for j in range(n): if (not visit[i][j]): temp = color[i][j] q.append((i, j)) visit[i][j] = True while (q): y, x = q.popleft() for idx in range(4): ny = y + dy[idx] nx = x + dx[idx] if (pos(ny, nx) and temp == color[ny][nx] and not visit[ny][nx]): q.append((ny, nx)) visit[ny][nx] = True cnt += 1 return cnt
def solution(maps): answer = 0 n = len(maps) m = len(maps[0]) distance = [[10001 for i in range(m)] for j in range(n)] distance[0][0] = 1 xy = [(1, 0), (-1, 0), (0, 1), (0, -1)] queue = dq([]) queue.append([0, 0]) while queue: nowX, nowY = queue.popleft() for x, y in xy: newX = nowX + x newY = nowY + y # xy=>newx newy 갈꺼임 if n > newX >= 0 and m > newY >= 0 and maps[newX][newY] != 0: if distance[newX][newY] > distance[nowX][nowY] + 1: distance[newX][newY] = distance[nowX][nowY] + 1 queue.append([newX, newY]) """ append를 거리가 작을 때만 해야 한다. (방문한지 체크 안함) """ # append는 거리가 작을 때만 한다 #pp.pprint(distance) answer = distance[n - 1][m - 1] if answer == 10001: answer = -1 return answer
def converter_(self, root: "TreeNode") -> List[int]: """ Approach: BFS Time Complexity: O(N) Space Complexity: O(N) :param root: :return: """ # base validation if not root: return [] # order - to maintain th zig zag order # level node - to maintain the level nodes order, level_nodes = [], dq() # queue - for bfs traversal # None - acts as a delimiter of that level queue = dq([root, None]) # flag to determine left node is_left = True while queue: curr_node = queue.popleft() if curr_node: if is_left: # append to the tail level_nodes.append(curr_node.val) else: level_nodes.appendleft(curr_node.val) if curr_node.left: queue.append(curr_node.left) if curr_node.right: queue.append(curr_node.right) else: # we have came to next level order.append(level_nodes) if queue: # reset the delimiter queue.append(None) # reset the level nodes level_nodes = dq() # reset the flag is_left = not is_left return order
def __init__(self, inputitems): self.queue = dq(inputitems) self.busy = 0 # is the queue busy? # system occupancy evolution for each Q: (timestamp, size) self.Qevolution = [(0., 0)] self.arrtimes = [] # arrival times self.deptimes = [] # departure times self.delays = [] # delays
def main(): global bags, jewels bags.sort() jewels = dq(sorted(jewels)) maxPrice = calculate_price() print(maxPrice)
def __init__(self,__max=10): self.__internallist = dq() self.__sortedlist = [] self.count = 0 self.median = 0.0 self.mean = 0.0 self.sum = 0.0 self.__max = __max return
def lvl_ord_double(root): """ 层序遍历的双队列实现,可以一排排的打印node 这里用stack实现的,不是标准方式,不过速度更快 """ if root == None: return cur, nxt = dq([root]), dq([]) while len(cur): node = cur.pop() if node: print node.val if node.left: nxt.appendleft(node.left) if node.right: nxt.appendleft(node.right) if len(cur) == 0: print '\n' cur, nxt = nxt, cur
def __init__(self, algo, initial_state=None): self.initial_state = initial_state if algo == "bfs" or algo == "dfs": self.frontier = dq() self.frontier.append(initial_state) else: self.frontier = PriorityQueue() self.frontier.put(initial_state) self.frontier_set.add(initial_state) self.algo = algo
def get_solution_moves(self, final_state): """ Gets the sequence of moves from parent to this state """ moves = dq() current_state = final_state while current_state is not None: if current_state.parent_move is not None: moves.appendleft(current_state.parent_move) current_state = current_state.parent res = [] [res.append(move) for move in moves] return res
def lvl_ord_single(root): """ 单队列层序遍历,用两个变量标记当前层以及下层的数, 原理其实跟双队列一样,不过把另一个队列换成了两个数来做 """ if root == None: return cur_num, nxt_num = 1, 0 store = dq([root]) while len(store): node = store.pop() print node.val cur_num -= 1 if node.left: store.appendleft(node.left) nxt_num += 1 if node.right: store.appendleft(node.right) nxt_num += 1 if cur_num == 0: cur_num, nxt_num = nxt_num, cur_num print '\n'
from collections import namedtuple as nt from collections import deque as dq import time import datetime Months = nt('month', 'year') month_q = dq('Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split()) curr_mo = month_q.pop() month_q.appendleft(curr_mo) month_l = list('Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split()) print month_l today = datetime.datetime.now() curr_mo = today.strftime('%b') mo = '' while(mo != curr_mo): mo = month_l.pop() month_l.insert(0, mo) print month_l LastThree = month_l[9:12] LastOne = month_l[-1:] print 'LastThree are ', LastThree print 'LastOne is ', LastOne t = (2000, 1, 21, 1, 2, 3, 4, 5, 6) t = time.mktime(t) print time.strftime("%b %d %Y %H:%M:%S", time.gmtime(t)) t = (2000, 2, 21, 1, 2, 3, 4, 5, 6)
from collections import deque as dq d = dq() for _ in range(int(input())): inp = input().split() getattr(d,inp[0])(*inp[1:]) [print(x,end= ' ') for x in d]
#!/usr/bin/python3 from pprint import pprint as pp from collections import deque as dq alist = [54,26,93,17,77,31,44,55,20] agraph = {'A': set('BC'), 'B': set('ADE'), 'C': set('AF'), 'D': set('B'), 'E': set('BF'), 'F': set('CE')} aqueue = dq([2],4) dq.enqueue(3) print(aqueue)
from collections import deque as dq for _ in range(int(input())): n,d,top,ret = input(),dq(list(map(int,input().split()))),[],False while d: tp = d.popleft() if d[0] > d[-1] else d.pop() if not top: top.append(tp) elif top[-1] >= tp: top.append(tp) else: ret = True break print('No' if ret else 'Yes')
from collections import deque as dq from random import randint as r a = 1 list1 = ["3","d","6"] list2 = ["d","4"] list3 = ["1","d","20"] while a != 1: #lst: numOfDice = dq([1]) valOfDie = dq([]) if lst(0) == 'd': lst.remove('d') lst.pop(valOfDie) xxx = [numOfDice,valOfDie] elif lst(0) == "1" and lst(1) == "d": #in case 10 - 19dx a = 1 #ans = ''.join(int(c) for c in lst) #def zzz(): # c = 11 # lst1 = [] # while c > 0: # lst1.append(r(1,3)) # c-=1 # return lst1
queue.pop(0) print current_milli_time()-start start = current_milli_time() queue = Queue.Queue() a = 0 while a < 100000: queue.put(a) a += 1 while not queue.empty(): queue.get() print current_milli_time()-start start = current_milli_time() queue = dq() a = 0 while a < 100000: queue.append(a) a += 1 while queue: queue.popleft() print current_milli_time()-start """ Result: 1588 426 23 deque is much much faster because it is implemented using c