def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: if not prerequisites: return True n = numCourses graph = [set() for _ in range(n)] in_degree = [0] * n for p in prerequisites: graph[p[1]].add(p[0]) in_degree[p[0]] += 1 queue = deque([]) for i in range(n): if in_degree[i] == 0: queue.append(i) count = 0 while queue: tmp = queue.popleft() count += 1 if count == n: return True for j in graph[tmp]: in_degree[j] -= 1 if in_degree[j] == 0: queue.append(j) return False
def __init__(self): self.memory_buffer = deque(maxlen=2000) self.gamma = 0.95 self.epsilon = 1 self.epsilon_decay = 0.95 self.epsilon_min = 0.01 self.env = gym.make('Cartpole-v0')
def _init_(slef, buffer_size, batch_size): """Initializer a ReplayBuffer object. Params ===== buffer_size: maxium size of buffer batch_size: size of each training batch """ self.memory = deque(maxlen=buffer_size) # internal memory self.batch_size = batch_size self.experience = namedtuple("Experience", field_names=["state", "action", "reward", "next_state", "done"])
def BFS(graph,u): visited=set() queue = deque() queue.append(u) visited.add(u) while len(queue)!=0: s = queue.popleft() print (s, end = " ") for i in graph[s]: if i not in visited: queue.append(i) visited.add(i)
def bfs(start): q = deque() q.append(start) visited.append(start) while q: dat = q.pop() for i in graph[dat]: if i not in visited: visited.append(i) q.append(i)
def FindPartsOfIsland(M, i, j, c, r): q = deque() q.append([i, j]) while (len(q) != 0): i = q.pop() x = i[0] y = i[1] if (M[x][y] == 1): M[x][y] = 2 appendIF(q, r, c, x + 1, y) appendIF(q, r, c, x, y + 1) appendIF(q, r, c, x - 1, y) appendIF(q, r, c, x, y - 1)
def bfs(computer): queue = deque() queue.append(1) count = 0 # 큐가 진행되는 동안 while queue: v = queue.popleft() # 현재 주어진 컴퓨터에 연결된 컴퓨터 찾기 for com in computer[v]: if virus[com] == 0: virus[com] = 1 queue.append(com) count += 1 return count
def joinall(threads): from collection import deque from sys import getswitchinterval interval = getswitchinterval() threads = deque(threads) while threads: t = threads[0] t.join(timeout=interval) if not t.is_alive(): threads.popleft() yield t else: threads.rotate(-1)
def BFS(v): from collection import deque queue = deque() queue.append(v) seen[v] = 1 parent[v] = -1 while queue: v = queue.popleft() for neighbor in graph[v]: if not seen[neighbor]: queue.append(neighbor) distance[neighbor] = distance[v] + 1 parent[neighbor] = v seen[neighbor] = 1
def depthFirst2(startingNode, soughtValue): visitedNodes = set() queue = deque([startingNode]) while len(queue) > 0: node = queue.pop() if node in visitedNodes: continue visitedNodes.add(node) if node.value == soughtValue: return True for n in node.adjacentNodes: if n not in visitedNodes: queue.appendleft(n) return False
def widthOfBinaryTree(self, root: TreeNode) -> int: if not root: return 0 res = 1 # q = deque((root, 0)) # q:[root, 0] q = deque() # The key to solve the problem though lie on how we index the nodes that are on the same level. q.append((root, 0)) # q:[(root, 0)] while q: level_length = len(q) _, level_head_index = q[0] for _ in range(level_length): node, col_index = q.popleft() if node.left: q.append([node.left, 2 * col_index]) if node.right: q.append([node.right, 2 * col_index + 1]) res = max(res, col_index - level_head_index + 1) return res
def ladderLength(beginWord, endWord, wordList): """ :type beginWord: str :type endWord: str :type wordList: List[str] :rtype: int """ wordList = set(wordList) alpha = ascii_lowercase visited = set() q = collection.deque() q.append([beginWord,1]) while q: cur_word, length = q.popleft() if cur_word == endWord: return length for i in range(len(cur_word)): for ch in alpha: new_word = cur_word[:i]+ch+cur_word[i+1:] if new_word in wordList and new_word not in visited: q.append([new_word,length+1)) visited.add(new_word) return 0
def mostDifferentNums(root): q = deque([root]) maxLevel = {} while len(q) > 0: uniqueNodesInLevel = set() toBeAdded = [] while len(q) > 0: curr = q.popleft() if curr not in uniqueNodesInLevel: maxLevel[curr.val] = maxLevel.get(curr.val, 0) + 1 uniqueNodesInLevel.add(curr.val) toBeAdded.append(curr) for i in toBeAdded: if i.left: q.append(i.left) if i.right: q.append(i.right) maxVal = -1 maxNode = None for key, val in maxLevel: if val > maxVal: maxVal = val maxNode = key return maxNode
""" BFS Template neighbor 表示从某个点 head 出发,可以走到的下一层的节点。 set 存储已经访问过的节点(已经丢到 queue 里去过的节点) queue 存储等待被拓展到下一层的节点 set 与 queue 是一对好基友,无时无刻都一起出现,往 queue 里新增一个节点,就要同时丢到 set 里。 无需分层:即问题不需要我区分开不同层级的结果信息 """ from collection import deque queue = deque() # list-like container with fast appends and pops on either end seen = set() seen.add(start) queue.append(start) while len(queue): head = queue.popleft() # Pop out the first element in the queue for neighbor in head.neighbors: #以head为起点,其附近所有的neighbor都检查一遍 if neighbor not in seen: seen.add(neighbor) queue.append(neighbor) """ BFS Template neighbor 表示从某个点 head 出发,可以走到的下一层的节点。
''' Collection that support adding and removing items LIFO Example: Order Processing, Messaging ''' from collection import deque queue = deque() # Inserting the data into queue queue.append(1) queue.append(2) queue.append(33) queue.append(6) queue.append(17) print(queue) # Poping the data from left x = queue.popleft() print(x) print(queue)
def __init__(self): self.items = deque()
plt.waitforbuttonpress() plt.close('all') test_videos_dir = join('data', 'test_videos') test_videos = [join(test_videos_dir, name) for name in os.listdir(test_videos_dir)] for test_video in test_videos: print('Processing video: {}'.format(test_video)) cap = cv2.VideoCapture(test_video) out = cv2.VideoWriter(join('out', 'videos', basename(test_video)), fourcc = cv2.VideoWriter_fourcc(*'DIVX'), fps = 20.0, frameSize= (resize_w, resize_h)) frame_buffer = deque(maxlen=10) while cap.isOpened(): ret, color_frame = cap.read() if ret: color_frame = cv2.cvtColor(color_frame, cv2.COLOR_BGR2RGB) color_frame = cv2.resize(color_frame, (resize_w, resize_h)) frame_buffer.append(color_frame) blend_frame = color_frame_pipeline(frames = frame_buffer, solid_lines = True, temporal_smoothing= True) out.write(cv2.cvtColor(blend_frame, cv2.COLOR_RGB2BGR)) cv2.imshow('blend', cv2.cvtColor(blend_frame, cv2.COLOR_RGB2BGR)) cv2.waitKey(1) else: break cap.release() out.release() cv2.destroyAllWindows()
floats *=.5 floats[-3:] from time import perf_counter as pc t0 = pc(); floats /=3; pc() - t0 numpy.save('floats-10M.npy', 'r+') floats2 = numpy.load('floats-10M.npy','r+') floats2 *=6 floats2[-3:] # Trabalhando com um deque from collection import deque dq = deque(range(10), maxlen=10) dq dq.rotate(3) dq dq.rotate(-4) dq dq.appendleft(-1) dq dq.extend([11,22,33]) dq dq.extendleft([10,20,30,40]) dq # Se estivermos lidando com lista de números, arrays é mais prático. # Usamos muito mais lista porque é bem mais prático.
from collection import deque class PuzzelState (object): def __str__ (self): r = "" i = 0 for tile in self.gamestate: r += str(tile) + "" if i % 3: i += "\n" i += 1 return r working = deque() visited = [] working.append(initial) while len(working): cur = working.popleft() if cur == goalstate: break stateleft =cur.moveLeft() if stateleft not in visited: working.append(stateleft) visited.append(stateleft) # do the same for other states
# Стек: last in, first out # Очередь: first in, first out # Медленная очередь — список queue_slow = [] queue_slow.append(5) queue_slow.append(10) queue_slow.append(7) print(queue_slow) # [5, 10, 7] x = queue_slow.pop(0) # O(N) по времени! print(x) # 5 print(queue_slow) # [10, 7] # Тяжёлая очередь queue_big = list(range(100000000)) q_start = 0 # remove превращается в две операции # мы не удаляем элемент из памяти, а просто сдвигаемся x = queue_big[q_start] # O(1) q_start += 1 # O(1) # быстро, но требует всегда держать резерв памяти занятым # Наиболее эффективная — в библиотеке deque from collection import deque queue = deque(range(10000000)) queue.append(1) x = queue.popleft() # медленнее, чем предыдущее, но всё равно очень быстро # можно написать самим через двусвязный список
from collection import deque import requests from bs4 import BeautifulSoup from urllib.parse import urlparse, urljoin base_url = 'http://register.start.bg/' links = deque() links.append(base_url) visited = set() while len(links) > 0: link = links.pop() visited.add(link) r = requests.get(link) html = r.text msg = link soup = BeautifulSoup(html, 'html.parser') for tag in soup.find_all('a'): if tag.get('href') is not None and '#' not in tag.get('href'): tag = tag.get('href') if 'http' in tag: links.append(tag) else: tag = urljoin(msg, tag) links.append(tag) # for item in visited: # r = requests.get(item, verify=False, timeout=5)
def __init__(self): self.cat_queue = deque() self.dog_queue = deque() self.order = 0
MSFT_x = MSFT_x.drop(['Date', 'Up_Down', 'Firm', 'Rating', 'Firm_Rating'], axis=1) #building RNN import tensorflow as tf import keras from keras.layers import Dense, Dropout, LSTM #for output and layers from keras.models import Sequential # for RNN from keras.utils import to_categorical #choosing interval to predict and sequence length seq_len = 60 fut_pred = 3 #pred_var = "" #fill in prev_days = deque(maxlen=seqlen) #cutting last 10 % of data to predict on L_10 = MSFT_x[int(0.9 * len(MSFT_x.index)):] test_x = MSFT_x[:int(0.9 * len(MSFT_x.index)) + 1] #create a future column fut_class = [] for i in list(range(0, (len(MSFT_x.index) - 3))): v = 0 if MSFT_x['Adj Close'][i + 3] > MSFT_x['Adj Close'][i]: v = 1 else: v = 0 fut_class.append(v)
['Mg Mg', 'Aye Aye', 'Mya Mya', 'Ko Ko', 'Phyu Phyu', 'Ni Ni'] >>> student.remove('Mya Mya') >>> student ['Mg Mg', 'Aye Aye', 'Ko Ko', 'Phyu Phyu', 'Ni Ni'] >>> student.pop() 'Ni Ni' >>> student ['Mg Mg', 'Aye Aye', 'Ko Ko', 'Phyu Phyu'] >>> from collection import deque Traceback (most recent call last): File "<stdin>", line 1, in <module> ModuleNotFoundError: No module named 'collection' >>> from collections import deque >>> queue = deque(["Eric", "John", "Micheal"]) >>> queue.append('Terry') >>> queue.append('Graham') >>> queue deque(['Eric', 'John', 'Micheal', 'Terry', 'Graham']) >>> queue.popleft() 'Eric' >>> queue.popleft() 'John' >>> queue deque(['Micheal', 'Terry', 'Graham']) >>> >>> cube = [] >>> for i in range(10):
def search(lines, pattern, history=5): previous_lines = deque(maxlen=history) for line in lines: if pattern in line: yield line, previous_lines previous_lines.append(line)
def serch(lines,pattern,history=5): previous_lines = deque(maxlen = history) for li in lines: if pattern in li : yield li, previous_lines # 生成器函数 previous_lines.append(li)
Queure: first in first out from collection import deque q = deque(['nikita','darshan','unnati']) q.append('shreyas') q.popleft() print(q) print(lsit(q)) output:: deque(['darshan','unnati','shreyas']) ['darshan','unnati','shreyas']
def __init__(self, lines, histlen=3): self.lines = lines self.history = deque(maxlen=hislen)