当前位置: 首页>>代码示例>>Python>>正文


Python iterables.flatten函数代码示例

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


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

示例1: get_transformation_function

def get_transformation_function(segments, fixed_endpoint=None, fixed_basepoint=None, use_dict=True):
  if fixed_endpoint:
    coordinate_labels = []
  else:
    coordinate_labels = ['x','y','z']
  if fixed_basepoint:
    inverse_coordinate_labels = []
  else:
    inverse_coordinate_labels = ['base_x','base_y','base_z']
  trans_mat, inv_trans_mat, var_names = get_sympy_reduction(segments, fixed_endpoint, fixed_basepoint, coordinate_labels, inverse_coordinate_labels)

  # Bake into a lambda func
  base_func = lambdify(flatten((coordinate_labels, var_names)), trans_mat)
  base_inv_func = lambdify(flatten((inverse_coordinate_labels, var_names)), inv_trans_mat)

  if use_dict:
    if fixed_endpoint:
      func = lambda var_dict: base_func(*flatten([var_dict[var_name] for var_name in var_names])).A
    else:
      func = lambda coords, var_dict: base_func(*flatten((coords, [var_dict[var_name] for var_name in var_names]))).A
    if fixed_basepoint:
      inv_func = lambda var_dict: base_inv_func(*flatten([var_dict[var_name] for var_name in var_names])).A
    else:
      inv_func = lambda coords, var_dict: base_inv_func(*flatten((coords, [var_dict[var_name] for var_name in var_names]))).A
  else:
    if fixed_endpoint:
      func = lambda var_vals: base_func(*flatten(var_vals)).A
    else:
      func = lambda coords, var_vals: base_func(*flatten((coords, var_vals))).A
    if fixed_basepoint:
      inv_func = lambda var_vals: base_inv_func(*flatten(var_vals)).A
    else:
      inv_func = lambda coords, var_vals: base_inv_func(*flatten((coords, var_vals))).A

  return func, inv_func
开发者ID:jefesaurus,项目名称:hexapod-engine,代码行数:35,代码来源:fk_math.py

示例2: permutation_matrix

def permutation_matrix(orig_vec, per_vec):
    """Compute the permutation matrix to change order of
    orig_vec into order of per_vec.

    Parameters
    ----------
    orig_vec : array_like
        Symbols in original ordering.
    per_vec : array_like
        Symbols in new ordering.

    Returns
    -------
    p_matrix : Matrix
        Permutation matrix such that orig_vec == (p_matrix * per_vec).
    """
    if not isinstance(orig_vec, (list, tuple)):
        orig_vec = flatten(orig_vec)
    if not isinstance(per_vec, (list, tuple)):
        per_vec = flatten(per_vec)
    if set(orig_vec) != set(per_vec):
        raise ValueError("orig_vec and per_vec must be the same length, " +
                "and contain the same symbols.")
    ind_list = [orig_vec.index(i) for i in per_vec]
    p_matrix = zeros(len(orig_vec))
    for i, j in enumerate(ind_list):
        p_matrix[i, j] = 1
    return p_matrix
开发者ID:Eskatrem,项目名称:sympy,代码行数:28,代码来源:linearize.py

示例3: test_flatten

def test_flatten():
    assert flatten( (1,(1,)) ) == [1,1]
    assert flatten( (x,(x,)) ) == [x,x]

    from sympy.core.basic import Basic
    class MyOp(Basic):
        pass
    assert flatten( [MyOp(x, y), z]) == [MyOp(x, y), z]
    assert flatten( [MyOp(x, y), z], cls=MyOp) == [x, y, z]
开发者ID:silver1543,项目名称:sympy,代码行数:9,代码来源:test_iterables.py

示例4: __new__

    def __new__(cls, *args, **kw_args):
        """
        Constructor for the Permutation object.

        Examples
        ========

        >>> from sympy.combinatorics.permutations import Permutation
        >>> p = Permutation([0,1,2])
        >>> p
        Permutation([0, 1, 2])
        >>> q = Permutation([[0,1],[2]])
        >>> q
        Permutation([[0, 1], [2]])
        """
        if not args or not is_sequence(args[0]) or len(args) > 1 or \
           len(set(is_sequence(a) for a in args[0])) > 1:
            raise ValueError('Permutation argument must be a list of ints or a list of lists.')

        # 0, 1, ..., n-1 should all be present

        temp = [int(i) for i in flatten(args[0])]
        if set(range(len(temp))) != set(temp):
            raise ValueError("Integers 0 through %s must be present." % len(temp))

        cform = aform = None
        if args[0] and is_sequence(args[0][0]):
            cform = [list(a) for a in args[0]]
        else:
            aform = list(args[0])

        ret_obj = Basic.__new__(cls, (cform or aform), **kw_args)
        ret_obj._cyclic_form, ret_obj._array_form = cform, aform
        return ret_obj
