content
stringlengths 7
1.05M
|
|---|
class Except(Exception):
def __init__(*args, **kwargs):
Exception.__init__(*args, **kwargs)
def CheckExceptions(data):
raise Except(data)
|
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 22 19:49:17 2020
@author: matth
"""
def _linprog_highs_doc(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None,
bounds=None, method='highs', callback=None,
maxiter=None, disp=False, presolve=True,
time_limit=None,
dual_feasibility_tolerance=None,
primal_feasibility_tolerance=None,
ipm_optimality_tolerance=None,
simplex_dual_edge_weight_strategy=None,
**unknown_options):
r"""
Linear programming: minimize a linear objective function subject to linear
equality and inequality constraints using one of the HiGHS solvers.
Linear programming solves problems of the following form:
.. math::
\min_x \ & c^T x \\
\mbox{such that} \ & A_{ub} x \leq b_{ub},\\
& A_{eq} x = b_{eq},\\
& l \leq x \leq u ,
where :math:`x` is a vector of decision variables; :math:`c`,
:math:`b_{ub}`, :math:`b_{eq}`, :math:`l`, and :math:`u` are vectors; and
:math:`A_{ub}` and :math:`A_{eq}` are matrices.
Alternatively, that's:
minimize::
c @ x
such that::
A_ub @ x <= b_ub
A_eq @ x == b_eq
lb <= x <= ub
Note that by default ``lb = 0`` and ``ub = None`` unless specified with
``bounds``.
Parameters
----------
c : 1-D array
The coefficients of the linear objective function to be minimized.
A_ub : 2-D array, optional
The inequality constraint matrix. Each row of ``A_ub`` specifies the
coefficients of a linear inequality constraint on ``x``.
b_ub : 1-D array, optional
The inequality constraint vector. Each element represents an
upper bound on the corresponding value of ``A_ub @ x``.
A_eq : 2-D array, optional
The equality constraint matrix. Each row of ``A_eq`` specifies the
coefficients of a linear equality constraint on ``x``.
b_eq : 1-D array, optional
The equality constraint vector. Each element of ``A_eq @ x`` must equal
the corresponding element of ``b_eq``.
bounds : sequence, optional
A sequence of ``(min, max)`` pairs for each element in ``x``, defining
the minimum and maximum values of that decision variable. Use ``None``
to indicate that there is no bound. By default, bounds are
``(0, None)`` (all decision variables are non-negative).
If a single tuple ``(min, max)`` is provided, then ``min`` and
``max`` will serve as bounds for all decision variables.
method : str
This is the method-specific documentation for 'highs', which chooses
automatically between
:ref:`'highs-ds' <optimize.linprog-highs-ds>` and
:ref:`'highs-ipm' <optimize.linprog-highs-ipm>`.
:ref:`'interior-point' <optimize.linprog-interior-point>` (default),
:ref:`'revised simplex' <optimize.linprog-revised_simplex>`, and
:ref:`'simplex' <optimize.linprog-simplex>` (legacy)
are also available.
integrality : 1-D array, optional
Indicates the type of integrality constraint on each decision variable.
``0`` : Continuous variable; no integrality constraint.
``1`` : Integer variable; decision variable must be an integer
within `bounds`.
``2`` : Semi-continuous variable; decision variable must be within
`bounds` or take value ``0``.
``3`` : Semi-integer variable; decision variable must be an integer
within `bounds` or take value ``0``.
By default, all variables are continuous.
Options
-------
maxiter : int
The maximum number of iterations to perform in either phase.
For :ref:`'highs-ipm' <optimize.linprog-highs-ipm>`, this does not
include the number of crossover iterations. Default is the largest
possible value for an ``int`` on the platform.
disp : bool (default: ``False``)
Set to ``True`` if indicators of optimization status are to be
printed to the console during optimization.
presolve : bool (default: ``True``)
Presolve attempts to identify trivial infeasibilities,
identify trivial unboundedness, and simplify the problem before
sending it to the main solver. It is generally recommended
to keep the default setting ``True``; set to ``False`` if
presolve is to be disabled.
time_limit : float
The maximum time in seconds allotted to solve the problem;
default is the largest possible value for a ``double`` on the
platform.
dual_feasibility_tolerance : double (default: 1e-07)
Dual feasibility tolerance for
:ref:`'highs-ds' <optimize.linprog-highs-ds>`.
The minimum of this and ``primal_feasibility_tolerance``
is used for the feasibility tolerance of
:ref:`'highs-ipm' <optimize.linprog-highs-ipm>`.
primal_feasibility_tolerance : double (default: 1e-07)
Primal feasibility tolerance for
:ref:`'highs-ds' <optimize.linprog-highs-ds>`.
The minimum of this and ``dual_feasibility_tolerance``
is used for the feasibility tolerance of
:ref:`'highs-ipm' <optimize.linprog-highs-ipm>`.
ipm_optimality_tolerance : double (default: ``1e-08``)
Optimality tolerance for
:ref:`'highs-ipm' <optimize.linprog-highs-ipm>`.
Minimum allowable value is 1e-12.
simplex_dual_edge_weight_strategy : str (default: None)
Strategy for simplex dual edge weights. The default, ``None``,
automatically selects one of the following.
``'dantzig'`` uses Dantzig's original strategy of choosing the most
negative reduced cost.
``'devex'`` uses the strategy described in [15]_.
``steepest`` uses the exact steepest edge strategy as described in
[16]_.
``'steepest-devex'`` begins with the exact steepest edge strategy
until the computation is too costly or inexact and then switches to
the devex method.
Curently, ``None`` always selects ``'steepest-devex'``, but this
may change as new options become available.
unknown_options : dict
Optional arguments not used by this particular solver. If
``unknown_options`` is non-empty, a warning is issued listing
all unused options.
Returns
-------
res : OptimizeResult
A :class:`scipy.optimize.OptimizeResult` consisting of the fields:
x : 1D array
The values of the decision variables that minimizes the
objective function while satisfying the constraints.
fun : float
The optimal value of the objective function ``c @ x``.
slack : 1D array
The (nominally positive) values of the slack,
``b_ub - A_ub @ x``.
con : 1D array
The (nominally zero) residuals of the equality constraints,
``b_eq - A_eq @ x``.
success : bool
``True`` when the algorithm succeeds in finding an optimal
solution.
status : int
An integer representing the exit status of the algorithm.
``0`` : Optimization terminated successfully.
``1`` : Iteration or time limit reached.
``2`` : Problem appears to be infeasible.
``3`` : Problem appears to be unbounded.
``4`` : The HiGHS solver ran into a problem.
message : str
A string descriptor of the exit status of the algorithm.
nit : int
The total number of iterations performed.
For the HiGHS simplex method, this includes iterations in all
phases. For the HiGHS interior-point method, this does not include
crossover iterations.
crossover_nit : int
The number of primal/dual pushes performed during the
crossover routine for the HiGHS interior-point method.
This is ``0`` for the HiGHS simplex method.
ineqlin : OptimizeResult
Solution and sensitivity information corresponding to the
inequality constraints, `b_ub`. A dictionary consisting of the
fields:
residual : np.ndnarray
The (nominally positive) values of the slack variables,
``b_ub - A_ub @ x``. This quantity is also commonly
referred to as "slack".
marginals : np.ndarray
The sensitivity (partial derivative) of the objective
function with respect to the right-hand side of the
inequality constraints, `b_ub`.
eqlin : OptimizeResult
Solution and sensitivity information corresponding to the
equality constraints, `b_eq`. A dictionary consisting of the
fields:
residual : np.ndarray
The (nominally zero) residuals of the equality constraints,
``b_eq - A_eq @ x``.
marginals : np.ndarray
The sensitivity (partial derivative) of the objective
function with respect to the right-hand side of the
equality constraints, `b_eq`.
lower, upper : OptimizeResult
Solution and sensitivity information corresponding to the
lower and upper bounds on decision variables, `bounds`.
residual : np.ndarray
The (nominally positive) values of the quantity
``x - lb`` (lower) or ``ub - x`` (upper).
marginals : np.ndarray
The sensitivity (partial derivative) of the objective
function with respect to the lower and upper
`bounds`.
Notes
-----
Method :ref:`'highs-ds' <optimize.linprog-highs-ds>` is a wrapper
of the C++ high performance dual revised simplex implementation (HSOL)
[13]_, [14]_. Method :ref:`'highs-ipm' <optimize.linprog-highs-ipm>`
is a wrapper of a C++ implementation of an **i**\ nterior-\ **p**\ oint
**m**\ ethod [13]_; it features a crossover routine, so it is as accurate
as a simplex solver. Method :ref:`'highs' <optimize.linprog-highs>` chooses
between the two automatically. For new code involving `linprog`, we
recommend explicitly choosing one of these three method values instead of
:ref:`'interior-point' <optimize.linprog-interior-point>` (default),
:ref:`'revised simplex' <optimize.linprog-revised_simplex>`, and
:ref:`'simplex' <optimize.linprog-simplex>` (legacy).
The result fields `ineqlin`, `eqlin`, `lower`, and `upper` all contain
`marginals`, or partial derivatives of the objective function with respect
to the right-hand side of each constraint. These partial derivatives are
also referred to as "Lagrange multipliers", "dual values", and
"shadow prices". The sign convention of `marginals` is opposite that
of Lagrange multipliers produced by many nonlinear solvers.
References
----------
.. [13] Huangfu, Q., Galabova, I., Feldmeier, M., and Hall, J. A. J.
"HiGHS - high performance software for linear optimization."
Accessed 4/16/2020 at https://www.maths.ed.ac.uk/hall/HiGHS/#guide
.. [14] Huangfu, Q. and Hall, J. A. J. "Parallelizing the dual revised
simplex method." Mathematical Programming Computation, 10 (1),
119-142, 2018. DOI: 10.1007/s12532-017-0130-5
.. [15] Harris, Paula MJ. "Pivot selection methods of the Devex LP code."
Mathematical programming 5.1 (1973): 1-28.
.. [16] Goldfarb, Donald, and John Ker Reid. "A practicable steepest-edge
simplex algorithm." Mathematical Programming 12.1 (1977): 361-371.
"""
pass
def _linprog_highs_ds_doc(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None,
bounds=None, method='highs-ds', callback=None,
maxiter=None, disp=False, presolve=True,
time_limit=None,
dual_feasibility_tolerance=None,
primal_feasibility_tolerance=None,
simplex_dual_edge_weight_strategy=None,
**unknown_options):
r"""
Linear programming: minimize a linear objective function subject to linear
equality and inequality constraints using the HiGHS dual simplex solver.
Linear programming solves problems of the following form:
.. math::
\min_x \ & c^T x \\
\mbox{such that} \ & A_{ub} x \leq b_{ub},\\
& A_{eq} x = b_{eq},\\
& l \leq x \leq u ,
where :math:`x` is a vector of decision variables; :math:`c`,
:math:`b_{ub}`, :math:`b_{eq}`, :math:`l`, and :math:`u` are vectors; and
:math:`A_{ub}` and :math:`A_{eq}` are matrices.
Alternatively, that's:
minimize::
c @ x
such that::
A_ub @ x <= b_ub
A_eq @ x == b_eq
lb <= x <= ub
Note that by default ``lb = 0`` and ``ub = None`` unless specified with
``bounds``.
Parameters
----------
c : 1-D array
The coefficients of the linear objective function to be minimized.
A_ub : 2-D array, optional
The inequality constraint matrix. Each row of ``A_ub`` specifies the
coefficients of a linear inequality constraint on ``x``.
b_ub : 1-D array, optional
The inequality constraint vector. Each element represents an
upper bound on the corresponding value of ``A_ub @ x``.
A_eq : 2-D array, optional
The equality constraint matrix. Each row of ``A_eq`` specifies the
coefficients of a linear equality constraint on ``x``.
b_eq : 1-D array, optional
The equality constraint vector. Each element of ``A_eq @ x`` must equal
the corresponding element of ``b_eq``.
bounds : sequence, optional
A sequence of ``(min, max)`` pairs for each element in ``x``, defining
the minimum and maximum values of that decision variable. Use ``None``
to indicate that there is no bound. By default, bounds are
``(0, None)`` (all decision variables are non-negative).
If a single tuple ``(min, max)`` is provided, then ``min`` and
``max`` will serve as bounds for all decision variables.
method : str
This is the method-specific documentation for 'highs-ds'.
:ref:`'highs' <optimize.linprog-highs>`,
:ref:`'highs-ipm' <optimize.linprog-highs-ipm>`,
:ref:`'interior-point' <optimize.linprog-interior-point>` (default),
:ref:`'revised simplex' <optimize.linprog-revised_simplex>`, and
:ref:`'simplex' <optimize.linprog-simplex>` (legacy)
are also available.
Options
-------
maxiter : int
The maximum number of iterations to perform in either phase.
Default is the largest possible value for an ``int`` on the platform.
disp : bool (default: ``False``)
Set to ``True`` if indicators of optimization status are to be
printed to the console during optimization.
presolve : bool (default: ``True``)
Presolve attempts to identify trivial infeasibilities,
identify trivial unboundedness, and simplify the problem before
sending it to the main solver. It is generally recommended
to keep the default setting ``True``; set to ``False`` if
presolve is to be disabled.
time_limit : float
The maximum time in seconds allotted to solve the problem;
default is the largest possible value for a ``double`` on the
platform.
dual_feasibility_tolerance : double (default: 1e-07)
Dual feasibility tolerance for
:ref:`'highs-ds' <optimize.linprog-highs-ds>`.
primal_feasibility_tolerance : double (default: 1e-07)
Primal feasibility tolerance for
:ref:`'highs-ds' <optimize.linprog-highs-ds>`.
simplex_dual_edge_weight_strategy : str (default: None)
Strategy for simplex dual edge weights. The default, ``None``,
automatically selects one of the following.
``'dantzig'`` uses Dantzig's original strategy of choosing the most
negative reduced cost.
``'devex'`` uses the strategy described in [15]_.
``steepest`` uses the exact steepest edge strategy as described in
[16]_.
``'steepest-devex'`` begins with the exact steepest edge strategy
until the computation is too costly or inexact and then switches to
the devex method.
Curently, ``None`` always selects ``'steepest-devex'``, but this
may change as new options become available.
unknown_options : dict
Optional arguments not used by this particular solver. If
``unknown_options`` is non-empty, a warning is issued listing
all unused options.
Returns
-------
res : OptimizeResult
A :class:`scipy.optimize.OptimizeResult` consisting of the fields:
x : 1D array
The values of the decision variables that minimizes the
objective function while satisfying the constraints.
fun : float
The optimal value of the objective function ``c @ x``.
slack : 1D array
The (nominally positive) values of the slack,
``b_ub - A_ub @ x``.
con : 1D array
The (nominally zero) residuals of the equality constraints,
``b_eq - A_eq @ x``.
success : bool
``True`` when the algorithm succeeds in finding an optimal
solution.
status : int
An integer representing the exit status of the algorithm.
``0`` : Optimization terminated successfully.
``1`` : Iteration or time limit reached.
``2`` : Problem appears to be infeasible.
``3`` : Problem appears to be unbounded.
``4`` : The HiGHS solver ran into a problem.
message : str
A string descriptor of the exit status of the algorithm.
nit : int
The total number of iterations performed. This includes iterations
in all phases.
crossover_nit : int
This is always ``0`` for the HiGHS simplex method.
For the HiGHS interior-point method, this is the number of
primal/dual pushes performed during the crossover routine.
ineqlin : OptimizeResult
Solution and sensitivity information corresponding to the
inequality constraints, `b_ub`. A dictionary consisting of the
fields:
residual : np.ndnarray
The (nominally positive) values of the slack variables,
``b_ub - A_ub @ x``. This quantity is also commonly
referred to as "slack".
marginals : np.ndarray
The sensitivity (partial derivative) of the objective
function with respect to the right-hand side of the
inequality constraints, `b_ub`.
eqlin : OptimizeResult
Solution and sensitivity information corresponding to the
equality constraints, `b_eq`. A dictionary consisting of the
fields:
residual : np.ndarray
The (nominally zero) residuals of the equality constraints,
``b_eq - A_eq @ x``.
marginals : np.ndarray
The sensitivity (partial derivative) of the objective
function with respect to the right-hand side of the
equality constraints, `b_eq`.
lower, upper : OptimizeResult
Solution and sensitivity information corresponding to the
lower and upper bounds on decision variables, `bounds`.
residual : np.ndarray
The (nominally positive) values of the quantity
``x - lb`` (lower) or ``ub - x`` (upper).
marginals : np.ndarray
The sensitivity (partial derivative) of the objective
function with respect to the lower and upper
`bounds`.
Notes
-----
Method :ref:`'highs-ds' <optimize.linprog-highs-ds>` is a wrapper
of the C++ high performance dual revised simplex implementation (HSOL)
[13]_, [14]_. Method :ref:`'highs-ipm' <optimize.linprog-highs-ipm>`
is a wrapper of a C++ implementation of an **i**\ nterior-\ **p**\ oint
**m**\ ethod [13]_; it features a crossover routine, so it is as accurate
as a simplex solver. Method :ref:`'highs' <optimize.linprog-highs>` chooses
between the two automatically. For new code involving `linprog`, we
recommend explicitly choosing one of these three method values instead of
:ref:`'interior-point' <optimize.linprog-interior-point>` (default),
:ref:`'revised simplex' <optimize.linprog-revised_simplex>`, and
:ref:`'simplex' <optimize.linprog-simplex>` (legacy).
The result fields `ineqlin`, `eqlin`, `lower`, and `upper` all contain
`marginals`, or partial derivatives of the objective function with respect
to the right-hand side of each constraint. These partial derivatives are
also referred to as "Lagrange multipliers", "dual values", and
"shadow prices". The sign convention of `marginals` is opposite that
of Lagrange multipliers produced by many nonlinear solvers.
References
----------
.. [13] Huangfu, Q., Galabova, I., Feldmeier, M., and Hall, J. A. J.
"HiGHS - high performance software for linear optimization."
Accessed 4/16/2020 at https://www.maths.ed.ac.uk/hall/HiGHS/#guide
.. [14] Huangfu, Q. and Hall, J. A. J. "Parallelizing the dual revised
simplex method." Mathematical Programming Computation, 10 (1),
119-142, 2018. DOI: 10.1007/s12532-017-0130-5
.. [15] Harris, Paula MJ. "Pivot selection methods of the Devex LP code."
Mathematical programming 5.1 (1973): 1-28.
.. [16] Goldfarb, Donald, and John Ker Reid. "A practicable steepest-edge
simplex algorithm." Mathematical Programming 12.1 (1977): 361-371.
"""
pass
def _linprog_highs_ipm_doc(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None,
bounds=None, method='highs-ipm', callback=None,
maxiter=None, disp=False, presolve=True,
time_limit=None,
dual_feasibility_tolerance=None,
primal_feasibility_tolerance=None,
ipm_optimality_tolerance=None,
**unknown_options):
r"""
Linear programming: minimize a linear objective function subject to linear
equality and inequality constraints using the HiGHS interior point solver.
Linear programming solves problems of the following form:
.. math::
\min_x \ & c^T x \\
\mbox{such that} \ & A_{ub} x \leq b_{ub},\\
& A_{eq} x = b_{eq},\\
& l \leq x \leq u ,
where :math:`x` is a vector of decision variables; :math:`c`,
:math:`b_{ub}`, :math:`b_{eq}`, :math:`l`, and :math:`u` are vectors; and
:math:`A_{ub}` and :math:`A_{eq}` are matrices.
Alternatively, that's:
minimize::
c @ x
such that::
A_ub @ x <= b_ub
A_eq @ x == b_eq
lb <= x <= ub
Note that by default ``lb = 0`` and ``ub = None`` unless specified with
``bounds``.
Parameters
----------
c : 1-D array
The coefficients of the linear objective function to be minimized.
A_ub : 2-D array, optional
The inequality constraint matrix. Each row of ``A_ub`` specifies the
coefficients of a linear inequality constraint on ``x``.
b_ub : 1-D array, optional
The inequality constraint vector. Each element represents an
upper bound on the corresponding value of ``A_ub @ x``.
A_eq : 2-D array, optional
The equality constraint matrix. Each row of ``A_eq`` specifies the
coefficients of a linear equality constraint on ``x``.
b_eq : 1-D array, optional
The equality constraint vector. Each element of ``A_eq @ x`` must equal
the corresponding element of ``b_eq``.
bounds : sequence, optional
A sequence of ``(min, max)`` pairs for each element in ``x``, defining
the minimum and maximum values of that decision variable. Use ``None``
to indicate that there is no bound. By default, bounds are
``(0, None)`` (all decision variables are non-negative).
If a single tuple ``(min, max)`` is provided, then ``min`` and
``max`` will serve as bounds for all decision variables.
method : str
This is the method-specific documentation for 'highs-ipm'.
:ref:`'highs-ipm' <optimize.linprog-highs>`,
:ref:`'highs-ds' <optimize.linprog-highs-ds>`,
:ref:`'interior-point' <optimize.linprog-interior-point>` (default),
:ref:`'revised simplex' <optimize.linprog-revised_simplex>`, and
:ref:`'simplex' <optimize.linprog-simplex>` (legacy)
are also available.
Options
-------
maxiter : int
The maximum number of iterations to perform in either phase.
For :ref:`'highs-ipm' <optimize.linprog-highs-ipm>`, this does not
include the number of crossover iterations. Default is the largest
possible value for an ``int`` on the platform.
disp : bool (default: ``False``)
Set to ``True`` if indicators of optimization status are to be
printed to the console during optimization.
presolve : bool (default: ``True``)
Presolve attempts to identify trivial infeasibilities,
identify trivial unboundedness, and simplify the problem before
sending it to the main solver. It is generally recommended
to keep the default setting ``True``; set to ``False`` if
presolve is to be disabled.
time_limit : float
The maximum time in seconds allotted to solve the problem;
default is the largest possible value for a ``double`` on the
platform.
dual_feasibility_tolerance : double (default: 1e-07)
The minimum of this and ``primal_feasibility_tolerance``
is used for the feasibility tolerance of
:ref:`'highs-ipm' <optimize.linprog-highs-ipm>`.
primal_feasibility_tolerance : double (default: 1e-07)
The minimum of this and ``dual_feasibility_tolerance``
is used for the feasibility tolerance of
:ref:`'highs-ipm' <optimize.linprog-highs-ipm>`.
ipm_optimality_tolerance : double (default: ``1e-08``)
Optimality tolerance for
:ref:`'highs-ipm' <optimize.linprog-highs-ipm>`.
Minimum allowable value is 1e-12.
unknown_options : dict
Optional arguments not used by this particular solver. If
``unknown_options`` is non-empty, a warning is issued listing
all unused options.
Returns
-------
res : OptimizeResult
A :class:`scipy.optimize.OptimizeResult` consisting of the fields:
x : 1D array
The values of the decision variables that minimizes the
objective function while satisfying the constraints.
fun : float
The optimal value of the objective function ``c @ x``.
slack : 1D array
The (nominally positive) values of the slack,
``b_ub - A_ub @ x``.
con : 1D array
The (nominally zero) residuals of the equality constraints,
``b_eq - A_eq @ x``.
success : bool
``True`` when the algorithm succeeds in finding an optimal
solution.
status : int
An integer representing the exit status of the algorithm.
``0`` : Optimization terminated successfully.
``1`` : Iteration or time limit reached.
``2`` : Problem appears to be infeasible.
``3`` : Problem appears to be unbounded.
``4`` : The HiGHS solver ran into a problem.
message : str
A string descriptor of the exit status of the algorithm.
nit : int
The total number of iterations performed.
For the HiGHS interior-point method, this does not include
crossover iterations.
crossover_nit : int
The number of primal/dual pushes performed during the
crossover routine for the HiGHS interior-point method.
ineqlin : OptimizeResult
Solution and sensitivity information corresponding to the
inequality constraints, `b_ub`. A dictionary consisting of the
fields:
residual : np.ndnarray
The (nominally positive) values of the slack variables,
``b_ub - A_ub @ x``. This quantity is also commonly
referred to as "slack".
marginals : np.ndarray
The sensitivity (partial derivative) of the objective
function with respect to the right-hand side of the
inequality constraints, `b_ub`.
eqlin : OptimizeResult
Solution and sensitivity information corresponding to the
equality constraints, `b_eq`. A dictionary consisting of the
fields:
residual : np.ndarray
The (nominally zero) residuals of the equality constraints,
``b_eq - A_eq @ x``.
marginals : np.ndarray
The sensitivity (partial derivative) of the objective
function with respect to the right-hand side of the
equality constraints, `b_eq`.
lower, upper : OptimizeResult
Solution and sensitivity information corresponding to the
lower and upper bounds on decision variables, `bounds`.
residual : np.ndarray
The (nominally positive) values of the quantity
``x - lb`` (lower) or ``ub - x`` (upper).
marginals : np.ndarray
The sensitivity (partial derivative) of the objective
function with respect to the lower and upper
`bounds`.
Notes
-----
Method :ref:`'highs-ipm' <optimize.linprog-highs-ipm>`
is a wrapper of a C++ implementation of an **i**\ nterior-\ **p**\ oint
**m**\ ethod [13]_; it features a crossover routine, so it is as accurate
as a simplex solver.
Method :ref:`'highs-ds' <optimize.linprog-highs-ds>` is a wrapper
of the C++ high performance dual revised simplex implementation (HSOL)
[13]_, [14]_. Method :ref:`'highs' <optimize.linprog-highs>` chooses
between the two automatically. For new code involving `linprog`, we
recommend explicitly choosing one of these three method values instead of
:ref:`'interior-point' <optimize.linprog-interior-point>` (default),
:ref:`'revised simplex' <optimize.linprog-revised_simplex>`, and
:ref:`'simplex' <optimize.linprog-simplex>` (legacy).
The result fields `ineqlin`, `eqlin`, `lower`, and `upper` all contain
`marginals`, or partial derivatives of the objective function with respect
to the right-hand side of each constraint. These partial derivatives are
also referred to as "Lagrange multipliers", "dual values", and
"shadow prices". The sign convention of `marginals` is opposite that
of Lagrange multipliers produced by many nonlinear solvers.
References
----------
.. [13] Huangfu, Q., Galabova, I., Feldmeier, M., and Hall, J. A. J.
"HiGHS - high performance software for linear optimization."
Accessed 4/16/2020 at https://www.maths.ed.ac.uk/hall/HiGHS/#guide
.. [14] Huangfu, Q. and Hall, J. A. J. "Parallelizing the dual revised
simplex method." Mathematical Programming Computation, 10 (1),
119-142, 2018. DOI: 10.1007/s12532-017-0130-5
"""
pass
def _linprog_ip_doc(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None,
bounds=None, method='interior-point', callback=None,
maxiter=1000, disp=False, presolve=True,
tol=1e-8, autoscale=False, rr=True,
alpha0=.99995, beta=0.1, sparse=False,
lstsq=False, sym_pos=True, cholesky=True, pc=True,
ip=False, permc_spec='MMD_AT_PLUS_A', **unknown_options):
r"""
Linear programming: minimize a linear objective function subject to linear
equality and inequality constraints using the interior-point method of
[4]_.
.. deprecated:: 1.9.0
`method='interior-point'` will be removed in SciPy 1.11.0.
It is replaced by `method='highs'` because the latter is
faster and more robust.
Linear programming solves problems of the following form:
.. math::
\min_x \ & c^T x \\
\mbox{such that} \ & A_{ub} x \leq b_{ub},\\
& A_{eq} x = b_{eq},\\
& l \leq x \leq u ,
where :math:`x` is a vector of decision variables; :math:`c`,
:math:`b_{ub}`, :math:`b_{eq}`, :math:`l`, and :math:`u` are vectors; and
:math:`A_{ub}` and :math:`A_{eq}` are matrices.
Alternatively, that's:
minimize::
c @ x
such that::
A_ub @ x <= b_ub
A_eq @ x == b_eq
lb <= x <= ub
Note that by default ``lb = 0`` and ``ub = None`` unless specified with
``bounds``.
Parameters
----------
c : 1-D array
The coefficients of the linear objective function to be minimized.
A_ub : 2-D array, optional
The inequality constraint matrix. Each row of ``A_ub`` specifies the
coefficients of a linear inequality constraint on ``x``.
b_ub : 1-D array, optional
The inequality constraint vector. Each element represents an
upper bound on the corresponding value of ``A_ub @ x``.
A_eq : 2-D array, optional
The equality constraint matrix. Each row of ``A_eq`` specifies the
coefficients of a linear equality constraint on ``x``.
b_eq : 1-D array, optional
The equality constraint vector. Each element of ``A_eq @ x`` must equal
the corresponding element of ``b_eq``.
bounds : sequence, optional
A sequence of ``(min, max)`` pairs for each element in ``x``, defining
the minimum and maximum values of that decision variable. Use ``None``
to indicate that there is no bound. By default, bounds are
``(0, None)`` (all decision variables are non-negative).
If a single tuple ``(min, max)`` is provided, then ``min`` and
``max`` will serve as bounds for all decision variables.
method : str
This is the method-specific documentation for 'interior-point'.
:ref:`'highs' <optimize.linprog-highs>`,
:ref:`'highs-ds' <optimize.linprog-highs-ds>`,
:ref:`'highs-ipm' <optimize.linprog-highs-ipm>`,
:ref:`'revised simplex' <optimize.linprog-revised_simplex>`, and
:ref:`'simplex' <optimize.linprog-simplex>` (legacy)
are also available.
callback : callable, optional
Callback function to be executed once per iteration.
Options
-------
maxiter : int (default: 1000)
The maximum number of iterations of the algorithm.
disp : bool (default: False)
Set to ``True`` if indicators of optimization status are to be printed
to the console each iteration.
presolve : bool (default: True)
Presolve attempts to identify trivial infeasibilities,
identify trivial unboundedness, and simplify the problem before
sending it to the main solver. It is generally recommended
to keep the default setting ``True``; set to ``False`` if
presolve is to be disabled.
tol : float (default: 1e-8)
Termination tolerance to be used for all termination criteria;
see [4]_ Section 4.5.
autoscale : bool (default: False)
Set to ``True`` to automatically perform equilibration.
Consider using this option if the numerical values in the
constraints are separated by several orders of magnitude.
rr : bool (default: True)
Set to ``False`` to disable automatic redundancy removal.
alpha0 : float (default: 0.99995)
The maximal step size for Mehrota's predictor-corrector search
direction; see :math:`\beta_{3}` of [4]_ Table 8.1.
beta : float (default: 0.1)
The desired reduction of the path parameter :math:`\mu` (see [6]_)
when Mehrota's predictor-corrector is not in use (uncommon).
sparse : bool (default: False)
Set to ``True`` if the problem is to be treated as sparse after
presolve. If either ``A_eq`` or ``A_ub`` is a sparse matrix,
this option will automatically be set ``True``, and the problem
will be treated as sparse even during presolve. If your constraint
matrices contain mostly zeros and the problem is not very small (less
than about 100 constraints or variables), consider setting ``True``
or providing ``A_eq`` and ``A_ub`` as sparse matrices.
lstsq : bool (default: ``False``)
Set to ``True`` if the problem is expected to be very poorly
conditioned. This should always be left ``False`` unless severe
numerical difficulties are encountered. Leave this at the default
unless you receive a warning message suggesting otherwise.
sym_pos : bool (default: True)
Leave ``True`` if the problem is expected to yield a well conditioned
symmetric positive definite normal equation matrix
(almost always). Leave this at the default unless you receive
a warning message suggesting otherwise.
cholesky : bool (default: True)
Set to ``True`` if the normal equations are to be solved by explicit
Cholesky decomposition followed by explicit forward/backward
substitution. This is typically faster for problems
that are numerically well-behaved.
pc : bool (default: True)
Leave ``True`` if the predictor-corrector method of Mehrota is to be
used. This is almost always (if not always) beneficial.
ip : bool (default: False)
Set to ``True`` if the improved initial point suggestion due to [4]_
Section 4.3 is desired. Whether this is beneficial or not
depends on the problem.
permc_spec : str (default: 'MMD_AT_PLUS_A')
(Has effect only with ``sparse = True``, ``lstsq = False``, ``sym_pos =
True``, and no SuiteSparse.)
A matrix is factorized in each iteration of the algorithm.
This option specifies how to permute the columns of the matrix for
sparsity preservation. Acceptable values are:
- ``NATURAL``: natural ordering.
- ``MMD_ATA``: minimum degree ordering on the structure of A^T A.
- ``MMD_AT_PLUS_A``: minimum degree ordering on the structure of A^T+A.
- ``COLAMD``: approximate minimum degree column ordering.
This option can impact the convergence of the
interior point algorithm; test different values to determine which
performs best for your problem. For more information, refer to
``scipy.sparse.linalg.splu``.
unknown_options : dict
Optional arguments not used by this particular solver. If
`unknown_options` is non-empty a warning is issued listing all
unused options.
Returns
-------
res : OptimizeResult
A :class:`scipy.optimize.OptimizeResult` consisting of the fields:
x : 1-D array
The values of the decision variables that minimizes the
objective function while satisfying the constraints.
fun : float
The optimal value of the objective function ``c @ x``.
slack : 1-D array
The (nominally positive) values of the slack variables,
``b_ub - A_ub @ x``.
con : 1-D array
The (nominally zero) residuals of the equality constraints,
``b_eq - A_eq @ x``.
success : bool
``True`` when the algorithm succeeds in finding an optimal
solution.
status : int
An integer representing the exit status of the algorithm.
``0`` : Optimization terminated successfully.
``1`` : Iteration limit reached.
``2`` : Problem appears to be infeasible.
``3`` : Problem appears to be unbounded.
``4`` : Numerical difficulties encountered.
message : str
A string descriptor of the exit status of the algorithm.
nit : int
The total number of iterations performed in all phases.
Notes
-----
This method implements the algorithm outlined in [4]_ with ideas from [8]_
and a structure inspired by the simpler methods of [6]_.
The primal-dual path following method begins with initial 'guesses' of
the primal and dual variables of the standard form problem and iteratively
attempts to solve the (nonlinear) Karush-Kuhn-Tucker conditions for the
problem with a gradually reduced logarithmic barrier term added to the
objective. This particular implementation uses a homogeneous self-dual
formulation, which provides certificates of infeasibility or unboundedness
where applicable.
The default initial point for the primal and dual variables is that
defined in [4]_ Section 4.4 Equation 8.22. Optionally (by setting initial
point option ``ip=True``), an alternate (potentially improved) starting
point can be calculated according to the additional recommendations of
[4]_ Section 4.4.
A search direction is calculated using the predictor-corrector method
(single correction) proposed by Mehrota and detailed in [4]_ Section 4.1.
(A potential improvement would be to implement the method of multiple
corrections described in [4]_ Section 4.2.) In practice, this is
accomplished by solving the normal equations, [4]_ Section 5.1 Equations
8.31 and 8.32, derived from the Newton equations [4]_ Section 5 Equations
8.25 (compare to [4]_ Section 4 Equations 8.6-8.8). The advantage of
solving the normal equations rather than 8.25 directly is that the
matrices involved are symmetric positive definite, so Cholesky
decomposition can be used rather than the more expensive LU factorization.
With default options, the solver used to perform the factorization depends
on third-party software availability and the conditioning of the problem.
For dense problems, solvers are tried in the following order:
1. ``scipy.linalg.cho_factor``
2. ``scipy.linalg.solve`` with option ``sym_pos=True``
3. ``scipy.linalg.solve`` with option ``sym_pos=False``
4. ``scipy.linalg.lstsq``
For sparse problems:
1. ``sksparse.cholmod.cholesky`` (if scikit-sparse and SuiteSparse are
installed)
2. ``scipy.sparse.linalg.factorized`` (if scikit-umfpack and SuiteSparse
are installed)
3. ``scipy.sparse.linalg.splu`` (which uses SuperLU distributed with SciPy)
4. ``scipy.sparse.linalg.lsqr``
If the solver fails for any reason, successively more robust (but slower)
solvers are attempted in the order indicated. Attempting, failing, and
re-starting factorization can be time consuming, so if the problem is
numerically challenging, options can be set to bypass solvers that are
failing. Setting ``cholesky=False`` skips to solver 2,
``sym_pos=False`` skips to solver 3, and ``lstsq=True`` skips
to solver 4 for both sparse and dense problems.
Potential improvements for combatting issues associated with dense
columns in otherwise sparse problems are outlined in [4]_ Section 5.3 and
[10]_ Section 4.1-4.2; the latter also discusses the alleviation of
accuracy issues associated with the substitution approach to free
variables.
After calculating the search direction, the maximum possible step size
that does not activate the non-negativity constraints is calculated, and
the smaller of this step size and unity is applied (as in [4]_ Section
4.1.) [4]_ Section 4.3 suggests improvements for choosing the step size.
The new point is tested according to the termination conditions of [4]_
Section 4.5. The same tolerance, which can be set using the ``tol`` option,
is used for all checks. (A potential improvement would be to expose
the different tolerances to be set independently.) If optimality,
unboundedness, or infeasibility is detected, the solve procedure
terminates; otherwise it repeats.
Whereas the top level ``linprog`` module expects a problem of form:
Minimize::
c @ x
Subject to::
A_ub @ x <= b_ub
A_eq @ x == b_eq
lb <= x <= ub
where ``lb = 0`` and ``ub = None`` unless set in ``bounds``. The problem
is automatically converted to the form:
Minimize::
c @ x
Subject to::
A @ x == b
x >= 0
for solution. That is, the original problem contains equality, upper-bound
and variable constraints whereas the method specific solver requires
equality constraints and variable non-negativity. ``linprog`` converts the
original problem to standard form by converting the simple bounds to upper
bound constraints, introducing non-negative slack variables for inequality
constraints, and expressing unbounded variables as the difference between
two non-negative variables. The problem is converted back to the original
form before results are reported.
References
----------
.. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point
optimizer for linear programming: an implementation of the
homogeneous algorithm." High performance optimization. Springer US,
2000. 197-232.
.. [6] Freund, Robert M. "Primal-Dual Interior-Point Methods for Linear
Programming based on Newton's Method." Unpublished Course Notes,
March 2004. Available 2/25/2017 at
https://ocw.mit.edu/courses/sloan-school-of-management/15-084j-nonlinear-programming-spring-2004/lecture-notes/lec14_int_pt_mthd.pdf
.. [8] Andersen, Erling D., and Knud D. Andersen. "Presolving in linear
programming." Mathematical Programming 71.2 (1995): 221-245.
.. [9] Bertsimas, Dimitris, and J. Tsitsiklis. "Introduction to linear
programming." Athena Scientific 1 (1997): 997.
.. [10] Andersen, Erling D., et al. Implementation of interior point
methods for large scale linear programming. HEC/Universite de
Geneve, 1996.
"""
pass
def _linprog_rs_doc(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None,
bounds=None, method='interior-point', callback=None,
x0=None, maxiter=5000, disp=False, presolve=True,
tol=1e-12, autoscale=False, rr=True, maxupdate=10,
mast=False, pivot="mrc", **unknown_options):
r"""
Linear programming: minimize a linear objective function subject to linear
equality and inequality constraints using the revised simplex method.
.. deprecated:: 1.9.0
`method='revised simplex'` will be removed in SciPy 1.11.0.
It is replaced by `method='highs'` because the latter is
faster and more robust.
Linear programming solves problems of the following form:
.. math::
\min_x \ & c^T x \\
\mbox{such that} \ & A_{ub} x \leq b_{ub},\\
& A_{eq} x = b_{eq},\\
& l \leq x \leq u ,
where :math:`x` is a vector of decision variables; :math:`c`,
:math:`b_{ub}`, :math:`b_{eq}`, :math:`l`, and :math:`u` are vectors; and
:math:`A_{ub}` and :math:`A_{eq}` are matrices.
Alternatively, that's:
minimize::
c @ x
such that::
A_ub @ x <= b_ub
A_eq @ x == b_eq
lb <= x <= ub
Note that by default ``lb = 0`` and ``ub = None`` unless specified with
``bounds``.
Parameters
----------
c : 1-D array
The coefficients of the linear objective function to be minimized.
A_ub : 2-D array, optional
The inequality constraint matrix. Each row of ``A_ub`` specifies the
coefficients of a linear inequality constraint on ``x``.
b_ub : 1-D array, optional
The inequality constraint vector. Each element represents an
upper bound on the corresponding value of ``A_ub @ x``.
A_eq : 2-D array, optional
The equality constraint matrix. Each row of ``A_eq`` specifies the
coefficients of a linear equality constraint on ``x``.
b_eq : 1-D array, optional
The equality constraint vector. Each element of ``A_eq @ x`` must equal
the corresponding element of ``b_eq``.
bounds : sequence, optional
A sequence of ``(min, max)`` pairs for each element in ``x``, defining
the minimum and maximum values of that decision variable. Use ``None``
to indicate that there is no bound. By default, bounds are
``(0, None)`` (all decision variables are non-negative).
If a single tuple ``(min, max)`` is provided, then ``min`` and
``max`` will serve as bounds for all decision variables.
method : str
This is the method-specific documentation for 'revised simplex'.
:ref:`'highs' <optimize.linprog-highs>`,
:ref:`'highs-ds' <optimize.linprog-highs-ds>`,
:ref:`'highs-ipm' <optimize.linprog-highs-ipm>`,
:ref:`'interior-point' <optimize.linprog-interior-point>` (default),
and :ref:`'simplex' <optimize.linprog-simplex>` (legacy)
are also available.
callback : callable, optional
Callback function to be executed once per iteration.
x0 : 1-D array, optional
Guess values of the decision variables, which will be refined by
the optimization algorithm. This argument is currently used only by the
'revised simplex' method, and can only be used if `x0` represents a
basic feasible solution.
Options
-------
maxiter : int (default: 5000)
The maximum number of iterations to perform in either phase.
disp : bool (default: False)
Set to ``True`` if indicators of optimization status are to be printed
to the console each iteration.
presolve : bool (default: True)
Presolve attempts to identify trivial infeasibilities,
identify trivial unboundedness, and simplify the problem before
sending it to the main solver. It is generally recommended
to keep the default setting ``True``; set to ``False`` if
presolve is to be disabled.
tol : float (default: 1e-12)
The tolerance which determines when a solution is "close enough" to
zero in Phase 1 to be considered a basic feasible solution or close
enough to positive to serve as an optimal solution.
autoscale : bool (default: False)
Set to ``True`` to automatically perform equilibration.
Consider using this option if the numerical values in the
constraints are separated by several orders of magnitude.
rr : bool (default: True)
Set to ``False`` to disable automatic redundancy removal.
maxupdate : int (default: 10)
The maximum number of updates performed on the LU factorization.
After this many updates is reached, the basis matrix is factorized
from scratch.
mast : bool (default: False)
Minimize Amortized Solve Time. If enabled, the average time to solve
a linear system using the basis factorization is measured. Typically,
the average solve time will decrease with each successive solve after
initial factorization, as factorization takes much more time than the
solve operation (and updates). Eventually, however, the updated
factorization becomes sufficiently complex that the average solve time
begins to increase. When this is detected, the basis is refactorized
from scratch. Enable this option to maximize speed at the risk of
nondeterministic behavior. Ignored if ``maxupdate`` is 0.
pivot : "mrc" or "bland" (default: "mrc")
Pivot rule: Minimum Reduced Cost ("mrc") or Bland's rule ("bland").
Choose Bland's rule if iteration limit is reached and cycling is
suspected.
unknown_options : dict
Optional arguments not used by this particular solver. If
`unknown_options` is non-empty a warning is issued listing all
unused options.
Returns
-------
res : OptimizeResult
A :class:`scipy.optimize.OptimizeResult` consisting of the fields:
x : 1-D array
The values of the decision variables that minimizes the
objective function while satisfying the constraints.
fun : float
The optimal value of the objective function ``c @ x``.
slack : 1-D array
The (nominally positive) values of the slack variables,
``b_ub - A_ub @ x``.
con : 1-D array
The (nominally zero) residuals of the equality constraints,
``b_eq - A_eq @ x``.
success : bool
``True`` when the algorithm succeeds in finding an optimal
solution.
status : int
An integer representing the exit status of the algorithm.
``0`` : Optimization terminated successfully.
``1`` : Iteration limit reached.
``2`` : Problem appears to be infeasible.
``3`` : Problem appears to be unbounded.
``4`` : Numerical difficulties encountered.
``5`` : Problem has no constraints; turn presolve on.
``6`` : Invalid guess provided.
message : str
A string descriptor of the exit status of the algorithm.
nit : int
The total number of iterations performed in all phases.
Notes
-----
Method *revised simplex* uses the revised simplex method as described in
[9]_, except that a factorization [11]_ of the basis matrix, rather than
its inverse, is efficiently maintained and used to solve the linear systems
at each iteration of the algorithm.
References
----------
.. [9] Bertsimas, Dimitris, and J. Tsitsiklis. "Introduction to linear
programming." Athena Scientific 1 (1997): 997.
.. [11] Bartels, Richard H. "A stabilization of the simplex method."
Journal in Numerische Mathematik 16.5 (1971): 414-434.
"""
pass
def _linprog_simplex_doc(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None,
bounds=None, method='interior-point', callback=None,
maxiter=5000, disp=False, presolve=True,
tol=1e-12, autoscale=False, rr=True, bland=False,
**unknown_options):
r"""
Linear programming: minimize a linear objective function subject to linear
equality and inequality constraints using the tableau-based simplex method.
.. deprecated:: 1.9.0
`method='simplex'` will be removed in SciPy 1.11.0.
It is replaced by `method='highs'` because the latter is
faster and more robust.
Linear programming solves problems of the following form:
.. math::
\min_x \ & c^T x \\
\mbox{such that} \ & A_{ub} x \leq b_{ub},\\
& A_{eq} x = b_{eq},\\
& l \leq x \leq u ,
where :math:`x` is a vector of decision variables; :math:`c`,
:math:`b_{ub}`, :math:`b_{eq}`, :math:`l`, and :math:`u` are vectors; and
:math:`A_{ub}` and :math:`A_{eq}` are matrices.
Alternatively, that's:
minimize::
c @ x
such that::
A_ub @ x <= b_ub
A_eq @ x == b_eq
lb <= x <= ub
Note that by default ``lb = 0`` and ``ub = None`` unless specified with
``bounds``.
Parameters
----------
c : 1-D array
The coefficients of the linear objective function to be minimized.
A_ub : 2-D array, optional
The inequality constraint matrix. Each row of ``A_ub`` specifies the
coefficients of a linear inequality constraint on ``x``.
b_ub : 1-D array, optional
The inequality constraint vector. Each element represents an
upper bound on the corresponding value of ``A_ub @ x``.
A_eq : 2-D array, optional
The equality constraint matrix. Each row of ``A_eq`` specifies the
coefficients of a linear equality constraint on ``x``.
b_eq : 1-D array, optional
The equality constraint vector. Each element of ``A_eq @ x`` must equal
the corresponding element of ``b_eq``.
bounds : sequence, optional
A sequence of ``(min, max)`` pairs for each element in ``x``, defining
the minimum and maximum values of that decision variable. Use ``None``
to indicate that there is no bound. By default, bounds are
``(0, None)`` (all decision variables are non-negative).
If a single tuple ``(min, max)`` is provided, then ``min`` and
``max`` will serve as bounds for all decision variables.
method : str
This is the method-specific documentation for 'simplex'.
:ref:`'highs' <optimize.linprog-highs>`,
:ref:`'highs-ds' <optimize.linprog-highs-ds>`,
:ref:`'highs-ipm' <optimize.linprog-highs-ipm>`,
:ref:`'interior-point' <optimize.linprog-interior-point>` (default),
and :ref:`'revised simplex' <optimize.linprog-revised_simplex>`
are also available.
callback : callable, optional
Callback function to be executed once per iteration.
Options
-------
maxiter : int (default: 5000)
The maximum number of iterations to perform in either phase.
disp : bool (default: False)
Set to ``True`` if indicators of optimization status are to be printed
to the console each iteration.
presolve : bool (default: True)
Presolve attempts to identify trivial infeasibilities,
identify trivial unboundedness, and simplify the problem before
sending it to the main solver. It is generally recommended
to keep the default setting ``True``; set to ``False`` if
presolve is to be disabled.
tol : float (default: 1e-12)
The tolerance which determines when a solution is "close enough" to
zero in Phase 1 to be considered a basic feasible solution or close
enough to positive to serve as an optimal solution.
autoscale : bool (default: False)
Set to ``True`` to automatically perform equilibration.
Consider using this option if the numerical values in the
constraints are separated by several orders of magnitude.
rr : bool (default: True)
Set to ``False`` to disable automatic redundancy removal.
bland : bool
If True, use Bland's anti-cycling rule [3]_ to choose pivots to
prevent cycling. If False, choose pivots which should lead to a
converged solution more quickly. The latter method is subject to
cycling (non-convergence) in rare instances.
unknown_options : dict
Optional arguments not used by this particular solver. If
`unknown_options` is non-empty a warning is issued listing all
unused options.
Returns
-------
res : OptimizeResult
A :class:`scipy.optimize.OptimizeResult` consisting of the fields:
x : 1-D array
The values of the decision variables that minimizes the
objective function while satisfying the constraints.
fun : float
The optimal value of the objective function ``c @ x``.
slack : 1-D array
The (nominally positive) values of the slack variables,
``b_ub - A_ub @ x``.
con : 1-D array
The (nominally zero) residuals of the equality constraints,
``b_eq - A_eq @ x``.
success : bool
``True`` when the algorithm succeeds in finding an optimal
solution.
status : int
An integer representing the exit status of the algorithm.
``0`` : Optimization terminated successfully.
``1`` : Iteration limit reached.
``2`` : Problem appears to be infeasible.
``3`` : Problem appears to be unbounded.
``4`` : Numerical difficulties encountered.
message : str
A string descriptor of the exit status of the algorithm.
nit : int
The total number of iterations performed in all phases.
References
----------
.. [1] Dantzig, George B., Linear programming and extensions. Rand
Corporation Research Study Princeton Univ. Press, Princeton, NJ,
1963
.. [2] Hillier, S.H. and Lieberman, G.J. (1995), "Introduction to
Mathematical Programming", McGraw-Hill, Chapter 4.
.. [3] Bland, Robert G. New finite pivoting rules for the simplex method.
Mathematics of Operations Research (2), 1977: pp. 103-107.
"""
pass
|
"""Devstack environment variables unique to the instructor plugin."""
def plugin_settings(settings):
"""Settings for the instructor plugin."""
# Set this to the dashboard URL in order to display the link from the
# dashboard to the Analytics Dashboard.
settings.ANALYTICS_DASHBOARD_URL = None
|
__version__ = '0.54'
class LandDegradationError(Exception):
"""Base class for exceptions in this module."""
def __init__(self, msg=None):
if msg is None:
msg = "An error occurred in the landdegradation module"
super(LandDegradationError, self).__init__(msg)
class GEEError(LandDegradationError):
"""Error related to GEE"""
def __init__(self, msg="Error with GEE JSON IO"):
super(LandDegradationError, self).__init__(msg)
class GEEIOError(GEEError):
"""Error related to GEE"""
def __init__(self, msg="Error with GEE JSON IO"):
super(GEEError, self).__init__(msg)
class GEEImageError(GEEError):
"""Error related to GEE"""
def __init__(self, msg="Error with GEE image handling"):
super(GEEError, self).__init__(msg)
class GEETaskFailure(GEEError):
"""Error running task on GEE"""
def __init__(self, task):
# super(GEEError, self).__init__("Task {} failed".format(task.status().get('id')))
super(GEEError, self).__init__("Task {} failed".format(task))
print(task)
self.task = task
|
del_items(0x80145350)
SetType(0x80145350, "void _cd_seek(int sec)")
del_items(0x801453BC)
SetType(0x801453BC, "void init_cdstream(int chunksize, unsigned char *buf, int bufsize)")
del_items(0x801453E4)
SetType(0x801453E4, "void flush_cdstream()")
del_items(0x80145438)
SetType(0x80145438, "void reset_cdstream()")
del_items(0x80145468)
SetType(0x80145468, "void kill_stream_handlers()")
del_items(0x80145498)
SetType(0x80145498, "void stream_cdready_handler(unsigned char status, unsigned char *result, int idx, int i, int sec, struct CdlLOC subcode[3])")
del_items(0x80145684)
SetType(0x80145684, "void install_stream_handlers()")
del_items(0x801456C0)
SetType(0x801456C0, "void cdstream_service()")
del_items(0x801457B0)
SetType(0x801457B0, "int cdstream_get_chunk(unsigned char **data, struct strheader **h)")
del_items(0x801458C8)
SetType(0x801458C8, "int cdstream_is_last_chunk()")
del_items(0x801458E0)
SetType(0x801458E0, "void cdstream_discard_chunk()")
del_items(0x80145A00)
SetType(0x80145A00, "void close_cdstream()")
del_items(0x80145A40)
SetType(0x80145A40, "void wait_cdstream()")
del_items(0x80145AF8)
SetType(0x80145AF8, "int open_cdstream(char *fname, int secoffs, int seclen)")
del_items(0x80145BFC)
SetType(0x80145BFC, "int set_mdec_img_buffer(unsigned char *p)")
del_items(0x80145C30)
SetType(0x80145C30, "void start_mdec_decode(unsigned char *data, int x, int y, int w, int h)")
del_items(0x80145DB4)
SetType(0x80145DB4, "void DCT_out_handler()")
del_items(0x80145E50)
SetType(0x80145E50, "void init_mdec(unsigned char *vlc_buffer, unsigned char *vlc_table)")
del_items(0x80145EC0)
SetType(0x80145EC0, "void init_mdec_buffer(char *buf, int size)")
del_items(0x80145EDC)
SetType(0x80145EDC, "int split_poly_area(struct POLY_FT4 *p, struct POLY_FT4 *bp, int offs, struct RECT *r, int sx, int sy, int correct)")
del_items(0x801462CC)
SetType(0x801462CC, "void rebuild_mdec_polys(int x, int y)")
del_items(0x801464A0)
SetType(0x801464A0, "void clear_mdec_frame()")
del_items(0x801464AC)
SetType(0x801464AC, "void draw_mdec_polys()")
del_items(0x801467F8)
SetType(0x801467F8, "void invalidate_mdec_frame()")
del_items(0x8014680C)
SetType(0x8014680C, "int is_frame_decoded()")
del_items(0x80146818)
SetType(0x80146818, "void init_mdec_polys(int x, int y, int w, int h, int bx1, int by1, int bx2, int by2, int correct)")
del_items(0x80146BA8)
SetType(0x80146BA8, "void set_mdec_poly_bright(int br)")
del_items(0x80146C10)
SetType(0x80146C10, "int init_mdec_stream(unsigned char *buftop, int sectors_per_frame, int mdec_frames_per_buffer)")
del_items(0x80146C60)
SetType(0x80146C60, "void init_mdec_audio(int rate)")
del_items(0x80146D68)
SetType(0x80146D68, "void kill_mdec_audio()")
del_items(0x80146D98)
SetType(0x80146D98, "void stop_mdec_audio()")
del_items(0x80146DBC)
SetType(0x80146DBC, "void play_mdec_audio(unsigned char *data, struct asec *h)")
del_items(0x80147054)
SetType(0x80147054, "void set_mdec_audio_volume(short vol, struct SpuVoiceAttr voice_attr)")
del_items(0x80147120)
SetType(0x80147120, "void resync_audio()")
del_items(0x80147150)
SetType(0x80147150, "void stop_mdec_stream()")
del_items(0x801471A4)
SetType(0x801471A4, "void dequeue_stream()")
del_items(0x80147290)
SetType(0x80147290, "void dequeue_animation()")
del_items(0x80147440)
SetType(0x80147440, "void decode_mdec_stream(int frames_elapsed)")
del_items(0x80147620)
SetType(0x80147620, "void play_mdec_stream(char *filename, int speed, int start, int end)")
del_items(0x801476D4)
SetType(0x801476D4, "void clear_mdec_queue()")
del_items(0x80147700)
SetType(0x80147700, "void StrClearVRAM()")
del_items(0x801477C0)
SetType(0x801477C0, "short PlayFMVOverLay(char *filename, int w, int h)")
del_items(0x80147C84)
SetType(0x80147C84, "unsigned short GetDown__C4CPad(struct CPad *this)")
|
# Sets an error rate of %0.025 (1 in 4,000) with a capacity of 5MM items.
# See https://hur.st/bloomfilter/?n=5000000&p=0.00025&m=& for more information
# 5MM was chosen for being a whole number roughly 2x the size of our most dense sparse plugin output in late July 2020.
DEFAULT_ERROR_RATE = 0.00025
DEFAULT_CAPACITY = 5000000
KEY_PREFIX = "fwan_dataset_bf:"
# The bloom filters are only useful for per-file-hash Firmware Analysis plugins with sparse output, as those are the
# scenarios where we are likely to avoid unnecessary object storage fetches.
exclusions = [
"augeas", # firmware-file-level
"file_hashes", # too dense
"file_tree", # firmware-level
"file_type", # too dense
"unpack_report", # irrelevant
"unpack_failed", # irrelevant
"printable_strings", # too dense
]
exclusion_prefixes = [
"firmware_cpes", # firmware-level
"sbom", # sbom/unified is firmware-level, sbom/apt_file is irrelevant
"similarity_hash", # irrelevant
]
|
fp = open("./packet.csv", "r")
vals = fp.readlines()
count = 1
pre_val = 0
current = 0
sampling_rate = 31
val_bins = []
for i in range(len(vals)):
pre_val = current
current = int(vals[i])
if current == pre_val:
count = count + 1
else:
count = 1
if count == sampling_rate:
val_bins.append(pre_val)
count = 1
pre_val = 0
current = 0
next_bins = []
for i in range(len(val_bins) // 2):
b0 = val_bins[i * 2]
b1 = val_bins[i * 2 + 1]
if b0 == 1 and b1 == 0:
next_bins.append(1)
elif b0 == 0 and b1 == 1:
next_bins.append(0)
val_bins = next_bins[3:]
c = 0
for i in range(len(val_bins)):
val = int(val_bins[i])
c = (c << 1) | val
if i % 8 == 7:
print(chr(c), end="")
c = 0
print("")
|
'''
Specifies the username and password required to log into the iNaturalist website.
These variables are imported into the 'inaturalist_scraper.py' script
'''
username = 'your_iNaturalist_username_here'
password = 'your_iNaturalist_password_here'
|
FRONT_LEFT_WHEEL_TOPIC = "/capo_front_left_wheel_controller/command"
FRONT_RIGHT_WHEEL_TOPIC = "/capo_front_right_wheel_controller/command"
# BACK_RIGHT_WHEEL_TOPIC = "/capo_rear_left_wheel_controller/command",
# BACK_LEFT_WHEEL_TOPIC = "/capo_rear_right_wheel_controller/command"
HEAD_JOINT_TOPIC = "/capo_head_rotation_controller/command"
CAPO_JOINT_STATES = '/joint_states'
TOPNAV_FEEDBACK_TOPIC = '/topnav/feedback'
TOPNAV_GUIDELINES_TOPIC = 'topnav/guidelines'
GAZEBO_MODEL_STATES_TOPIC = "/gazebo/model_states"
|
class BasicEnvironment:
"""Object to pass containing data used for solve. Individuals are mapped
to this data upon evaluation. Environments also hold additional evaluation
data."""
def __init__(self, df, _dict=None):
self.df = df
self._dict = _dict
|
# -*- coding:utf-8 -*-
pizzas = ['fruit', 'buff', 'milk', 'zhishi', 'little']
# for pizza in pizzas:
# print(pizza)
# print(pizza.title() + ", I like eat !")
# print("I like eat pizza!")
pizzas_bak = pizzas[:]
pizzas.append('chicken')
pizzas_bak.append('dog')
print(pizzas_bak)
print(pizzas)
|
class Solution:
def reformatDate(self, date: str) -> str:
pattern = re.compile(r'[0-9]+')
dateList=date.split(' ')
day=pattern.findall(dateList[0])[0]
monthList=["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
month=monthList.index(dateList[1])+1
year=dateList[2]
return year+'-'+str(month).zfill(2)+'-'+str(day).zfill(2)
|
inp = open('input_d24.txt').read().strip().split('\n')
graph = dict()
n = 0
yn = len(inp)
xn = len(inp[0])
poss = '01234567'
def find_n(ton):
for y in range(len(inp)):
for x in range(len(inp[y])):
if inp[y][x] == str(ton):
return (x,y)
def exists(n, found):
for ele in list(graph[n]):
if ele[0] == int(found):
return True
return False
def find_adj(x,y):
res = set()
for (a,b) in [(x-1,y), (x+1,y), (x,y-1), (x,y+1)]:
if a >= 0 and a < xn and b >= 0 and b < yn:
if inp[b][a] != '#':
res.add((a,b))
return res
for n in range(8):
x,y = find_n(n)
if n not in graph:
graph[n] = set()
visited = set()
queue = [((x,y), set([(x,y)]))]
while queue:
(vertex, path) = queue.pop(0)
for nex in find_adj(*vertex) - path:
if nex in visited:
continue
visited.add(nex)
found = inp[nex[1]][nex[0]]
if found in poss:
if not exists(n,found):
graph[n].add((int(found), len(path)))
if int(found) not in graph:
graph[int(found)] = set()
graph[int(found)].add((n, len(path)))
else:
p = path.copy()
p.add(nex)
queue.append((nex, p))
print(graph)
print('bruteforcing TSP (fun times)')
smallest = 10000
queue = [(0, set([0]), 0)]
while queue:
(current, visited, count) = queue.pop(0)
if count >= smallest:
continue
for pos in graph[current]:
nv = visited.copy()
nv.add(pos[0])
nc = count + pos[1]
if all([int(p) in nv for p in poss]) and pos[0] == 0 and nc < smallest:
smallest = nc
print(smallest)
elif pos[0] not in visited and nc < smallest:
queue.append((pos[0], nv, nc))
print(smallest)
|
array = []
for i in range (16):
# array.append([i,0])
array.append([i,5])
print(array)
|
#
# PySNMP MIB module Juniper-PPPOE-PROFILE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Juniper-PPPOE-PROFILE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:03:50 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsUnion, SingleValueConstraint, ValueSizeConstraint, ValueRangeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "SingleValueConstraint", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsIntersection")
juniMibs, = mibBuilder.importSymbols("Juniper-MIBs", "juniMibs")
JuniEnable, JuniSetMap = mibBuilder.importSymbols("Juniper-TC", "JuniEnable", "JuniSetMap")
ObjectGroup, ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ObjectGroup", "ModuleCompliance", "NotificationGroup")
IpAddress, ModuleIdentity, MibIdentifier, Integer32, Gauge32, iso, Counter32, TimeTicks, Unsigned32, Counter64, NotificationType, ObjectIdentity, Bits, MibScalar, MibTable, MibTableRow, MibTableColumn = mibBuilder.importSymbols("SNMPv2-SMI", "IpAddress", "ModuleIdentity", "MibIdentifier", "Integer32", "Gauge32", "iso", "Counter32", "TimeTicks", "Unsigned32", "Counter64", "NotificationType", "ObjectIdentity", "Bits", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
juniPppoeProfileMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 4874, 2, 2, 46))
juniPppoeProfileMIB.setRevisions(('2008-06-18 10:29', '2005-07-13 11:40', '2004-06-10 19:25', '2003-03-11 21:58', '2002-09-16 21:44', '2002-08-15 20:34', '2002-08-15 19:07', '2001-03-21 18:32',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: juniPppoeProfileMIB.setRevisionsDescriptions(('Added juniPppoeProfileMaxSessionOverride object.', 'Added MTU control object.', 'Added Remote Circuit Id Capture object.', 'Added Service Name Table object.', 'Replaced Unisphere names with Juniper names.', 'Added PADI flag and packet trace support.', 'Added duplicate MAC address indicator and AC-NAME tag objects.', 'Initial version of this MIB module.',))
if mibBuilder.loadTexts: juniPppoeProfileMIB.setLastUpdated('200806181029Z')
if mibBuilder.loadTexts: juniPppoeProfileMIB.setOrganization('Juniper Networks, Inc.')
if mibBuilder.loadTexts: juniPppoeProfileMIB.setContactInfo(' Juniper Networks, Inc. Postal: 10 Technology Park Drive Westford, MA 01886-3146 USA Tel: +1 978 589 5800 Email: mib@Juniper.net')
if mibBuilder.loadTexts: juniPppoeProfileMIB.setDescription('The point-to-point protocol over Ethernet (PPPoE) profile MIB for the Juniper enterprise.')
juniPppoeProfileObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 2, 2, 46, 1))
juniPppoeProfile = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 2, 2, 46, 1, 1))
juniPppoeProfileTable = MibTable((1, 3, 6, 1, 4, 1, 4874, 2, 2, 46, 1, 1, 1), )
if mibBuilder.loadTexts: juniPppoeProfileTable.setStatus('current')
if mibBuilder.loadTexts: juniPppoeProfileTable.setDescription('This table contains profiles for configuring PPPoE interfaces/sessions. Entries in this table are created/deleted as a side-effect of corresponding operations to the juniProfileNameTable in the Juniper-PROFILE-MIB.')
juniPppoeProfileEntry = MibTableRow((1, 3, 6, 1, 4, 1, 4874, 2, 2, 46, 1, 1, 1, 1), ).setIndexNames((0, "Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileId"))
if mibBuilder.loadTexts: juniPppoeProfileEntry.setStatus('current')
if mibBuilder.loadTexts: juniPppoeProfileEntry.setDescription('A profile describing configuration of a PPPoE interface and its subinterfaces (sessions).')
juniPppoeProfileId = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 46, 1, 1, 1, 1, 1), Unsigned32())
if mibBuilder.loadTexts: juniPppoeProfileId.setStatus('current')
if mibBuilder.loadTexts: juniPppoeProfileId.setDescription('The integer identifier associated with this profile. A value for this identifier is determined by locating or creating a profile name in the juniProfileNameTable.')
juniPppoeProfileSetMap = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 46, 1, 1, 1, 1, 2), JuniSetMap()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniPppoeProfileSetMap.setStatus('current')
if mibBuilder.loadTexts: juniPppoeProfileSetMap.setDescription("A bitmap representing which objects in this entry have been explicitly configured. See the definition of the JuniSetMap TEXTUAL-CONVENTION for details of use. The INDEX object(s) and this object are excluded from representation (i.e. their bits are never set). When a SET request does not explicitly configure JuniSetMap, bits in JuniSetMap are set as a side-effect of configuring other profile attributes in the same entry. If, however, a SET request explicitly configures JuniSetMap, the explicitly configured value overrides 1) any previous bit settings, and 2) any simultaneous 'side-effect' settings that would otherwise occur. Once set, bits can only be cleared by explicitly configuring JuniSetMap.")
juniPppoeProfileMaxNumSessions = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 46, 1, 1, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniPppoeProfileMaxNumSessions.setStatus('current')
if mibBuilder.loadTexts: juniPppoeProfileMaxNumSessions.setDescription('The maximum number of PPPoE sessions (subinterfaces) that can be configured on the main PPPoE interface created using this profile. A value of zero indicates no bound is configured.')
juniPppoeProfileSubMotm = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 46, 1, 1, 1, 1, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 127))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniPppoeProfileSubMotm.setStatus('current')
if mibBuilder.loadTexts: juniPppoeProfileSubMotm.setDescription('A message to send via a PADM on the sub-interface when this profile is applied to the IP interface above this PPPoE sub- interface. A client may choose to display this message to the user.')
juniPppoeProfileSubUrl = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 46, 1, 1, 1, 1, 5), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 127))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniPppoeProfileSubUrl.setStatus('current')
if mibBuilder.loadTexts: juniPppoeProfileSubUrl.setDescription('A URL to be sent via a PADM on the sub-interface when this profile is applied to the IP interface above this PPPoE sub-interface. The string entered here can have several substitutions applied: %D is replaced with the profile name %d is replaced with the domain name %u is replaced with the user name %U is replaced with the user/domain name together %% is replaced with the % character The resulting string must not be greater than 127 octets long. The client may use this URL as the initial web-page for the user.')
juniPppoeProfileDupProtect = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 46, 1, 1, 1, 1, 6), JuniEnable().clone('disable')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniPppoeProfileDupProtect.setStatus('current')
if mibBuilder.loadTexts: juniPppoeProfileDupProtect.setDescription('Flag to control whether duplicate MAC addresses are allowed')
juniPppoeProfileAcName = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 46, 1, 1, 1, 1, 7), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniPppoeProfileAcName.setStatus('current')
if mibBuilder.loadTexts: juniPppoeProfileAcName.setDescription('The name to use for the AC-NAME tag that is sent in any PADO that is sent on this interface.')
juniPppoeProfilePadiFlag = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 46, 1, 1, 1, 1, 8), JuniEnable().clone('disable')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniPppoeProfilePadiFlag.setStatus('current')
if mibBuilder.loadTexts: juniPppoeProfilePadiFlag.setDescription('The PPPoE major interface parameter PADI flag controls whether to always repsond to a PADI with a PADO regardless of the ability to create the session and allow the session establish phase to resolve it.')
juniPppoeProfilePacketTrace = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 46, 1, 1, 1, 1, 9), JuniEnable().clone('disable')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniPppoeProfilePacketTrace.setStatus('current')
if mibBuilder.loadTexts: juniPppoeProfilePacketTrace.setDescription('The PPPoE major interface parameter packet tracing flag controls whether packet tracing is enable or not.')
juniPppoeProfileServiceNameTableName = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 46, 1, 1, 1, 1, 10), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 31))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniPppoeProfileServiceNameTableName.setStatus('current')
if mibBuilder.loadTexts: juniPppoeProfileServiceNameTableName.setDescription('The PPPoE Service name table controls behavior of PADO control packets.')
juniPppoeProfilePadrRemoteCircuitIdCapture = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 46, 1, 1, 1, 1, 11), JuniEnable().clone('disable')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniPppoeProfilePadrRemoteCircuitIdCapture.setStatus('current')
if mibBuilder.loadTexts: juniPppoeProfilePadrRemoteCircuitIdCapture.setDescription('The PPPoE major interface parameter PADR remote circuit id capture flag controls whether the remote circuit id string possibly contained in the PADR packet will be saved and used by AAA to replace the NAS-PORT-ID field.')
juniPppoeProfileMtu = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 46, 1, 1, 1, 1, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(1, 1), ValueRangeConstraint(2, 2), ValueRangeConstraint(66, 65535), )).clone(1494)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniPppoeProfileMtu.setStatus('current')
if mibBuilder.loadTexts: juniPppoeProfileMtu.setDescription('The initial Maximum Transmit Unit (MTU) that the PPPoE major interface entity will advertise to the remote entity. If the value of this variable is 1 then the local PPPoE entity will use an MTU value determined by its underlying media interface. If the value of this variable is 2 then the local PPPoE entity will use a value determined by the PPPoE Max-Mtu-Tag transmitted from the client in the PADR packet. If no Max-Mtu-Tag is received, the value defaults to a maximum of 1494. The operational MTU is limited by the MTU of the underlying media interface minus the PPPoE frame overhead.')
juniPppoeProfileMaxSessionOverride = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 46, 1, 1, 1, 1, 13), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("override", 1), ("ignore", 2))).clone('ignore')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniPppoeProfileMaxSessionOverride.setStatus('current')
if mibBuilder.loadTexts: juniPppoeProfileMaxSessionOverride.setDescription('Configure the action to be taken by PPPoE when RADIUS server returns the PPPoE max-session value: override Override the current PPPoE max-session value with the value returned by RADIUS server Ignore Ignore the max-session value returned by RADIUS server')
juniPppoeProfileConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 2, 2, 46, 4))
juniPppoeProfileCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 2, 2, 46, 4, 1))
juniPppoeProfileGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 2, 2, 46, 4, 2))
juniPppoeProfileCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 4874, 2, 2, 46, 4, 1, 1)).setObjects(("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
juniPppoeProfileCompliance = juniPppoeProfileCompliance.setStatus('obsolete')
if mibBuilder.loadTexts: juniPppoeProfileCompliance.setDescription('Obsolete compliance statement for entities which implement the Juniper PPPoE Profile MIB. This statement became obsolete when the duplicate MAC address indicator and AC-NAME tag were added.')
juniPppoeCompliance2 = ModuleCompliance((1, 3, 6, 1, 4, 1, 4874, 2, 2, 46, 4, 1, 2)).setObjects(("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileGroup2"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
juniPppoeCompliance2 = juniPppoeCompliance2.setStatus('obsolete')
if mibBuilder.loadTexts: juniPppoeCompliance2.setDescription('Obsolete compliance statement for entities which implement the Juniper PPPoE profile MIB. This statement became obsolete when PADI flag, AC-name and packet trace objects were added.')
juniPppoeCompliance3 = ModuleCompliance((1, 3, 6, 1, 4, 1, 4874, 2, 2, 46, 4, 1, 3)).setObjects(("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileGroup3"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
juniPppoeCompliance3 = juniPppoeCompliance3.setStatus('obsolete')
if mibBuilder.loadTexts: juniPppoeCompliance3.setDescription('Obsolete compliance statement for entities which implement the Juniper PPPoE profile MIB. This statement became obsolete when the service name table was added.')
juniPppoeCompliance4 = ModuleCompliance((1, 3, 6, 1, 4, 1, 4874, 2, 2, 46, 4, 1, 4)).setObjects(("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileGroup4"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
juniPppoeCompliance4 = juniPppoeCompliance4.setStatus('obsolete')
if mibBuilder.loadTexts: juniPppoeCompliance4.setDescription('Obsolete compliance statement for entities which implement the Juniper PPPoE profile MIB. This statement became obsolete when the remote circuit id capture was added.')
juniPppoeCompliance5 = ModuleCompliance((1, 3, 6, 1, 4, 1, 4874, 2, 2, 46, 4, 1, 5)).setObjects(("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileGroup5"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
juniPppoeCompliance5 = juniPppoeCompliance5.setStatus('obsolete')
if mibBuilder.loadTexts: juniPppoeCompliance5.setDescription('Obsolete compliance statement for entities which implement the Juniper PPPoE MIB. This statement became obsolete when support was added for MTU configuration.')
juniPppoeCompliance6 = ModuleCompliance((1, 3, 6, 1, 4, 1, 4874, 2, 2, 46, 4, 1, 6)).setObjects(("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileGroup6"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
juniPppoeCompliance6 = juniPppoeCompliance6.setStatus('obsolete')
if mibBuilder.loadTexts: juniPppoeCompliance6.setDescription('Obsolete compliance statement for entities which implement the Juniper PPPoE MIB. This statement became obsolete when support was added for juniPppoeProfileMaxSessionOverride.')
juniPppoeCompliance7 = ModuleCompliance((1, 3, 6, 1, 4, 1, 4874, 2, 2, 46, 4, 1, 7)).setObjects(("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileGroup7"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
juniPppoeCompliance7 = juniPppoeCompliance7.setStatus('current')
if mibBuilder.loadTexts: juniPppoeCompliance7.setDescription('The compliance statement for entities which implement the Juniper PPPoE Profile MIB.')
juniPppoeProfileGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 4874, 2, 2, 46, 4, 2, 1)).setObjects(("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileSetMap"), ("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileMaxNumSessions"), ("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileSubMotm"), ("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileSubUrl"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
juniPppoeProfileGroup = juniPppoeProfileGroup.setStatus('obsolete')
if mibBuilder.loadTexts: juniPppoeProfileGroup.setDescription('Obsolete collection of objects providing management of profile functionality for PPPoE interfaces in a Juniper product. This group became obsolete when the duplicate MAC address indicator and AC-NAME tag objects were added.')
juniPppoeProfileGroup2 = ObjectGroup((1, 3, 6, 1, 4, 1, 4874, 2, 2, 46, 4, 2, 2)).setObjects(("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileSetMap"), ("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileMaxNumSessions"), ("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileSubMotm"), ("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileSubUrl"), ("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileDupProtect"), ("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileAcName"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
juniPppoeProfileGroup2 = juniPppoeProfileGroup2.setStatus('obsolete')
if mibBuilder.loadTexts: juniPppoeProfileGroup2.setDescription('Obsolete collection of objects providing management of profile functionality for PPPOE interfaces in a Juniper product. This group became obsolete when PADI flag, AC-name and packet trace objects were added.')
juniPppoeProfileGroup3 = ObjectGroup((1, 3, 6, 1, 4, 1, 4874, 2, 2, 46, 4, 2, 3)).setObjects(("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileSetMap"), ("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileMaxNumSessions"), ("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileSubMotm"), ("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileSubUrl"), ("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileDupProtect"), ("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileAcName"), ("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfilePadiFlag"), ("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfilePacketTrace"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
juniPppoeProfileGroup3 = juniPppoeProfileGroup3.setStatus('obsolete')
if mibBuilder.loadTexts: juniPppoeProfileGroup3.setDescription('A collection of objects providing management of profile functionality for PPPOE interfaces in a Juniper product.')
juniPppoeProfileGroup4 = ObjectGroup((1, 3, 6, 1, 4, 1, 4874, 2, 2, 46, 4, 2, 4)).setObjects(("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileSetMap"), ("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileMaxNumSessions"), ("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileSubMotm"), ("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileSubUrl"), ("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileDupProtect"), ("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileAcName"), ("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfilePadiFlag"), ("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfilePacketTrace"), ("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileServiceNameTableName"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
juniPppoeProfileGroup4 = juniPppoeProfileGroup4.setStatus('obsolete')
if mibBuilder.loadTexts: juniPppoeProfileGroup4.setDescription('A collection of objects providing management of profile functionality for PPPOE interfaces in a Juniper product.')
juniPppoeProfileGroup5 = ObjectGroup((1, 3, 6, 1, 4, 1, 4874, 2, 2, 46, 4, 2, 5)).setObjects(("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileSetMap"), ("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileMaxNumSessions"), ("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileSubMotm"), ("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileSubUrl"), ("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileDupProtect"), ("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileAcName"), ("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfilePadiFlag"), ("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfilePacketTrace"), ("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileServiceNameTableName"), ("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfilePadrRemoteCircuitIdCapture"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
juniPppoeProfileGroup5 = juniPppoeProfileGroup5.setStatus('obsolete')
if mibBuilder.loadTexts: juniPppoeProfileGroup5.setDescription('A collection of objects providing management of profile functionality for PPPOE interfaces in a Juniper product.')
juniPppoeProfileGroup6 = ObjectGroup((1, 3, 6, 1, 4, 1, 4874, 2, 2, 46, 4, 2, 6)).setObjects(("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileSetMap"), ("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileMaxNumSessions"), ("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileSubMotm"), ("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileSubUrl"), ("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileDupProtect"), ("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileAcName"), ("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfilePadiFlag"), ("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfilePacketTrace"), ("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileServiceNameTableName"), ("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfilePadrRemoteCircuitIdCapture"), ("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileMtu"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
juniPppoeProfileGroup6 = juniPppoeProfileGroup6.setStatus('obsolete')
if mibBuilder.loadTexts: juniPppoeProfileGroup6.setDescription('A collection of objects providing management of profile functionality for PPPOE interfaces in a Juniper product.')
juniPppoeProfileGroup7 = ObjectGroup((1, 3, 6, 1, 4, 1, 4874, 2, 2, 46, 4, 2, 7)).setObjects(("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileSetMap"), ("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileMaxNumSessions"), ("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileSubMotm"), ("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileSubUrl"), ("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileDupProtect"), ("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileAcName"), ("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfilePadiFlag"), ("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfilePacketTrace"), ("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileServiceNameTableName"), ("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfilePadrRemoteCircuitIdCapture"), ("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileMtu"), ("Juniper-PPPOE-PROFILE-MIB", "juniPppoeProfileMaxSessionOverride"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
juniPppoeProfileGroup7 = juniPppoeProfileGroup7.setStatus('current')
if mibBuilder.loadTexts: juniPppoeProfileGroup7.setDescription('A collection of objects providing management of profile functionality for PPPOE interfaces in a Juniper product.')
mibBuilder.exportSymbols("Juniper-PPPOE-PROFILE-MIB", juniPppoeCompliance5=juniPppoeCompliance5, juniPppoeProfileGroup2=juniPppoeProfileGroup2, juniPppoeProfileMtu=juniPppoeProfileMtu, juniPppoeProfile=juniPppoeProfile, juniPppoeProfileSetMap=juniPppoeProfileSetMap, juniPppoeProfilePadiFlag=juniPppoeProfilePadiFlag, juniPppoeProfileTable=juniPppoeProfileTable, juniPppoeProfileDupProtect=juniPppoeProfileDupProtect, juniPppoeCompliance4=juniPppoeCompliance4, juniPppoeProfileGroup=juniPppoeProfileGroup, juniPppoeProfileMIB=juniPppoeProfileMIB, juniPppoeProfileGroup4=juniPppoeProfileGroup4, juniPppoeProfileCompliances=juniPppoeProfileCompliances, juniPppoeProfileAcName=juniPppoeProfileAcName, juniPppoeProfileGroup3=juniPppoeProfileGroup3, juniPppoeProfilePadrRemoteCircuitIdCapture=juniPppoeProfilePadrRemoteCircuitIdCapture, juniPppoeProfileSubMotm=juniPppoeProfileSubMotm, juniPppoeProfilePacketTrace=juniPppoeProfilePacketTrace, juniPppoeProfileEntry=juniPppoeProfileEntry, juniPppoeProfileGroup5=juniPppoeProfileGroup5, juniPppoeProfileMaxSessionOverride=juniPppoeProfileMaxSessionOverride, juniPppoeCompliance2=juniPppoeCompliance2, juniPppoeProfileGroups=juniPppoeProfileGroups, juniPppoeCompliance6=juniPppoeCompliance6, juniPppoeProfileCompliance=juniPppoeProfileCompliance, juniPppoeCompliance3=juniPppoeCompliance3, juniPppoeCompliance7=juniPppoeCompliance7, juniPppoeProfileGroup6=juniPppoeProfileGroup6, juniPppoeProfileMaxNumSessions=juniPppoeProfileMaxNumSessions, juniPppoeProfileId=juniPppoeProfileId, juniPppoeProfileConformance=juniPppoeProfileConformance, PYSNMP_MODULE_ID=juniPppoeProfileMIB, juniPppoeProfileObjects=juniPppoeProfileObjects, juniPppoeProfileServiceNameTableName=juniPppoeProfileServiceNameTableName, juniPppoeProfileSubUrl=juniPppoeProfileSubUrl, juniPppoeProfileGroup7=juniPppoeProfileGroup7)
|
class Solution(object):
def isValidSudoku(self, board):
return (self.is_row_valid(board) and
self.is_col_valid(board) and
self.is_square_valid(board))
def is_row_valid(self, board):
for row in board:
if not self.is_unit_valid(row):
return False
return True
def is_col_valid(self, board):
# zip turns column into tuple
for col in zip(*board):
if not self.is_unit_valid(col):
return False
return True
def is_square_valid(self, board):
for i in (0, 3, 6):
for j in (0, 3, 6):
square = [board[x][y] for x in range(i, i + 3) for y in range(j, j + 3)]
if not self.is_unit_valid(square):
return False
return True
def is_unit_valid(self, unit):
unit = [i for i in unit if i != '.']
return len(set(unit)) == len(unit)
test1 = [
["5","3",".",".","7",".",".",".","."],
["6",".",".","1","9","5",".",".","."],
[".","9","8",".",".",".",".","6","."],
["8",".",".",".","6",".",".",".","3"],
["4",".",".","8",".","3",".",".","1"],
["7",".",".",".","2",".",".",".","6"],
[".","6",".",".",".",".","2","8","."],
[".",".",".","4","1","9",".",".","5"],
[".",".",".",".","8",".",".","7","9"]
]
test2 = [
["8","3",".",".","7",".",".",".","."],
["6",".",".","1","9","5",".",".","."],
[".","9","8",".",".",".",".","6","."],
["8",".",".",".","6",".",".",".","3"],
["4",".",".","8",".","3",".",".","1"],
["7",".",".",".","2",".",".",".","6"],
[".","6",".",".",".",".","2","8","."],
[".",".",".","4","1","9",".",".","5"],
[".",".",".",".","8",".",".","7","9"]
]
solver = Solution()
print(solver.isValidSudoku(test1))
|
n = int(input())
D = [list(map(int,input().split())) for i in range(n)]
D.sort(key = lambda t: t[0])
S = 0
for i in D:
S += i[1]
S = (S+1)//2
S2 = 0
for i in D:
S2 += i[1]
if S2 >= S:
print(i[0])
break
|
#!/usr/local/bin/python3
# Copyright 2019 NineFx Inc.
# Justin Baum
# 20 May 2019
# Precis Code-Generator ReasonML
# https://github.com/NineFX/smeagol/blob/master/spec/code_gen/precis_cp.txt
fp = open('unicodedata.txt', 'r')
ranges = []
line = fp.readline()
prev = ""
start = 0
while line:
if len(line) < 2: break
linesplit = line.split(";")
if ", First" in line:
nextline = fp.readline().split(";")
start = int(linesplit[0], 16)
finish = int(nextline[0], 16)
code = linesplit[4]
ranges.append((start, finish + 1, code))
else:
code = linesplit[4]
if code != prev:
value = int(linesplit[0], 16)
ranges.append((start, value, prev if len(prev) != 0 else "Illegal"))
start = value
prev = code
line = fp.readline()
def splitHalf(listy):
if len(listy) <= 2:
print("switch (point) {")
for item in listy:
if item[0] == item[1] - 1:
print(" | point when (point == " + str(item[0]) + ") => " + str(item[2]))
else:
print(" | point when (point >= " + str(item[0]) + " && point < " + str(item[1]) +") => " + str(item[2]))
print("| _point => raise(PrecisUtils.PrecisError(BidiError))")
print("}")
return
splitValue = listy[len(listy)//2]
firstHalf = listy[:len(listy)//2]
secondHalf = listy[len(listy)//2:]
print("if (point < " +str(splitValue[0]) + ") {")
splitHalf(firstHalf)
print("} else {")
splitHalf(secondHalf)
print("}")
splitHalf(ranges)
|
# Public Attributes
class Employee:
def __init__(self, ID, salary):
# all properties are public
self.ID = ID
self.salary = salary
def displayID(self):
print("ID:", self.ID)
Steve = Employee(3789, 2500)
Steve.displayID()
print(Steve.salary)
|
m: int; n: int; j: int; i: int
m = int(input("Quantas linhas vai ter cada matriz? "))
n = int(input("Quantas colunas vai ter cada matriz? "))
A: [[int]] = [[0 for x in range(n)] for x in range(m)]
B: [[int]] = [[0 for x in range(n)] for x in range(m)]
C: [[int]] = [[0 for x in range(n)] for x in range(m)]
print("Digite os valores da matriz A:")
for i in range(0, m):
for j in range(0, n):
A[i][j] = int(input(f"Elemento [{i},{j}]: "))
print("Digite os valores da matriz B:")
for i in range(0, m):
for j in range(0, n):
B[i][j] = int(input(f"Elemento [{i},{j}]: "))
for i in range(0, m):
for j in range(0, n):
C[i][j] = A[i][j] + B[i][j]
print("MATRIZ SOMA:")
for i in range(0, m):
for j in range(0, n):
print(f"{C[i][j]} ", end="")
print()
|
'''
POO - O método super()
O método super() se refere á super classe.
'''
class Animal:
def __init__(self, nome, especie):
self.__nome = nome
self.__especie = especie
def faz_som(self, som):
print(f'O {self.__nome} fala {som}')
class Gato(Animal):
def __init__(self, nome, especie, raca):
#Animal.__init__(self, nome, especie)
super().__init__(nome, especie)
self.__raca = raca
felix = Gato('Felix', 'Felino', 'Angorá')
felix.faz_som('miau')
|
"""
Python列表解析式
https://codingpy.com/article/python-list-comprehensions-explained-visually/
"""
numbers = [1, 2, 3, 4, 5]
# 如果你熟悉函数式编程(functional programming),你可以把列表解析式看作为结合了filter函数与map函数功能的语法糖:
a_list = list(map(lambda n: n * 2, filter(lambda n: n % 2 == 1, numbers)))
b_list = [n * 2 for n in numbers if n % 2 == 1]
print(a_list, b_list, a_list == b_list, '\n')
"""
每个列表解析式都可以重写为for循环,但不是每个for循环都能重写为列表解析式。
掌握列表解析式使用时机的关键,在于不断练习识别那些看上去像列表解析式的问题
(practice identifying problems that smell like list comprehensions)。
如果你能将自己的代码改写成类似下面这个for循环的形式,那么你也就可以将其改写为列表解析式:
:::python
new_things = []
for ITEM in old_things:
if condition_based_on(ITEM):
new_things.append("something with " + ITEM)
你可以将上面的for循环改写成这样的列表解析式:
:::python
new_things = ["something with " + ITEM for ITEM in old_things if condition_based_on(ITEM)]
"""
c_list = []
for n in numbers:
c_list.append(n * 2)
d_list = [n * 2 for n in numbers]
print(c_list, d_list, c_list == d_list, '\n')
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
e_list = []
for row in matrix:
for n in row:
e_list.append(n)
# 如果要在列表解析式中处理嵌套循环,请记住for循环子句的顺序与我们原来for循环的顺序是一致的。
f_list = [n for row in matrix for n in row]
print(e_list, f_list, e_list == f_list, '\n')
words = ['tom', 'smith', 'jack']
a_set = set()
for w in words:
a_set.add(w[0])
b_set = {w[0] for w in words}
print(a_set, b_set, a_set == b_set, '\n')
source_map = {'tom': 88, 'jack': 72, 'jenny': 99}
a_map = {}
for k, v in source_map.items():
a_map[v] = k
b_map = {v: k for k, v in source_map.items()}
print(a_map, b_map, a_map == b_map, '\n')
"""
还要注意可读性
你有没有发现上面的列表解析式读起来很困难?
我经常发现,如果较长的列表解析式写成一行代码,那么阅读起来就非常困难。
不过,还好Python支持在括号和花括号之间断行。
"""
b_list_easy_to_read = [
n * 2
for n in numbers
if n % 2 == 1
]
print(b_list_easy_to_read, '\n')
f_list_easy_to_read = [
n
for row in matrix
for n in row
]
print(f_list_easy_to_read, '\n')
b_set_easy_to_read = {
w[0]
for w in words
}
print(b_set_easy_to_read, '\n')
b_map_easy_to_read = {
v: k
for k, v in source_map.items()
}
print(b_map_easy_to_read, '\n')
"""
[2, 6, 10] [2, 6, 10] True
[2, 4, 6, 8, 10] [2, 4, 6, 8, 10] True
[1, 2, 3, 4, 5, 6, 7, 8, 9] [1, 2, 3, 4, 5, 6, 7, 8, 9] True
{'j', 't', 's'} {'j', 't', 's'} True
{88: 'tom', 72: 'jack', 99: 'jenny'} {88: 'tom', 72: 'jack', 99: 'jenny'} True
[2, 6, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
{'t', 's', 'j'}
{88: 'tom', 72: 'jack', 99: 'jenny'}
"""
|
# class Tree:
# def __init__(self, val, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def solve(self, root):
stack = []
stack.append(root)
level = -1
min_sum = float('inf')
l = 0
while stack:
new = []
s = 0
for node in stack:
if node.left:
new.append(node.left)
if node.right:
new.append(node.right)
s += node.val
if s < min_sum:
level = l
min_sum = s
l += 1
stack = new
return level
|
"""
1. Clarification
2. Possible solutions
- Backtracking
3. Coding
4. Tests
"""
# T=O(sum(feasible solutions' len)), S=O(target)
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
if not candidates or target < 1: return []
ans, tmp = [], []
def backtrack(idx, Sum):
if idx >= len(candidates) or Sum >= target:
if Sum == target:
ans.append(tmp[:])
return
tmp.append(candidates[idx])
backtrack(idx, Sum + candidates[idx])
tmp.pop()
backtrack(idx + 1, Sum)
backtrack(0, 0)
return ans
|
def ack ( m, n ):
'''
ack: Evaluates Ackermann function with the given arguments
m: Positive integer value
n: Positive integer value
'''
# Guard against error from incorrect input
if n < 0 or (not isinstance(n, int)):
return "Error: n is either negative or not an integer"
if m < 0 or (not isinstance(m, int)):
return "Error: m is either negative or not an integer"
if m == 0:
return n + 1
elif m > 0 and n == 0:
return ack(m-1, 1)
else:
return ack(m-1, ack(m, n-1))
print(ack(3, 4))
|
# Copyright (c) 2021 Ben Maddison. All rights reserved.
#
"""aspa.as_path Module."""
AS_SEQUENCE = 0x0
AS_SET = 0x1
class AsPathSegment(object):
def __init__(self, segment_type, values):
if segment_type not in (AS_SEQUENCE, AS_SET):
raise ValueError(int)
self.type = segment_type
self.values = values
def __repr__(self):
values = map(str, reversed(self.values))
if self.type == AS_SEQUENCE:
return f"{'_'.join(values)}"
else:
return f"[ {' '.join(values)} ]"
class AsPath(object):
def __init__(self, *segments):
for s in segments:
if not isinstance(s, AsPathSegment):
raise TypeError(f"expected AsPathSegment, got {s}")
self.segments = segments
def __repr__(self):
return f"{'_'.join(map(repr, reversed(self.segments)))}"
def flatten(self):
return [AsPathElement(orig_segment_type=s.type, value=v)
for s in self.segments
for v in s.values]
class AsPathElement(object):
def __init__(self, orig_segment_type, value):
self.type = orig_segment_type
self.value = value
|
def love():
lover = 'sure'
lover
|
""" Parses a Markdown file in the Task.md format.
:params doc:
:returns: a dictionary containing the main fields of the task.
"""
def remove_obsidian_syntax(string):
"Removes Obsidian syntax from a string, namely []'s, [[]]'s and #'s"
pass
def parse_md(filename):
"Parses a markdown file in the Task.md format"
# initialize the task object
task = {"description": ''}
# start reading the input file
with open(filename, "r") as read_obj:
count = 0
while True:
line = read_obj.readline()
if not line:
break
if count == 2:
task['title'] = remove_obsidian_syntax(' '.join(line.split()[1:]))
if count == 3:
task['status'] = remove_obsidian_syntax(line.split()[1])
if count == 4:
task['priority'] = remove_obsidian_syntax(line.split()[1])
if count == 5:
task['due_date'] = line.split()[2]
if count == 6:
task['start_date'] = line.split()[2]
if count == 7:
task['deliverable'] = remove_obsidian_syntax(' '.join(line.split()[1:]))
if count >= 9:
task['description'] += remove_obsidian_syntax(line)
count += 1
print(task)
return task
if __name__ == "__main__":
parse_md("tests/tasks/sampleTask.md")
|
#
class OtsUtil(object):
STEP_THRESHOLD = 408
step = 0
@staticmethod
def log(msg):
if OtsUtil.step >= OtsUtil.STEP_THRESHOLD:
print(msg)
|
#Program to Remove Punctuations From a String
string="Wow! What a beautiful nature!"
new_string=string.replace("!","")
print(new_string)
|
def condensate_to_gas_equivalence(api, stb):
"Derivation from real gas equation"
Tsc = 519.57 # standard temp in Rankine
psc = 14.7 # standard pressure in psi
R = 10.732
rho_w = 350.16 # water density in lbm/STB
so = 141.5 / (api + 131.5) # so: specific gravity of oil (dimensionless)
Mo = 5854 / (api - 8.811) # molecular weight of oil
n = (rho_w * so) / Mo
V1stb = ((n * R * Tsc) / psc)
V = V1stb * stb
return(V)
def general_equivalence(gamma, M):
"Calculate equivalence of 1 STB of water/condensate to scf of gas"
# gamma: specific gravity of condensate/water. oil specific gravity use formula: so=141.5/(api+131.5). water specific gravity = 1
# M: molecular weight of condensate/water. oil: Mo = 5854 / (api - 8.811). water: Mw = 18
V1stb = 132849 * (gamma / M)
return(V1stb)
|
def fibonacci():
number = 0
previous_number = 1
while True:
if number == 0:
yield number
number += previous_number
if number == 1:
yield number
number += previous_number
if number == 2:
yield previous_number
if number > 1:
yield number
cutternt_number = previous_number
previous_number = number
number = cutternt_number + previous_number
generator = fibonacci()
for i in range(5):
print(next(generator))
|
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def __repr__(self):
return str(self.data)
def count_unival_trees(root):
if not root:
return 0
elif not root.left and not root.right:
return 1
elif not root.left and root.data == root.right.data:
return 1 + count_unival_trees(root.right)
elif not root.right and root.data == root.left.data:
return 1 + count_unival_trees(root.left)
child_counts = count_unival_trees(root.left) + count_unival_trees(root.right)
current_node_count = 0
if root.data == root.left.data and root.data == root.left.data:
current_node_count = 1
return current_node_count + child_counts
node_a = Node('0')
node_b = Node('1')
node_c = Node('0')
node_d = Node('1')
node_e = Node('0')
node_f = Node('1')
node_g = Node('1')
node_a.left = node_b
node_a.right = node_c
node_c.left = node_d
node_c.right = node_e
node_d.left = node_f
node_d.right = node_g
assert count_unival_trees(None) == 0
assert count_unival_trees(node_a) == 5
assert count_unival_trees(node_c) == 4
assert count_unival_trees(node_g) == 1
assert count_unival_trees(node_d) == 3
|
"""
A valid parentheses string is either empty (""), "(" + A + ")", or A + B, where A and B are valid parentheses
strings, and + represents string concatenation. For example, "", "()", "(())()", and "(()(()))" are all valid
parentheses strings.
A valid parentheses string S is primitive if it is nonempty, and there does not exist a way to split it into
S = A+B, with A and B nonempty valid parentheses strings.
Given a valid parentheses string S, consider its primitive decomposition: S = P_1 + P_2 + ... + P_k, where P_i
are primitive valid parentheses strings.
Return S after removing the outermost parentheses of every primitive string in the primitive decomposition of S.
Example 1:
Input: "(()())(())"
Output: "()()()"
Explanation:
The input string is "(()())(())", with primitive decomposition "(()())" + "(())".
After removing outer parentheses of each part, this is "()()" + "()" = "()()()".
Example 2:
Input: "(()())(())(()(()))"
Output: "()()()()(())"
Explanation:
The input string is "(()())(())(()(()))", with primitive decomposition "(()())" + "(())" + "(()(()))".
After removing outer parentheses of each part, this is "()()" + "()" + "()(())" = "()()()()(())".
Example 3:
Input: "()()"
Output: ""
Explanation:
The input string is "()()", with primitive decomposition "()" + "()".
After removing outer parentheses of each part, this is "" + "" = "".
Note:
1. S.length <= 10000
2. S[i] is "(" or ")"
3. S is a valid parentheses string
"""
class Solution:
def removeOuterParentheses(self, S: str) -> str:
res, stack = [], 0
for s in S:
if s == '(':
if stack > 0:
res.append(s)
stack += 1
else:
stack -= 1
if stack > 0:
res.append(s)
return ''.join(res)
|
# List Operations and Functions
# '+' Operator
print('-----------+ Operator------------')
a = [1,2,3]
b = [4,5,6]
c = a + b
print(c)
print('----------* Operator--------------')
# '*' Operator
a1 = a * 2
print(a1)
print('--------len function----------------')
print(len(a))
print('--------max function----------------')
print(max(a))
print('--------min function----------------')
print(min(a))
print('--------sum function----------------')
print(sum(a))
print("----------Average--------------")
mylist = []
while(True):
value = (input("Enter the number: "))
if value == 'done': break
value = float(value)
mylist.append(value)
average = sum(mylist)/len(mylist)
print("Average : ", average)
# Strings and Lists
print("----------Strings to Lists split function--------------")
mystring = 'Sagar Sanjeev Potnis'
print(mystring)
newlist = mystring.split()
print(newlist)
mystring1 = 'Sagar-Sanjeev-Potnis'
print(mystring1)
newlist1 = mystring1.split('-')
print(newlist1)
print("---------- List to String join function--------------")
joinstring = " ".join(newlist)
print(joinstring)
print("----------map function--------------")
print("Please Enter list :")
maplist = list(map(int, input().split()))
print(maplist)
print("----------Pitfalls and how to avoid them--------------")
pitylist = [5,4,3,2,1]
pitylist = sorted(pitylist)
print(pitylist)
# Sorted function does not modify original list unline sort fucntion!!! so it is better
|
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "9de928d7",
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"import csv\n",
"import pandas as pd"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "8f1478f8",
"metadata": {},
"outputs": [],
"source": [
"#Set Path\n",
"pollCSV = os.path.join('Resources', 'election_data.CSV')\n",
"pollCSV = r'C:\\Users\\rzh00\\Documents\\gt-virt-atl-data-pt-09-2021-u-c-master\\02-Homework\\03-Python\\Instructions\\PyPoll\\Resources\\election_data.csv'"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "0f207e3c",
"metadata": {},
"outputs": [],
"source": [
"#Varibales\n",
"candi = []\n",
"vote_count = []\n",
"vote_percent = []\n",
"\n",
"num_vote = 0"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "08423af7",
"metadata": {},
"outputs": [],
"source": [
"#Open CSV\n",
"with open(pollCSV) as csvfile:\n",
" csvreader = csv.reader(csvfile, delimiter = ',')\n",
" csvheader = next(csvreader)\n",
" for row in csvreader: \n",
" num_vote = num_vote + 1 # total votes\n",
" candi_name = row[2] # adding candidate name to array\n",
" \n",
" if candi_name not in candi: #conditional to append any new candidates \n",
" candi.append(candi_name)\n",
" index = candi.index(row[2])\n",
" vote_count.append(1)\n",
" else:\n",
" index = candi.index(row[2])\n",
" vote_count[index] += 1\n",
" \n",
" for i in vote_count: # find the percentage of the votes recieved\n",
" percent = round((i/num_vote) * 100)\n",
" percent = '%.3f%%' % percent\n",
" vote_percent.append(percent)\n",
" \n",
" winner = max(vote_count) # determine winner and update the value\n",
" index = vote_count.index(winner)\n",
" candi_winner = candi[index]"
]
},
{
"cell_type": "code",
"execution_count": 16,
"id": "400521a2",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Election Results\n",
"--------------------\n",
"Total Votes[4436463, 1408401, 985880, 211260]\n",
"--------------------\n",
"Khan: 63.000% (4436463)\n",
"Correy: 20.000% (1408401)\n",
"Li: 14.000% (985880)\n",
"O'Tooley: 3.000% (211260)\n",
"--------------------\n",
"Winning Candidate: 4436463\n"
]
}
],
"source": [
"#Print Results\n",
"print('Election Results')\n",
"print('-' * 20)\n",
"print(f'Total Votes' + str(vote_count))\n",
"print('-' * 20)\n",
"for i in range(len(candi)):\n",
" print(f'{candi[i]}: {str(vote_percent[i])} ({str(vote_count[i])})')\n",
"print('-' * 20)\n",
"print(f'Winning Candidate: {winner}')"
]
},
{
"cell_type": "code",
"execution_count": 14,
"id": "18e81981",
"metadata": {},
"outputs": [],
"source": [
"result = os.path.join('output', 'result.txt')\n",
"result = r'C:\\Users\\rzh00\\Documents\\gt-virt-atl-data-pt-09-2021-u-c-master\\02-Homework\\03-Python\\Instructions\\PyPoll\\result.txt'\n",
"\n",
"with open(result, 'w') as txt:\n",
" txt.write('Election Results')\n",
" txt.write('-' * 20)\n",
" txt.write(f'Total Votes' + str(vote_count))\n",
" txt.write('-' * 20)\n",
" for i in range(len(candi)):\n",
" txt.write(f'{candi[i]}: {str(vote_percent[i])} ({str(vote_count[i])})')\n",
" txt.write('-' * 20)\n",
" txt.write(f'Winning Candidate: {winner}')\n",
" txt.close()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c5893e30",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.8"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|
"""
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the
diagram below).
The robot can only move either down or right at any point in time. The robot is
trying to reach the bottom-right corner of the grid (marked 'Finish' in the
diagram below).
How many possible unique paths are there?

