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


Python typing.Sequence方法代码示例

本文整理汇总了Python中typing.Sequence方法的典型用法代码示例。如果您正苦于以下问题:Python typing.Sequence方法的具体用法?Python typing.Sequence怎么用?Python typing.Sequence使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在typing的用法示例。


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

示例1: _generic_gaussian_circuit

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Sequence [as 别名]
def _generic_gaussian_circuit(
        qubits: Sequence[cirq.Qid],
        quadratic_hamiltonian: QuadraticHamiltonian,
        occupied_orbitals: Optional[Sequence[int]],
        initial_state: Union[int, Sequence[int]]) -> cirq.OP_TREE:

    n_qubits = len(qubits)
    circuit_description, start_orbitals = gaussian_state_preparation_circuit(
            quadratic_hamiltonian, occupied_orbitals)

    if isinstance(initial_state, int):
        initially_occupied_orbitals = _occupied_orbitals(
                initial_state, n_qubits)
    else:
        initially_occupied_orbitals = initial_state  # type: ignore

    # Flip bits so that the correct starting orbitals are occupied
    yield (cirq.X(qubits[j]) for j in range(n_qubits)
           if (j in initially_occupied_orbitals) != (j in start_orbitals))

    yield _ops_from_givens_rotations_circuit_description(
            qubits, circuit_description) 
开发者ID:quantumlib,项目名称:OpenFermion-Cirq,代码行数:24,代码来源:state_preparation.py

示例2: finish

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Sequence [as 别名]
def finish(self,
               qubits: Sequence[cirq.Qid],
               n_steps: int,
               control_qubit: Optional[cirq.Qid]=None,
               omit_final_swaps: bool=False
               ) -> cirq.OP_TREE:
        """Operations to perform after all Trotter steps are done.

        Args:
            qubits: The qubits on which to perform operations.
            hamiltonian: The Hamiltonian to simulate.
            n_steps: The total number of Trotter steps that have been performed.
            control_qubit: The control qubit, if the algorithm is controlled.
            omit_final_swaps: Whether or not to omit swap gates at the end of
                the circuit.
        """
        # Default: do nothing
        return () 
开发者ID:quantumlib,项目名称:OpenFermion-Cirq,代码行数:20,代码来源:trotter_algorithm.py

示例3: trotter_step

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Sequence [as 别名]
def trotter_step(
            self,
            qubits: Sequence[cirq.Qid],
            time: float,
            control_qubit: Optional[cirq.Qid]=None
            ) -> cirq.OP_TREE:

        n_qubits = len(qubits)

        # Apply one- and two-body interactions for the full time
        def one_and_two_body_interaction(p, q, a, b) -> cirq.OP_TREE:
            yield Rxxyy(
                    self.hamiltonian.one_body[p, q].real * time).on(a, b)
            yield Ryxxy(
                    self.hamiltonian.one_body[p, q].imag * time).on(a, b)
            yield rot11(rads=
                    -2 * self.hamiltonian.two_body[p, q] * time).on(a, b)
        yield swap_network(qubits, one_and_two_body_interaction, fermionic=True)
        qubits = qubits[::-1]

        # Apply one-body potential for the full time
        yield (cirq.rz(rads=
                   -self.hamiltonian.one_body[i, i].real * time).on(qubits[i])
               for i in range(n_qubits)) 
开发者ID:quantumlib,项目名称:OpenFermion-Cirq,代码行数:26,代码来源:linear_swap_network.py

示例4: assert_implements_consistent_protocols

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Sequence [as 别名]
def assert_implements_consistent_protocols(
        val: Any,
        *,
        exponents: Sequence[Any] = (
            0, 1, -1, 0.5, 0.25, -0.5, 0.1, sympy.Symbol('s')),
        qubit_count: Optional[int] = None,
        ignoring_global_phase: bool=False,
        setup_code: str = _setup_code,
        global_vals: Optional[Dict[str, Any]] = None,
        local_vals: Optional[Dict[str, Any]] = None
        ) -> None:
    """Checks that a value is internally consistent and has a good __repr__."""

    cirq.testing.assert_implements_consistent_protocols(
        val,
        exponents=exponents,
        qubit_count=qubit_count,
        ignoring_global_phase=ignoring_global_phase,
        setup_code=setup_code,
        global_vals=global_vals,
        local_vals=local_vals) 
开发者ID:quantumlib,项目名称:OpenFermion-Cirq,代码行数:23,代码来源:wrapped.py

