本文整理汇总了Python中itertools.permutations方法的典型用法代码示例。如果您正苦于以下问题:Python itertools.permutations方法的具体用法?Python itertools.permutations怎么用?Python itertools.permutations使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类itertools
的用法示例。
在下文中一共展示了itertools.permutations方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: assert_permute_consistent
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import permutations [as 别名]
def assert_permute_consistent(gate):
gate = gate.__copy__()
n_qubits = gate.num_qubits()
qubits = cirq.LineQubit.range(n_qubits)
for pos in itertools.permutations(range(n_qubits)):
permuted_gate = gate.__copy__()
gate.permute(pos)
assert permuted_gate.permuted(pos) == gate
actual_unitary = cirq.unitary(permuted_gate)
ops = [
cca.LinearPermutationGate(n_qubits, dict(zip(range(n_qubits), pos)),
ofc.FSWAP)(*qubits),
gate(*qubits),
cca.LinearPermutationGate(n_qubits, dict(zip(pos, range(n_qubits))),
ofc.FSWAP)(*qubits)
]
circuit = cirq.Circuit(ops)
expected_unitary = cirq.unitary(circuit)
assert np.allclose(actual_unitary, expected_unitary)
with pytest.raises(ValueError):
gate.permute(range(1, n_qubits))
with pytest.raises(ValueError):
gate.permute([1] * n_qubits)
示例2: apply
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import permutations [as 别名]
def apply(self, solver, players_dict):
if not self.optimizer.opposing_teams_position_restriction:
return
for game in self.optimizer.games:
first_team_players = {player: variable for player, variable in players_dict.items()
if player.team == game.home_team}
second_team_players = {player: variable for player, variable in players_dict.items()
if player.team == game.away_team}
for first_team_positions, second_team_positions in \
permutations(self.optimizer.opposing_teams_position_restriction, 2):
first_team_variables = [variable for player, variable in first_team_players.items()
if list_intersection(player.positions, first_team_positions)]
second_team_variables = [variable for player, variable in second_team_players.items()
if list_intersection(player.positions, second_team_positions)]
for variables in product(first_team_variables, second_team_variables):
solver.add_constraint(variables, None, SolverSign.LTE, 1)
示例3: partitions
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import permutations [as 别名]
def partitions(n):
"""
Iterate over all partitions of integer `n`.
A partition of `n` here is defined as a list of one or more non-zero
integers which sum to `n`. Every partition is iterated over exacty
once - there are no duplicates/repetitions.
Parameters
----------
n : int
The number to partition.
Returns
-------
iterator
Iterates over arrays of integers (partitions).
"""
for p in sorted_partitions(n):
previous = tuple()
for pp in _itertools.permutations(p[::-1]): # flip p so it's in *ascending* order
if pp > previous: # only *unique* permutations
previous = pp # (relies in itertools implementatin detail that
yield pp # any permutations of a sorted iterable are in
# sorted order unless they are duplicates of prior permutations
示例4: _validate_options
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import permutations [as 别名]
def _validate_options(cls, options):
"""Validate the mutually exclusive options.
Return `True` iff only zero or one of `BASE_ERROR_SELECTION_OPTIONS`
was selected.
"""
for opt1, opt2 in \
itertools.permutations(cls.BASE_ERROR_SELECTION_OPTIONS, 2):
if getattr(options, opt1) and getattr(options, opt2):
log.error('Cannot pass both {} and {}. They are '
'mutually exclusive.'.format(opt1, opt2))
return False
if options.convention and options.convention not in conventions:
log.error("Illegal convention '{}'. Possible conventions: {}"
.format(options.convention,
', '.join(conventions.keys())))
return False
return True
示例5: test_ybd
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import permutations [as 别名]
def test_ybd(self):
# If we have a 4-digit year, a non-numeric month (abbreviated or not),
# and a day (1 or 2 digits), then there is no ambiguity as to which
# token is a year/month/day. This holds regardless of what order the
# terms are in and for each of the separators below.
seps = ['-', ' ', '/', '.']
year_tokens = ['%Y']
month_tokens = ['%b', '%B']
day_tokens = ['%d']
if PLATFORM_HAS_DASH_D:
day_tokens.append('%-d')
prods = itertools.product(year_tokens, month_tokens, day_tokens)
perms = [y for x in prods for y in itertools.permutations(x)]
unambig_fmts = [sep.join(perm) for sep in seps for perm in perms]
actual = datetime(2003, 9, 25)
for fmt in unambig_fmts:
dstr = actual.strftime(fmt)
res = parse(dstr)
self.assertEqual(res, actual)
示例6: test_count_nonzero_axis_consistent
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import permutations [as 别名]
def test_count_nonzero_axis_consistent(self):
# Check that the axis behaviour for valid axes in
# non-special cases is consistent (and therefore
# correct) by checking it against an integer array
# that is then casted to the generic object dtype
from itertools import combinations, permutations
axis = (0, 1, 2, 3)
size = (5, 5, 5, 5)
msg = "Mismatch for axis: %s"
rng = np.random.RandomState(1234)
m = rng.randint(-100, 100, size=size)
n = m.astype(object)
for length in range(len(axis)):
for combo in combinations(axis, length):
for perm in permutations(combo):
assert_equal(
np.count_nonzero(m, axis=perm),
np.count_nonzero(n, axis=perm),
err_msg=msg % (perm,))
示例7: test_unstack
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import permutations [as 别名]
def test_unstack(self, data, index, obj):
data = data[:len(index)]
if obj == "series":
ser = pd.Series(data, index=index)
else:
ser = pd.DataFrame({"A": data, "B": data}, index=index)
n = index.nlevels
levels = list(range(n))
# [0, 1, 2]
# [(0,), (1,), (2,), (0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]
combinations = itertools.chain.from_iterable(
itertools.permutations(levels, i) for i in range(1, n)
)
for level in combinations:
result = ser.unstack(level=level)
assert all(isinstance(result[col].array, type(data))
for col in result.columns)
expected = ser.astype(object).unstack(level=level)
result = result.astype(object)
self.assert_frame_equal(result, expected)
示例8: test_equals_block_order_different_dtypes
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import permutations [as 别名]
def test_equals_block_order_different_dtypes(self):
# GH 9330
mgr_strings = [
"a:i8;b:f8", # basic case
"a:i8;b:f8;c:c8;d:b", # many types
"a:i8;e:dt;f:td;g:string", # more types
"a:i8;b:category;c:category2;d:category2", # categories
"c:sparse;d:sparse_na;b:f8", # sparse
]
for mgr_string in mgr_strings:
bm = create_mgr(mgr_string)
block_perms = itertools.permutations(bm.blocks)
for bm_perm in block_perms:
bm_this = BlockManager(bm_perm, bm.axes)
assert bm.equals(bm_this)
assert bm_this.equals(bm)
示例9: testGetBackwardOpsChain
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import permutations [as 别名]
def testGetBackwardOpsChain(self):
# a -> b -> c
a = tf.placeholder(tf.float32)
b = tf.sqrt(a)
c = tf.square(b)
for n in range(4):
for seed_tensors in permutations([a, b, c], n):
if c in seed_tensors:
truth = [a.op, b.op, c.op]
elif b in seed_tensors:
truth = [a.op, b.op]
elif a in seed_tensors:
truth = [a.op]
else:
truth = []
self.assertEqual(get_backward_ops(seed_tensors), truth)
self.assertEqual(get_backward_ops([c], treat_as_inputs=[b]), [c.op])
self.assertEqual(
get_backward_ops([b, c], treat_as_inputs=[b]), [c.op])
self.assertEqual(
get_backward_ops([a, c], treat_as_inputs=[b]), [a.op, c.op])
示例10: visit_BoolOp
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import permutations [as 别名]
def visit_BoolOp(self, target, pattern):
'Match pattern on flattened operators of same length and same type'
conds = (type(target.op) == type(pattern.op) and
len(target.values) == len(pattern.values))
if not conds:
return False
# try every combination wildcard <=> value
old_context = deepcopy(self.wildcards)
for perm in itertools.permutations(target.values):
self.wildcards = deepcopy(old_context)
res = True
i = 0
for i in range(len(pattern.values)):
res &= self.visit(perm[i], pattern.values[i])
if res:
return res
return False
示例11: get_all_sub_obj_pairs
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import permutations [as 别名]
def get_all_sub_obj_pairs(self, sent):
if isinstance(sent, str):
sents_doc = self.nlp(sent)
else:
sents_doc = sent
sent_ = next(sents_doc.sents)
root = sent_.root
#print('Root: ', root.text)
subject = None; objs = []; pairs = []
for child in root.children:
#print(child.dep_)
if child.dep_ in ["nsubj", "nsubjpass"]:
if len(re.findall("[a-z]+",child.text.lower())) > 0: # filter out all numbers/symbols
subject = child; #print('Subject: ', child)
elif child.dep_ in ["dobj", "attr", "prep", "ccomp"]:
objs.append(child); #print('Object ', child)
if (subject is not None) and (len(objs) > 0):
for a, b in permutations([subject] + [obj for obj in objs], 2):
a_ = [w for w in a.subtree]
b_ = [w for w in b.subtree]
pairs.append((a_[0] if (len(a_) == 1) else a_ , b_[0] if (len(b_) == 1) else b_))
return pairs
示例12: get_subject_objects
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import permutations [as 别名]
def get_subject_objects(sent_):
### get subject, object entities by dependency tree parsing
#sent_ = next(sents_doc.sents)
root = sent_.root
subject = None; objs = []; pairs = []
for child in root.children:
#print(child.dep_)
if child.dep_ in ["nsubj", "nsubjpass"]:
if len(re.findall("[a-z]+",child.text.lower())) > 0: # filter out all numbers/symbols
subject = child; #print('Subject: ', child)
elif child.dep_ in ["dobj", "attr", "prep", "ccomp"]:
objs.append(child); #print('Object ', child)
if (subject is not None) and (len(objs) > 0):
for a, b in permutations([subject] + [obj for obj in objs], 2):
a_ = [w for w in a.subtree]
b_ = [w for w in b.subtree]
pairs.append((a_[0] if (len(a_) == 1) else a_ , b_[0] if (len(b_) == 1) else b_))
return pairs
示例13: permscan
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import permutations [as 别名]
def permscan(self, address_space, offset = 0, maxlen = None):
times = []
# Run a warm-up scan to ensure the file is cached as much as possible
self.oldscan(address_space, offset, maxlen)
perms = list(itertools.permutations(self.checks))
for i in range(len(perms)):
self.checks = perms[i]
print "Running scan {0}/{1}...".format(i + 1, len(perms))
profobj = ScanProfInstance(self.oldscan, address_space, offset, maxlen)
value = timeit.timeit(profobj, number = self.repeats)
times.append((value, len(list(profobj.results)), i))
print "Scan results"
print "{0:20} | {1:7} | {2:6} | {3}".format("Time", "Results", "Perm #", "Ordering")
for val, l, ordering in sorted(times):
print "{0:20} | {1:7} | {2:6} | {3}".format(val, l, ordering, perms[ordering])
sys.exit(1)
示例14: __call__
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import permutations [as 别名]
def __call__(self, *sequences):
if not sequences:
return 0
sequences = self._get_sequences(*sequences)
concat_len = float('Inf')
empty = type(sequences[0])()
for data in permutations(sequences):
if isinstance(empty, (str, bytes)):
data = empty.join(data)
else:
data = sum(data, empty)
concat_len = min(concat_len, self._get_size(data))
compressed_lens = [self._get_size(s) for s in sequences]
max_len = max(compressed_lens)
if max_len == 0:
return 0
return (concat_len - min(compressed_lens) * (len(sequences) - 1)) / max_len
示例15: test_calc_object_time_options
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import permutations [as 别名]
def test_calc_object_time_options():
time_options = ['av', 'std', 'ts', 'reg.av', 'reg.std', 'reg.ts']
for i in range(1, len(time_options) + 1):
for time_option in list(itertools.permutations(time_options, i)):
if time_option != ('None',):
test_params_not_time_defined['dtype_out_time'] = time_option
with pytest.raises(ValueError):
Calc(**test_params_not_time_defined)