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()
def bfs(queue): while len(queue): node = queue.popleft() process(node) if node.left: queue.append(node.left) if node.right: queue.append(node.right)
def ipic_cmake(args): # get the input file inputfile, args = get_inputfile(args) # extract the values of any options from args #system, parhdf5, args = get_cmake_options(args) # make src a link to the code numargs = len(args) if numargs==0: sourcedir = os.getenv('IPIC_HOME','..'); else: args = deque(args) sourcedir = deque.popleft(args) if sourcedir!='src': rm_command = ['rm', '-f', 'src']; issue_command(rm_command); ln_command = ['ln', '-s', str(sourcedir), 'src']; issue_command(ln_command) ipic_env = os.getenv('IPIC_ENV','') if ipic_env != '': ipic_home = os.getenv('IPIC_HOME','') if ipic_home != '': jobscript_file = ipic_home+'/env/'+ipic_env+'/job.sh' if os.path.isfile(jobscript_file): command = ['cp', jobscript_file, '.']; issue_command(command) # copy input file to current directory copy_input_file_command = ['cp', inputfile, './parameters.inp'] issue_command(copy_input_file_command) ipic_make_data(); # invoke cmake cmake = os.getenv('IPIC_CMAKE','cmake'); cmake_command = [cmake]; # add arguments particular to intel #cmake_command.extend(['-DCMAKE_CXX_FLAGS=-DMPICH_IGNORE_CXX_SEEK']) # add rest of args to end of cmake command # issue the command cmake_command.extend(['src']) cmake_command.extend(args) # a string is a list of individual characters, # so we append rather than extend the list cmake_command.append(os.getenv('IPIC_CMAKE_ARGS','')) # by spawning a subshell we allow the content of # IPIC_CMAKE_ARGS to be interpreted by shell issue_shell_command(' '.join(cmake_command))
def bfs(tree, val): """ Returns whether a node is present in a tree using breadth-first search """ deque = deque([tree.root]) while deque: current = deque.popleft() if current.data == val: return True else: if current.left: deque.append(current.left) if current.right: deque.append(current.right) return False
def _merge_prefix(deque, size): if len(deque) == 1 and len(deque[0]) <= size: return prefix = [] remaining = size while deque and remaining > 0: chunk = deque.popleft() if len(chunk) > remaining: deque.appendleft(chunk[remaining:]) chunk = chunk[:remaining] prefix.append(chunk) remaining -= len(chunk) if prefix: deque.appendleft(type(prefix[0])().join(prefix)) if not deque: deque.appendleft(b"")
def append(self, timeStampedValue): cutoffDateTime = datetime.now() - self.MaximumAge #print 'cutoffDateTime: ' + str(cutoffDateTime) #print(timeStampedValue) done = False while not done: if len(self) == 0: done = True else: oldestTimeStampedValue = deque.popleft(self) if oldestTimeStampedValue.TimeStamp >= cutoffDateTime: # not old enough; we need to keep it deque.appendleft(self, oldestTimeStampedValue) done = True deque.append(self, timeStampedValue)
def clone_graph(self, node): if not node: return None root = UndirectedGraphNode(node.label) visted = {root.label: root} to_visit = deque([node]) while to_visit: front_node = deque.popleft() for neighbor in front_node.neighbors: if neighbor not in visted: visted[neighbor.label] = neighbor to_visit.append(neighbor) visted[front_node].neighbors.append(visted[neighbor]) return root
def expand_orbits(deque, num_expansions): r"""Takes a *deque* whose elements are a list of words. The following process is repeated *num_expansions* times. 1. Pop an orbit :math:`\mathcal{O} = [o_1, \dotsc, o_d]` from the left of the deque. 2. For :math:`i = 1, \dotsc, n` (where :math:`n` is the arity): a. Compute the new orbit :math:`\mathcal{O_i} =[o_1\alpha_i, \dotsc, o_d\alpha_i]` b. Append this orbit to the right of *deque*. Once complete, the number of orbits in *deque* has increased by :math:`\text{(arity -1) $\times$ num_expansions}` """ for _ in range(num_expansions): orbit = deque.popleft() arity = orbit[0].signature.arity for i in range(1, arity+1): new_orbit = tuple(w.alpha(i) for w in orbit) deque.append(new_orbit)
def breadth_first_search(source, destination): node_deqeue = deque([(source, 0)]) while len(node_deqeue): popped_node, level = deque.popleft() s if popped_node.left: if popped_node.left.val == destination: return level + 1 node_deqeue.append(popped_node.left, level + 1) if popped_node.right: if popped_node.right.val == destination: return level + 1 node_deqeue.append(popped_node.right, level + 1)
def ipic_help(args): if len(args) == 0: ipic_basic_help() sys.exit() command = deque.popleft(args) if command == "show": ipic_help_show(args) elif command == "run": ipic_help_run(args) elif command == "mic": ipic_help_mic(args) elif command == "deep": ipic_help_deep(args) elif command == "cmake": ipic_help_cmake(args) elif command == "ctags": ipic_help_ctags(args) elif command == "git": ipic_help_git(args) else: print "ipic help", command, "is not supported" sys.exit(-1)
deque = deque() for _ in range(N): command = sys.stdin.readline().rstrip() command = command.split(' ') if command[0] == 'push_front': num = int(command[1]) deque.appendleft(num) elif command[0] == 'push_back': num = int(command[1]) deque.append(num) elif command[0] == 'pop_front': print(-1 if not deque else deque.popleft()) elif command[0] == 'pop_back': print(-1 if not deque else deque.pop()) elif command[0] == 'size': print(len(deque)) elif command[0] == 'empty': print(1 if not deque else 0) elif command[0] == 'front': print(-1 if not deque else deque[0]) elif command[0] == 'back': print(-1 if not deque else deque[-1])
class Deque(Queue): # 큐 상속 def enqueue_back(self, element): self.items.append(element) def dequeue_front(self): element = self.items.pop(0) # 첫번째 인덱스 뽑기 if element is not None: return element else: print('Deque is empty.') deque = Deque() print('데크 비어있는지 확인 : ', deque.isEmpty()) deque.enqueue(10) """ from collections import deque deque = deque(['삼성', 'LG', '카카오']) print(deque) # deque(['삼성', 'LG', '카카오']) deque.append('네이버') print(deque) # deque(['삼성', 'LG', '카카오', '네이버']) deque.popleft() #삼성이 꺼내진다. print(deque) # deque(['LG', '카카오', '네이버']) deque.pop() # 제일 오른쪽인 네이버가 꺼내진다. print(deque) # deque(['LG', '카카오']) deque.appendleft('삼성') deque.append('네이버') print(deque) # deque(['삼성', 'LG', '카카오', '네이버'])
from collections import deque roll_call = deque(['shade', 'tolu', 'lyon,', 'brian', 'meghan']) deque.popleft(roll_call) print(roll_call) deque.popleft(roll_call) print(roll_call)
def prune(self): last_five_mins = time.time() - SECONDS_IN_FIVE while len(self.log) > 0 and self.log[0] < last_five_mins: deque.popleft()
def read(self): deque.popleft()
def play_smart_v2(self, screen): 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] #print("uso", optimal_move_x, optimal_move_y) 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 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 if self.finished(): return self.moves first_hit = self.matrix[optimal_move_x][optimal_move_y] self.list_of_hits.append(first_hit) self._update_screen(screen) self.hits += 1 self._add_vertical_neighbours_deque(deque, optimal_move_x, optimal_move_y) miss_counter = 0 tries = 0 while not self.finished() and miss_counter < 2 and len(deque) != 0: self.moves += 1 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.list_of_hits.append(next_field) next_field.visited = True self._add_vertical_neighbours_deque(deque, next_field.x, next_field.y) self._update_screen(screen) else: miss_counter += 1 next_field.visited = True self._update_screen(screen) if tries <= 2: deque.clear() self._add_horizontal_neighbours_deque(deque, first_hit) miss_counter = 0 while not self.finished() and miss_counter < 2 and len(deque) != 0: next_field = deque.popleft() self.moves += 1 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.list_of_hits.append(next_field) next_field.visited = True self._add_horizontal_neighbours_deque(deque, next_field) self._update_screen(screen) else: miss_counter += 1 next_field.visited = True self._update_screen(screen) if self.hits == 16: deque.clear() for element in self.list_of_hits: self.add_neighbours_deque(deque, element.x, element.y) while not self.finished(): if len(deque) == 0: print(self.list_of_hits) break 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: next_field.visited = True self._update_screen(screen) return self.moves
from collections import deque import sys input = sys.stdin.readline N = int(input()) deque = deque() for _ in range(N): cmds = input().split() if cmds[0] == "push_front": deque.appendleft(cmds[1]) elif cmds[0] == "push_back": deque.append(cmds[1]) elif cmds[0] == "pop_front": if deque: print(deque.popleft()) else: print(-1) elif cmds[0] == "pop_back": if deque: print(deque.pop()) else: print(-1) elif cmds[0] == "size": print(len(deque)) elif cmds[0] == "empty": if deque: print(0) else: print(1) elif cmds[0] == "front": if deque: print(deque[0]) else: print(-1) elif cmds[0] == "back": if deque: print(deque[-1]) else: print(-1)
def get_back(self): return -1 if self.empty() == 1 else self.arr[self.rear] num = int(sys.stdin.readline().strip()) deque = deque() for i in range(num): line = sys.stdin.readline().strip().split() if line[0] == 'pop_front': if len(deque) == 0: print('-1') else: print(str(deque.popleft())) elif line[0] == 'pop_back': if len(deque) == 0: print('-1') else: print(str(deque.pop())) elif line[0] == 'push_front': deque.appendleft(line[1]) elif line[0] == 'push_back': deque.append(line[1]) elif line[0] == 'empty': print('1' if len(deque) == 0 else '0') elif line[0] == 'front': if len(deque) == 0: print('-1') else:
from collections import deque def is_more_dangerous(deq): for i in deq: if deq[0] < i: return True return False cnt = 0 n, m = map(int, input().split()) idx = m lst = list(map(int, input().split())) deque = deque(lst) while True: val = deque.popleft() if is_more_dangerous(deque): deque.append(val) if idx == 0: idx = len(deque) else: cnt += 1 if idx == 0: break idx -= 1 print(cnt)
def rmvBlank(deque: deque): for _ in range(4): deque.popleft()
from collections import deque N, X, Y = map(int, input().split()) p = deque() p.append([0, 0, 1]) checked = {} for _ in range(N): x, y = map(int, input().split()) key = str(x) + '_' + str(y) checked[key] = True move = [[1, 1], [0, 1], [-1, 1], [1, 0], [-1, 0], [0, -1]] while len(p) != 0: xy = deque.popleft(p) for m in move: x = xy[0] + m[0] y = xy[1] + m[1] key = str(x) + '_' + str(y) if key in checked: continue if x == X and y == Y: print(xy[2]) exit(0) elif -202 <= x <= 202 and -202 <= y <= 202: p.append([x, y, xy[2] + 1]) checked[key] = True print(-1)
import sys from collections import deque N = int(sys.stdin.readline()) deque = deque() for i in range(1,N+1): deque.append(i) # print(len(deque)) while len(deque) > 1: deque.popleft() a = deque.popleft() deque.append(a) print(deque.pop())
#deque가 비어있는 지 확인하는 함수 def isEmpty(deque) : if not deque : return True else : return False #명령어 수를 입력받는다. n=int(input()) #명령어를 입력받는다. for _ in range(n) : cmd=input().split() #push 3 입력 시 cmd=['push', '3'] if cmd[0] == 'push_front' : deque.appendleft(cmd[1]) elif cmd[0] == 'push_back' : deque.append(cmd[1]) elif cmd[0] == 'pop_front' : print(-1) if isEmpty(deque) else print(deque.popleft()) elif cmd[0] == 'pop_back' : print(-1) if isEmpty(deque) else print(deque.pop()) elif cmd[0] == 'size' : print(len(deque)) elif cmd[0] == 'empty' : print(1) if isEmpty(deque) else print(0) elif cmd[0] == 'front' : print(-1) if isEmpty(deque) else print(deque[0]) elif cmd[0] == 'back' : print(-1) if isEmpty(deque) else print(deque[-1])
from collections import deque food = int(input()) deque = deque([int(x) for x in input().split(" ")]) biggest_order = max(deque) print(biggest_order) while deque: current_order = deque.popleft() if food >= current_order: food -= current_order else: deque.appendleft(current_order) print(f"Orders left: {' '.join([str(x) for x in deque])}") break if not deque: print("Orders complete")
cranes.sort(reverse=True) weights.sort(reverse=True) deque = deque(weights) result = [] count = 0 answer = 0 switch = False if cranes[0] < weights[0]: print(-1) else: while (len(deque) != 0): for i in cranes: for j in deque: if j <= i: result.append(deque.popleft()) switch = True count += 1 break if switch: switch = False break if count == len(cranes): answer += 1 count = 0 # 6 10 # 9 if len(deque) == 0: answer += 1 print(answer) break
from collections import deque n, k = map(int, input().split()) deque = deque() count = [] for i in range(n): deque.append(i + 1) print('<', end='') while deque: for i in range(k - 1): deque.append(deque[0]) deque.popleft() count.append(deque.popleft()) for i in range(len(count) - 1): print(count[i], end=', ') print(count[len(count) - 1], end='>')
import sys from collections import deque n = int(sys.stdin.readline()) cards = deque([i + 1 for i in range(n)]) while len(cards) != 1: print(deque.popleft(cards), end=' ') c = deque.popleft(cards) cards.append(c) print(deque.popleft(cards)) ''' 입력 예시 4 7 출력 예시 1 3 2 4 1 3 5 7 4 2 6 '''
def shift(deque): try: return deque.popleft() except: return None
import sys from collections import deque num = int(sys.stdin.readline()) deque = deque() cnt = 1 for i in range(num): deque.append(i + 1) while True: if len(deque) == 1: print(deque[0]) break elif cnt % 2 != 0: deque.popleft() cnt += 1 elif cnt % 2 == 0: number = deque.popleft() deque.append(number) cnt += 1
def popleft(self): x = deque.popleft(self) if self.mins[0] == x: self.mins.popleft() return x
usage_error() for o, a in opts: if o in ("-h", "--help"): usage_error() #else: # assert False, "unhandled option" #print "type(args)", type(args) numargs = len(args) if numargs==0: usage_error() args = deque(args) command = deque.popleft(args) if command == "help": ipic_help(args) elif command == "grep": ipic_grep(args) elif command == "ctags": ipic_ctags(args) elif command == "cmake": ipic_cmake(args) elif command == "make": ipic_make(args) elif command == "run": ipic_run(args, 'mpirun') elif command == "exec": ipic_run(args, 'mpiexec')
def popleft(self): v = deque.popleft(self) if len(self[0])>0: self[0].handle_head_of_queue() return v
def popleft(self): self.__size_sema.acquire() return deque.popleft(self)
def pop(): if not deque: return (-1) else: return (deque.popleft())
usage_error() for o, a in opts: if o in ("-h", "--help"): usage_error() #else: # assert False, "unhandled option" #print "type(args)", type(args) numargs = len(args) if numargs==0: usage_error() args = deque(args) command = deque.popleft(args) if command == "help": ipic_help(args) elif command == "ctags": ipic_ctags(args) elif command == "cmake": ipic_cmake(args) elif command == "make": ipic_make(args) elif command == "run": ipic_run(args, 'mpirun') elif command == "exec": ipic_run(args, 'mpiexec') elif command == "setstripe" \ or command == "getstripe":
from collections import deque n = int(input()) deque = deque([i for i in range(1, n + 1)]) while (len(deque)) > 1: deque.popleft() move = deque.popleft() deque.append(move) print(deque[0])
#嵌套使用List Comprehensions matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] print([[row[i] for row in matrix] for i in range(4)]) #使用List Comprehensions square = [(x, y) for x in [1, 2, 3] for y in [3, 1, 4] if x != y] [x * 2 for x in range(1, 4)] [(x, x**2) for x in range(1, 4)] vec = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] [num for elem in vec for num in elem] print(square) #使用lambda表达式 square = list(map(lambda x: x**2, range(10))) print(square) #注意下面的i不是临时变量 square = [] for i in range(1, 5): square.append(i) print(square) print(i) li = ['1', '2'] li.sort(key=1, reverse=False) li = ['1', '2'] li.extend(range(5, 10)) li.remove(5) deque = deque(["Eric", "John", "Michael"]) deque.popleft() print(deque)
temp = [] # 입력받고 정렬후 큐에 넣기 for i in range(n): matrix.append([i for i in list(map(int, sys.stdin.readline().split()))]) for j in range(n): if matrix[i][j] != 0: temp.append([matrix[i][j], i, j, 0]) s, x, y = map(int, input().split()) temp.sort(key=lambda x: x[0]) q = q(temp) dx = [-1, 1, 0, 0] dy = [0, 0, -1, 1] #전염 시작 while q: val, nx, ny, ns = q.popleft() #찾는 위치에 값이 들어온 경우 혹은 시간이 다된 경우 if nx == x - 1 and ny == y - 1 or ns == s: break for i in range(4): ix = nx + dx[i] iy = ny + dy[i] # 범위 안에 있고 감엽시킬수있으면 큐에 저장 if ix >= 0 and ix < n and iy >= 0 and iy < n: if matrix[ix][iy] == 0: q.append([val, ix, iy, ns + 1]) matrix[ix][iy] = val print(matrix[x - 1][y - 1]) ''' 경쟁적 전염 사용한 자료구조: DFS -> 시간 초과
from collections import deque N, K = map(int, input().split()) numbers = deque([i for i in range(2, N + 1)]) count = 0 while numbers: P = deque.popleft(numbers) count += 1 if count == K: print(P) exit(0) i = 2 while P * i <= N: if P * i in numbers: numbers.remove(P * i) count += 1 if count == K: print(P * i) exit(0) i += 1
# 백준 알고리즘 - 2164 # 시간초과 # n = int(input()) # card = [] # for i in range(n, 0, -1) : # card.append(i) # while len(card) != 1 : # card.pop() # card.insert(0, card.pop()) # print(card[-1]) from collections import deque N = int(input()) deque = deque([i for i in range(1, N + 1)]) while (not (len(deque) == 1)): # 버리고, deque.popleft() # 맨 앞의 숫자를 뒤로 옮기자. move_num = deque.popleft() deque.append(move_num) print(deque[0])
from collections import deque n = int(input()) deque = deque([i for i in range(1, n + 1)]) while len(deque) > 1: deque.popleft() deque.append(deque.popleft()) print(deque[0])
T = Tree(n) for _ in range(n - 1): a, b = map(int, input().split()) T.add_edge(a - 1, b - 1) T.set_root(0) for x in T.order: 行きがけ順 for x in T.order[::-1]: 帰りがけ順で from collections import deque P = [-1] * N # P[i] はiの親。iが根なら-1 Q = deque([0]) # queue。根にするやつを最初に追加 R = [] # トポロジカルソート while Q: i = deque.popleft(Q) R.append(i) for a in X[i]: if a == P[i]: continue P[a] = i X[a].remove(i) # ☆☆☆ deque.append(Q, a) print("X =", X) # 子リスト print("P =", P) # 親 print("R =", R) # トポロジカルソート