Python itertools 模块,permutations() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用itertools.permutations()

项目:tipi-engine    作者:CIECODE-Madrid    | 项目源码 | 文件源码
def __shuffleTerms(self, terms):
        new_terms = []
        delimiter = '.*'
        for term in terms:
            if term is not None:
                term['original'] = term['term']
                if term['shuffle']:
                    perms = itertools.permutations(term['term'].split(delimiter))
                    for perm in perms:
                        new_terms.append({
                                'term': delimiter.join(perm),
                                'humanterm': term['humanterm'],
                                'original': term['original']
                                });
                else:
                    new_terms.append(term)
        return new_terms
项目:fluxpart    作者:usda-ars-ussl    | 项目源码 | 文件源码
def stats2(sarray, names=None):
    """Calculate means and (co)variances for structured array data."""

    if names is None:
        names = sarray.dtype.names
    nvar = len(names)
    data = tuple(sarray[name] for name in names)
    cov = np.cov(data)
    nondiag_cov = list(cov[i, j] for i, j in permutations(range(nvar), 2))

    names_ave = list('ave_' + name for name in names)
    names_var = list('var_' + name for name in names)
    names_cov = list(
        'cov_' + n1 + "_" + n2 for n1, n2 in permutations(names, 2))

    out = dict(zip(names_ave, np.mean(data, axis=1)))
    out.update(zip(names_var, cov.diagonal()))
    out.update(zip(names_cov, nondiag_cov))

    NamedStats = namedtuple('Stats2', names_ave + names_var + names_cov)
    return NamedStats(**out)
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def solve(s):
    '''Find solutions to alphametic equations.

    >>> solve('SEND + MORE == MONEY')
    9567 + 1085 == 10652

    '''
    words = findall('[A-Za-z]+', s)
    chars = set(''.join(words))         # characters to be substituted
    assert len(chars) <= 10             # there are only ten possible digits
    firsts = set(w[0] for w in words)   # first letters of each of word
    chars = ''.join(firsts) + ''.join(chars - firsts)   
    n = len(firsts)                     # chars[:n] cannot be assigned zero
    for perm in permutations('0123456789', len(chars)):
        if '0' not in perm[:n]:
            trans = maketrans(chars, ''.join(perm))
            equation = s.translate(trans)
            try:
                if eval(equation):
                    print equation
            except ArithmeticError:
                pass
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def createSequences(self, fromPosition, toPosition):
        """ using the permutation of all functions to generate sequences
            @param fromPosition start position/index/value
            @param toPosition end position/index/value
        """
        self.sequences = set()
        for r in range(1,len(self.registeredFunctions)):
            for functions in itertools.permutations(self.registeredFunctions, r):
                position = fromPosition
                sequence = []
                while position <= toPosition:
                    value = position
                    for function in functions:
                        value = function(value)
                    sequence.append(value)
                    position += 1
                self.sequences.add(Sequence(sequence[0:], self.combineFunctions(functions)))
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def dateformats():
    "Yield all combinations of valid date formats."

    years = ("%Y",)
    months = ("%b", "%B")
    days = ("%d",)
    times = ("%I%p", "%I:%M%p", "%H:%M", "")

    for year in years:
        for month in months:
            for day in days:
                for args in ((day, month), (month, day)):
                    date = " ".join(args)
                    for time in times:
                        for combo in permutations([year, date, time]):
                            yield " ".join(combo).strip()
项目:pyt    作者:SW10IoT    | 项目源码 | 文件源码
def get_children(p, s, length):
    children = set()
    if length < 0:
        return children
    for subset in permutations(s, length):
        setsubset = set(subset)
        append = True
        for node in children:
            if setsubset == node.s:
                append = False
                break
        n = Node(setsubset, p)
        n.children = get_children(n, setsubset, length-1)
        if append:
            children.add(n)
    return children
项目:pyt    作者:SW10IoT    | 项目源码 | 文件源码
def get_children(p, s, length):
    children = set()
    if length < 0:
        return children
    for subset in permutations(s, length):
        setsubset = set(subset)
        append = True
        for node in children:
            if setsubset == node.s:
                append = False
                break
        if append:
            n = Node(setsubset, p)
            n.children = get_children(n, setsubset, length-1)
            children.add(n)
    return children
项目:Gaia    作者:splcurran    | 项目源码 | 文件源码
def fHighDotOperator(stack, z, mode):
    if mode == 1:   # num
        def subfactorial(n):
            soFar = [1, 0]
            if n < 0:
                raise ValueError("can't comput subfactorial of negative number")
            if n < 2:
                return soFar[n]

            i = 2
            while i <= n:
                soFar.append((i-1)*(soFar[i-1]+soFar[i-2]))
                i += 1

            return soFar[-1]

        stack.append(subfactorial(int(z)))
    elif mode == 2: # str
        stack.append([''.join(p) for p in itertools.permutations(z) if all(''.join(p)[i] != z[i] for i in range(len(z)))])
    elif mode == 3: # list
        stack.append([list(p) for p in itertools.permutations(z) if all(list(p)[i] != z[i] for i in range(len(z)))])
    else:
        monadNotImplemented(mode, '')

