Python itertools.permutations() Examples
The following are 30
code examples of itertools.permutations().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
itertools
, or try the search function
.
Example #1
Source File: pattern_matcher.py From sspam with BSD 3-Clause "New" or "Revised" License | 6 votes |
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
Example #2
Source File: test_parser.py From plugin.video.emby with GNU General Public License v3.0 | 6 votes |
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)
Example #3
Source File: config.py From linter-pylama with MIT License | 6 votes |
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
Example #4
Source File: scanprof.py From aumfor with GNU General Public License v3.0 | 6 votes |
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)
Example #5
Source File: test_numeric.py From recruit with Apache License 2.0 | 6 votes |
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,))
Example #6
Source File: listtools.py From pyGSTi with Apache License 2.0 | 6 votes |
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
Example #7
Source File: reshaping.py From recruit with Apache License 2.0 | 6 votes |
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)
Example #8
Source File: test_internals.py From recruit with Apache License 2.0 | 6 votes |
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)
Example #9
Source File: misc.py From BERT-Relation-Extraction with Apache License 2.0 | 6 votes |
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
Example #10
Source File: infer.py From BERT-Relation-Extraction with Apache License 2.0 | 6 votes |
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
Example #11
Source File: rules.py From pydfs-lineup-optimizer with MIT License | 6 votes |
def apply(self, solver, players_dict): raw_all_force_positions = self.optimizer.opposing_team_force_positions if not raw_all_force_positions: return all_force_positions = [tuple(sorted(positions)) for positions in raw_all_force_positions] for positions, total_combinations in Counter(all_force_positions).items(): positions_vars = [] combinations_count = 0 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(positions, 2): first_team_variables = [variable for player, variable in first_team_players.items() if first_team_positions in player.positions] second_team_variables = [variable for player, variable in second_team_players.items() if second_team_positions in player.positions] for variables in product(first_team_variables, second_team_variables): solver_variable = solver.add_variable('force_positions_%s_%d' % (positions, combinations_count)) combinations_count += 1 positions_vars.append(solver_variable) solver.add_constraint(variables, None, SolverSign.GTE, 2 * solver_variable) solver.add_constraint(positions_vars, None, SolverSign.GTE, total_combinations)
Example #12
Source File: compression_based.py From textdistance with MIT License | 6 votes |
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
Example #13
Source File: rules.py From pydfs-lineup-optimizer with MIT License | 6 votes |
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)
Example #14
Source File: test_numeric.py From vnpy_crypto with MIT License | 6 votes |
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,))
Example #15
Source File: test_internals.py From vnpy_crypto with MIT License | 6 votes |
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)
Example #16
Source File: fermionic_simulation_test.py From OpenFermion-Cirq with Apache License 2.0 | 6 votes |
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)
Example #17
Source File: test_utils.py From zhusuan with MIT License | 6 votes |
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])
Example #18
Source File: test_multilevel.py From vnpy_crypto with MIT License | 5 votes |
def test_stack_order_with_unsorted_levels(self): # GH 16323 def manual_compare_stacked(df, df_stacked, lev0, lev1): assert all(df.loc[row, col] == df_stacked.loc[(row, col[lev0]), col[lev1]] for row in df.index for col in df.columns) # deep check for 1-row case for width in [2, 3]: levels_poss = itertools.product( itertools.permutations([0, 1, 2], width), repeat=2) for levels in levels_poss: columns = MultiIndex(levels=levels, labels=[[0, 0, 1, 1], [0, 1, 0, 1]]) df = DataFrame(columns=columns, data=[range(4)]) for stack_lev in range(2): df_stacked = df.stack(stack_lev) manual_compare_stacked(df, df_stacked, stack_lev, 1 - stack_lev) # check multi-row case mi = MultiIndex(levels=[["A", "C", "B"], ["B", "A", "C"]], labels=[np.repeat(range(3), 3), np.tile(range(3), 3)]) df = DataFrame(columns=mi, index=range(5), data=np.arange(5 * len(mi)).reshape(5, -1)) manual_compare_stacked(df, df.stack(0), 0, 1)
Example #19
Source File: token_based.py From textdistance with MIT License | 5 votes |
def __call__(self, *sequences): result = self.quick_answer(*sequences) if result is not None: return result sequences = self._get_sequences(*sequences) if self.symmetric: result = [] for seqs in permutations(sequences): result.append(self._calc(*seqs)) return sum(result) / len(result) else: return self._calc(*sequences)
Example #20
Source File: solution_1.py From ProjectEuler with MIT License | 5 votes |
def permutations(self): return set(map(int, (''.join(x) for x in permutations(str(self)))))
Example #21
Source File: test_loop_blocking_fixture.py From nn_dataflow with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _gen_loopblocking_all(self, wlkey='BASE'): ''' Generate all combinations of loop blocking factors and orders. ''' for ti, to, tb, orders in itertools.product( util.factorize(self.nld[wlkey].loopcnt[le.IFM], 3), util.factorize(self.nld[wlkey].loopcnt[le.OFM], 3), util.factorize(self.nld[wlkey].loopcnt[le.BAT], 3), itertools.product( itertools.permutations(range(le.NUM)), itertools.permutations(range(le.NUM)))): lp_ts = [None] * le.NUM lp_ts[le.IFM] = ti lp_ts[le.OFM] = to lp_ts[le.BAT] = tb yield tuple(zip(*lp_ts)), orders
Example #22
Source File: util.py From Obfuscapk with MIT License | 5 votes |
def get_random_list_permutations(input_list: list) -> list: permuted_list = list(itertools.permutations(input_list)) random.shuffle(permuted_list) return permuted_list
Example #23
Source File: test_scheduling_constraint.py From nn_dataflow with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _gen_bl(t_end=9): ''' Generator for bl_t and bl_ord. ''' return itertools.product(itertools.product(*[range(1, t_end)] * le.NUM), itertools.permutations(range(le.NUM)))
Example #24
Source File: testing_tool.py From Google-Code-Jam-2019 with GNU General Public License v3.0 | 5 votes |
def __init__(self, max_inspection, io): self.io = io self.io.SetCurrentCase(self) self.max_inspection = max_inspection permutations = [''.join(p) for p in itertools.permutations('ABCDE')] random.shuffle(permutations) self.answer = permutations.pop() self.figures = ''.join(permutations)
Example #25
Source File: _filter.py From pyuavcan with MIT License | 5 votes |
def optimize_filter_configurations(configurations: typing.Iterable[FilterConfiguration], target_number_of_configurations: int) -> typing.Sequence[FilterConfiguration]: """ Implements the CAN acceptance filter configuration optimization algorithm described in the Specification. The algorithm was originally proposed by P. Kirienko and I. Sheremet. Given a set of ``K`` filter configurations that accept CAN frames whose identifiers belong to the set ``C``, and ``N`` acceptance filters implemented in hardware, where ``1 <= N < K``, find a new set of ``K'`` filter configurations that accept CAN frames whose identifiers belong to the set ``C'``, such that ``K' <= N``, ``C'`` is a superset of ``C``, and ``|C'|`` is minimized. The algorithm is not defined for ``N >= K`` because this configuration is considered optimal. The function returns the input set unchanged in this case. If the target number of configurations is not positive, a ValueError is raised. The time complexity of this implementation is ``O(K!)``; it should be optimized. """ if target_number_of_configurations < 1: raise ValueError(f'The number of configurations must be positive; found {target_number_of_configurations}') configurations = list(configurations) while len(configurations) > target_number_of_configurations: options = itertools.starmap(lambda ia, ib: (ia[0], ib[0], ia[1].merge(ib[1])), itertools.permutations(enumerate(configurations), 2)) index_replace, index_remove, merged = max(options, key=lambda x: x[2].rank) configurations[index_replace] = merged del configurations[index_remove] # Invalidates indexes assert all(map(lambda x: isinstance(x, FilterConfiguration), configurations)) return configurations
Example #26
Source File: test_numexpr_execute.py From mars with Apache License 2.0 | 5 votes |
def testUnaryExecution(self): from mars.tensor.arithmetic import UNARY_UFUNC, arccosh, invert, sin, conj _sp_unary_ufunc = {arccosh, invert, conj} _new_unary_ufunc = list(UNARY_UFUNC - _sp_unary_ufunc) executor_numexpr = Executor() def _normalize_by_sin(func1, func2, arr): return func1(abs(sin((func2(arr))))) for i, j in itertools.permutations(range(len(_new_unary_ufunc)), 2): raw = np.random.random((8, 8, 8)) arr1 = tensor(raw, chunk_size=4) func1 = _new_unary_ufunc[i] func2 = _new_unary_ufunc[j] arr2 = _normalize_by_sin(func1, func2, arr1) res = executor_numexpr.execute_tensor(arr2, concat=True) res_cmp = self.executor.execute_tensor(arr2, concat=True) np.testing.assert_allclose(res[0], res_cmp[0]) raw = np.random.randint(100, size=(8, 8, 8)) arr1 = tensor(raw, chunk_size=4) arr2 = arccosh(1 + abs(invert(arr1))) res = executor_numexpr.execute_tensor(arr2, concat=True) res_cmp = self.executor.execute_tensor(arr2, concat=True) self.assertTrue(np.allclose(res[0], res_cmp[0]))
Example #27
Source File: test_numexpr_execute.py From mars with Apache License 2.0 | 5 votes |
def testBinExecution(self): from mars.tensor.arithmetic import BIN_UFUNC, mod, fmod, \ bitand, bitor, bitxor, lshift, rshift, ldexp _sp_bin_ufunc = [mod, fmod, bitand, bitor, bitxor, lshift, rshift] _new_bin_ufunc = list(BIN_UFUNC - set(_sp_bin_ufunc) - {ldexp}) executor_numexpr = Executor() for i, j in itertools.permutations(range(len(_new_bin_ufunc)), 2): raw = np.random.random((9, 9, 9)) arr1 = tensor(raw, chunk_size=5) func1 = _new_bin_ufunc[i] func2 = _new_bin_ufunc[j] arr2 = func1(1, func2(2, arr1)) res = executor_numexpr.execute_tensor(arr2, concat=True) res_cmp = self.executor.execute_tensor(arr2, concat=True) self.assertTrue(np.allclose(res[0], res_cmp[0])) for i, j in itertools.permutations(range(len(_sp_bin_ufunc)), 2): raw = np.random.randint(1, 100, size=(10, 10, 10)) arr1 = tensor(raw, chunk_size=3) func1 = _sp_bin_ufunc[i] func2 = _sp_bin_ufunc[j] arr2 = func1(10, func2(arr1, 5)) res = executor_numexpr.execute_tensor(arr2, concat=True) res_cmp = self.executor.execute_tensor(arr2, concat=True) self.assertTrue(np.allclose(res[0], res_cmp[0]))
Example #28
Source File: test_trie.py From pyquarkchain with MIT License | 5 votes |
def run_test(name, pairs): Logger.debug('testing %s' % name) def _dec(x): if isinstance(x, str) and x.startswith('0x'): return bytes.fromhex(str(x[2:])) if isinstance(x, str): return bytes(x, "ascii") return x pairs['in'] = [(_dec(k), _dec(v)) for k, v in pairs['in']] deletes = [(k, v) for k, v in pairs['in'] if v is None] N_PERMUTATIONS = 100 for i, permut in enumerate(itertools.permutations(pairs['in'])): if i > N_PERMUTATIONS: break if pairs.get('nopermute', None) is not None and pairs['nopermute']: permut = pairs['in'] N_PERMUTATIONS = 1 t = trie.Trie(InMemoryDb()) for k, v in permut: # logger.debug('updating with (%s, %s)' %(k, v)) if v is not None: t.update(k, v) else: t.delete(k) # make sure we have deletes at the end for k, v in deletes: t.delete(k) if pairs['root'] != '0x' + t.root_hash.hex(): raise Exception("Mismatch: %r %r %r %r" % ( name, pairs['root'], '0x' + t.root_hash.hex(), (i, list(permut) + deletes)))
Example #29
Source File: gan_component.py From HyperGAN with MIT License | 5 votes |
def permute(self, nets, k): return list(itertools.permutations(nets, k)) #this is broken
Example #30
Source File: infer.py From BERT-Relation-Extraction with Apache License 2.0 | 5 votes |
def get_all_ent_pairs(self, sent): if isinstance(sent, str): sents_doc = self.nlp(sent) else: sents_doc = sent ents = sents_doc.ents pairs = [] if len(ents) > 1: for a, b in permutations([ent for ent in ents], 2): pairs.append((a,b)) return pairs