示例5: assert_eigengate_implements_consistent_protocols

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Sequence [as 别名]
def assert_eigengate_implements_consistent_protocols(
        eigen_gate_type: Type[cirq.EigenGate],
        *,
        exponents: Sequence[Union[sympy.Basic, float]] = (
            0, 1, -1, 0.25, -0.5, 0.1, sympy.Symbol('s')),
        global_shifts: Sequence[float] = (0, -0.5, 0.1),
        qubit_count: Optional[int] = None,
        ignoring_global_phase: bool=False,
        setup_code: str = _setup_code,
        global_vals: Optional[Dict[str, Any]] = None,
        local_vals: Optional[Dict[str, Any]] = None) -> None:
    """Checks that an EigenGate subclass is internally consistent and has a
    good __repr__."""

    cirq.testing.assert_eigengate_implements_consistent_protocols(
        eigen_gate_type,
        exponents=exponents,
        global_shifts=global_shifts,
        qubit_count=qubit_count,
        ignoring_global_phase=ignoring_global_phase,
        setup_code=setup_code,
        global_vals=global_vals,
        local_vals=local_vals) 
开发者ID:quantumlib,项目名称:OpenFermion-Cirq,代码行数:25,代码来源:wrapped.py

示例6: replace_post_order

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Sequence [as 别名]
def replace_post_order(self, expression: Expression) -> Union[Expression, Sequence[Expression]]:
        """Replace all occurrences of the patterns according to the replacement rules.

        Replaces innermost expressions first.

        Args:
            expression:
                The expression to which the replacement rules are applied.
            max_count:
                If given, at most *max_count* applications of the rules are performed. Otherwise, the rules
                are applied until there is no more match. If the set of replacement rules is not confluent,
                the replacement might not terminate without a *max_count* set.

        Returns:
            The resulting expression after the application of the replacement rules. This can also be a sequence of
            expressions, if the root expression is replaced with a sequence of expressions by a rule.
        """
        return self._replace_post_order(expression)[0] 
开发者ID:HPAC,项目名称:matchpy,代码行数:20,代码来源:many_to_one.py

示例7: _match_sequence_variables

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Sequence [as 别名]
def _match_sequence_variables(
            self,
            subjects: MultisetOfExpression,
            pattern_vars: Sequence[VariableWithCount],
            substitution: Substitution,
    ) -> Iterator[Substitution]:
        only_counts = [info for info, _ in pattern_vars]
        wrapped_vars = [name for (name, _, _, _), wrap in pattern_vars if wrap and name]
        for variable_substitution in commutative_sequence_variable_partition_iter(subjects, only_counts):
            for var in wrapped_vars:
                operands = variable_substitution[var]
                if isinstance(operands, (tuple, list, Multiset)):
                    if len(operands) > 1:
                        variable_substitution[var] = self.associative(*operands)
                    else:
                        variable_substitution[var] = next(iter(operands))
            try:
                result_substitution = substitution.union(variable_substitution)
            except ValueError:
                continue
            yield result_substitution 
开发者ID:HPAC,项目名称:matchpy,代码行数:23,代码来源:many_to_one.py

示例8: determine_files_to_test

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Sequence [as 别名]
def determine_files_to_test(*, typeshed_location: str, paths: Sequence[str]) -> List[Tuple[str, int]]:
    """Determine all files to test, checking if it's in the exclude list and which Python versions to use.

    Returns a list of pairs of the file path and Python version as an int."""
    skipped = PathMatcher(load_exclude_list(typeshed_location))
    filenames = find_stubs_in_paths(paths)
    files = []
    for f in sorted(filenames):
        rel = _get_relative(f)
        if skipped.search(rel):
            continue
        if _is_version(f, "2and3"):
            files.append((f, 2))
            files.append((f, 3))
        elif _is_version(f, "2"):
            files.append((f, 2))
        elif _is_version(f, "3"):
            files.append((f, 3))
        else:
            print("Unrecognized path: {}".format(f))
    return files 
开发者ID:python,项目名称:typeshed,代码行数:23,代码来源:pytype_test.py

示例9: cli_args

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Sequence [as 别名]
def cli_args(args: Sequence[str], search_config_files: bool = True) -> argparse.Namespace:
    """Command line arguments as parsed args.

    If a INI configuration file is set it is used to set additional default arguments, but
    the CLI arguments override any INI file settings.

    Args:
        args: the argument sequence from the command line
        search_config_files: flag for looking through ``SETTINGS_FILES`` for settings

    Returns:
        Parsed args from ArgumentParser
    """
    parser = cli_parser()

    if search_config_files:
        for ini_config_file in SETTINGS_FILES:

            if ini_config_file.path.exists():
                try:
                    ini_config = read_ini_config(ini_config_file.path, ini_config_file.sections)
                    ini_cli_args = parse_ini_config_with_cli(parser, ini_config, args)
                    return parser.parse_args(ini_cli_args)

                except KeyError:
                    # read_ini_config will raise KeyError if the section is not valid
                    continue

    return parser.parse_args(args) 
开发者ID:EvanKepner,项目名称:mutatest,代码行数:31,代码来源:cli.py

