• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python moves.range函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中six.moves.range函数的典型用法代码示例。如果您正苦于以下问题:Python range函数的具体用法?Python range怎么用?Python range使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了range函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: linear_branch_number

    def linear_branch_number(self):
        r"""
        Return linear branch number of this S-Box.

        The linear branch number of an S-Box `S` is defined as

        .. MATH::

            \min_{\substack{\alpha \neq 0, \beta \\ \mathrm{LAM}(\alpha, \beta) \neq 0}}
                \{ \mathrm{wt}(\alpha) + \mathrm{wt}(\beta) \}

        where `\mathrm{LAM}(\alpha, \beta)` is the entry at row `\alpha` and
        column `\beta` of linear approximation matrix correspond to this
        S-Box. The `\mathrm{wt}(x)` denotes the Hamming weight of `x`.

        EXAMPLES::

            sage: S = mq.SBox([12,5,6,11,9,0,10,13,3,14,15,8,4,7,1,2])
            sage: S.linear_branch_number()
            2
        """
        m = self.m
        n = self.n
        ret = (1<<m) + (1<<n)
        lat = self.linear_approximation_matrix()

        for a in range(1, 1<<m):
            for b in range(1<<n):
                if lat[a,b] != 0:
                    w = ZZ(a).popcount() + ZZ(b).popcount()
                    if w < ret:
                        ret = w
        return ret
开发者ID:robertwb,项目名称:sage,代码行数:33,代码来源:sbox.py


示例2: test_deep_merge_lists_delete_no_conflict

def test_deep_merge_lists_delete_no_conflict():
    # local removes an entry
    b = [[1, 3, 5], [2, 4, 6]]
    for i in range(len(b)):
        for j in range(len(b[i])):
            l = copy.deepcopy(b)
            r = copy.deepcopy(b)
            l[i].pop(j)
            m, lc, rc = merge(b, l, r)
            assert m == l
            assert lc == []
            assert rc == []

    # remote removes an entry
    b = [[1, 3, 5], [2, 4, 6]]
    for i in range(len(b)):
        for j in range(len(b[i])):
            l = copy.deepcopy(b)
            r = copy.deepcopy(b)
            r[i].pop(j)
            m, lc, rc = merge(b, l, r)
            assert m == r
            assert lc == []
            assert rc == []

    # both remove the same entry and one each
    b = [[1, 3, 5], [2, 4, 6]]
    l = [[1, 5], [2, 4]]  # deletes 3 and 6
    r = [[1, 5], [4, 6]]  # deletes 3 and 2
    m, lc, rc = merge(b, l, r)
    assert m == [[1, 5], [2, 4], [1, 5], [4, 6]]  # This is expected behaviour today: clear b, add l, add r
    #assert m == [[1, 5], [4]]  # 2,3,6 should be gone. TODO: This is the behaviour we want.
    assert lc == []
    assert rc == []
开发者ID:ijstokes,项目名称:nbdime,代码行数:34,代码来源:test_merge.py


示例3: make_domains

def make_domains(lists):
    """
    Given a list of lists, return a list of domain for each list to produce all
    combinations of possibles values.

    :rtype: list

    Example:

    >>> make_domains(['a', 'b'], ['c','d', 'e'])
    [['a', 'b', 'a', 'b', 'a', 'b'], ['c', 'c', 'd', 'd', 'e', 'e']]
    """
    from six.moves import range

    domains = []
    for iterable in lists:
        new_domain = iterable[:]
        for i in range(len(domains)):
            domains[i] = domains[i] * len(iterable)
        if domains:
            missing = (len(domains[0]) - len(iterable)) / len(iterable)
            i = 0
            for j in range(len(iterable)):
                value = iterable[j]
                for dummy in range(missing):
                    new_domain.insert(i, value)
                    i += 1
                i += 1
        domains.append(new_domain)
    return domains
开发者ID:metamorph-inc,项目名称:meta-core,代码行数:30,代码来源:__init__.py