# ?
项目:HyperGAN    作者:255BITS    | 项目源码 | 文件源码
def relation_layer(self, net):
        ops = self.ops

        #hack
        shape = ops.shape(net)
        input_size = shape[1]*shape[2]*shape[3]

        netlist = self.split_by_width_height(net)
        permutations = self.permute(netlist, 2)
        permutations = self.fully_connected_from_list(permutations)
        net = ops.concat(permutations, axis=3)

        #hack
        bs = ops.shape(net)[0]
        net = ops.reshape(net, [bs, -1])
        net = ops.linear(net, input_size)
        net = ops.reshape(net, shape)

        return net
项目:pyt    作者:python-security    | 项目源码 | 文件源码
def get_children(p, s, length):
    children = set()
    if length < 0:
        return children
    for subset in permutations(s, length):
        setsubset = set(subset)
        append = True
        for node in children:
            if setsubset == node.s:
                append = False
                break
        if append:
            n = Node(setsubset, p)
            n.children = get_children(n, setsubset, length-1)
            children.add(n)
    return children
项目:zhusuan    作者:thu-ml    | 项目源码 | 文件源码
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])
项目:pipelines    作者:InformaticsMatters    | 项目源码 | 文件源码
def enumerateStereoIsomers(mol):
    out = []
    chiralCentres = Chem.FindMolChiralCenters(mol, includeUnassigned=True)
    #return the molecule object when no chiral centres where identified
    if chiralCentres == []:
        return [mol]

    #All bit permutations with number of bits equals number of chiralCentres
    elements = _spam(len(chiralCentres))

    for isoId,element in enumerate(elements):
        for centreId,i in enumerate(element):
            atomId = chiralCentres[centreId][0]
            if i == 0:
                mol.GetAtomWithIdx(atomId).SetChiralTag(Chem.rdchem.ChiralType.CHI_TETRAHEDRAL_CW)
            elif i == 1:
                mol.GetAtomWithIdx(atomId).SetChiralTag(Chem.rdchem.ChiralType.CHI_TETRAHEDRAL_CCW)
        outmol = copy(mol)
        utils.log("Enumerated ", Chem.MolToSmiles(mol, isomericSmiles=True))
        out.append(outmol)
    return out
项目:Taigabot    作者:FrozenPigs    | 项目源码 | 文件源码
def test_is_ancestor(self):
        git = self.rorepo.git
        if git.version_info[:3] < (1, 8, 0):
            raise SkipTest("git merge-base --is-ancestor feature unsupported")

        repo = self.rorepo
        c1 = 'f6aa8d1'
        c2 = '763ef75'
        self.assertTrue(repo.is_ancestor(c1, c1))
        self.assertTrue(repo.is_ancestor("master", "master"))
        self.assertTrue(repo.is_ancestor(c1, c2))
        self.assertTrue(repo.is_ancestor(c1, "master"))
        self.assertFalse(repo.is_ancestor(c2, c1))
        self.assertFalse(repo.is_ancestor("master", c1))
        for i, j in itertools.permutations([c1, 'ffffff', ''], r=2):
            self.assertRaises(GitCommandError, repo.is_ancestor, i, j)
项目:pydictor    作者:LandGrey    | 项目源码 | 文件源码
def get_chunk_dic(objflag):
    countchecker(len(objflag))
    storepath = finalsavepath(paths.results_path, pystrs.CHUNK_prefix, mybuildtime(), pyoptions.filextension, paths.results_file_name)
    with open(storepath, "a") as f:
        for item in itertools.permutations(objflag):
            item = filterforfun("".join(item), head=pyoptions.head, tail=pyoptions.tail,
                                lenght_is_filter=pyoptions.args_pick,
                                minlen=pyoptions.minlen, maxlen=pyoptions.maxlen,
                                regex_is_filter=True, regex=pyoptions.filter_regex,
                                encode_is_filter=True, encode=pyoptions.encode,
                                occur_is_filter=True,
                                letter_occur=pyoptions.letter_occur,
                                digital_occur=pyoptions.digital_occur,
                                special_occur=pyoptions.special_occur,
                                types_is_filter=True,
                                letter_types=pyoptions.letter_types,
                                digital_types=pyoptions.digital_types,
                                special_types=pyoptions.special_types,
                                )
            if item:
                f.write(item + pyoptions.CRLF)
    finishprinter(finishcounter(storepath), storepath)