示例10: _recover_secret

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Sequence [as 别名]
def _recover_secret(threshold: int, shares: Sequence[RawShare]) -> bytes:
    # If the threshold is 1, then the digest of the shared secret is not used.
    if threshold == 1:
        return next(iter(shares))[1]

    shared_secret = _interpolate(shares, SECRET_INDEX)
    digest_share = _interpolate(shares, DIGEST_INDEX)
    digest = digest_share[:DIGEST_LENGTH_BYTES]
    random_part = digest_share[DIGEST_LENGTH_BYTES:]

    if digest != _create_digest(random_part, shared_secret):
        raise MnemonicError("Invalid digest of the shared secret.")

    return shared_secret 
开发者ID:trezor,项目名称:python-shamir-mnemonic,代码行数:16,代码来源:shamir.py

示例11: generate_mnemonics

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Sequence [as 别名]
def generate_mnemonics(
    group_threshold: int,
    groups: Sequence[Tuple[int, int]],
    master_secret: bytes,
    passphrase: bytes = b"",
    iteration_exponent: int = 1,
) -> List[List[str]]:
    """
    Split a master secret into mnemonic shares using Shamir's secret sharing scheme.

    The supplied Master Secret is encrypted by the passphrase (empty passphrase is used
    if none is provided) and split into a set of mnemonic shares.

    This is the user-friendly method to back up a pre-existing secret with the Shamir
    scheme, optionally protected by a passphrase.

    :param group_threshold: The number of groups required to reconstruct the master secret.
    :param groups: A list of (member_threshold, member_count) pairs for each group, where member_count
        is the number of shares to generate for the group and member_threshold is the number of members required to
        reconstruct the group secret.
    :param master_secret: The master secret to split.
    :param passphrase: The passphrase used to encrypt the master secret.
    :param int iteration_exponent: The encryption iteration exponent.
    :return: List of groups mnemonics.
    """
    if not all(32 <= c <= 126 for c in passphrase):
        raise ValueError(
            "The passphrase must contain only printable ASCII characters (code points 32-126)."
        )

    identifier = _random_identifier()
    encrypted_master_secret = cipher.encrypt(
        master_secret, passphrase, iteration_exponent, identifier
    )

    return split_ems(
        group_threshold, groups, identifier, iteration_exponent, encrypted_master_secret
    ) 
开发者ID:trezor,项目名称:python-shamir-mnemonic,代码行数:40,代码来源:shamir.py

示例12: mnemonic_to_indices

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Sequence [as 别名]
def mnemonic_to_indices(mnemonic: str) -> Sequence[int]:
    try:
        return [WORD_INDEX_MAP[word.lower()] for word in mnemonic.split()]
    except KeyError as key_error:
        raise MnemonicError(f"Invalid mnemonic word {key_error}.") from None 
开发者ID:trezor,项目名称:python-shamir-mnemonic,代码行数:7,代码来源:wordlist.py

示例13: as_release

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Sequence [as 别名]
def as_release(self) -> t.Sequence[int]:
        return (self.major, self.minor) if self.micro is None \
            else (self.major, self.minor, self.micro) 
开发者ID:pcah,项目名称:python-clean-architecture,代码行数:5,代码来源:version.py

示例14: interactor_factory

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Sequence [as 别名]
def interactor_factory(
        error_handler: t.Callable = None,
        error_class: t.Union[t.Type[Exception], t.Sequence[t.Type[Exception]]] = ProcessError
):
    """
    Decorator factory that builds a decorator to enriches an application function
    with additional features:

    * input data will be validated using given validators
    * decorated function can use Inject descriptors in its signature
    * errors, described with `error_class`, raised during validation and interaction itself,
      will be turned into a result using `error_handler`
    """
    def interactor(*validators: Validator):
        """
        Closure which encloses arguments of error handling. Takes series of validators
        as the arguments.

        :param validators: callables that make some validation; it might be instances of
            schemas or plain functions that make some additional validation; they should
            take the same signature as the decorated function, ie. may use injected
            dependencies
        :returns: container closure that returns decorated interactor
        """
        def decorator(f: InteractorFunction):
            """
            The actual decorator of an interactor function. Enwraps decorated with decorators
            of validation, error handling and dependency injection.
            """
            decorated_f = validated_by(*validators)(f)
            decorated_f = error_catcher(
                error_class=error_class,
                error_constructor=error_handler
            )(decorated_f)
            decorated_f = inject(decorated_f)
            decorated_f = container_supplier(decorated_f)
            return decorated_f

        return decorator

    return interactor 
开发者ID:pcah,项目名称:python-clean-architecture,代码行数:43,代码来源:interactor.py

示例15: _

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Sequence [as 别名]
def _(s: t.Sequence) -> tuple:
    return tuple(freeze(e) for e in s) 
开发者ID:pcah,项目名称:python-clean-architecture,代码行数:4,代码来源:collections.py


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