Above is a 3 x 7 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
"""
class Solution(object):
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
if m == 0 or n == 0:
return 0
grid = [[0 for j in range(m)] for i in range(n)]
for i in range(n):
for j in range(m):
if i == 0 or j == 0:
grid[i][j] = 1
else:
grid[i][j] = grid[i - 1][j] + grid[i][j - 1]
return grid[-1][-1]
|
text = input().split(' ')
new_text = ''
for word in text:
if len(word) > 4:
if word[:2] in word[2:]:
word = word[2:]
new_text += ' ' + word
print(new_text[1:])
|
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if len(strs) == 0:
return ""
resLen = 0
while True:
if len(strs[0]) == resLen:
return strs[0]
curChar = strs[0][resLen]
for i in range(1, len(strs)):
if len(strs[i]) == resLen or strs[i][resLen] != curChar:
return strs[0][: resLen]
resLen += 1
return strs[0][: resLen]
|
#!python3
# -*- coding:utf-8 -*-
'''
this code is a sample of code for learn how to use python test modules.
'''
def aaa():
'''
printing tree ! mark.
'''
print("!!!")
def bbb():
'''
printing tree chars.
'''
print("BBB")
def ccc():
'''
printing number with loop.
'''
for i in range(5):
print(i)
|
# Project Framework default is 1 (Model/View/Provider)
# src is source where is the lib folder located
def startmain(src="flutterproject/myapp/lib", pkg="Provider", file="app_widget", home="",
project_framework=1, autoconfigfile=True):
maindart = open(src + "/main.dart", "w")
if project_framework == 1:
maindart.write(
"import 'package:flutter/material.dart';\n"
"import '" + pkg + "/" + file + ".dart';\n\n"
"void main() => runApp(AppWidget());")
else:
print("This project framework is not avaliable yet. :(")
maindart.close()
if autoconfigfile:
configfile(home, src, pkg, file)
# Its not recomended use this manually
def configfile(home, src, pkg, file):
app_widgetdart = open(src+"/"+pkg+"/"+file+".dart", "w")
if home == "":
app_widgetdart.write("import 'package:flutter/material.dart';\n\n"
"class AppWidget extends StatelessWidget {\n"
" @override\n"
" Widget build(BuildContext context) {\n"
" return MaterialApp();\n"
" }\n"
"}")
else:
app_widgetdart.write("import 'package:flutter/material.dart';\n"
"import '../View/Screens/homepage.dart';\n\n"
"class AppWidget extends StatelessWidget {\n"
" @override\n"
" Widget build(BuildContext context) {\n"
" return MaterialApp(\n"
" home:" + home + "(),\n"
" );\n"
" }\n"
"}")
app_widgetdart.close()
|
def max_consecutive_ones(x):
# e.g. x= 95 (1101111)
"""
Steps
1. x & x<<1 --> 1101111 & 1011110 == 1001110
2. x & x<<1 --> 1001110 & 0011100 == 0001100
3. x & x<<1 --> 0001100 & 0011000 == 0001000
4. x & x<<1 --> 0001000 & 0010000 == 0000000
:param x:
:return:
"""
count = 0
while x > 0:
x = x & (x << 1)
count += 1
return count
if __name__ == '__main__':
print(max_consecutive_ones(7))
|
# Avg week temperature
print("Enter temperatures of 7 days:")
a = float(input())
b = float(input())
c = float(input())
d = float(input())
e = float(input())
f = float(input())
g = float(input())
print("Average temperature:", (a+b+c+d+e+f+g)/7)
|
def digitSum(n,step):
res=0
while(n>0):
res+=n%10
n=n//10
step+=1
if(res<=9):
return (res,step)
else:
return digitSum(res,step)
t=int(input())
for _ in range(t):
minstep=[99999999 for i in range(10)] #cache
hitratio=[0 for i in range(10)]
maxhit=0
n,d=[int(x) for x in input().strip().split()]
if(n==1):
print("{0} {1}".format(n,0))
continue
if(d>9):
d=digitSum(d,0)[0] #minimize it to single digit
steps=0
if(n>9):
n,steps=digitSum(n,steps)
minstep[n]=min(minstep[n],steps)
minstep[n]=min(minstep[n],steps)
hitratio[n]+=1
maxhit=max(maxhit,hitratio[n])
if(n==1):
print("{0} {1}".format(n,steps))
continue
iteration=1
while(n!=1 and iteration<(10**8)):
iteration+=1
#print(minstep)
n=n+d
steps+=1
if(n<10):
minstep[n] = min(minstep[n],steps)
hitratio[n]+=1
maxhit=max(maxhit,hitratio[n])
if(n>9):
n,steps=digitSum(n,steps)
minstep[n] = min(minstep[n],steps)
hitratio[n]+=1
maxhit=max(maxhit,hitratio[n])
if(maxhit>100):
break
tempmin=10
for i in range(2,10):
if(minstep[i]!=99999999 and i<tempmin):
tempmin=i
print("{0} {1}".format(tempmin,minstep[tempmin]))
|
######################################################
# #
# author #
# Parth Lathiya #
# https://www.cse.iitb.ac.in/~parthiitb/ #
# #
######################################################
at = int(input().strip())
for att in range(at):
u = list(map(int, input().strip().split()))
u.remove(len(u)-1)
print(max(u))
|
# 15/15
num_of_flicks = int(input())
art = []
for _ in range(num_of_flicks):
coords = input().split(",")
art.append((int(coords[0]), int(coords[1])))
lowest_x = min(art, key=lambda x: x[0])[0] - 1
lowest_y = min(art, key=lambda x: x[1])[1] - 1
highest_x = max(art, key=lambda x: x[0])[0] + 1
highest_y = max(art, key=lambda x: x[1])[1] + 1
print(f"{lowest_x},{lowest_y}")
print(f"{highest_x},{highest_y}")
|
print("Leap Year Range Calculator: ")
year1=int(input("Enter First Year: "))
year2 = int(input("Enter Last Year: "))
while year1<=year2:
if year1 % 4 == 0 :
print(year1,"is a leap year")
year1= year1 + 1
|
# Given an array nums of n integers,
# are there elements a, b, c in nums such that a + b + c = 0?
# Find all unique triplets in the array which gives the sum of zero.
# Note:
# The solution set must not contain duplicate triplets.
# Example:
# Given array nums = [-1, 0, 1, 2, -1, -4],
# A solution set is:
# [
# [-1, 0, 1],
# [-1, -1, 2]
# ]
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
# M1. 双指针法
# 固定其中一位,转化为双指针问题
res = set() # 去除重复结果
nums.sort()
for i in range(len(nums) - 2):
if i > 0 and nums[i] == nums[i - 1]:
continue
low, high = i + 1, len(nums) - 1
while low < high:
s = nums[i] + nums[low] + nums[high]
if s > 0:
high -= 1
elif s < 0:
low += 1
else:
res.add((nums[i], nums[low], nums[high]))
low += 1
high -= 1
return list(res)
|
I = lambda : int(input())
LI = lambda : [int(x) for x in input().split()]
MI = lambda : map(int, input().split())
SI = lambda : input()
"""
#Leer de archivo
for line in sys.stdin:
...
"""
"""
def fastio():
import sys
from io import StringIO
from atexit import register
global input
sys.stdin = StringIO(sys.stdin.read())
input = lambda : sys.stdin.readline().rstrip()
sys.stdout = StringIO()
register(lambda : sys.__stdout__.write(sys.stdout.getvalue()))
fastio()
"""
class PointSystem:
def oddsOfWinning(self, pointsToWin, pointsToWinBy, skill):
n = 1000
p = [[0 for i in range(n)] for j in range(n)]
p[0][0] = 1
for i in range(n-1):
for j in range(n-1):
if(max(i, j) >= pointsToWin and max(i, j) - min(i, j) >= pointsToWinBy):
continue
p[i+1][j] += p[i][j] * skill/100.0
p[i][j+1] += p[i][j] * (100-skill)/100.0
ans = 0.0
for i in range(n):
for j in range(n):
if(i > j and i >= pointsToWin and i - j >= pointsToWinBy):
ans += p[i][j]
return ans
# x = PointSystem()
# print(x.oddsOfWinning(2, 1, 40))
# print(x.oddsOfWinning(4, 5, 50))
# print(x.oddsOfWinning(3, 3, 25))
|
"""
Generator with a finite loop
can be used with for
"""
def count():
n = 1
while n < 1000:
yield n
n *= 2
gen = count()
for number in gen:
print(number)
|
"""
Constants to be used in the module
"""
__author__ = 'Santiago Flores Kanter (sfloresk@cisco.com)'
QUERY_TARGET_CHILDREN = 'children'
QUERY_TARGET_SELF = 'self'
QUERY_TARGET_SUBTREE = 'subtree'
API_URL = 'api/'
MQ_API2_URL = 'mqapi2/'
|
# Escreva um programa que leia duas strings e gere uma terceira, na qual os caracteres da segunda foram retirados da primeira
# 1ª string: AATTGGAA
# 2ª string: TG
# 3ª string: AAAA
# str1 = 'AATTGGAA'
# str2 = 'TG'
#
# print(f'\nPrimeira string: {str1}')
# print(f'Segunda string: {str2}')
str1 = str(input('\nPrimeira string: '))
str2 = str(input('Segunda string: '))
str3 = ''
for letter in str1:
if letter not in str2:
str3 += letter
if str3 == '':
print('Todos os caracteres foram removidos.')
else:
print(f'\nCaracteres {str2} removidos de {str1}, sobrando apenas: {str3}')
|
#!/usr/bin/env python
"""
File: pentagon_p_solution-garid.py
Find the perimeter of pentagon.
"""
__author__ = "Ochirgarid Chinzorig (Ochirgarid)"
__version__ = "1.0"
# Open file on read mode
inp = open("../test/test1.txt", "r")
# read input lines one by one
# and convert them to integer
a = int(inp.readline().strip())
b = int(inp.readline().strip())
c = int(inp.readline().strip())
d = int(inp.readline().strip())
e = int(inp.readline().strip())
# must close opened file
inp.close()
# calculate perimeter
p = a + b + c + d + e
# print for std out
print("Perimeter : {}".format(p))
|
#
# PySNMP MIB module MITEL-IPVIRTUAL-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MITEL-IPVIRTUAL-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:03:05 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsUnion, SingleValueConstraint, ConstraintsIntersection, ValueRangeConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "SingleValueConstraint", "ConstraintsIntersection", "ValueRangeConstraint", "ValueSizeConstraint")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
IpAddress, iso, Unsigned32, Counter64, TimeTicks, Bits, enterprises, ModuleIdentity, Gauge32, ObjectIdentity, Integer32, NotificationType, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter32 = mibBuilder.importSymbols("SNMPv2-SMI", "IpAddress", "iso", "Unsigned32", "Counter64", "TimeTicks", "Bits", "enterprises", "ModuleIdentity", "Gauge32", "ObjectIdentity", "Integer32", "NotificationType", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter32")
RowStatus, DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "DisplayString", "TextualConvention")
mitelIpGrpIpVirtualGroup = ModuleIdentity((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 4))
mitelIpGrpIpVirtualGroup.setRevisions(('2003-03-24 09:31', '1999-03-01 00:00',))
if mibBuilder.loadTexts: mitelIpGrpIpVirtualGroup.setLastUpdated('200303240931Z')
if mibBuilder.loadTexts: mitelIpGrpIpVirtualGroup.setOrganization('MITEL Corporation')
mitel = MibIdentifier((1, 3, 6, 1, 4, 1, 1027))
mitelProprietary = MibIdentifier((1, 3, 6, 1, 4, 1, 1027, 4))
mitelPropIpNetworking = MibIdentifier((1, 3, 6, 1, 4, 1, 1027, 4, 8))
mitelIpNetRouter = MibIdentifier((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1))
mitelRouterIpGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1))
mitelIpVGrpPortTable = MibTable((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 4, 1), )
if mibBuilder.loadTexts: mitelIpVGrpPortTable.setStatus('current')
mitelIpVGrpPortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 4, 1, 1), ).setIndexNames((0, "MITEL-IPVIRTUAL-MIB", "mitelIpVGrpPortTableNetAddr"), (0, "MITEL-IPVIRTUAL-MIB", "mitelIpVGrpPortTableIfIndex"))
if mibBuilder.loadTexts: mitelIpVGrpPortEntry.setStatus('current')
mitelIpVGrpPortTableNetAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 4, 1, 1, 1), IpAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: mitelIpVGrpPortTableNetAddr.setStatus('current')
mitelIpVGrpPortTableNetMask = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 4, 1, 1, 2), IpAddress()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: mitelIpVGrpPortTableNetMask.setStatus('current')
mitelIpVGrpPortTableIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 4, 1, 1, 11), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: mitelIpVGrpPortTableIfIndex.setStatus('current')
mitelIpVGrpPortTableStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 4, 1, 1, 12), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: mitelIpVGrpPortTableStatus.setStatus('current')
mitelIpVGrpPortTableCfgMethod = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 4, 1, 1, 15), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("static", 1), ("addressless", 2), ("dhcp", 3), ("ipcp", 4)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: mitelIpVGrpPortTableCfgMethod.setStatus('current')
mitelIpVGrpRipTable = MibTable((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 4, 2), )
if mibBuilder.loadTexts: mitelIpVGrpRipTable.setStatus('current')
mitelIpVGrpRipEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 4, 2, 1), ).setIndexNames((0, "MITEL-IPVIRTUAL-MIB", "mitelIpVGrpTableRipIpAddr"))
if mibBuilder.loadTexts: mitelIpVGrpRipEntry.setStatus('current')
mitelIpVGrpTableRipIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 4, 2, 1, 1), IpAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: mitelIpVGrpTableRipIpAddr.setStatus('current')
mitelIpVGrpTableRipRxPkts = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 4, 2, 1, 2), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: mitelIpVGrpTableRipRxPkts.setStatus('current')
mitelIpVGrpTableRipRxBadPkts = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 4, 2, 1, 3), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: mitelIpVGrpTableRipRxBadPkts.setStatus('current')
mitelIpVGrpTableRipRxBadRtes = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 4, 2, 1, 4), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: mitelIpVGrpTableRipRxBadRtes.setStatus('current')
mitelIpVGrpTableRipTxUpdates = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 4, 2, 1, 5), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: mitelIpVGrpTableRipTxUpdates.setStatus('current')
mibBuilder.exportSymbols("MITEL-IPVIRTUAL-MIB", mitelIpVGrpTableRipRxBadRtes=mitelIpVGrpTableRipRxBadRtes, mitel=mitel, mitelIpVGrpRipTable=mitelIpVGrpRipTable, mitelIpVGrpPortTableNetMask=mitelIpVGrpPortTableNetMask, mitelIpVGrpPortTableStatus=mitelIpVGrpPortTableStatus, mitelIpGrpIpVirtualGroup=mitelIpGrpIpVirtualGroup, mitelIpVGrpPortTable=mitelIpVGrpPortTable, mitelIpVGrpTableRipIpAddr=mitelIpVGrpTableRipIpAddr, mitelIpNetRouter=mitelIpNetRouter, PYSNMP_MODULE_ID=mitelIpGrpIpVirtualGroup, mitelIpVGrpPortEntry=mitelIpVGrpPortEntry, mitelIpVGrpPortTableIfIndex=mitelIpVGrpPortTableIfIndex, mitelProprietary=mitelProprietary, mitelPropIpNetworking=mitelPropIpNetworking, mitelIpVGrpTableRipRxPkts=mitelIpVGrpTableRipRxPkts, mitelIpVGrpRipEntry=mitelIpVGrpRipEntry, mitelIpVGrpTableRipRxBadPkts=mitelIpVGrpTableRipRxBadPkts, mitelRouterIpGroup=mitelRouterIpGroup, mitelIpVGrpPortTableCfgMethod=mitelIpVGrpPortTableCfgMethod, mitelIpVGrpTableRipTxUpdates=mitelIpVGrpTableRipTxUpdates, mitelIpVGrpPortTableNetAddr=mitelIpVGrpPortTableNetAddr)
|
def Reverse(Dna):
tt = {
'A' : 'T',
'T' : 'A',
'G' : 'C',
'C' : 'G',
}
ans = ''
for a in Dna:
ans += tt[a]
return ans[::-1]
def main(infile, outfile):
# Read the input, but do something non-trivial instead of count the lines in the file
inp = lines = [line.rstrip('\n') for line in infile]
print(inp)
output = str(Reverse(inp[0]))
# For debugging, print something to console
print(output)
# Write the output.
outfile.write(output)
|
# configuracoes pessoais
PERSONAL_NAME = 'YOU'
# configuracoes de email
EMAIL = 'your gmail account'
PASSWORD = 'your gmail PASSWORD'
RECEIVER_EMAIL = 'email to forward the contact messages'
# configuracoes do Google ReCaptha
SECRET_KEY = "Google ReCaptha's Secret key"
SITE_KEY = "Google ReCaptha's Site key"
APP_SECRET_KEY = '65#9DMN_T'
SKILLS = [
{
'name': 'Quick learner',
'strength': '90%'
},
{
'name': 'Flask',
'strength': '70%'
},
{
'name': 'Javascript',
'strength': '50%'
},
{
'name': 'Unit Test',
'strength': '30%'
}
]
EXPERINCES = [
{
'name': 'Intership',
'company': 'Stark Industries',
'location': 'New York City',
'working_period': 'May 2014 - June 2016',
'job_description': 'Developed tests for Mark IV, also designed some helmets for Mr. Stark.'
},
{
'name': 'Developer',
'company': 'Matrix',
'location': 'New York City',
'working_period': 'June 2016 - Currently',
'job_description': 'Created the main training prograns for martial arts.'
}
]
EDUCATION = [
{
'name': 'Bachelor of Computer Science',
'institution': 'University of Brasil',
'location': 'Brasil',
'graduation_year': '2016'
# 'extra_information': None
}
]
OBJECTIVE = 'Python developer'
|
"""Data set for text records.
A Dataset maintains the collection of data instances and metadata
associated with the dataset.
"""
class Dataset(object):
"""Data set for text records.
A Dataset maintains the collection of data instances and metadata
associated with the dataset.
Parameters
-------
id : uuid
Unique identifier for a dataset in a TextStudio project.
loader : text_studio.DataLoader
The DataLoader object responsible for loading the data
from an external source and/or writing the data set to an
external location.
file_path : string
The file path points to the location of the data set.
Attributes
-------
instances : list of dicts
Collection of data instances contained in the dataset.
loaded : bool
True if all data instances in the dataset have been loaded
into the dataset. Data instances are not loaded from disk
or an external location until needed.
Methods
-------
load(self, **kwargs):
Load the dataset using the Dataset's loader.
save(self, **kwargs):
Save the dataset using the Dataset's loader.
"""
def __init__(self, id, loader=None, file_path=""):
self.id = id
self.loader = loader
self.file_path = file_path
self.instances = []
self.loaded = False
def load(self, **kwargs):
"""Load the dataset using the Dataset's loader.
Load the data set from its stored location,
populating the data instances collection. Set the
loaded flag to True if the instances were retrieved
successfully.
Parameters
----------
**kwargs : dictionary
Keyword arguments passed to the DataLoader
to configure its settings for loading the dataset.
"""
if self.loader and self.file_path:
with open(self.file_path, "r") as file:
self.instances = self.loader.load(file, **kwargs)
self.loaded = True
def save(self, **kwargs):
"""Save the dataset using the Dataset's loader.
Save the data set in its current state to a storage location.
Parameters
----------
**kwargs : dictionary
Keyword arguments passed to the DataLoader
to configure its settings for writing the dataset.
"""
if self.loader and self.file_path:
with open(self.file_path, "w") as file:
self.loader.save(self.instances, file, **kwargs)
|
OCTICON_PAPER_AIRPLANE = """
<svg class="octicon octicon-paper-airplane" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path fill-rule="evenodd" d="M1.592 2.712L2.38 7.25h4.87a.75.75 0 110 1.5H2.38l-.788 4.538L13.929 8 1.592 2.712zM.989 8L.064 2.68a1.341 1.341 0 011.85-1.462l13.402 5.744a1.13 1.13 0 010 2.076L1.913 14.782a1.341 1.341 0 01-1.85-1.463L.99 8z"></path></svg>
"""
|
def test():
a = 10
fun1 = lambda: a
fun1()
print(a)
a += 1
fun1()
print(a)
return fun1
fun = test()
print(f"Fun: {fun()}")
|
# Author: OMKAR PATHAK
# In this example, we will see how to implement graphs in Python
class Vertex(object):
''' This class helps to create a Vertex for our graph '''
def __init__(self, key):
self.key = key
self.edges = {}
def addNeighbour(self, neighbour, weight = 0):
self.edges[neighbour] = weight
def __str__(self):
return str(self.key) + 'connected to: ' + str([x.key for x in self.edges])
def getEdges(self):
return self.edges.keys()
def getKey(self):
return self.key
def getWeight(self, neighbour):
try:
return self.edges[neighbour]
except:
return None
class Graph(object):
''' This class helps to create Graph with the help of created vertexes '''
def __init__(self):
self.vertexList = {}
self.count = 0
def addVertex(self, key):
self.count += 1
newVertex = Vertex(key)
self.vertexList[key] = newVertex
return newVertex
def getVertex(self, vertex):
if vertex in self.vertexList:
return self.vertexList[vertex]
else:
return None
def addEdge(self, fromEdge, toEdge, cost = 0):
if fromEdge not in self.vertexList:
newVertex = self.addVertex(fromEdge)
if toEdge not in self.vertexList:
newVertex = self.addVertex(toEdge)
self.vertexList[fromEdge].addNeighbour(self.vertexList[toEdge], cost)
def getVertices(self):
return self.vertexList.keys()
def __iter__(self):
return iter(self.vertexList.values())
if __name__ == '__main__':
graph = Graph()
graph.addVertex('A')
graph.addVertex('B')
graph.addVertex('C')
graph.addVertex('D')
graph.addEdge('A', 'B', 5)
graph.addEdge('A', 'C', 6)
graph.addEdge('A', 'D', 2)
graph.addEdge('C', 'D', 3)
for vertex in graph:
for vertexes in vertex.getEdges():
print('({}, {}) => {}'.format(vertex.getKey(), vertexes.getKey(), vertex.getWeight(vertexes)))
# OUTPUT:
# (C, D) => 3
# (A, C) => 6
# (A, D) => 2
# (A, B) => 5
|
# -*- coding: utf-8 -*-
"""
neutrino_api
This file was automatically generated for NeutrinoAPI by APIMATIC v2.0 ( https://apimatic.io ).
"""
class Blacklist(object):
"""Implementation of the 'Blacklist' model.
TODO: type model description here.
Attributes:
is_listed (bool): true if listed, false if not
list_host (string): the domain/hostname of the DNSBL
list_rating (int): the list rating [1-3] with 1 being the best rating
and 3 the lowest rating
list_name (string): the name of the DNSBL
txt_record (string): the TXT record returned for this listing (if
listed)
return_code (string): the specific return code for this listing (if
listed)
response_time (int): the DNSBL server response time in milliseconds
"""
# Create a mapping from Model property names to API property names
_names = {
"is_listed":'isListed',
"list_host":'listHost',
"list_rating":'listRating',
"list_name":'listName',
"txt_record":'txtRecord',
"return_code":'returnCode',
"response_time":'responseTime'
}
def __init__(self,
is_listed=None,
list_host=None,
list_rating=None,
list_name=None,
txt_record=None,
return_code=None,
response_time=None):
"""Constructor for the Blacklist class"""
# Initialize members of the class
self.is_listed = is_listed
self.list_host = list_host
self.list_rating = list_rating
self.list_name = list_name
self.txt_record = txt_record
self.return_code = return_code
self.response_time = response_time
@classmethod
def from_dictionary(cls,
dictionary):
"""Creates an instance of this model from a dictionary
Args:
dictionary (dictionary): A dictionary representation of the object as
obtained from the deserialization of the server's response. The keys
MUST match property names in the API description.
Returns:
object: An instance of this structure class.
"""
if dictionary is None:
return None
# Extract variables from the dictionary
is_listed = dictionary.get('isListed')
list_host = dictionary.get('listHost')
list_rating = dictionary.get('listRating')
list_name = dictionary.get('listName')
txt_record = dictionary.get('txtRecord')
return_code = dictionary.get('returnCode')
response_time = dictionary.get('responseTime')
# Return an object of this model
return cls(is_listed,
list_host,
list_rating,
list_name,
txt_record,
return_code,
response_time)
|
class DmpIo():
def __init__(self):
# inputs
self.event = None
self.username = None
self.password = None
|
'''
Inhalte Arbeit:
- Werte einlesen mit try except block
- if - Verzweigungen
- for - Schleifen (for in ....)
for i in lst:
for i in range(10):
- list - anhängen, sortieren, löschen, ist etwas in einer Liste
- dict - keys zugreifen - values zugreifen und auf beide zugreifen
- files - lesen und schreiben
Übungsprogramm:
- wie viele Namen möchtest Du eingeben?
- dann fragt das Programm die Namen und das Alter ab
- Name und Alter in einem dict speichern
(Name ist der Key; Alter ist der Value)
- die Namen und Alter in einer Datei speichern
Frank:26
Sabine:24
Tom:18
- Datei lesen
- und die gelesen Namen und Alter in ein neues dict speichern
- Werte aus dem neuen dict schön ausgeben
'''
alterNamen = {44: "Frank",
28: "Jan",
44: "Toll"}
for i in alterNamen.keys():
print(i)
namenAlter = {"Frank": 44,
"Jan": 38,
"Peter": 16,
"Timmy": 12}
for name, alter in namenAlter.items():
print("Hallo " + name)
if alter < 14:
print("Du junger Mensch " + str(alter) + " Jahr alt.")
elif alter > 14 and alter < 40:
print("mmhh")
else:
print("oho....")
for name in namenAlter.keys():
print(name)
for alter in namenAlter.values():
print(alter)
print(sorted(namenAlter.values()))
primeNumber = "1,3,5,7,11,17,19,23"
with open("primeNumberString.txt", "w") as fd:
fd.write(primeNumber)
with open("primeNumberString.txt", "r") as toll:
numbersAsString = toll.read()
print(numbersAsString)
numbers = numbersAsString.split(",")
for number in numbers:
print(number)
primeNumbers = [1,3,5,7,11,13,17,19,23]
with open("primeNumbersList.txt", "w") as fd:
for primeNumber in primeNumbers:
fd.write(str(primeNumber)+"\n")
with open("primeNumbersList.txt", "r") as fd:
tmp = fd.read()
print(type(tmp))
print(tmp)
with open("primeNumbersList.txt", "r") as fd:
lst = fd.readlines()
print(lst)
for i in lst:
print(i)
for i in lst:
print(i[0:-1])
|
#!/usr/bin/env python3
"""
This prints out my node IPs.
nodes-005.py is used to print out.....
al;jsdflkajsdf
l;ajdsl;faj
a;ljsdklfj
--------------------------------------------------
"""
print('10.10.10.5')
print('10.10.10.4')
print('10.10.10.3')
print('10.10.10.2')
print('10.10.10.1')
|
"""
Exercise 7: Rewrite the grade program from the previous chapter using a function called computegrade that takes a score as its parameter and returns a grade as a string.
"""
def computegrade(score):
if score >= 0.9:
return 'A'
elif score >= 0.8:
return 'B'
elif score >= 0.7:
return 'C'
elif score >= 0.6:
return 'D'
else:
return 'F'
try:
score = float(input("Enter score: "))
if score > 1 or score < 0:
raise ValueError('Bad score')
print(computegrade(score))
except:
print('Bad score')
|
# Desenvolva um programa que pergunte a distancia de uma viagem em Km.
#Calcule o preço da passagem, cobrando R$0,50 por Km para viagens de até 200Km e R$0,45
# para viagens mais longas.
#minha resposta
#dist = float(input('Qual a distancia da sua viagem? '))
#print('Voce está prestes a começar uma viagem de {:.1f}Km'.format(dist))
#if dist <= 200:
# print('E o preço da sua passagem será de R${:.2f}'.format(dist * 0.50))
#else:
# print('E o preço da sua passagem será de R${:.2f}'.format(dist * 0.45))
#resposta1 do Gustavo
#distancia = float(input('Qual a distancia da sua viagem? '))
#print('Voce está prestes a começar uma viagem de {:.1f}Km'.format(distancia))
#if distancia <= 200:
# preco = distancia * 0.50
#else:
# preco = distancia * 0.45
#print('E o preço da sua passagem será de R${:.2f}'.format(preco))
#resposta2 do gustavo
distancia = float(input('Qual a distancia da sua viagem? '))
print('Voce está prestes a começar uma viagem de {:.1f}Km'.format(distancia))
preco = distancia * 0.50 if distancia <= 200 else distancia * 0.45 #if in line ou operador ternario
print('E o preço da sua passagem será de R${:.2f}'.format(preco))
|
name = input("Как вас зовут?:")
age = input("Сколько вам лет?:")
livePlace = input("Где вы живете?:")
age = int(age)
print("Это ", name)
print("Ему/ей ", age, " лет")
print("Он/она живет ", livePlace)
|
#
# PySNMP MIB module CISCO-STACK-CAPABILITY (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-STACK-CAPABILITY
# Produced by pysmi-0.3.4 at Wed May 1 12:12:54 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsUnion, ConstraintsIntersection, ValueRangeConstraint, SingleValueConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ConstraintsIntersection", "ValueRangeConstraint", "SingleValueConstraint", "ValueSizeConstraint")
ciscoAgentCapability, = mibBuilder.importSymbols("CISCO-SMI", "ciscoAgentCapability")
AgentCapabilities, NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "AgentCapabilities", "NotificationGroup", "ModuleCompliance")
ObjectIdentity, Gauge32, Counter64, Counter32, Integer32, Bits, ModuleIdentity, iso, Unsigned32, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, MibIdentifier, IpAddress, NotificationType = mibBuilder.importSymbols("SNMPv2-SMI", "ObjectIdentity", "Gauge32", "Counter64", "Counter32", "Integer32", "Bits", "ModuleIdentity", "iso", "Unsigned32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "MibIdentifier", "IpAddress", "NotificationType")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
ciscoStackCapability = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 7, 378))
ciscoStackCapability.setRevisions(('2008-03-19 00:00', '2006-03-15 00:00', '2005-01-19 00:00', '2003-12-17 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: ciscoStackCapability.setRevisionsDescriptions(('Added ciscoStackCapCatOSV08R0701PCat6k for Cisco CatOS 8.7(1).', 'Add VARIATIONs for notifications chassisAlarmOff, chassisAlarmOn, moduleDown and moduleUp, in ciscoStackCapCatOSV08R0101Cat6k.', 'Added ciscoStackCapV12R0112cE01PCat6k for Cisco IOS 12.1(12c)E1.', 'Initial version of this MIB module.',))
if mibBuilder.loadTexts: ciscoStackCapability.setLastUpdated('200803190000Z')
if mibBuilder.loadTexts: ciscoStackCapability.setOrganization('Cisco Systems, Inc.')
if mibBuilder.loadTexts: ciscoStackCapability.setContactInfo(' Cisco Systems Customer Service Postal: 170 West Tasman Drive San Jose, CA 95134 USA Tel: +1 800 553-NETS E-mail: cs-lan-switch-snmp@cisco.com, cs-snmp@cisco.com')
if mibBuilder.loadTexts: ciscoStackCapability.setDescription('The capabilities description of CISCO-STACK-MIB.')
ciscoStackCapCatOSV08R0101Cat6k = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 378, 1))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoStackCapCatOSV08R0101Cat6k = ciscoStackCapCatOSV08R0101Cat6k.setProductRelease('Cisco CatOS 8.1(1) on Catalyst 6000/6500\n and Cisco 7600 series devices.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoStackCapCatOSV08R0101Cat6k = ciscoStackCapCatOSV08R0101Cat6k.setStatus('current')
if mibBuilder.loadTexts: ciscoStackCapCatOSV08R0101Cat6k.setDescription('CISCO-STACK-MIB capabilities.')
ciscoStackCapV12R0111bEXCat6k = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 378, 2))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoStackCapV12R0111bEXCat6k = ciscoStackCapV12R0111bEXCat6k.setProductRelease('Cisco IOS 12.1(11b)EX on Catalyst 6000/6500\n and Cisco 7600 series devices.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoStackCapV12R0111bEXCat6k = ciscoStackCapV12R0111bEXCat6k.setStatus('current')
if mibBuilder.loadTexts: ciscoStackCapV12R0111bEXCat6k.setDescription('CISCO-STACK-MIB capabilities.')
ciscoStackCapV12R0112cE01PCat6k = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 378, 3))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoStackCapV12R0112cE01PCat6k = ciscoStackCapV12R0112cE01PCat6k.setProductRelease('Cisco IOS 12.1(12c)E1 on Catalyst 6000/6500\n and Cisco 7600 series devices.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoStackCapV12R0112cE01PCat6k = ciscoStackCapV12R0112cE01PCat6k.setStatus('current')
if mibBuilder.loadTexts: ciscoStackCapV12R0112cE01PCat6k.setDescription('CISCO-STACK-MIB capabilities.')
ciscoStackCapCatOSV08R0701PCat6k = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 378, 4))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoStackCapCatOSV08R0701PCat6k = ciscoStackCapCatOSV08R0701PCat6k.setProductRelease('Cisco CatOS 8.7(1) on Catalyst 6000/6500\n and Cisco 7600 series devices.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoStackCapCatOSV08R0701PCat6k = ciscoStackCapCatOSV08R0701PCat6k.setStatus('current')
if mibBuilder.loadTexts: ciscoStackCapCatOSV08R0701PCat6k.setDescription('CISCO-STACK-MIB capabilities.')
mibBuilder.exportSymbols("CISCO-STACK-CAPABILITY", ciscoStackCapCatOSV08R0101Cat6k=ciscoStackCapCatOSV08R0101Cat6k, ciscoStackCapability=ciscoStackCapability, PYSNMP_MODULE_ID=ciscoStackCapability, ciscoStackCapCatOSV08R0701PCat6k=ciscoStackCapCatOSV08R0701PCat6k, ciscoStackCapV12R0112cE01PCat6k=ciscoStackCapV12R0112cE01PCat6k, ciscoStackCapV12R0111bEXCat6k=ciscoStackCapV12R0111bEXCat6k)
|
description = 'system setup'
group = 'lowlevel'
sysconfig = dict(
cache='localhost',
instrument='ESTIA',
experiment='Exp',
datasinks=['conssink', 'filesink', 'daemonsink'],
)
modules = ['nicos.commands.standard']
includes = ['temp']
devices = dict(
ESTIA=device('nicos.devices.instrument.Instrument',
description='instrument object',
instrument='estia',
responsible='Artur Glavic <artur.glavic@psi.ch>',
website='https://confluence.esss.lu.se/display/ESTIA',
operators=['ESS', 'PSI'],
facility='Paul Scherrer Institut (PSI)',
),
Sample=device('nicos.devices.sample.Sample',
description='The currently used sample',
),
Exp=device('nicos.devices.experiment.Experiment',
description='experiment object',
dataroot='/opt/nicos-data',
sendmail=True,
serviceexp='p0',
sample='Sample',
),
filesink=device('nicos.devices.datasinks.AsciiScanfileSink',
),
conssink=device('nicos.devices.datasinks.ConsoleScanSink',
),
daemonsink=device('nicos.devices.datasinks.DaemonSink',
),
Space=device('nicos.devices.generic.FreeSpace',
description='The amount of free space for storing data',
path='/opt/nicos-data',
minfree=5,
),
)
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#Script by: Jesús Redondo García
#Date: 28-10-2014
#Script to process the user metadata about the catalog.
#Get all the fields from fields.conf
fields_conf_file = open('fields.conf','r')
fields_lines = fields_conf_file.readlines()
fields_conf_file.close()
for line in fields_lines :
if '{-URL-CATALOG-} : ' in line : url_catalog = line.replace('{-URL-CATALOG-} : ','').replace('\n','')
elif '{-URL-DATASET-} : ' in line : url_dataset = line.replace('{-URL-DATASET-} : ','').replace('\n','')
elif '{-LANGUAGE-} : ' in line : language = line.replace('{-LANGUAGE-} : ','').replace('\n','')
elif '{-TITLE-} : ' in line : title = line.replace('{-TITLE-} : ','').replace('\n','')
elif '{-DESCRIPTION-} : ' in line : description = line.replace('{-DESCRIPTION-} : ','').replace('\n','')
elif '{-ISSUED-} : ' in line : issued = line.replace('{-ISSUED-} : ','').replace('\n','')
elif '{-URL-PUBLISHER-} : ' in line : url_publisher = line.replace('{-URL-PUBLISHER-} : ','').replace('\n','')
elif '{-URL-LICENSE-} : ' in line : url_license = line.replace('{-URL-LICENSE-} : ','').replace('\n','')
#Save the metadata in the base catalog.
fIn = open('base_catalog_template.rdf','r')
filedata = fIn.read()
fIn.close()
newdata = filedata.replace('{-URL-CATALOG-}',url_catalog)
newdata = newdata.replace('{-URL-DATASET-}',url_dataset)
newdata = newdata.replace('{-LANGUAGE-}',language)
newdata = newdata.replace('{-TITLE-}',title)
newdata = newdata.replace('{-DESCRIPTION-}',description)
newdata = newdata.replace('{-ISSUED-}',issued)
newdata = newdata.replace('{-URL-PUBLISHER-}',url_publisher)
newdata = newdata.replace('{-URL-LICENSE-}',url_license)
fOut = open('base_catalog.rdf','w')
fOut.write(newdata)
fOut.close()
|
a = float(input())
b = float(input())
c = float(input())
media = (a * 2 + b * 3 + c * 5) / (2 + 3 + 5)
print("MEDIA = {:.1f}".format(media))
|
#Aula 7
#Dicionarios
lista = []
# dicionario = {'Nome':'Matheus', 'Sobrenome': 'Schuetz' }
# print(dicionario)
# print(dicionario['Sobrenome'])
nome = 'Maria'
lista_notas = [10,20,50,70]
media = sum(lista_notas)/len(lista_notas)
situacao = 'Reprovado'
if media >=7:
situacao = 'Aprovado'
dicionario_alunos = {'Nome':nome, 'Lista_Notas':lista_notas, 'Media':media, 'Situacao':situacao}
print(f"{dicionario_alunos['Nome']} - {dicionario_alunos['Situacao']}")
|
TEACHER_AUTHORITIES = [
'VIEW_PROFILE',
'JUDGE_TASK',
'SHARE_TASK',
'VIEW_ABSENT',
'SUBMIT_LESSON',
'VIEW_LESSON',
'VIEW_ACTIVITY',
'EDIT_PROFILE',
'GIVE_TASK',
'VIEW_TASK',
'ADD_ABSENT'
]
STUDENT_AUTHORITIES = [
'VIEW_PROFILE',
'VIEW_LESSON',
'VIEW_ACTIVITY',
'VIEW_TASK_FRAGMENT',
'DOING_TASK',
'VIEW_ABSENT',
'EDIT_PROFILE',
]
OTHER_AUTHORITIES = [
'VIEW_LESSON',
'VIEW_MAP',
'VIEW_CHALLENGE'
'EDIT_SCHOOL',
'EDIT_PROFILE',
'DO_CHALLENGE',
'ADD_SCHOOL'
]
|
def _init():
global _global_dict
_global_dict = {}
def set_value(key, value):
_global_dict[key] = value
def get_value(key):
return _global_dict.get(key)
_init()
|
palavra = input('Digite uma palavra para ser advinhada: ')
digitadas =[]
chances = int(len(palavra)/2)
print('\n'*50)
while True:
if chances <= 0:
print(f'Voce perdeu! A palavra era {palavra}')
break
letra = input('Digite uma letra: ')
if len(letra) > 1:
print ('Favor, digitar somente uma letra!')
continue
digitadas.append(letra)
print()
if letra in palavra:
print(f'A letra {letra} existe na palavra')
else:
print(f'A letra {letra} não existe na palavra')
digitadas.pop()
print()
formacao = ''
for letra_nova in palavra:
if letra_nova in digitadas:
formacao += letra_nova
else:
formacao += '*'
if formacao == palavra:
print(f'Você ganhou!!! A palavra é {palavra}.')
break
else:
print(formacao)
if letra not in palavra:
chances -= 1
if chances > 0:
print(f'\nVocê ainda tem {chances} chances.')
print()
|
#
# PySNMP MIB module CISCO-VLAN-GROUP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-VLAN-GROUP-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:02:29 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueRangeConstraint, ConstraintsUnion, SingleValueConstraint, ValueSizeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsUnion", "SingleValueConstraint", "ValueSizeConstraint", "ConstraintsIntersection")
ciscoMgmt, = mibBuilder.importSymbols("CISCO-SMI", "ciscoMgmt")
Cisco2KVlanList, = mibBuilder.importSymbols("CISCO-TC", "Cisco2KVlanList")
SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString")
NotificationGroup, ModuleCompliance, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance", "ObjectGroup")
Unsigned32, IpAddress, ModuleIdentity, Bits, MibScalar, MibTable, MibTableRow, MibTableColumn, iso, Counter64, NotificationType, ObjectIdentity, Gauge32, Integer32, TimeTicks, Counter32, MibIdentifier = mibBuilder.importSymbols("SNMPv2-SMI", "Unsigned32", "IpAddress", "ModuleIdentity", "Bits", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "iso", "Counter64", "NotificationType", "ObjectIdentity", "Gauge32", "Integer32", "TimeTicks", "Counter32", "MibIdentifier")
RowStatus, TextualConvention, DisplayString, StorageType = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "TextualConvention", "DisplayString", "StorageType")
ciscoVlanGroupMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 9, 709))
ciscoVlanGroupMIB.setRevisions(('2011-03-22 00:00', '2009-11-20 00:00',))
if mibBuilder.loadTexts: ciscoVlanGroupMIB.setLastUpdated('201103220000Z')
if mibBuilder.loadTexts: ciscoVlanGroupMIB.setOrganization('Cisco Systems, Inc.')
ciscoVlanGroupMIBNotifs = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 709, 0))
ciscoVlanGroupMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 709, 1))
ciscoVlanGroupMIBConform = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 709, 2))
cvgConfigTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 709, 1, 1), )
if mibBuilder.loadTexts: cvgConfigTable.setStatus('current')
cvgConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 709, 1, 1, 1), ).setIndexNames((0, "CISCO-VLAN-GROUP-MIB", "cvgConfigGroupName"))
if mibBuilder.loadTexts: cvgConfigEntry.setStatus('current')
cvgConfigGroupName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 709, 1, 1, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32)))
if mibBuilder.loadTexts: cvgConfigGroupName.setStatus('current')
cvgConfigVlansFirst2K = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 709, 1, 1, 1, 2), Cisco2KVlanList()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cvgConfigVlansFirst2K.setStatus('current')
cvgConfigVlansSecond2K = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 709, 1, 1, 1, 3), Cisco2KVlanList()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cvgConfigVlansSecond2K.setStatus('current')
cvgConfigStorageType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 709, 1, 1, 1, 4), StorageType().clone('volatile')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cvgConfigStorageType.setStatus('current')
cvgConfigRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 709, 1, 1, 1, 5), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cvgConfigRowStatus.setStatus('current')
cvgConfigTableSize = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 709, 1, 2), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cvgConfigTableSize.setStatus('current')
ciscoVlanGroupMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 709, 2, 1))
ciscoVlanGroupMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 709, 2, 2))
ciscoVlanGroupMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 709, 2, 1, 1)).setObjects(("CISCO-VLAN-GROUP-MIB", "ciscoVlanGroupConfigGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoVlanGroupMIBCompliance = ciscoVlanGroupMIBCompliance.setStatus('deprecated')
ciscoVlanGroupMIBCompliance2 = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 709, 2, 1, 2)).setObjects(("CISCO-VLAN-GROUP-MIB", "ciscoVlanGroupConfigGroup"), ("CISCO-VLAN-GROUP-MIB", "cvgConfigTableSizeGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoVlanGroupMIBCompliance2 = ciscoVlanGroupMIBCompliance2.setStatus('current')
ciscoVlanGroupConfigGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 709, 2, 2, 1)).setObjects(("CISCO-VLAN-GROUP-MIB", "cvgConfigVlansFirst2K"), ("CISCO-VLAN-GROUP-MIB", "cvgConfigVlansSecond2K"), ("CISCO-VLAN-GROUP-MIB", "cvgConfigRowStatus"), ("CISCO-VLAN-GROUP-MIB", "cvgConfigStorageType"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoVlanGroupConfigGroup = ciscoVlanGroupConfigGroup.setStatus('current')
cvgConfigTableSizeGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 709, 2, 2, 2)).setObjects(("CISCO-VLAN-GROUP-MIB", "cvgConfigTableSize"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cvgConfigTableSizeGroup = cvgConfigTableSizeGroup.setStatus('current')
mibBuilder.exportSymbols("CISCO-VLAN-GROUP-MIB", cvgConfigEntry=cvgConfigEntry, cvgConfigTableSizeGroup=cvgConfigTableSizeGroup, cvgConfigTable=cvgConfigTable, ciscoVlanGroupConfigGroup=ciscoVlanGroupConfigGroup, ciscoVlanGroupMIBNotifs=ciscoVlanGroupMIBNotifs, ciscoVlanGroupMIBGroups=ciscoVlanGroupMIBGroups, cvgConfigGroupName=cvgConfigGroupName, ciscoVlanGroupMIBConform=ciscoVlanGroupMIBConform, ciscoVlanGroupMIBCompliance2=ciscoVlanGroupMIBCompliance2, ciscoVlanGroupMIB=ciscoVlanGroupMIB, ciscoVlanGroupMIBCompliance=ciscoVlanGroupMIBCompliance, PYSNMP_MODULE_ID=ciscoVlanGroupMIB, cvgConfigRowStatus=cvgConfigRowStatus, cvgConfigVlansFirst2K=cvgConfigVlansFirst2K, ciscoVlanGroupMIBCompliances=ciscoVlanGroupMIBCompliances, cvgConfigVlansSecond2K=cvgConfigVlansSecond2K, ciscoVlanGroupMIBObjects=ciscoVlanGroupMIBObjects, cvgConfigTableSize=cvgConfigTableSize, cvgConfigStorageType=cvgConfigStorageType)
|
def hello_world():
print("hello world")
# [REQ-002]
def hello_world_2():
print("hello world")
# [/REQ-002]
|
class Solution:
def solve(self, s, pairs):
letters = set(ascii_lowercase)
leaders = {letter:letter for letter in letters}
followers = {letter:[letter] for letter in letters}
for a,b in pairs:
if leaders[a] == leaders[b]: continue
if len(followers[a]) < len(followers[b]): a,b = b,a
old_leader = leaders[b]
new_leader = leaders[a]
for follower in followers[old_leader]:
leaders[follower] = new_leader
followers[new_leader].append(follower)
followers[old_leader] = []
return all(leaders[s[i]]==leaders[s[~i]] for i in range(len(s)))
|
prompt = "How old are you?"
message = ""
while message != 'quit':
message = input(prompt)
if message != 'quit':
age = int(message)
if age < 3:
print("Free")
elif age < 12:
print("The fare is 10 dollar")
else:
print("The fare is 15 dollar")
|
# Variables
first_name = "Ada"
# print function followed by variable name.
print("Hello,", first_name)
print(first_name, "is learning Python")
# print takes multiple arguments.
print("These", "will be", "joined together by spaces")
# input statement.
first_name = input("What is your first name? ")
print("Hello,", first_name)
|
def extractThehlifestyleCom(item):
'''
Parser for 'thehlifestyle.com'
'''
tstr = str(item['tags']).lower()
if 'review' in tstr:
return None
if 'actors' in tstr:
return None
if 'game' in tstr:
return None
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('The Beloved Imperial Consort translation', 'The Beloved Imperial Consort', 'translated'),
('Good Morning, Miss Undercover Translation', 'Good Morning, Miss Undercover', 'translated'),
('Hilarous Pampered Consort Translation', 'Hilarous Pampered Consort', 'translated'),
('PRC', 'PRC', 'translated'),
('Loiterous', 'Loiterous', 'oel'),
]
for tagname, name, tl_type in tagmap:
if tagname in item['tags']:
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False
|
# This file is Copyright 2019 Volatility Foundation and licensed under the Volatility Software License 1.0
# which is available at https://www.volatilityfoundation.org/license/vsl-v1.0
#
"""Volatility 3 Linux Constants.
Windows-specific values that aren't found in debug symbols
"""
KERNEL_MODULE_NAMES = ["ntkrnlmp", "ntkrnlpa", "ntkrpamp", "ntoskrnl"]
"""The list of names that kernel modules can have within the windows OS"""
|
"""
This subpackage is intented for low-level extension developers and compiler
developers. Regular user SHOULD NOT use code in this module.
This contains compilable utility functions that can interact directly with
the compiler to implement low-level internal code.
"""
|
'''
Given the root of a binary tree,
check whether it is a mirror of itself (i.e., symmetric around its center).
"""
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following is not:
1
/ \
2 2
\ \
3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.
"""
n1 = Node(1)
n2 = Node(2)
n3 = Node(3)
n1.left = n2
n1.right = n3
'''
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
def dfs(root1, root2):
if root1 == root2 == None: return True
if not root1 or not root2: return False
if root1.val != root2.val: return False
return dfs(root1.left, root2.right) and dfs(root1.right, root2.left)
if not root: return True
return dfs(root.left, root.right)
def isSymmetric_iter_TLE(self, root: Optional[TreeNode]) -> bool:
que = []
ans = True
que.append(root)
if not root:
return ans
if not root.left and not root.right:
return ans
while que:
length = len(que)
val_list = []
for _ in range(length):
root = que.pop(0)
if not root:
val_list.append(None)
else:
val_list.append(root.val)
if root.left:
que.append(root.left)
else:
que.append(None)
if root.right:
que.append(root.right)
else:
que.append(None)
if length == 1:
ans = ans and True
else:
a, b = val_list[:int(length / 2)], val_list[int(length / 2):]
b.reverse()
if a == b:
ans = ans and True
else:
ans = ans and False
return ans
|
# list - список, послідовність елементів
# Ініціалізація змінних типу list
names = ["john", "rob", "bill"]
chars = list("hello")
new_chars = ["h", "e", "l", "l", "o"]
new_users = []
numbers = list(range(1, 11))
# Перевірка типу
print(type(names))
# Перевірка змінної типу list
print("rob" in names)
print(chars == new_chars)
print(len(names))
# Отримання довжини списку
print(len(names))
# Отримання елемента списку за індексом
# першого
print(names[0]) # надрукує рядок "john"
# останнього
print(names[-1]) # надрукує рядок "bill"
# Отримання зрізу списку (елементи з індексом від 1 включно до 5 виключно)
print(numbers[1:5]) # надрукує частину списку (зріз) [2, 3, 4, 5]
# від елементу з індексом 6 до кінця списку
print(numbers[6:]) # надрукує частину списку (зріз) [7, 8, 9, 10]
# від елементу з індексом 6 до останньої літери виключно
print(numbers[6:-1]) # надрукує частину списку (зріз) [7, 8, 9]
# від елементу з індексом 0 до 5 виключно
print(numbers[:5]) # надрукує частину списку (зріз) [1, 2, 3, 4, 5]
# від початку списку до кінця з кроком 2 (0, 2, 4, 6, 8, 10)
print(numbers[:5:2]) # надрукує частину списку
# від кінця списку до початку з кроком -1
print(numbers[-1::-1]) #
# Переглянути усі атрибути типу list
print(dir(list))
print(dir([]))
print(dir(names))
# Переглянути довідку по типу list
print(help(list.append))
print(help([]))
print(help(names))
# Робота з методами типу list
# Порахувати кількість елементів "l"
print(new_chars.count("l"))
# Знайти індекс першої літери "l" з ліва направо
print(new_chars.index("lay"))
# Додавання елементу у кінець списку
print(names)
names.append("jason")
print(names)
# Додавання елементу у вказану позицію
print(names)
names.insert(2, "max")
print(names)
# Заміна елемента у списку
print(names)
names[1] = "brian"
print(names)
# Видалення елементу зі списку
names.remove("brian")
print(names)
# Видалення та повернення елементу зі списку
name = names.pop(3)
print(names)
print(name)
# Поєднання списків методом додавання
sum_chars = chars + new_chars
print(sum_chars)
# Розширення існуючого списку
chars.extend(new_chars)
print(chars)
# Сортування списку
names.sort()
print(names)
# Сортування від більшого до меншого
names.sort(reverse=True)
print(names)
sorted_chars = sorted(chars)
print(sorted_chars)
print(chars)
new_chars.reverse()
print(new_chars)
# Створення неглибокої копії списку
additional_names = ["joey", "bred"]
another_names = additional_names
names.append(additional_names)
copied_names = names.copy()
print(copied_names)
print(id(names))
print(id(copied_names))
print(id(copied_names[-1]))
print(id(additional_names))
additional_names.append("jeremy")
print(additional_names)
print(copied_names[-1])
print(another_names)
# Очищення списку
names.clear()
print(names)
# Робота із вкладеними списками
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
matrix_2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(matrix)
print(matrix[0])
print(matrix[0][0])
print(matrix[1][1])
print(matrix[2][0])
# tuple - кортеж, незмінювана послідовність об'єктів
# Ініціалізація змінних типу tuple
user_statuses = ("active", "inactive", "pending")
new_user_statuses = "active", "inactive", "pending"
statuses = ["active", "inactive", "pending"]
new_statuses = tuple(statuses)
new_chars = tuple(new_chars)
empty = ()
empty_2 = tuple()
print(statuses)
print(new_statuses)
# Переглянути усі атрибути типу tuple
print(dir(tuple))
print(dir(()))
print(dir(new_statuses))
# Переглянути довідку по типу tuple
print(help(tuple))
print(help(()))
print(help(new_statuses))
# Робота з методами типу tuple
# Порахувати кількість елементів "l"
print(new_chars.count("l"))
# Знайти індекс першої літери "l" з ліва направо
print(new_chars.index("l"))
if __name__ == "__main__":
pass
|
""" Definitions used to parse DTED files. """
# Definitions of DTED Record lengths.
UHL_SIZE = 80
DSI_SIZE = 648
ACC_SIZE = 2700
# Definitions of the value DTED uses for void data.
VOID_DATA_VALUE = (-1 << 15) + 1
_UTF8 = "utf-8"
|
#Input
tamanhoArquivo = float(input("Digite o tamanho do arquivo(em MB): "))
velocidadeInternet = float(input("Digite a velocidade de download ou upload (em Mbps): "))
#Algoritmo
velocidadeInternet *= 1024 / 8000
tempoEstimadoInteiro = (tamanhoArquivo / velocidadeInternet) // 60
tempoEstimadoDecimal = (tamanhoArquivo / velocidadeInternet) % 60
#Print
print('O tempo estimado para o download (ou upload) é de {:.0f} minutos e {:.0f} segundos.'.format(tempoEstimadoInteiro, tempoEstimadoDecimal))
|
ATTACK = '-'
SUPPORT = '+'
NEUTRAL = '0'
CRITICAL_SUPPORT = '+!'
CRITICAL_ATTACK = '-!'
WEAK_SUPPORT = '+*'
WEAK_ATTACK = '-*'
NON_SUPPORT = '+~'
NON_ATTACK = '-~'
TRIPOLAR_RELATIONS = [ATTACK, SUPPORT, NEUTRAL]
QUADPOLAR_RELATIONS = [ATTACK, SUPPORT, NEUTRAL, CRITICAL_SUPPORT]
def get_type(val):
if val > 0:
return SUPPORT
elif val < 0:
return ATTACK
else:
return NEUTRAL
def get_relations_set(G, rel=None):
return set([edge for edge in G.edges if rel is None or G.edges[edge]['type'] == rel])
|
# repeating strings
s = "?"
for i in range(4):
print(s, end="")
print()
print(s * 4)
# looping strings
text = "This is an example."
count = 0
for char in text:
# isalpha() returns true if the character is a-z
if char.isalpha():
count += 1
|
CREDENTIALS = {
'username': 'Replace with your WA username',
'password': 'Replace with your WA password (b64)'
}
DEFAULT_RECIPIENTS = ('single-user@s.whatsapp.net', 'group-chat@g.us',)
HOST_NOTIFICATION = '%(emoji)s %(type)s HOST ALERT %(emoji)s\n\n' + \
'Host %(host)s, %(address)s is %(state)s.\n\n' + \
'%(info)s\n\n' + \
'%(time)s'
SERVICE_NOTIFICATION = '%(emoji)s %(type)s SERVICE ALERT %(emoji)s\n\n' + \
'Service %(service)s @ %(host)s, %(address)s is %(state)s.\n\n' + \
'%(info)s\n\n' + \
'%(time)s'
|
'''9. Write a Python program to get the difference between the two lists. '''
def difference_twoLists(lst1, lst2):
lst1 = set(lst1)
lst2 = set(lst2)
return list(lst1 - lst2)
print(difference_twoLists([1, 2, 3, 4], [4, 5, 6, 7]))
print(difference_twoLists([1, 2, 3, 4], [0, 5, 6, 7]))
print(difference_twoLists([1, 2, 3, 4], [3, 5, 6, 7]))
|
'''
module for implementation of
cycle sort
'''
def cycle_sort(arr: list):
writes = 0
for cycleStart in range(0, len(arr) - 1):
item = arr[cycleStart]
pos = cycleStart
for i in range(cycleStart + 1, len(arr)):
if (arr[i] < item):
pos += 1
if (pos == cycleStart):
continue
while (item == arr[pos]):
pos += 1
arr[pos], item = item, arr[pos]
writes += 1
while (pos != cycleStart):
pos = cycleStart
for i in range(cycleStart + 1, len(arr)):
if (arr[i] < item):
pos += 1
while (item == arr[pos]):
pos += 1
arr[pos], item = item, arr[pos]
writes += 1
return arr
'''
PyAlgo
Devansh Singh
'''
|
class Error(Exception):
"""Base class for BMI exceptions"""
pass
class VarNameError(Error):
"""Exception to indicate a bad input/output variable name"""
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
class BMI(object):
def initialize(self, filename):
pass
def run(self, time):
pass
def finalize(self):
pass
def get_input_var_names(self):
pass
def get_output_var_names(self):
pass
def get_var_grid(self, var_name):
pass
def get_var_type(self, var_name):
pass
def get_var_units(self, var_name):
pass
def get_time_step(self):
pass
def get_start_time(self):
pass
def get_current_time(self):
pass
def get_end_time(self):
pass
def get_grid_rank(self, grid_id):
pass
def get_grid_spacing(self, grid_id):
pass
def get_grid_shape(self, grid_id):
pass
def get_grid_x(self, grid_id):
pass
def get_grid_y(self, grid_id):
pass
def get_grid_z(self, grid_id):
pass
def get_grid_connectivity(self, grid_id):
pass
def get_grid_offset(self, grid_id):
pass
|
class Script:
@staticmethod
def main():
cities = ["Albuquerque", "Anaheim", "Anchorage", "Arlington", "Atlanta", "Aurora", "Austin", "Bakersfield", "Baltimore", "Boston", "Buffalo", "Charlotte-Mecklenburg", "Cincinnati", "Cleveland", "Colorado Springs", "Corpus Christi", "Dallas", "Denver", "Detroit", "El Paso", "Fort Wayne", "Fort Worth", "Fresno", "Greensboro", "Henderson", "Houston", "Indianapolis", "Jacksonville", "Jersey City", "Kansas City", "Las Vegas", "Lexington", "Lincoln", "Long Beach", "Los Angeles", "Louisville Metro", "Memphis", "Mesa", "Miami", "Milwaukee", "Minneapolis", "Mobile", "Nashville", "New Orleans", "New York", "Newark", "Oakland", "Oklahoma City", "Omaha", "Philadelphia", "Phoenix", "Pittsburgh", "Plano", "Portland", "Raleigh", "Riverside", "Sacramento", "San Antonio", "San Diego", "San Francisco", "San Jose", "Santa Ana", "Seattle", "St. Louis", "St. Paul", "Stockton", "Tampa", "Toledo", "Tucson", "Tulsa", "Virginia Beach", "Washington", "Wichita"]
first_alb = ((cities[0] if 0 < len(cities) else None) == "Albuquerque")
second_alb = ((cities[1] if 1 < len(cities) else None) == "Albuquerque")
first_last = ((cities[0] if 0 < len(cities) else None) == python_internal_ArrayImpl._get(cities, (len(cities) - 1)))
print(str(first_alb))
print(str(second_alb))
print(str(first_last))
class python_internal_ArrayImpl:
@staticmethod
def _get(x,idx):
if ((idx > -1) and ((idx < len(x)))):
return x[idx]
else:
return None
Script.main()
|
class VendingMachine:
def __init__(self):
self.change = 0
def run(self, raw):
tokens = raw.split(" ")
cmd, params = tokens[0], tokens[1:]
if cmd == "잔돈":
return "잔돈은 %d 원입니다" %self.change
elif cmd == "동전":
coin = params[0]
self.change += coin
return "inserted %d won" %coin
|
"""
Some of the options of the protocol specification
LINE
1-8
PAGE
A-Z (remapped to 0-25)
LEADING
A/a = Immediate (Image will be immediately disappeared)
B/b = Xopen (Image will be disappeared from center and extend to 4 side)
C/c = Curtain UP (Image will be disappeared one line by one line from bottom to top).
D/d = Curtain Down(Image will be disappeared one line by one Line from Top to Bottom
E/e = Scroll Left (Image will be scrolled from Right to Left and disappeared )
F/f = Scroll Right (Image will be scrolled from Right to Left and disappeared)
G/g = Vopen (Image will be disappeared from center to top and Bottom one line by one line)
H/h = Vclose(Image will be disappeared from Top and Bottom to Center one line by one line.)
I/i = Scroll Up(Image will be scrolled from Bottom to Top and disappeared)
J/j = Scroll Down (Image will be scrolled from Bottom to Top and disappeared)
K/k = Hold (Screen will be kept)
"""
def get_message_cmd(
message,
line = '1',
page = 0,
leading = 'E',
method = 'A',
wait = 'C',
lagging = 'E'):
""" returns the command to send a message into a line of a page """
return '<L%s><P%s><F%s><M%s><W%s><F%s>%s' % (
line,
_num_to_code(page),
leading,
method,
wait,
lagging,
message
)
def get_schedule_cmd(pages):
""" returns the command to set the schedule (order) of the pages """
# no support for start date / end date
return '<TA>00010100009912302359' + _nums_to_codestr(pages)
def _num_to_code(n):
# converts 0 -> A, 1 -> B
# using 'A', 'B', 'C' ... for pages is uncomfortable
return chr(ord('A') + n)
def _nums_to_codestr(numbers):
return "".join(map(_num_to_code, numbers))
|
fig, ax = create_map_background()
# Contour 1 - Temperature, dotted
cs2 = ax.contour(lon, lat, tmpk_850.to('degC'), range(-50, 50, 2),
colors='grey', linestyles='dotted', transform=dataproj)
plt.clabel(cs2, fontsize=10, inline=1, inline_spacing=10, fmt='%i',
rightside_up=True, use_clabeltext=True)
# Contour 2
clev850 = np.arange(0, 4000, 30)
cs = ax.contour(lon, lat, hght_850, clev850, colors='k',
linewidths=1.0, linestyles='solid', transform=dataproj)
plt.clabel(cs, fontsize=10, inline=1, inline_spacing=10, fmt='%i',
rightside_up=True, use_clabeltext=True)
# Filled contours - Temperature advection
contours = [-3, -2.2, -2, -1.5, -1, -0.5, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0]
cf = ax.contourf(lon, lat, tmpc_adv_850*3600, contours,
cmap='bwr', extend='both', transform=dataproj)
plt.colorbar(cf, orientation='horizontal', pad=0, aspect=50,
extendrect=True, ticks=contours)
# Vector
ax.barbs(lon, lat, uwnd_850.to('kts').m, vwnd_850.to('kts').m,
regrid_shape=15, transform=dataproj)
# Titles
plt.title('850-hPa Geopotential Heights, Temperature (C), \
Temp Adv (C/h), and Wind Barbs (kts)', loc='left')
plt.title('VALID: {}'.format(vtime), loc='right')
plt.tight_layout()
plt.show()
|
#Ejercicio 01
def binarySearch(arr, valor):
#Dado un arreglo y un elemento
#Busca el elemento dado en el arreglo
inicio = 0
final = len(arr) - 1
while inicio <= final:
medio = (inicio + final) // 2
if arr[medio] == valor:
return True
elif arr[medio] < valor:
inicio = medio + 1
elif arr[medio] > valor:
final = medio -1
return False
arreglo = [2,4,8,9,10,22,25,26,28,29,30,42,45,56]
print(binarySearch(arreglo,22))
print(binarySearch(arreglo,24))
|
# William Thompson (wtt53)
# Software Testing and QA
# Assignment 1: Test Driven Development
# Retirement: Takes current age (int), annual salary (float),
# percent of annual salary saved (float), and savings goal (float)
# and outputs what age savings goal will be met
def calc_retirement(age, salary, percent, goal):
# cast each variable as its proper data type
try:
age = int(age)
salary = float(salary)
percent = float(percent)
goal = float(goal)
except Exception:
return (False)
# check each value to make sure it is in the proper range
if ((age < 15 or age > 99)
or (salary <= 0)
or (percent <= 0)
or (goal <= 0)):
return (False)
# savings from salary without employer's 35%
rawAnnualSavings = salary * (percent / 100)
# total annual savings including employer's 35%
annualSavings = rawAnnualSavings + (rawAnnualSavings * 0.35)
# total savings so far
currentSavings = 0.00
# add annual savings to total savings for each year until age 100
for i in range(age, 100):
currentSavings += annualSavings
if currentSavings >= goal:
return("You will meet your savings goal at age "+str(i))
# Notify user if they will not meet their goal
return("Sorry, your goal won't be met.")
|
"""
this module provides encryption and decryption of strings
"""
_eng_alphabet = [chr(i) for i in range(97, 123)] + [chr(i) for i in range(65, 91)]
_rus_alphabet = [chr(i) for i in range(1072, 1104)] + [chr(i) for i in range(1040, 1072)]
_alphabets = {'en': _eng_alphabet, 'rus': _rus_alphabet}
def _add_encrypted_char(string, original_char, step):
if char.isupper():
required_index = (alphabet.index(char) + step) % (alphabet_len // 2) + (alphabet_len // 2)
encoded_str += alphabet[required_index]
else:
required_index = (alphabet.index(char) + step) % (alphabet_len // 2)
encoded_str += alphabet[required_index]
def encode(original_str, lang='en', step=1):
'''Return the string with encoding chars according the chosen language.
Numbers and other signs do not change.'''
encoded_str = ''
alphabet = _alphabets[lang]
alphabet_len = len(alphabet)
for char in original_str:
if char in alphabet:
add_encrypted_char(original_str, char, step)
else:
encoded_str += char
return encoded_str
def encode_all_lang(original_str, step=1):
'''Return the string with encoding chars.
Numbers and other signs do not change.'''
encoded_str = ''
for char in original_str:
if not char.isalpha():
encoded_str += char
for alphabet in _alphabets.values():
if char in alphabet:
alphabet_len = len(alphabet)
add_encrypted_char(original_str, char, step=step)
return encoded_str
def encode_pro(original_str, lang='en'):
'''Return the string with encoding chars according the chosen language.
Numbers and other signs do not change.
The shift to encode the chars of each word is the length of the word.'''
encoded_str = ''
for word in original_str.split():
encoded_str += encode(word, lang=lang, step=len(word)) + ' '
return encoded_str
def encode_pro_all_lang(original_str):
'''Return the string with encoding chars.
Numbers and other signs do not change.
The shift to encode the chars of each word is the length of the word.'''
encoded_str = ''
for word in original_str.split():
encoded_str += encode_all_lang(word, step=len(word)) + ' '
return encoded_str
def decode(original_str, lang='en', step=1):
'''Return the string with decoding chars according the chosen language.
Numbers and other signs do not change.'''
return encode(original_str, lang=lang, step=-step)
def decode_all_lang(original_str, step=1):
'''Return the string with decoding chars.
Numbers and other signs do not change.'''
return encode_all_lang(original_str, step=-step)
def decode_pro(original_str, lang='en'):
'''Return the string with decoding chars according the chosen language.
Numbers and other signs do not change.
The shift to encode the chars of each word is the length of the word.'''
encoded_str = ''
for word in original_str.split():
encoded_str += encode(word, step=-len(word)) + ' '
return encoded_str
def decode_pro_all_lang(original_str):
'''Return the string with decoding chars according the chosen language.
Numbers and other signs do not change.
The shift to encode the chars of each word is the length of the word.'''
encoded_str = ''
for word in original_str.split():
encoded_str += encode_all_lang(word, step=-len(word)) + ' '
return encoded_str
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.