示例4: test_add_variable

    def test_add_variable(self, core_model):
        cache = ProblemCache(core_model)

        def add_var(model, var_id):
            return model.solver.interface.Variable(var_id, ub=0)

        def update_var(model, var):
            return setattr(var, "ub", 1000)
        for i in range(10):
            cache.add_variable("%i" % i, add_var, update_var)

        for i in range(10):
            assert cache.variables["%i" % i] in core_model.solver.variables
            assert cache.variables["%i" % i].ub == 0
            assert core_model.solver.variables["%i" % i].ub == 0

        for i in range(10):
            cache.add_variable("%i" % i, add_var, update_var)
            assert cache.variables["%i" % i].ub == 1000
            assert core_model.solver.variables["%i" % i].ub == 1000

        cache.reset()

        for i in range(10):
            with pytest.raises(KeyError):
                core_model.solver.variables.__getitem__("%i" % i)
开发者ID:biosustain,项目名称:cameo,代码行数:26,代码来源:test_util.py


示例5: fit

    def fit(self, X,
            augment=False,
            rounds=1,
            seed=None):
        '''Required for featurewise_center, featurewise_std_normalization
        and zca_whitening.

        # Arguments
            X: Numpy array, the data to fit on.
            augment: whether to fit on randomly augmented samples
            rounds: if `augment`,
                how many augmentation passes to do over the data
            seed: random seed.
        '''
        X = np.copy(X)
        if augment:
            aX = np.zeros(tuple([rounds * X.shape[0]] + list(X.shape)[1:]))
            for r in range(rounds):
                for i in range(X.shape[0]):
                    aX[i + r * X.shape[0]] = self.random_transform(X[i])
            X = aX

        if self.featurewise_center:
            self.mean = np.mean(X, axis=0)
            X -= self.mean

        if self.featurewise_std_normalization:
            self.std = np.std(X, axis=0)
            X /= (self.std + 1e-7)

        if self.zca_whitening:
            flatX = np.reshape(X, (X.shape[0], X.shape[1] * X.shape[2] * X.shape[3]))
            sigma = np.dot(flatX.T, flatX) / flatX.shape[1]
            U, S, V = linalg.svd(sigma)
            self.principal_components = np.dot(np.dot(U, np.diag(1. / np.sqrt(S + 10e-7))), U.T)
开发者ID:bkj,项目名称:keras,代码行数:35,代码来源:image.py


示例6: test_cloud_cover

 def test_cloud_cover(self):
     iplt.symbols(list(range(10)),
                  [0] * 10,
                  [iris.symbols.CLOUD_COVER[i] for i in range(10)],
                  0.375)
     iplt.plt.axis('off')
     self.check_graphic()
开发者ID:QuLogic,项目名称:iris,代码行数:7,代码来源:test_plot.py


示例7: test_add_constraint

    def test_add_constraint(self, core_model):
        cache = ProblemCache(core_model)

        def add_var(model, var_id):
            return model.solver.interface.Variable(var_id, ub=0)

        def add_constraint(m, const_id, var):
            return m.solver.interface.Constraint(var, lb=-10, ub=10, name=const_id)

        def update_constraint(model, const, var):
            return setattr(const, "ub", 1000)

        for i in range(10):
            cache.add_variable("%i" % i, add_var, None)
            cache.add_constraint("c%i" % i, add_constraint, update_constraint, cache.variables["%i" % i])

        for i in range(10):
            assert cache.constraints["c%i" % i] in core_model.solver.constraints
            assert cache.constraints["c%i" % i].ub == 10
            assert cache.constraints["c%i" % i].lb == -10
            assert core_model.solver.constraints["c%i" % i].ub == 10
            assert core_model.solver.constraints["c%i" % i].lb == -10

        for i in range(10):
            cache.add_constraint("c%i" % i, add_constraint, update_constraint, cache.variables["%i" % i])
            assert core_model.solver.constraints["c%i" % i].ub == 1000

        cache.reset()

        for i in range(10):
            with pytest.raises(KeyError):
                core_model.solver.variables.__getitem__("%i" % i)
            with pytest.raises(KeyError):
                core_model.solver.constraints.__getitem__("c%i" % i)