项目:catalyst    作者:enigmampc    | 项目源码 | 文件源码
def test_duplicate_values(self):
        UNIMPORTANT_VALUE = 57

        panel = pd.Panel(
            UNIMPORTANT_VALUE,
            items=['a', 'b', 'b', 'a'],
            major_axis=['c'],
            minor_axis=['d'],
        )
        unused = ExplodingObject()

        axis_names = ['items', 'major_axis', 'minor_axis']

        for axis_order in permutations((0, 1, 2)):
            transposed = panel.transpose(*axis_order)
            with self.assertRaises(ValueError) as e:
                PanelBarReader(unused, transposed, 'daily')

            expected = (
                "Duplicate entries in Panel.{name}: ['a', 'b'].".format(
                    name=axis_names[axis_order.index(0)],
                )
            )
            self.assertEqual(str(e.exception), expected)
项目:ropf    作者:kevinkoo001    | 项目源码 | 文件源码
def get_reg_swaps(live_regs):
    """Given all the registers' live subsets, check which of them can
    be swapped. Returns a list with Swap objects."""

    swaps = set()
    # filter out any registers that are not used
    reg_vals = filter(lambda x: not x.dont_touch(), live_regs.values())
    for reg, other in itertools.permutations(reg_vals, 2):
        for subset in reg.subsets:
            if subset.no_swap:
                continue
            # print "ASDASD", reg, subset
            swap_subset = other.get_swap_subset(subset, reg)
            if swap_subset != None and swap_subset.size == 0:
                print "BUG: empty subset in get_swap_subset"
                continue
            if swap_subset != None:
                swaps.add(Swap(reg, other, swap_subset))

    return list(swaps)
项目:leetcode    作者:thomasyimgit    | 项目源码 | 文件源码
def _all_string_prefixes():
    # The valid string prefixes. Only contain the lower case versions,
    #  and don't contain any permuations (include 'fr', but not
    #  'rf'). The various permutations will be generated.
    _valid_string_prefixes = ['b', 'r', 'u', 'br']
    if py_version >= 36:
        _valid_string_prefixes += ['f', 'fr']
    if py_version <= 27:
        # TODO this is actually not 100% valid. ur is valid in Python 2.7,
        # while ru is not.
        _valid_string_prefixes.append('ur')

    # if we add binary f-strings, add: ['fb', 'fbr']
    result = set([''])
    for prefix in _valid_string_prefixes:
        for t in _itertools.permutations(prefix):
            # create a list with upper and lower versions of each
            #  character
            for u in _itertools.product(*[(c, c.upper()) for c in t]):
                result.add(''.join(u))
    return result
项目:dutchembeddings    作者:clips    | 项目源码 | 文件源码
def create_set(categories, outfile):
        """
        Creates a test-set .txt file for use in word2vec.
        Conforms to word2vec specs, from the google code repository: https://code.google.com/archive/p/word2vec/

        :param categories: The categories and words in the categories: {NAME: [[tuple_1],[tuple_2],...,[tuple_n]]}
        :param outfile: The file to which to write the text.
        :return: None
        """

        with open(outfile, 'w', encoding='utf8') as f:

            for k, v in categories.items():
                f.write(u": {0}\n".format(k))
                for x in permutations([" ".join(x).lower() for x in v], 2):
                    f.write(u"{0}\n".format(" ".join(x)))
项目:biglambda_hadoop    作者:henry8527    | 项目源码 | 文件源码
def csg_check(self, li, writer):
        m = writer(self._m)
        r = uncurry(writer(self._r))
        old_value = None
        mapped = map(m, li)
        if self._flattened:
            mapped = flatten(mapped)
        for permuted in itertools.permutations(mapped):
            if self._keyed:
                reduced = []
                for k, v in collect(permuted):
                    reduced.append( (k, reduce(r, v)) )
            else:
                reduced = reduce(r, permuted)
            if isinstance(reduced, list):
                return sorted(reduced)
            if old_value and (reduced != old_value):
                return False
            else:
                old_value = reduced
        return True
项目:NetPower_TestBed    作者:Vignesh2208    | 项目源码 | 文件源码
def prepare_all_flow_specifications(self):

        flow_specs = []

        flow_match = Match(is_wildcard=True)
        #flow_match["ethernet_type"] = 0x0800

        for src_host_id, dst_host_id in permutations(self.ng.host_ids, 2):

            if src_host_id == dst_host_id:
                continue

            fs = FlowSpecification(src_host_id, dst_host_id, flow_match)
            fs.ng_src_host = self.ng.get_node_object(src_host_id)
            fs.ng_dst_host = self.ng.get_node_object(dst_host_id)
            fs.mn_src_host = self.mininet_obj.get(src_host_id)
            fs.mn_dst_host = self.mininet_obj.get(dst_host_id)

            flow_specs.append(fs)

        return flow_specs