开发者ID:piyushbansal,项目名称:sympy,代码行数:34,代码来源:permutations.py

示例5: _preprocess

    def _preprocess(self, args, expr):
        """Preprocess args, expr to replace arguments that do not map
        to valid Python identifiers.

        Returns string form of args, and updated expr.
        """
        from sympy import Dummy, Function, flatten, Derivative, ordered, Basic
        from sympy.matrices import DeferredVector

        # Args of type Dummy can cause name collisions with args
        # of type Symbol.  Force dummify of everything in this
        # situation.
        dummify = self._dummify or any(
            isinstance(arg, Dummy) for arg in flatten(args))

        argstrs = [None]*len(args)
        for arg, i in reversed(list(ordered(zip(args, range(len(args)))))):
            if iterable(arg):
                s, expr = self._preprocess(arg, expr)
            elif isinstance(arg, DeferredVector):
                s = str(arg)
            elif isinstance(arg, Basic) and arg.is_symbol:
                s = self._argrepr(arg)
                if dummify or not self._is_safe_ident(s):
                    dummy = Dummy()
                    s = self._argrepr(dummy)
                    expr = self._subexpr(expr, {arg: dummy})
            elif dummify or isinstance(arg, (Function, Derivative)):
                dummy = Dummy()
                s = self._argrepr(dummy)
                expr = self._subexpr(expr, {arg: dummy})
            else:
                s = str(arg)
            argstrs[i] = s
        return argstrs, expr
开发者ID:cmarqu,项目名称:sympy,代码行数:35,代码来源:lambdify.py

示例6: _pgroup_of_double

 def _pgroup_of_double(polyh, ordered_faces, pgroup):
     n = len(ordered_faces[0])
     # the vertices of the double which sits inside a give polyhedron
     # can be found by tracking the faces of the outer polyhedron.
     # A map between face and the vertex of the double is made so that
     # after rotation the position of the vertices can be located
     fmap = dict(zip(ordered_faces,
                     range(len(ordered_faces))))
     flat_faces = flatten(ordered_faces)
     new_pgroup = []
     for i, p in enumerate(pgroup):
         h = polyh.copy()
         h.rotate(p)
         c = h.corners
         # reorder corners in the order they should appear when
         # enumerating the faces
         reorder = unflatten([c[j] for j in flat_faces], n)
         # make them canonical
         reorder = [tuple(map(as_int,
                    minlex(f, directed=False, is_set=True)))
                    for f in reorder]
         # map face to vertex: the resulting list of vertices are the
         # permutation that we seek for the double
         new_pgroup.append(Perm([fmap[f] for f in reorder]))
     return new_pgroup
开发者ID:ChaliZhg,项目名称:sympy,代码行数:25,代码来源:polyhedron.py

示例7: __new__

    def __new__(cls, iterable=None, shape=None, **kwargs):
        from sympy.utilities.iterables import flatten

        shape, flat_list = cls._handle_ndarray_creation_inputs(iterable, shape, **kwargs)
        shape = Tuple(*map(_sympify, shape))
        loop_size = functools.reduce(lambda x,y: x*y, shape) if shape else 0

        # Sparse array:
        if isinstance(flat_list, (dict, Dict)):
            sparse_array = Dict(flat_list)
        else:
            sparse_array = {}
            for i, el in enumerate(flatten(flat_list)):
                if el != 0:
                    sparse_array[i] = _sympify(el)

        sparse_array = Dict(sparse_array)

        self = Basic.__new__(cls, sparse_array, shape, **kwargs)
        self._shape = shape
        self._rank = len(shape)
        self._loop_size = loop_size
        self._sparse_array = sparse_array

        return self
开发者ID:jarthurgross,项目名称:sympy,代码行数:25,代码来源:sparse_ndim_array.py

示例8: has

    def has(self, *patterns):
        """
        Return True if self has any of the patterns.

        Example:
        >>> from sympy.abc import x
        >>> (2*x).has(x)
        True
        >>> (2*x/x).has(x)
        False

        """
        from sympy.utilities.iterables import flatten
        from sympy.core.symbol import Wild
        if len(patterns)>1:
            for p in patterns:
                if self.has(p):
                    return True
            return False
        elif not patterns:
            raise TypeError("has() requires at least 1 argument (got none)")
        p = sympify(patterns[0])
        if isinstance(p, BasicType):
            return bool(self.atoms(p))
        if p.is_Atom and not isinstance(p, Wild):
            return p in self.atoms(p.func)
        if p.matches(self) is not None:
            return True
        for e in flatten(self.args):
            if isinstance(e, Basic) and e.has(p):
                return True
        return False