开发者ID:biosustain,项目名称:cameo,代码行数:34,代码来源:test_util.py


示例8: fixed_ips_fake

 def fixed_ips_fake(*args, **kwargs):
     global fixed_ips
     ips = [next_fixed_ip(i, floating_ips_per_fixed_ip)
            for i in range(1, num_networks + 1)
            for j in range(ips_per_vif)]
     fixed_ips = ips
     return ips
开发者ID:Juniper,项目名称:nova,代码行数:7,代码来源:fake_network.py


示例9: get_refined_face

    def get_refined_face(a, b):
        if a > b:
            a, b = b, a
            flipped = True
        else:
            flipped = False

        try:
            face_points = face_point_dict[a, b]
        except KeyError:
            a_pt, b_pt = [points[idx] for idx in [a, b]]
            dx = (b_pt - a_pt)/factor

            # build subdivided facet
            face_points = [a]

            for i in range(1, points_per_edge-1):
                face_points.append(len(new_points))
                new_points.append(a_pt + dx*i)

            face_points.append(b)

            face_point_dict[a, b] = face_points

            # build old_face_to_new_faces
            old_face_to_new_faces[frozenset([a, b])] = [
                    (face_points[i], face_points[i+1])
                    for i in range(factor)]

        if flipped:
            return face_points[::-1]
        else:
            return face_points
开发者ID:Xuge06,项目名称:meshpy,代码行数:33,代码来源:tools.py


示例10: parsesection_mapper

    def parsesection_mapper(self, numlines, mapper):
        """Parses FORTRAN formatted section, and returns a list of all entries
        in each line

        Parameters
        ----------
        numlines : int
            The number of lines to be parsed in this section
        mapper : lambda operator
            Operator to format entries in current section

        Returns
        -------
        section : list
            A list of all entries in a given parm7 section
        """
        section = []
        y = next(self.topfile).strip("%FORMAT(")
        y.strip(")")
        x = FORTRANReader(y)
        for i in range(numlines):
            l = next(self.topfile)
            for j in range(len(x.entries)):
                val = l[x.entries[j].start:x.entries[j].stop].strip()
                if val:
                    section.append(mapper(val))
        return section
开发者ID:MDAnalysis,项目名称:mdanalysis,代码行数:27,代码来源:TOPParser.py


示例11: test_auto_cohorting_randomization

    def test_auto_cohorting_randomization(self):
        """
        Make sure cohorts.get_cohort() randomizes properly.
        """
        course = modulestore().get_course(self.toy_course_key)
        self.assertFalse(cohorts.is_course_cohorted(course.id))

        groups = ["group_{0}".format(n) for n in range(5)]
        config_course_cohorts(
            course, is_cohorted=True, auto_cohorts=groups
        )

        # Assign 100 users to cohorts
        for i in range(100):
            user = UserFactory(
                username="test_{0}".format(i),
                email="[email protected]{0}.com".format(i)
            )
            cohorts.get_cohort(user, course.id)

        # Now make sure that the assignment was at least vaguely random:
        # each cohort should have at least 1, and fewer than 50 students.
        # (with 5 groups, probability of 0 users in any group is about
        # .8**100= 2.0e-10)
        for cohort_name in groups:
            cohort = cohorts.get_cohort_by_name(course.id, cohort_name)
            num_users = cohort.users.count()
            self.assertGreater(num_users, 1)
            self.assertLess(num_users, 50)
开发者ID:mitodl,项目名称:edx-platform,代码行数:29,代码来源:test_cohorts.py


