本文整理汇总了Python中collections.deque方法的典型用法代码示例。如果您正苦于以下问题:Python collections.deque方法的具体用法?Python collections.deque怎么用?Python collections.deque使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类collections
的用法示例。
在下文中一共展示了collections.deque方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _check_for_obst
# 需要导入模块: import collections [as 别名]
# 或者: from collections import deque [as 别名]
def _check_for_obst(self, steps, vector_mag, clear_x, clear_y):
"""
Look for obstacles in the path 'steps'
and stop short if they are there.
clear_x and clear_y start out as the agent's current pos,
which must, of course, be clear for this agent to occupy!
If there happens to be an obstacle less than tolerance - 1
from the agent's initial square, well, we just stay put.
"""
lag = self.tolerance - 1
lookahead = deque(maxlen=lag + 1)
for (x, y) in steps:
lookahead.append((x, y))
if not self.env.is_cell_empty(x, y):
return (clear_x, clear_y)
elif lag > 0:
lag -= 1
else:
(clear_x, clear_y) = lookahead.popleft()
return (clear_x, clear_y)
示例2: __init__
# 需要导入模块: import collections [as 别名]
# 或者: from collections import deque [as 别名]
def __init__(self, width, height, depth, rand_max, table=None):
self.toroidal = True
self._rand_max = rand_max
if table:
self.table = table
self.depth = len(table)
self.height = len(table[0])
self.width = len(table[0][0])
else:
self.height = height
self.width = width
self.depth = depth
self.genNewTable()
self._oldStates = deque()
for i in range(3):
self._oldStates.append([])
self.offsets = list(itertools.product([-1, 0, 1], repeat=3))
self.offsets.remove((0, 0, 0)) # remove center point
示例3: _bfs
# 需要导入模块: import collections [as 别名]
# 或者: from collections import deque [as 别名]
def _bfs(root_node, process_node):
"""
Implementation of Breadth-first search (BFS) on caffe network DAG
:param root_node: root node of caffe network DAG
:param process_node: function to run on each node
"""
from collections import deque
seen_nodes = set()
next_nodes = deque()
seen_nodes.add(root_node)
next_nodes.append(root_node)
while next_nodes:
current_node = next_nodes.popleft()
# process current node
process_node(current_node)
for child_node in current_node.children:
if child_node not in seen_nodes:
seen_nodes.add(child_node)
next_nodes.append(child_node)
示例4: topsort
# 需要导入模块: import collections [as 别名]
# 或者: from collections import deque [as 别名]
def topsort(nodes):
n = len(nodes)
deg = [0]*n
g = [[] for _ in xrange(n)]
for i,node in enumerate(nodes):
if 'inputs' in node:
for j in node['inputs']:
deg[i] += 1
g[j[0]].append(i)
from collections import deque
q = deque([i for i in xrange(n) if deg[i]==0])
res = []
for its in xrange(n):
i = q.popleft()
res.append(nodes[i])
for j in g[i]:
deg[j] -= 1
if deg[j] == 0:
q.append(j)
new_ids=dict([(node['name'],i) for i,node in enumerate(res)])
for node in res:
if 'inputs' in node:
for j in node['inputs']:
j[0]=new_ids[nodes[j[0]]['name']]
return res
示例5: parse
# 需要导入模块: import collections [as 别名]
# 或者: from collections import deque [as 别名]
def parse(file_like):
"""
Parse a model in the TMHMM 2.0 format.
:param file_like: a file-like object to read and parse.
:return: a model
"""
contents = _strip_comments(file_like)
tokens = collections.deque(_tokenize(contents))
tokens, header = _parse_header(tokens)
states = {}
while tokens:
tokens, (name, state) = _parse_state(tokens)
states[name] = state
assert not tokens, "list of tokens not consumed completely"
return header, _to_matrix_form(header['alphabet'],
_normalize_states(states))
示例6: __init__
# 需要导入模块: import collections [as 别名]
# 或者: from collections import deque [as 别名]
def __init__(self, authClient=None, product_id=None, userorder=None,
orders_class=None):
self.authClient = authClient
self.product_id = product_id
self.maxthreads = 10
self.lastb_thread = 0
self.lasts_thread = 0
self.lastc_thread = 0
self.order = []
self.orders_class = orders_class
self.orders = None
self.size = 0
self.price = 0
self.allocated_funds = 0
self.rejected = False
self.no_funds = False
self.adduserorder = userorder
self.bnthreads = deque(maxlen=self.maxthreads)
self.snthreads = deque(maxlen=self.maxthreads)
self.cancelnthreads = deque(maxlen=self.maxthreads)
self.buildThreads(n=self.maxthreads)
示例7: __init__
# 需要导入模块: import collections [as 别名]
# 或者: from collections import deque [as 别名]
def __init__(self, env, warm_up_examples=0,
ball_down_skip=0,
big_ball=False,
include_direction_info=False,
reward_clipping=True):
super(BreakoutWrapper, self).__init__(
env, warm_up_examples=warm_up_examples,
warmup_action=BreakoutWrapper.FIRE_ACTION)
self.warm_up_examples = warm_up_examples
self.observation_space = gym.spaces.Box(low=0, high=255,
shape=(210, 160, 3),
dtype=np.uint8)
self.ball_down_skip = ball_down_skip
self.big_ball = big_ball
self.reward_clipping = reward_clipping
self.include_direction_info = include_direction_info
self.direction_info = deque([], maxlen=2)
self.points_gained = False
msg = ("ball_down_skip should be bigger equal 9 for "
"include_direction_info to work correctly")
assert not self.include_direction_info or ball_down_skip >= 9, msg
示例8: _insert_header
# 需要导入模块: import collections [as 别名]
# 或者: from collections import deque [as 别名]
def _insert_header(network_str, incomings, outgoings):
""" Insert the header (first two lines) in the representation."""
line_1 = deque([])
if incomings:
line_1.append('In -->')
line_1.append('Layer')
if outgoings:
line_1.append('--> Out')
line_1.append('Description')
line_2 = deque([])
if incomings:
line_2.append('-------')
line_2.append('-----')
if outgoings:
line_2.append('-------')
line_2.append('-----------')
network_str.appendleft(line_2)
network_str.appendleft(line_1)
return network_str
示例9: from_text
# 需要导入模块: import collections [as 别名]
# 或者: from collections import deque [as 别名]
def from_text(cls, text):
"""Create tree from bracket notation
Bracket notation encodes the trees with nested parentheses, for example,
in tree {A{B{X}{Y}{F}}{C}} the root node has label A and two children
with labels B and C. Node with label B has three children with labels
X, Y, F.
"""
tree_stack = []
stack = []
for letter in text:
if letter == "{":
stack.append("")
elif letter == "}":
text = stack.pop()
children = deque()
while tree_stack and tree_stack[-1][1] > len(stack):
child, _ = tree_stack.pop()
children.appendleft(child)
tree_stack.append((cls(text, *children), len(stack)))
else:
stack[-1] += letter
return tree_stack[0][0]
示例10: post_macro_functions
# 需要导入模块: import collections [as 别名]
# 或者: from collections import deque [as 别名]
def post_macro_functions(lines):
""" This function is called after the regular macros have been expanded. lines is a
collections.deque of Line objects - see ksp_compiler.py."""
handleIncrementer(lines)
handleConstBlock(lines)
handleStructs(lines)
handleUIArrays(lines)
handleSameLineDeclaration(lines)
handleMultidimensionalArrays(lines)
handleListBlocks(lines)
handleOpenSizeArrays(lines)
handlePersistence(lines)
handleLists(lines)
handleUIFunctions(lines)
handleStringArrayInitialisation(lines)
handleArrayConcat(lines)
#=================================================================================================
示例11: buildLines
# 需要导入模块: import collections [as 别名]
# 或者: from collections import deque [as 别名]
def buildLines(self):
""" Return all the lines needed to perfrom the concat. """
newLines = collections.deque()
numArgs = len(self.arraysToConcat)
offsets = ["0"]
offsets.extend(["num_elements(%s)" % arrName for arrName in self.arraysToConcat])
addOffset = ""
if numArgs != 1:
addOffset = " + concat_offset"
newLines.append(self.line.copy("concat_offset := 0"))
offsetCommand = "concat_offset := concat_offset + #offset#"
templateText = [
"for concat_it := 0 to num_elements(#arg#) - 1",
" #parent#[concat_it%s] := #arg#[concat_it]" % addOffset,
"end for"]
for j in range(numArgs):
if j != 0 and numArgs != 1:
newLines.append(self.line.copy(offsetCommand.replace("#offset#", offsets[j])))
for text in templateText:
newLines.append(self.line.copy(text.replace("#arg#", self.arraysToConcat[j]).replace("#parent#", self.arrayToFill)))
return(newLines)
示例12: handleArrayConcat
# 需要导入模块: import collections [as 别名]
# 或者: from collections import deque [as 别名]
def handleArrayConcat(lines):
arrayConcatRe = r"(?P<declare>^\s*declare\s+)?%s\s*(?P<brackets>\[(?P<arraysize>.*)\])?\s*:=\s*%s\s*\((?P<arraylist>[^\)]*)" % (variableNameRe, concatSyntax)
newLines = collections.deque()
for lineIdx in range(len(lines)):
line = lines[lineIdx].command.strip()
if "concat" in line:
m = re.search(arrayConcatRe, line)
if m:
concatObj = ArrayConcat(m.group("whole"), m.group("declare"), m.group("brackets"), m.group("arraysize"), m.group("arraylist"), lines[lineIdx])
concatObj.checkArraySize(lineIdx, lines)
if m.group("declare"):
newLines.append(lines[lineIdx].copy(concatObj.getRawArrayDeclaration()))
newLines.extend(concatObj.buildLines())
continue
# The variables needed are declared at the start of the init callback.
elif line.startswith("on"):
if re.search(initRe, line):
newLines.append(lines[lineIdx])
newLines.append(lines[lineIdx].copy("declare concat_it"))
newLines.append(lines[lineIdx].copy("declare concat_offset"))
continue
newLines.append(lines[lineIdx])
replaceLines(lines, newLines)
#=================================================================================================
示例13: handleListBlocks
# 需要导入模块: import collections [as 别名]
# 或者: from collections import deque [as 别名]
def handleListBlocks(lines):
listBlockStartRe = r"^list\s*%s\s*(?:\[(?P<size>%s)?\])?$" % (variableNameRe, variableOrInt)
listBlockEndRe = r"^end\s+list$"
newLines = collections.deque()
listBlockObj = None
isListBlock = False
for lineIdx in range(len(lines)):
line = lines[lineIdx].command.strip()
m = re.search(listBlockStartRe, line)
if m:
isListBlock = True
listBlockObj = ListBlock(m.group("whole"), m.group("size"))
elif isListBlock and not line == "":
if re.search(listBlockEndRe, line):
isListBlock = False
if listBlockObj.members:
newLines.extend(listBlockObj.buildLines(lines[lineIdx]))
else:
listBlockObj.addMember(line)
else:
newLines.append(lines[lineIdx])
replaceLines(lines, newLines)
#=================================================================================================
示例14: handleOpenSizeArrays
# 需要导入模块: import collections [as 别名]
# 或者: from collections import deque [as 别名]
def handleOpenSizeArrays(lines):
""" When an array size is left with an open number of elements, use the list of initialisers to provide the array size.
Const variables are also generated for the array size. """
openArrayRe = r"^\s*declare\s+%s%s\s*\[\s*\]\s*:=\s*\(" % (persistenceRe, variableNameRe)
newLines = collections.deque()
for lineIdx in range(len(lines)):
line = lines[lineIdx].command.strip()
m = re.search(openArrayRe, line)
if m:
stringList = ksp_compiler.split_args(line[line.find("(") + 1 : len(line) - 1], line)
numElements = len(stringList)
name = m.group("name")
newLines.append(lines[lineIdx].copy(line[: line.find("[") + 1] + str(numElements) + line[line.find("[") + 1 :]))
newLines.append(lines[lineIdx].copy("declare const %s.SIZE := %s" % (name, str(numElements))))
else:
newLines.append(lines[lineIdx])
replaceLines(lines, newLines)
#=================================================================================================
示例15: handleIterateMacro
# 需要导入模块: import collections [as 别名]
# 或者: from collections import deque [as 别名]
def handleIterateMacro(lines):
scan = False
newLines = collections.deque()
for lineIdx in range(len(lines)):
line = lines[lineIdx].command.strip()
if line.startswith("iterate_macro"):
scan = True
m = re.search(r"^iterate_macro\s*\((?P<macro>.+)\)\s*:=\s*(?P<min>.+)\b(?P<direction>to|downto)(?P<max>(?:.(?!\bstep\b))+)(?:\s+step\s+(?P<step>.+))?$", line)
if m:
iterateObj = IterateMacro(m.group("macro"), m.group("min"), m.group("max"), m.group("step"), m.group("direction"), lines[lineIdx])
newLines.extend(iterateObj.buildLines())
else:
newLines.append(lines[lineIdx])
else:
newLines.append(lines[lineIdx])
replaceLines(lines, newLines)
return scan
#=================================================================================================