开发者ID:Sumith1896,项目名称:sympy-polys,代码行数:32,代码来源:basic.py

示例9: letter_form

    def letter_form(self):
        """
        The  letter  representation  of an `FreeGroupElement` is as a
        tuple of generator symbols, each entry corresponding to a group
        generator. Inverses of the generators are represented by
        negative generator symbols.

        Examples
        ========

        >>> from sympy.combinatorics.free_group import free_group
        >>> f, a, b, c, d = free_group("a b c d")
        >>> (a**3).letter_form
        (a, a, a)
        >>> (a**2*d**-2*a*b**-4).letter_form
        (a, a, -d, -d, a, -b, -b, -b, -b)
        >>> (a**-2*b**3*d).letter_form
        (-a, -a, b, b, b, d)

        See Also
        ========

        array_form

        """
        return tuple(flatten([(i,)*j if j > 0 else (-i,)*(-j)
                    for i, j in self.array_form]))
开发者ID:AlexanderKulka,项目名称:sympy,代码行数:27,代码来源:free_group.py

示例10: __new__

    def __new__(cls, periodical, limits=None):
        x, start, stop = None, None, None
        if limits is None:
            x, start, stop = Dummy("k"), 0, S.Infinity
        if is_sequence(limits, Tuple):
            if len(limits) == 3:
                x, start, stop = limits
            elif len(limits) == 2:
                x = Dummy("k")
                start, stop = limits

        if not isinstance(x, Symbol) or start is None or stop is None:
            raise ValueError("Invalid limits given: %s" % str(limits))

        if start is S.NegativeInfinity and stop is S.Infinity:
            raise ValueError("Both the start and end value" " cannot be unbounded")

        limits = sympify((x, start, stop))

        if is_sequence(periodical, Tuple):
            periodical = sympify(tuple(flatten(periodical)))
        else:
            raise ValueError("invalid period %s should be something " "like e.g (1, 2) " % periodical)

        if Interval(limits[1], limits[2]) is S.EmptySet:
            return S.EmptySequence

        return Basic.__new__(cls, periodical, limits)
开发者ID:LuckyStrikes1090,项目名称:sympy,代码行数:28,代码来源:sequences.py

示例11: decipher_hill

def decipher_hill(ct, key, symbols="ABCDEFGHIJKLMNOPQRSTUVWXYZ"):
    """
    Deciphering is the same as enciphering but using the inverse of the key matrix.

    Examples
    ========

    >>> from sympy.crypto.crypto import decipher_hill
    >>> from sympy import Matrix
    >>> ct = "UEQDUEODOCTCWQ"
    >>> key = Matrix([[1, 2], [3, 5]])
    >>> decipher_hill(ct, key)
    'MEETMEONMONDAY'
    >>> ct = "UEQDUEODHBOYDJYU"
    >>> decipher_hill(ct, key)
    'MEETMEONTUESDAYA'

    """
    symbols = "".join(symbols)
    A = alphabet_of_cipher(symbols)
    N = len(A)   # normally, 26
    k = key.cols
    ct0 = [x.capitalize() for x in ct if x.isalnum()]
    C = [A.index(x) for x in ct0]
    n = len(C)
    m = n//k
    if n > m*k:
        C = C + [0]*(n - m*k)
        m = m + 1
    key_inv = key.inv_mod(N)
    P = [list(key_inv*Matrix(k, 1, [C[i] for i in range(k*j, k*(j + 1))])) for j in range(m)]
    P = flatten(P)
    return "".join([A[i % N] for i in P])
开发者ID:Upabjojr,项目名称:sympy,代码行数:33,代码来源:crypto.py

示例12: decipher_bifid6

