python类permutations()的实例源码

motor_pcre.py 文件源码 项目:tipi-engine 作者: CIECODE-Madrid 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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
util.py 文件源码 项目:fluxpart 作者: usda-ars-ussl 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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)
recipe-576615.py 文件源码 项目:code 作者: ActiveState 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
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
recipe-578061.py 文件源码 项目:code 作者: ActiveState 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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)))
recipe-578245.py 文件源码 项目:code 作者: ActiveState 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
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()
lattice.py 文件源码 项目:pyt 作者: SW10IoT 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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
draw.py 文件源码 项目:pyt 作者: SW10IoT 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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
operators.py 文件源码 项目:Gaia 作者: splcurran 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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, '')

# ?
gan_component.py 文件源码 项目:HyperGAN 作者: 255BITS 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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
draw.py 文件源码 项目:pyt 作者: python-security 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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
test_utils.py 文件源码 项目:zhusuan 作者: thu-ml 项目源码 文件源码 阅读 36 收藏 0 点赞 0 评论 0
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])
sanify_utils.py 文件源码 项目:pipelines 作者: InformaticsMatters 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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
test_repo.py 文件源码 项目:Taigabot 作者: FrozenPigs 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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)
CHUNK.py 文件源码 项目:pydictor 作者: LandGrey 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
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)
test_panel_bar_reader.py 文件源码 项目:catalyst 作者: enigmampc 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
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)
swap.py 文件源码 项目:ropf 作者: kevinkoo001 项目源码 文件源码 阅读 36 收藏 0 点赞 0 评论 0
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)
tokenize.py 文件源码 项目:leetcode 作者: thomasyimgit 项目源码 文件源码 阅读 38 收藏 0 点赞 0 评论 0
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
relation.py 文件源码 项目:dutchembeddings 作者: clips 项目源码 文件源码 阅读 42 收藏 0 点赞 0 评论 0
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)))
hos.py 文件源码 项目:biglambda_hadoop 作者: henry8527 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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
network_configuration.py 文件源码 项目:NetPower_TestBed 作者: Vignesh2208 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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
Problem-51.py 文件源码 项目:Project-Euler 作者: XiaoTaoWang 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
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)
Problem-93.py 文件源码 项目:Project-Euler 作者: XiaoTaoWang 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
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
table.py 文件源码 项目:PokerBot 作者: KanishkT123 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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
test_AFW.py 文件源码 项目:PySimpleAutomata 作者: Oneiroe 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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
test_AFW.py 文件源码 项目:PySimpleAutomata 作者: Oneiroe 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
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
test_AFW.py 文件源码 项目:PySimpleAutomata 作者: Oneiroe 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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
test_AFW.py 文件源码 项目:PySimpleAutomata 作者: Oneiroe 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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
test_AFW.py 文件源码 项目:PySimpleAutomata 作者: Oneiroe 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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
test_AFW.py 文件源码 项目:PySimpleAutomata 作者: Oneiroe 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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
test_AFW.py 文件源码 项目:PySimpleAutomata 作者: Oneiroe 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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


问题


面经


文章

微信
公众号

扫码关注公众号