示例12: __init__

    def __init__(self, card=None, data=None, comment=''):
        Constraint.__init__(self, card, data)
        if comment:
            self._comment = comment

        self.IDs = [] ## TODO:  IDs reference nodes???
        self.Cs = []
        if card:
            # TODO: remove fields...
            fields = card.fields(1)

            nfields = len(card)
            assert len(card) > 1, card
            nterms = int(nfields / 2.)
            n = 1
            for i in range(nterms):
                nstart = 1 + 2 * i
                ID = integer(card, nstart, 'ID%s' % n)
                C = components_or_blank(card, nstart + 1, 'component%s' % n, '0')
                self.IDs.append(ID)
                self.Cs.append(C)
                n += 1
        else:
            fields = data
            for i in range(0, len(fields), 2):
                self.IDs.append(fields[i])
                self.Cs.append(fields[i + 1])
        assert len(self.IDs) > 0
        assert len(self.IDs) == len(self.Cs)
开发者ID:HibernantBear,项目名称:pyNastran,代码行数:29,代码来源:constraints.py


示例13: test_multiple_connections

    def test_multiple_connections(self):
        """
        Test multiple connections with pipelined requests.
        """
        conns = [self.get_connection() for i in range(5)]
        events = [Event() for i in range(5)]
        query = "SELECT keyspace_name FROM system.schema_keyspaces LIMIT 1"

        def cb(event, conn, count, *args, **kwargs):
            count += 1
            if count >= 10:
                conn.close()
                event.set()
            else:
                conn.send_msg(
                    QueryMessage(query=query, consistency_level=ConsistencyLevel.ONE),
                    request_id=count,
                    cb=partial(cb, event, conn, count))

        for event, conn in zip(events, conns):
            conn.send_msg(
                QueryMessage(query=query, consistency_level=ConsistencyLevel.ONE),
                request_id=0,
                cb=partial(cb, event, conn, 0))

        for event in events:
            event.wait()
开发者ID:IChocolateKapa,项目名称:python-driver,代码行数:27,代码来源:test_connection.py


示例14: linear_structures

    def linear_structures(self):
        r"""
        Return a list of 3-valued tuple `(b, \alpha, c)` such that `\alpha` is
        a `c`-linear structure of the component function `b \cdot S(x)`.

        A Boolean function `f : \GF{2}^m \mapsto \GF{2}` is said
        to have a `c`-linear structure if there exists a nonzero `\alpha` such
        that `f(x) \oplus f(x \oplus \alpha)` is a constant function `c`.

        An `m \times n` S-Box `S` has a linear structure if there exists a
        component function `b \cdot S(x)` that has a linear structure.

        The three valued tuple `(b, \alpha, c)` shows that `\alpha` is a
        `c`-linear structure of the component function `b \cdot S(x)`. This
        implies that for all output differences `\beta` of the S-Box
        correspond to input difference `\alpha`, we have `b \cdot \beta = c`.

        EXAMPLES::

            sage: S = mq.SBox([0,1,3,6,7,4,5,2])
            sage: S.linear_structures()
            [(1, 1, 1), (2, 2, 1), (3, 3, 1), (4, 4, 1), (5, 5, 1), (6, 6, 1), (7, 7, 1)]
        """
        n = self.n
        m = self.m
        act = self.autocorrelation_matrix()
        ret = []

        for j in range(1, 1<<n):
            for i in range(1, 1<<m):
                if (abs(act[i,j]) == (1<<m)):
                    c = ((1 - (act[i][j] >> self.m)) >> 1)
                    ret.append((j, i, c))
        return ret
开发者ID:robertwb,项目名称:sage,代码行数:34,代码来源:sbox.py


示例15: stl_to_plot3d_filename