项目:Project-Euler    作者:XiaoTaoWang    | 项目源码 | 文件源码
def genMod(digitnum = 5):

    pool = range(digitnum)
    # The repeating part must be 3 or multiple of 3
    # The repeating part cannot include the last digit
    tset = set(range(digitnum-1))
    repeats = itertools.combinations(range(digitnum-1), 3)
    for r in repeats:
        rset = set(r)
        oset = tset - rset
        for i in r:
            pool[i] = '{0}'
        odigits = itertools.permutations('0123456789', len(oset))
        for o in odigits:
            idx = 0
            for i in oset:
                pool[i] = o[idx]
                idx += 1
            for last in ['1','3','7','9']:
                pool[-1] = last
                if pool[0] != '0':
                    yield ''.join(pool)
项目:Project-Euler    作者:XiaoTaoWang    | 项目源码 | 文件源码
def worker():
    patterns = genpattern()
    digits = itertools.combinations(range(10),4)
    med = 0
    abcd = None
    targets = None
    for d in digits:
        res = set()
        perm = itertools.permutations(d)
        for p in perm:
            for pat in patterns:
                exp = pat % p
                try:
                    r = eval(exp)
                    if int(r)==r:
                        res.add(int(r))
                except:
                    pass
        n = maxn(res)
        if n > med:
            med = n
            abcd = d
            targets = res
    return sorted(abcd), med, targets
项目:PokerBot    作者:KanishkT123    | 项目源码 | 文件源码
def permutation(current, indices):
    """
    Permutes a certain section of a list and returns all permutations
        -current: current list/input list
        -indices: All indices to be permuted (assumes that all indices
                  sequential)
    """
    indices.sort()
    permuter = [current[a] for a in indices]
    permutations = [list(x) for x in list(itertools.permutations(permuter))]
    temp1 = current[:min(indices)]
    temp2 = current[max(indices)+1:]
    alllist = []
    for i in permutations:
        alllist.append(temp1 + i + temp2)
    return alllist
项目:PySimpleAutomata    作者:Oneiroe    | 项目源码 | 文件源码
def test_afw_to_nfa_conversion_language(self):
        """ Test a correct afw conversion to nfa comparing the language read 
        by the two automaton """
        nfa_01 = AFW.afw_to_nfa_conversion(self.afw_afw_to_nfa_test_01)
        # automata_IO.nfa_to_dot(nfa_01, 'afw_to_nfa_01')
        i = 0
        last = 7
        while i <= last:
            base = list(itertools.repeat('a', i))
            base += list(itertools.repeat('b', i))
            # build all permutation of 'a' and 'b' till length i
            word_set = set(itertools.permutations(base, i))
            for word in word_set:
                word = list(word)
                # print(word)
                afw_acceptance = AFW.afw_word_acceptance(
                    self.afw_afw_to_nfa_test_01, word)
                nfa_acceptance = NFA.nfa_word_acceptance(nfa_01, word)
                self.assertEqual(afw_acceptance, nfa_acceptance)
            i += 1
项目:PySimpleAutomata    作者:Oneiroe    | 项目源码 | 文件源码
def test_afw_to_nfa_conversion_language_bis_bis(self):
        """ Test a correct afw conversion to nfa comparing the language read 
        by the two automaton """
        nfa_01 = AFW.afw_to_nfa_conversion(self.afw_nonemptiness_check_test_2)
        # automata_IO.nfa_to_dot(nfa_01, 'afw_to_nfa_strange')
        i = 0
        last = 7
        while i <= last:
            base = list(itertools.repeat('a', i))
            base += list(itertools.repeat('b', i))
            # build all permutation of 'a' and 'b' till length i
            word_set = set(itertools.permutations(base, i))
            for word in word_set:
                word = list(word)
                # print(word)
                afw_acceptance = AFW.afw_word_acceptance(
                    self.afw_nonemptiness_check_test_2, word)
                nfa_acceptance = NFA.nfa_word_acceptance(nfa_01, word)
                self.assertEqual(afw_acceptance, nfa_acceptance)
            i += 1
项目:PySimpleAutomata    作者:Oneiroe    | 项目源码 | 文件源码
def test_afw_to_nfa_conversion_language_bis(self):
        """ Test a correct afw conversion to nfa comparing the language read 
        by the two automaton.
            Here we take a nfa, we covert it to afw and back to nfa,
            then the original and final nfa are compared trough the language 
            read.
        """
        original_nfa_to_afw = AFW.nfa_to_afw_conversion(
            self.nfa_afw_to_nfa_test_01)
        nfa_01 = AFW.afw_to_nfa_conversion(original_nfa_to_afw)
        i = 0
        last = 7
        while i <= last:
            base = list(itertools.repeat('a', i))
            base += list(itertools.repeat('b', i))
            # build all permutation of 'a' and 'b' till length i
            word_set = set(itertools.permutations(base, i))
            for word in word_set:
                word = list(word)
                # print(word)
                original_nfa_acceptance = NFA.nfa_word_acceptance(
                    self.nfa_afw_to_nfa_test_01, word)
                nfa_acceptance = NFA.nfa_word_acceptance(nfa_01, word)
                self.assertEqual(original_nfa_acceptance, nfa_acceptance)
            i += 1