def decipher_bifid6(ct, key):
    r"""
    Performs the Bifid cipher decryption on ciphertext ``ct``, and returns the plaintext.

    This is the version of the Bifid cipher that uses the `6 \times 6` Polybius square.
    Assumes alphabet of symbols is "A", ..., "Z", "0", ..., "9".

    INPUT:

        ``ct``: ciphertext string (digits okay)

        ``key``: short string for key (no repetitions, digits okay)

    OUTPUT:

        plaintext from Bifid cipher (all caps, no spaces)

    Examples
    ========

    >>> from sympy.crypto.crypto import encipher_bifid6, decipher_bifid6
    >>> key = "encrypt"
    >>> pt = "meet me on monday at 8am"
    >>> encipher_bifid6(pt, key)
    'HNHOKNTA5MEPEGNQZYG'
    >>> ct = "HNHOKNTA5MEPEGNQZYG"
    >>> decipher_bifid6(ct, key)
    'MEETMEONMONDAYAT8AM'

    """
    A = alphabet_of_cipher() + [str(a) for a in range(10)]
    # first make sure the letters are capitalized
    # and text has no spaces
    key = uniq(key)
    key0 = [x.capitalize() for x in key if x.isalnum()]
    ct0 = [x.capitalize() for x in ct if x.isalnum()]
    # create long key
    long_key = key0 + [x for x in A if not(x in key0)]
    n = len(ct0)
    # the fractionalization
    pairs = flatten([[long_key.index(x)//6, long_key.index(x) % 6] for x in ct0])
    tmp_plain = flatten([[pairs[i], pairs[n + i]] for i in range(n)])
    pt = "".join([long_key[6*tmp_plain[2*i] + tmp_plain[2*i + 1]] for i in range(n)])
    return pt
开发者ID:Upabjojr,项目名称:sympy,代码行数:44,代码来源:crypto.py

示例13: decipher_bifid5

def decipher_bifid5(ct, key):
    r"""
    Performs the Bifid cipher decryption on ciphertext ``ct``, and returns the plaintext.

    This is the version of the Bifid cipher that uses the `5 \times 5` Polybius square.

    INPUT:

        ``ct``: ciphertext string (digits okay)

        ``key``: short string for key (no repetitions, digits okay)

    OUTPUT:

        plaintext from Bifid5 cipher (all caps, no spaces, no "J"s)

    Examples
    ========

    >>> from sympy.crypto.crypto import encipher_bifid5, decipher_bifid5
    >>> key = "encrypt"
    >>> pt = "meet me on monday"
    >>> encipher_bifid5(pt, key)
    'LNLLQNPPNPGADK'
    >>> ct = 'LNLLQNPPNPGADK'
    >>> decipher_bifid5(ct, key)
    'MEETMEONMONDAY'

    """
    A = alphabet_of_cipher()
    # first make sure the letters are capitalized
    # and text has no spaces
    key = uniq(key)
    key0 = [x.capitalize() for x in key if x.isalnum()]
    ct0 = [x.capitalize() for x in ct if x.isalnum()]
    # create long key
    long_key = key0 + [x for x in A if (not(x in key0) and x != "J")]
    n = len(ct0)
    # the fractionalization
    pairs = flatten([[long_key.index(x)//5, long_key.index(x) % 5] for x in ct0 if x != "J"])
    tmp_plain = flatten([[pairs[i], pairs[n + i]] for i in range(n)])
    pt = "".join([long_key[5*tmp_plain[2*i] + tmp_plain[2*i + 1]] for i in range(n)])
    return pt
开发者ID:Upabjojr,项目名称:sympy,代码行数:43,代码来源:crypto.py

示例14: _new

    def _new(cls, iterable, shape, **kwargs):
        from sympy.utilities.iterables import flatten

        shape, flat_list = cls._handle_ndarray_creation_inputs(iterable, shape, **kwargs)
        flat_list = flatten(flat_list)
        self = object.__new__(cls)
        self._shape = shape
        self._array = list(flat_list)
        self._rank = len(shape)
        self._loop_size = functools.reduce(lambda x,y: x*y, shape) if shape else 0
        return self
开发者ID:jarthurgross,项目名称:sympy,代码行数:11,代码来源:dense_ndim_array.py

示例15: test_flatten

def test_flatten():
    assert flatten((1, (1,))) == [1, 1]
    assert flatten((x, (x,))) == [x, x]

    ls = [[(-2, -1), (1, 2)], [(0, 0)]]

    assert flatten(ls, levels=0) == ls
    assert flatten(ls, levels=1) == [(-2, -1), (1, 2), (0, 0)]
    assert flatten(ls, levels=2) == [-2, -1, 1, 2, 0, 0]
    assert flatten(ls, levels=3) == [-2, -1, 1, 2, 0, 0]

    raises(ValueError, lambda: flatten(ls, levels=-1))

    class MyOp(Basic):
        pass

    assert flatten([MyOp(x, y), z]) == [MyOp(x, y), z]
    assert flatten([MyOp(x, y), z], cls=MyOp) == [x, y, z]

    assert flatten(set([1, 11, 2])) == list(set([1, 11, 2]))
开发者ID:Acebulf,项目名称:sympy,代码行数:20,代码来源:test_iterables.py


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