def stl_to_plot3d_filename(stl_filename, p3d_filename, log=None, ascii=True):
    model = STL(log=log)
    model.read_stl(stl_filename)

    # nodal_normals = model.get_normals_at_nodes(model.elements)

    with open(p3d_filename, "wb") as p3d:
        nblocks = len(model.elements)
        # nblocks = 10
        p3d.write("%i\n" % nblocks)
        for iblock in range(nblocks):
            p3d.write("2 2 1\n")

        nodes = model.nodes
        elements = model.elements
        if 0:
            for i in [0, 1, 2]:
                for iblock in range(nblocks):
                    (n1, n2, n3) = elements[iblock]
                    p1 = nodes[n1, :]
                    p2 = nodes[n2, :]
                    p3 = nodes[n3, :]
                    p4 = p3
                    xi = [[p1[i], p2[i], p3[i], p4[i]]]
                    savetxt(p3d, xi, fmt="%f")
        else:
            for iblock in range(nblocks):
                for i in [0, 1, 2]:
                    (n1, n2, n3) = elements[iblock]
                    p1 = nodes[n1, :]
                    p2 = nodes[n2, :]
                    p3 = nodes[n3, :]
                    p4 = p3
                    xi = [[p1[i], p2[i], p3[i], p4[i]]]
                    savetxt(p3d, xi, fmt="%f")
开发者ID:hurlei,项目名称:pyNastran,代码行数:35,代码来源:stl_to_plot3d.py


示例16: left_table

    def left_table(self):
        """
        Return the list of matrices for left multiplication by the
        basis elements.

        EXAMPLES::

            sage: B = FiniteDimensionalAlgebra(QQ, [Matrix([[1,0], [0,1]]), Matrix([[0,1],[-1,0]])])
            sage: T = B.left_table(); T
            (
            [1 0]  [ 0  1]
            [0 1], [-1  0]
            )

        We check immutability::

            sage: T[0] = "vandalized by h4xx0r"
            Traceback (most recent call last):
            ...
            TypeError: 'tuple' object does not support item assignment
            sage: T[1][0] = [13, 37]
            Traceback (most recent call last):
            ...
            ValueError: matrix is immutable; please change a copy instead
             (i.e., use copy(M) to change a copy of M).
        """
        B = self.table()
        n = self.degree()
        table = [Matrix([B[j][i] for j in range(n)]) for i in range(n)]
        for b in table:
            b.set_immutable()
        return tuple(table)
开发者ID:saraedum,项目名称:sage-renamed,代码行数:32,代码来源:finite_dimensional_algebra.py


示例17: setUp

    def setUp(self):
        """Setup for Identity Limit Test Cases."""
        super(IdentityTestListLimitCase, self).setUp()

        # Create 10 entries for each of the entities we are going to test
        self.ENTITY_TYPES = ['user', 'group', 'project']
        self.entity_lists = {}
        for entity in self.ENTITY_TYPES:
            self.entity_lists[entity] = self._create_test_data(entity, 10)
            # Make sure we clean up when finished
            self.addCleanup(self.clean_up_entity, entity)

        self.service_list = []
        self.addCleanup(self.clean_up_service)
        for _ in range(10):
            new_entity = unit.new_service_ref()
            service = self.catalog_api.create_service(new_entity['id'],
                                                      new_entity)
            self.service_list.append(service)

        self.policy_list = []
        self.addCleanup(self.clean_up_policy)
        for _ in range(10):
            new_entity = unit.new_policy_ref()
            policy = self.policy_api.create_policy(new_entity['id'],
                                                   new_entity)
            self.policy_list.append(policy)
开发者ID:lbragstad,项目名称:keystone,代码行数:27,代码来源:test_v3_filters.py


示例18: is_associative

    def is_associative(self):
        """
        Return ``True`` if ``self`` is associative.

        EXAMPLES::

            sage: A = FiniteDimensionalAlgebra(QQ, [Matrix([[1,0], [0,1]]), Matrix([[0,1],[-1,0]])])
            sage: A.is_associative()
            True

            sage: B = FiniteDimensionalAlgebra(QQ, [Matrix([[1,0,0], [0,1,0], [0,0,1]]), Matrix([[0,1,0], [0,0,0], [0,0,0]]), Matrix([[0,0,1], [0,0,0], [1,0,0]])])
            sage: B.is_associative()
            False

            sage: e = B.basis()
            sage: (e[1]*e[2])*e[2]==e[1]*(e[2]*e[2])
            False
        """
        B = self.table()
        n = self.degree()
        for i in range(n):
            for j in range(n):
                eiej = B[j][i]
                if B[i]*B[j] != sum(eiej[k] * B[k] for k in range(n)):
                    return False
        return True