项目:PySimpleAutomata    作者:Oneiroe    | 项目源码 | 文件源码
def test_afw_completion(self):
        """ Tests a correct afw completion comparing the language read, 
        that must be the same"""
        original = copy.deepcopy(self.afw_completion_test_01)
        AFW.afw_completion(self.afw_completion_test_01)

        i = 0
        last = 7
        while i <= last:
            base = list(itertools.repeat('a', i))
            base += list(itertools.repeat('b', i))
            # build all permutation of 'a' and 'b' till length i
            word_set = set(itertools.permutations(base, i))
            for word in word_set:
                word = list(word)
                original_acceptance = AFW.afw_word_acceptance(original, word)
                completed_acceptance = AFW.afw_word_acceptance(
                    self.afw_completion_test_01, word)
                self.assertEqual(original_acceptance, completed_acceptance)
            i += 1
项目:PySimpleAutomata    作者:Oneiroe    | 项目源码 | 文件源码
def test_afw_complementation(self):
        """ Test a correct afw complementation comparing the language read, 
        that must be discording"""
        afw_complemented = AFW.afw_complementation(
            self.afw_complementation_test_01)

        i = 0
        last = 7
        while i <= last:
            base = list(itertools.repeat('a', i))
            base += list(itertools.repeat('b', i))
            # build all permutation of 'a' and 'b' till length i
            word_set = set(itertools.permutations(base, i))
            for word in word_set:
                word = list(word)
                afw_acceptance = AFW.afw_word_acceptance(
                    self.afw_complementation_test_01, word)
                complement_acceptance = AFW.afw_word_acceptance(
                    afw_complemented, word)
                self.assertNotEqual(afw_acceptance, complement_acceptance)
            i += 1
项目:PySimpleAutomata    作者:Oneiroe    | 项目源码 | 文件源码
def test_afw_union_equals(self):
        """ Tests a correct afw union with the same afw """
        AFW.rename_afw_states(self.afw_union_1_test_01, 'a_')
        union = AFW.afw_union(self.afw_union_1_test_01,
                              self.afw_union_1_test_01)

        i = 0
        last = 7
        while i <= last:
            base = list(itertools.repeat('a', i))
            base += list(itertools.repeat('b', i))
            # build all permutation of 'a' and 'b' till length i
            word_set = set(itertools.permutations(base, i))
            for word in word_set:
                word = list(word)
                original_acceptance_1 = AFW.afw_word_acceptance(
                    self.afw_union_1_test_01, word)
                original_acceptance_2 = AFW.afw_word_acceptance(
                    self.afw_union_1_test_01, word)
                union_acceptance = AFW.afw_word_acceptance(union, word)
                self.assertEqual(
                    original_acceptance_1 or original_acceptance_2,
                    union_acceptance)
            i += 1
项目:PySimpleAutomata    作者:Oneiroe    | 项目源码 | 文件源码
def test_afw_union_empty_states_1(self):
        """ Tests a afw union where the first afw is empty """
        union = AFW.afw_union(self.afw_union_test_empty,
                              self.afw_union_1_test_01)
        i = 0
        last = 7
        while i <= last:
            base = list(itertools.repeat('a', i))
            base += list(itertools.repeat('b', i))
            # build all permutation of 'a' and 'b' till length i
            word_set = set(itertools.permutations(base, i))
            for word in word_set:
                word = list(word)
                original_acceptance_1 = AFW.afw_word_acceptance(
                    self.afw_union_1_test_01, word)
                original_acceptance_2 = AFW.afw_word_acceptance(
                    self.afw_union_test_empty, word)
                union_acceptance = AFW.afw_word_acceptance(union, word)
                self.assertEqual(
                    original_acceptance_1 or original_acceptance_2,
                    union_acceptance)
            i += 1
项目:PySimpleAutomata    作者:Oneiroe    | 项目源码 | 文件源码
def test_afw_union_empty_states_2(self):
        """ Tests a afw union where the second afw is empty """
        union = AFW.afw_union(self.afw_union_1_test_01,
                              self.afw_union_test_empty)
        i = 0
        last = 7
        while i <= last:
            base = list(itertools.repeat('a', i))
            base += list(itertools.repeat('b', i))
            # build all permutation of 'a' and 'b' till length i
            word_set = set(itertools.permutations(base, i))
            for word in word_set:
                word = list(word)
                original_acceptance_1 = AFW.afw_word_acceptance(
                    self.afw_union_1_test_01, word)
                original_acceptance_2 = AFW.afw_word_acceptance(
                    self.afw_union_test_empty, word)
                union_acceptance = AFW.afw_word_acceptance(union, word)
                self.assertEqual(
                    original_acceptance_1 or original_acceptance_2,
                    union_acceptance)
            i += 1
项目:PySimpleAutomata    作者:Oneiroe    | 项目源码 | 文件源码
def test_afw_intersection_disjoint(self):
        """ Tests a correct afw intersection with completely disjoint afws  """
        AFW.rename_afw_states(self.afw_intersection_2_test_01, 'a_')
        intersection = AFW.afw_intersection(self.afw_intersection_1_test_01,
                                            self.afw_intersection_2_test_01)

        i = 0
        last = 7
        while i <= last:
            base = list(itertools.repeat('a', i))
            base += list(itertools.repeat('b', i))
            # build all permutation of 'a' and 'b' till length i
            word_set = set(itertools.permutations(base, i))
            for word in word_set:
                word = list(word)
                original_acceptance_1 = AFW.afw_word_acceptance(
                    self.afw_intersection_1_test_01, word)
                original_acceptance_2 = AFW.afw_word_acceptance(
                    self.afw_intersection_2_test_01, word)
                intersection_acceptance = AFW.afw_word_acceptance(intersection,
                                                                  word)
                self.assertEqual(
                    original_acceptance_1 and original_acceptance_2,
                    intersection_acceptance)
            i += 1
项目:PySimpleAutomata    作者:Oneiroe    | 项目源码 | 文件源码
def test_afw_intersection_equals(self):
        """ Tests a correct afw intersection with the same afw """
        AFW.rename_afw_states(self.afw_intersection_1_test_01, 'a_')
        intersection = AFW.afw_intersection(self.afw_intersection_1_test_01,
                                            self.afw_intersection_1_test_01)

        i = 0
        last = 7
        while i <= last:
            base = list(itertools.repeat('a', i))
            base += list(itertools.repeat('b', i))
            # build all permutation of 'a' and 'b' till length i
            word_set = set(itertools.permutations(base, i))
            for word in word_set:
                word = list(word)
                original_acceptance_1 = AFW.afw_word_acceptance(
                    self.afw_intersection_1_test_01, word)
                original_acceptance_2 = AFW.afw_word_acceptance(
                    self.afw_intersection_1_test_01, word)
                intersection_acceptance = AFW.afw_word_acceptance(intersection,
                                                                  word)
                self.assertEqual(
                    original_acceptance_1 and original_acceptance_2,
                    intersection_acceptance)
            i += 1
项目:PySimpleAutomata    作者:Oneiroe    | 项目源码 | 文件源码
def test_afw_intersection_empty_states_1(self):
        """ Tests a afw intersection where the first afw is empty """
        intersection = AFW.afw_intersection(self.afw_intersection_test_empty,
                                            self.afw_intersection_1_test_01)
        i = 0
        last = 7
        while i <= last:
            base = list(itertools.repeat('a', i))
            base += list(itertools.repeat('b', i))
            # build all permutation of 'a' and 'b' till length i
            word_set = set(itertools.permutations(base, i))
            for word in word_set:
                word = list(word)
                original_acceptance_1 = AFW.afw_word_acceptance(
                    self.afw_intersection_1_test_01, word)
                original_acceptance_2 = AFW.afw_word_acceptance(
                    self.afw_intersection_test_empty, word)
                intersection_acceptance = AFW.afw_word_acceptance(intersection,
                                                                  word)
                self.assertEqual(
                    original_acceptance_1 and original_acceptance_2,
                    intersection_acceptance)
            i += 1
项目:PySimpleAutomata    作者:Oneiroe    | 项目源码 | 文件源码
def test_afw_intersection_empty_states_2(self):
        """ Tests a afw intersection where the second afw is empty """
        intersection = AFW.afw_intersection(self.afw_intersection_1_test_01,
                                            self.afw_intersection_test_empty)
        i = 0
        last = 7
        while i <= last:
            base = list(itertools.repeat('a', i))
            base += list(itertools.repeat('b', i))
            # build all permutation of 'a' and 'b' till length i
            word_set = set(itertools.permutations(base, i))
            for word in word_set:
                word = list(word)
                original_acceptance_1 = AFW.afw_word_acceptance(
                    self.afw_intersection_1_test_01, word)
                original_acceptance_2 = AFW.afw_word_acceptance(
                    self.afw_intersection_test_empty, word)
                intersection_acceptance = AFW.afw_word_acceptance(intersection,
                                                                  word)
                self.assertEqual(
                    original_acceptance_1 and original_acceptance_2,
                    intersection_acceptance)
            i += 1
项目:006764    作者:gilbutITbook    | 项目源码 | 文件源码
def find_anagrams(word, dictionary):
    """Find all anagrams for a word.

    This function only runs as fast as the test for
    membership in the 'dictionary' container. It will
    be slow if the dictionary is a list and fast if
    it's a set.

    Args:
        word: String of the target word.
        dictionary: Container with all strings that
            are known to be actual words.

    Returns:
        List of anagrams that were found. Empty if
        none were found.
    """
    permutations = itertools.permutations(word, len(word))
    possible = (''.join(x) for x in permutations)
    found = {word for word in possible if word in dictionary}
    return list(found)
项目:algorithm-in-Python    作者:Microndgt    | 项目源码 | 文件源码
def countArrangement(self, N):
        """
        :type N: int
        :rtype: int
        """

        def judge(num, pos):
            if not (num % pos) or not (pos % num):
                return True
            return False

        from itertools import permutations
        seq = range(1, N + 1)
        seq_len = len(seq)
        count = 0
        for arrangement in (permutations(seq, seq_len)):
            for index, ele in enumerate(arrangement, 1):
                res = judge(ele, index)
                if not res:
                    break
            else:
                count += 1

        return count
项目:LSAT    作者:BillVanderLugt    | 项目源码 | 文件源码
def step_2(self):
        '''
        STEP 2: Set-Up Puzzle
            - Extract Variable Names
            - Populate Event Space
        '''

        first = self._find_first()
        i = first
        # print ('first var is ', self.prompt_text[first])
        # print ('PROMPT', self.prompt_pairs)
        # print ()
        self.vars = self._collect_vars(i)
        #print ('generating permutations...')
        perms = list(itertools.permutations(self.vars))
        print ('Possible permutations of {} variables: {}'.format(len(self.vars), len(perms)))
        self.permutations = perms # before any rules
        self.viable = perms # viable candidates after rule(s)
        #print ()
        return self.vars
项目:LSAT    作者:BillVanderLugt    | 项目源码 | 文件源码
def _winnow_all(self):
        '''
        Apply all the rules to the pool of conceivable permutations.
        Winnow out those that satisfy all the rules.

        Return: the winnowed pool as a list
        '''
        pool = self.viable
        print ("With {} variables, the pool starts with {} permutations...".format(len(self.vars), len(pool)))
        for i, rule in enumerate(self.rules):
            print ("    ", " ".join(rule.text_list))
            pool = self._winnow_one(rule.output, pool)
            print ("After rule {} pool size shrunk down to {}".format(i, len(pool)))
            print ()
        if len(pool)<10: # if the remaining pool is small, go ahead and print it
            print(pool)
        return pool
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
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)
                self.assertTrue(bm.equals(bm_this))
                self.assertTrue(bm_this.equals(bm))
项目:FermiLib    作者:ProjectQ-Framework    | 项目源码 | 文件源码
def test_hf_state_plane_wave_basis_lowest_single_determinant_state(self):
        grid_length = 7
        dimension = 1
        spinless = True
        n_particles = 4
        length_scale = 2.0

        grid = Grid(dimension, grid_length, length_scale)
        hamiltonian = jellium_model(grid, spinless)
        hamiltonian_sparse = get_sparse_operator(hamiltonian)

        hf_state = hartree_fock_state_jellium(grid, n_particles,
                                              spinless, plane_wave=True)

        HF_energy = expectation(hamiltonian_sparse, hf_state)

        for occupied_orbitals in permutations(
                [1] * n_particles + [0] * (grid_length - n_particles)):
            state_index = numpy.sum(2 ** numpy.array(occupied_orbitals))
            HF_competitor = csr_matrix(([1.0], ([state_index], [0])),
                                       shape=(2 ** grid_length, 1))

            self.assertLessEqual(
                HF_energy, expectation(hamiltonian_sparse, HF_competitor))
项目:Leetcode    作者:staticor    | 项目源码 | 文件源码
def permutations(iterable):
    pool = list(iterable)
    n = len(pool)
    indices = list(range(n))
    cycles = list(range(n, n-r, -1))
    yield tuple(pool[i] for i in indices[:r])
    while n:
        for i in reversed(range(r)):
            cycles[i] -= 1
            if cycles[i] == 0:
                indices[i:] = indices[i+1:] + indices[i:i+1]
                cycles[i] = n - i
            else:
                j = cycles[i]
                indices[i], indices[-j] = indices[-j], indices[i]
                yield tuple(pool[i] for i in indices[:r])
                break
        else:
            return
项目:sublimeTextConfig    作者:luoye-fe    | 项目源码 | 文件源码
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 {0} and {1}. They are '
                          'mutually exclusive.'.format(opt1, opt2))
                return False

        if options.convention and options.convention not in conventions:
            log.error("Illegal convention '{0}'. Possible conventions: {1}"
                      .format(options.convention,
                              ', '.join(conventions.keys())))
            return False
        return True
项目:txpoloniex    作者:congruency    | 项目源码 | 文件源码
def find_routes(primaries, currencies, pairs):
    """
    Find all permutations of trade routes for pairs
    """
    discovered = []
    for c in currencies:

        for p in permutations(c, 3):

            # We want to end with the beginning currency
            p = p + (p[0],)

            if not p in discovered and \
               has_two_primary(primaries, p) and \
               valid_pairs(pairs, p):

                discovered.append(p)

                yield p
项目:little-python    作者:JeffyLu    | 项目源码 | 文件源码
def main():
    count = 0  
    start = time.time()
    for i in itertools.permutations(range(1, 10), 9):
        if cube3(i):
            count += 1
            flag = 1
            print('result %d:' % (count))
            for k in i:
                print('%d ' % (k), end = '')
                if not(flag % 3):
                    print()
                flag += 1     
    end = time.time()
    print('time:', end - start)
    print('total:', count)
项目:biglambda    作者:csmith49    | 项目源码 | 文件源码
def csg_check(self, li, writer):
        m = writer(self._m)
        r = uncurry(writer(self._r))
        old_value = None
        mapped = map(m, li)
        if self._flattened:
            mapped = flatten(mapped)
        for permuted in itertools.permutations(mapped):
            if self._keyed:
                reduced = []
                for k, v in collect(permuted):
                    reduced.append( (k, reduce(r, v)) )
            else:
                reduced = reduce(r, permuted)
            if isinstance(reduced, list):
                return sorted(reduced)
            if old_value and (reduced != old_value):
                return False
            else:
                old_value = reduced
        return True
项目:1337dict    作者:cym13    | 项目源码 | 文件源码
def gen_passwords(wordset, minlen, maxlen, permute, skip):
    combinations, skip = drop_combinations(skip, wordset, permute)

    variations = []

    for combination in combinations:
        if (len(''.join(combination)) < minlen
         or len(''.join(combination)) > maxlen):
            continue

        if permute:
            permutations, skip = drop_permutations(skip, combination)

            for permutation in permutations:
                variations = chain(variations, leet_word(''.join(permutation)))
        else:
            variations = chain(variations, leet_word(''.join(combination)))

    try:
        drop(skip, variations)
    except AttributeError:
        return
    yield from variations
项目:1337dict    作者:cym13    | 项目源码 | 文件源码
def test_drop_permutations():
    combination = ('ha', 'bc', 'de')
    varnum      = variations_number(''.join(combination))

    permutations, iteration = drop_permutations(0, combination)
    assert (list(permutations) ==
            [('ha', 'bc', 'de'), ('ha', 'de', 'bc'), ('bc', 'ha', 'de'),
             ('bc', 'de', 'ha'), ('de', 'ha', 'bc'), ('de', 'bc', 'ha')])
    assert iteration == 0

    permutations, iteration = drop_permutations(varnum-1, combination)
    assert (list(permutations) ==
            [('ha', 'bc', 'de'), ('ha', 'de', 'bc'), ('bc', 'ha', 'de'),
             ('bc', 'de', 'ha'), ('de', 'ha', 'bc'), ('de', 'bc', 'ha')])
    assert iteration == varnum-1

    permutations, iteration = drop_permutations(varnum+1, combination)
    assert (list(permutations) ==
            [                    ('ha', 'de', 'bc'), ('bc', 'ha', 'de'),
             ('bc', 'de', 'ha'), ('de', 'ha', 'bc'), ('de', 'bc', 'ha')])
    assert iteration == 1
项目:multipath-sdn-controller    作者:dariobanfi    | 项目源码 | 文件源码
def multipath_computation(self):
        edges = []
        self.mp_config = {}

        for dpid, switch in self.dpid_to_switch.iteritems():
            #  Updating the capacity_maxflow variable which will be
            # modified by the algorithm with the realtime monitored capacity
            for port_no, port in switch.ports.iteritems():
                port.capacity_maxflow = port.capacity
            # Adding the edge switches to a list
            if switch.edge_port:
                edges.append(switch)

        # Calculate forwarding paths between all edges couples
        logger.info('%s', self.dpid_to_switch)
        for edge_couple in itertools.permutations(edges, 2):
            self.calculate_multipath(edge_couple[0], edge_couple[1])
            self.create_flow_rules(edge_couple[0], edge_couple[1])
            logger.info('-' * 20)
项目:python-    作者:secondtonone1    | 项目源码 | 文件源码
def _all_string_prefixes():
    # The valid string prefixes. Only contain the lower case versions,
    #  and don't contain any permuations (include 'fr', but not
    #  'rf'). The various permutations will be generated.
    _valid_string_prefixes = ['b', 'r', 'u', 'f', 'br', 'fr']
    # if we add binary f-strings, add: ['fb', 'fbr']
    result = set([''])
    for prefix in _valid_string_prefixes:
        for t in _itertools.permutations(prefix):
            # create a list with upper and lower versions of each
            #  character
            for u in _itertools.product(*[(c, c.upper()) for c in t]):
                result.add(''.join(u))
    return result