开发者ID:saraedum,项目名称:sage-renamed,代码行数:26,代码来源:finite_dimensional_algebra.py


示例19: eval_epoch

def eval_epoch(Xs, Ys, y, sess, stream, cw):
    """
    Evaluate the model against a dataset, and return the PSNR.

    Args:
      Xs: example placeholders list
      Ys: label placeholders list
      y: model output tensor
      sess: session
      stream: DataStream for the dataset
      cw: crop border
    Returns:
      psnr: PSNR of model's inference on dataset
    """
    se = 0.
    for X_c, y_c in stream.get_epoch_iterator():
        y_c = y_c[:, cw:-cw, cw:-cw]
        chunk_size = X_c.shape[0]
        gpu_chunk = chunk_size // FLAGS.num_gpus
        dict_input1 = [(Xs[i], X_c[i*gpu_chunk : \
                                   ((i + 1)*gpu_chunk) \
                                   if (i != FLAGS.num_gpus - 1) \
                                   else chunk_size]) \
                       for i in range(FLAGS.num_gpus)]
        dict_input2 = [(Ys[i], y_c[i*gpu_chunk : \
                                   ((i + 1)*gpu_chunk) \
                                   if (i != FLAGS.num_gpus - 1) \
                                   else chunk_size]) \
                       for i in range(FLAGS.num_gpus)]
        feed = dict(dict_input1 + dict_input2)
        y_eval = sess.run(y, feed_dict=feed)
        se += np.sum((y_eval - y_c) ** 2.0)
    rmse = np.sqrt(se / (stream.dataset.num_examples * y_c.shape[1] * y_c.shape[2]))
    psnr = 20 * np.log10(1.0 / rmse)
    return psnr
开发者ID:ulysseses,项目名称:sr_exp,代码行数:35,代码来源:run_model.py


示例20: coproduct_on_basis

        def coproduct_on_basis(self, A):
            r"""
            Return the coproduct of a `\mathbf{w}` basis element.

            The coproduct on the basis element `\mathbf{w}_A` is the sum over
            tensor product terms `\mathbf{w}_B \otimes \mathbf{w}_C` where
            `B` is the restriction of `A` to `\{1,2,\ldots,k\}` and `C` is
            the restriction of `A` to `\{k+1, k+2, \ldots, n\}`.

            INPUT:

            - ``A`` -- a set partition

            OUTPUT:

            - The coproduct applied to the `\mathbf{w}` dual symmetric function
              in non-commuting variables indexed by ``A`` expressed in the
              `\mathbf{w}` basis.

            EXAMPLES::

                sage: w = SymmetricFunctionsNonCommutingVariables(QQ).dual().w()
                sage: w[[1], [2,3]].coproduct()
                w{} # w{{1}, {2, 3}} + w{{1}} # w{{1, 2}}
                 + w{{1}, {2}} # w{{1}} + w{{1}, {2, 3}} # w{}
                sage: w.coproduct_on_basis(SetPartition([]))
                w{} # w{}
            """
            n = A.size()
            return self.tensor_square().sum_of_terms([
                (( A.restriction(range(1, i+1)).standardization(),
                   A.restriction(range(i+1, n+1)).standardization() ), 1)
                for i in range(n+1)], distinct=True)
开发者ID:sagemath,项目名称:sage,代码行数:33,代码来源:dual.py



注:本文中的six.moves.range函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python moves.reduce函数代码示例发布时间:2022-05-27
下一篇:
Python moves.map函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap