text stringlengths 37 1.41M |
|---|
import tkinter
from tkinter import ttk
def go(*args): # 处理事件,*args表示可变参数
print(comboxlist.get()) # 打印选中的值
win = tkinter.Tk() # 构造窗体
win.title('网关控制小程序') # 顶层窗口名称
win.geometry("500x300+200+20") # 设置窗口大小
win.resizable(width=True, height=True) # 设置窗口是否可变,宽不可变,高可变,默认为True
comvalue = tkinter.StringVar() # 窗体自带的文本,新建一个值
comboxlist = ttk.Combobox(win, textvariable=comvalue) # 初始化
comboxlist["values"] = ("启动", "停止", "重启")
# comboxlist.current(0) # 选择第一个
comboxlist.bind("<<ComboboxSelected>>", go) # 绑定事件,(下拉列表框被选中时,绑定go()函数)
comboxlist.pack()
win.mainloop() |
# Online Python compiler (interpreter) to run Python online.
# Write Python 3 code in this online editor and run it.
array=[ 4,2,0,1,-94,100]
sorted=False
while(sorted==False):
sorted=True
for j in range(1,len(array)):
if(array[j-1]>array[j]):
temp=array[j-1]
array[j-1]=array[j]
array[j]=temp
sorted=False
print(array) |
"""Dual quaternion operations."""
import numpy as np
from ._utils import check_dual_quaternion
from ._conversions import (screw_parameters_from_dual_quaternion,
dual_quaternion_from_screw_parameters)
from ..rotations import concatenate_quaternions
def dq_conj(dq):
"""Conjugate of dual quaternion.
There are three different conjugates for dual quaternions. The one that we
use here converts (pw, px, py, pz, qw, qx, qy, qz) to
(pw, -px, -py, -pz, -qw, qx, qy, qz). It is a combination of the quaternion
conjugate and the dual number conjugate.
Parameters
----------
dq : array-like, shape (8,)
Unit dual quaternion to represent transform:
(pw, px, py, pz, qw, qx, qy, qz)
Returns
-------
dq_conjugate : array-like, shape (8,)
Conjugate of dual quaternion: (pw, -px, -py, -pz, -qw, qx, qy, qz)
"""
dq = check_dual_quaternion(dq)
return np.r_[dq[0], -dq[1:5], dq[5:]]
def dq_q_conj(dq):
"""Quaternion conjugate of dual quaternion.
There are three different conjugates for dual quaternions. The one that we
use here converts (pw, px, py, pz, qw, qx, qy, qz) to
(pw, -px, -py, -pz, qw, -qx, -qy, -qz). It is the quaternion conjugate
applied to each of the two quaternions.
For unit dual quaternions that represent transformations, this function
is equivalent to the inverse of the corresponding transformation matrix.
Parameters
----------
dq : array-like, shape (8,)
Unit dual quaternion to represent transform:
(pw, px, py, pz, qw, qx, qy, qz)
Returns
-------
dq_q_conjugate : array-like, shape (8,)
Conjugate of dual quaternion: (pw, -px, -py, -pz, qw, -qx, -qy, -qz)
"""
dq = check_dual_quaternion(dq)
return np.r_[dq[0], -dq[1:4], dq[4], -dq[5:]]
def concatenate_dual_quaternions(dq1, dq2):
"""Concatenate dual quaternions.
Suppose we want to apply two extrinsic transforms given by dual
quaternions dq1 and dq2 to a vector v. We can either apply dq2 to v and
then dq1 to the result or we can concatenate dq1 and dq2 and apply the
result to v.
.. warning::
Note that the order of arguments is different than the order in
:func:`concat`.
Parameters
----------
dq1 : array-like, shape (8,)
Dual quaternion to represent transform:
(pw, px, py, pz, qw, qx, qy, qz)
dq2 : array-like, shape (8,)
Dual quaternion to represent transform:
(pw, px, py, pz, qw, qx, qy, qz)
Returns
-------
dq3 : array, shape (8,)
Product of the two dual quaternions:
(pw, px, py, pz, qw, qx, qy, qz)
"""
dq1 = check_dual_quaternion(dq1)
dq2 = check_dual_quaternion(dq2)
real = concatenate_quaternions(dq1[:4], dq2[:4])
dual = (concatenate_quaternions(dq1[:4], dq2[4:]) +
concatenate_quaternions(dq1[4:], dq2[:4]))
return np.hstack((real, dual))
def dq_prod_vector(dq, v):
"""Apply transform represented by a dual quaternion to a vector.
Parameters
----------
dq : array-like, shape (8,)
Unit dual quaternion to represent transform:
(pw, px, py, pz, qw, qx, qy, qz)
v : array-like, shape (3,)
3d vector
Returns
-------
w : array, shape (3,)
3d vector
"""
dq = check_dual_quaternion(dq)
v_dq = np.r_[1, 0, 0, 0, 0, v]
v_dq_transformed = concatenate_dual_quaternions(
concatenate_dual_quaternions(dq, v_dq),
dq_conj(dq))
return v_dq_transformed[5:]
def dual_quaternion_sclerp(start, end, t):
"""Screw linear interpolation (ScLERP) for dual quaternions.
Although linear interpolation of dual quaternions is possible, this does
not result in constant velocities. If you want to generate interpolations
with constant velocity, you have to use ScLERP.
Parameters
----------
start : array-like, shape (8,)
Unit dual quaternion to represent start pose:
(pw, px, py, pz, qw, qx, qy, qz)
end : array-like, shape (8,)
Unit dual quaternion to represent end pose:
(pw, px, py, pz, qw, qx, qy, qz)
t : float in [0, 1]
Position between start and goal
Returns
-------
a : array, shape (8,)
Interpolated unit dual quaternion: (pw, px, py, pz, qw, qx, qy, qz)
References
----------
Kavan, Collins, O'Sullivan, Zara: Dual Quaternions for Rigid Transformation
Blending (2006), Technical report, Trinity College Dublin,
https://users.cs.utah.edu/~ladislav/kavan06dual/kavan06dual.pdf
"""
start = check_dual_quaternion(start)
end = check_dual_quaternion(end)
diff = concatenate_dual_quaternions(dq_q_conj(start), end)
return concatenate_dual_quaternions(start, dual_quaternion_power(diff, t))
def dual_quaternion_power(dq, t):
r"""Compute power of unit dual quaternion with respect to scalar.
.. math::
(p + \epsilon q)^t
Parameters
----------
dq : array-like, shape (8,)
Unit dual quaternion to represent transform:
(pw, px, py, pz, qw, qx, qy, qz)
t : float
Exponent
Returns
-------
dq_t : array-like, shape (8,)
Unit dual quaternion to represent transform:
(pw, px, py, pz, qw, qx, qy, qz) ** t
"""
dq = check_dual_quaternion(dq)
q, s_axis, h, theta = screw_parameters_from_dual_quaternion(dq)
return dual_quaternion_from_screw_parameters(q, s_axis, h, theta * t)
|
"""Utility functions for rotations."""
import warnings
import math
import numpy as np
from ._constants import unitz, eps, two_pi
def norm_vector(v):
"""Normalize vector.
Parameters
----------
v : array-like, shape (n,)
nd vector
Returns
-------
u : array, shape (n,)
nd unit vector with norm 1 or the zero vector
"""
norm = np.linalg.norm(v)
if norm == 0.0:
return v
return np.asarray(v) / norm
def norm_matrix(R):
"""Orthonormalize rotation matrix.
Parameters
----------
R : array-like, shape (3, 3)
Rotation matrix with small numerical errors
Returns
-------
R : array, shape (3, 3)
Normalized rotation matrix
"""
R = np.asarray(R)
c2 = R[:, 1]
c3 = norm_vector(R[:, 2])
c1 = norm_vector(np.cross(c2, c3))
c2 = norm_vector(np.cross(c3, c1))
return np.column_stack((c1, c2, c3))
def norm_angle(a):
"""Normalize angle to (-pi, pi].
It is worth noting that using `numpy.ceil` to normalize angles will lose
more digits of precision as angles going larger but can keep more digits
of precision when angles are around zero. In common use cases, for example,
-10.0*pi to 10.0*pi, it performs well.
For more discussions on numerical precision:
https://github.com/dfki-ric/pytransform3d/pull/263
Parameters
----------
a : float or array-like, shape (n,)
Angle(s) in radians
Returns
-------
a_norm : float or array-like, shape (n,)
Normalized angle(s) in radians
"""
a = np.asarray(a, dtype=np.float64)
return (a - (np.ceil((a + np.pi) / two_pi) - 1.0) * two_pi)
def norm_axis_angle(a):
"""Normalize axis-angle representation.
Parameters
----------
a : array-like, shape (4,)
Axis of rotation and rotation angle: (x, y, z, angle)
Returns
-------
a : array-like, shape (4,)
Axis of rotation and rotation angle: (x, y, z, angle). The length
of the axis vector is 1 and the angle is in [0, pi). No rotation
is represented by [1, 0, 0, 0].
"""
angle = a[3]
norm = np.linalg.norm(a[:3])
if angle == 0.0 or norm == 0.0:
return np.array([1.0, 0.0, 0.0, 0.0])
res = np.empty(4)
res[:3] = a[:3] / norm
angle = norm_angle(angle)
if angle < 0.0:
angle *= -1.0
res[:3] *= -1.0
res[3] = angle
return res
def norm_compact_axis_angle(a):
"""Normalize compact axis-angle representation.
Parameters
----------
a : array-like, shape (3,)
Axis of rotation and rotation angle: angle * (x, y, z)
Returns
-------
a : array-like, shape (3,)
Axis of rotation and rotation angle: angle * (x, y, z).
The angle is in [0, pi). No rotation is represented by [0, 0, 0].
"""
angle = np.linalg.norm(a)
if angle == 0.0:
return np.zeros(3)
axis = a / angle
return axis * norm_angle(angle)
def perpendicular_to_vectors(a, b):
"""Compute perpendicular vector to two other vectors.
Parameters
----------
a : array-like, shape (3,)
3d vector
b : array-like, shape (3,)
3d vector
Returns
-------
c : array-like, shape (3,)
3d vector that is orthogonal to a and b
"""
return np.cross(a, b)
def perpendicular_to_vector(a):
"""Compute perpendicular vector to one other vector.
There is an infinite number of solutions to this problem. Thus, we
restrict the solutions to [1, 0, z] and return [0, 0, 1] if the
z component of a is 0.
Parameters
----------
a : array-like, shape (3,)
3d vector
Returns
-------
b : array-like, shape (3,)
A 3d vector that is orthogonal to a. It does not necessarily have
unit length.
"""
if abs(a[2]) < eps:
return np.copy(unitz)
# Now that we solved the problem for [x, y, 0], we can solve it for all
# other vectors by restricting solutions to [1, 0, z] and find z.
# The dot product of orthogonal vectors is 0, thus
# a[0] * 1 + a[1] * 0 + a[2] * z == 0 or -a[0] / a[2] = z
return np.array([1.0, 0.0, -a[0] / a[2]])
def angle_between_vectors(a, b, fast=False):
"""Compute angle between two vectors.
Parameters
----------
a : array-like, shape (n,)
nd vector
b : array-like, shape (n,)
nd vector
fast : bool, optional (default: False)
Use fast implementation instead of numerically stable solution
Returns
-------
angle : float
Angle between a and b
"""
if len(a) != 3 or fast:
return np.arccos(
np.clip(np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b)),
-1.0, 1.0))
return np.arctan2(np.linalg.norm(np.cross(a, b)), np.dot(a, b))
def vector_projection(a, b):
"""Orthogonal projection of vector a on vector b.
Parameters
----------
a : array-like, shape (3,)
Vector a that will be projected on vector b
b : array-like, shape (3,)
Vector b on which vector a will be projected
Returns
-------
a_on_b : array, shape (3,)
Vector a
"""
b_norm_squared = np.dot(b, b)
if b_norm_squared == 0.0:
return np.zeros(3)
return np.dot(a, b) * b / b_norm_squared
def plane_basis_from_normal(plane_normal):
"""Compute two basis vectors of a plane from the plane's normal vector.
Note that there are infinitely many solutions because any rotation of the
basis vectors about the normal is also a solution. This function
deterministically picks one of the solutions.
The two basis vectors of the plane together with the normal form an
orthonormal basis in 3D space and could be used as columns to form a
rotation matrix.
Parameters
----------
plane_normal : array-like, shape (3,)
Plane normal of unit length.
Returns
-------
x_axis : array, shape (3,)
x-axis of the plane.
y_axis : array, shape (3,)
y-axis of the plane.
"""
if abs(plane_normal[0]) >= abs(plane_normal[1]):
# x or z is the largest magnitude component, swap them
length = math.sqrt(
plane_normal[0] * plane_normal[0]
+ plane_normal[2] * plane_normal[2])
x_axis = np.array([-plane_normal[2] / length, 0.0,
plane_normal[0] / length])
y_axis = np.array([
plane_normal[1] * x_axis[2],
plane_normal[2] * x_axis[0] - plane_normal[0] * x_axis[2],
-plane_normal[1] * x_axis[0]])
else:
# y or z is the largest magnitude component, swap them
length = math.sqrt(plane_normal[1] * plane_normal[1]
+ plane_normal[2] * plane_normal[2])
x_axis = np.array([0.0, plane_normal[2] / length,
-plane_normal[1] / length])
y_axis = np.array([
plane_normal[1] * x_axis[2] - plane_normal[2] * x_axis[1],
-plane_normal[0] * x_axis[2], plane_normal[0] * x_axis[1]])
return x_axis, y_axis
def random_vector(rng=np.random.default_rng(0), n=3):
r"""Generate an nd vector with normally distributed components.
Each component will be sampled from :math:`\mathcal{N}(\mu=0, \sigma=1)`.
Parameters
----------
rng : np.random.Generator, optional (default: random seed 0)
Random number generator
n : int, optional (default: 3)
Number of vector components
Returns
-------
v : array, shape (n,)
Random vector
"""
return rng.standard_normal(size=n)
def random_axis_angle(rng=np.random.default_rng(0)):
r"""Generate random axis-angle.
The angle will be sampled uniformly from the interval :math:`[0, \pi)`
and each component of the rotation axis will be sampled from
:math:`\mathcal{N}(\mu=0, \sigma=1)` and than the axis will be normalized
to length 1.
Parameters
----------
rng : np.random.Generator, optional (default: random seed 0)
Random number generator
Returns
-------
a : array, shape (4,)
Axis of rotation and rotation angle: (x, y, z, angle)
"""
angle = np.pi * rng.random()
a = np.array([0, 0, 0, angle])
a[:3] = norm_vector(rng.standard_normal(size=3))
return a
def random_compact_axis_angle(rng=np.random.default_rng(0)):
r"""Generate random compact axis-angle.
The angle will be sampled uniformly from the interval :math:`[0, \pi)`
and each component of the rotation axis will be sampled from
:math:`\mathcal{N}(\mu=0, \sigma=1)` and then the axis will be normalized
to length 1.
Parameters
----------
rng : np.random.Generator, optional (default: random seed 0)
Random number generator
Returns
-------
a : array, shape (3,)
Axis of rotation and rotation angle: angle * (x, y, z)
"""
a = random_axis_angle(rng)
return a[:3] * a[3]
def random_quaternion(rng=np.random.default_rng(0)):
"""Generate random quaternion.
Parameters
----------
rng : np.random.Generator, optional (default: random seed 0)
Random number generator
Returns
-------
q : array, shape (4,)
Unit quaternion to represent rotation: (w, x, y, z)
"""
return norm_vector(rng.standard_normal(size=4))
def check_skew_symmetric_matrix(V, tolerance=1e-6, strict_check=True):
"""Input validation of a skew-symmetric matrix.
Check whether the transpose of the matrix is its negative:
.. math::
V^T = -V
Parameters
----------
V : array-like, shape (3, 3)
Cross-product matrix
tolerance : float, optional (default: 1e-6)
Tolerance threshold for checks.
strict_check : bool, optional (default: True)
Raise a ValueError if V.T is not numerically close enough to -V.
Otherwise we print a warning.
Returns
-------
V : array, shape (3, 3)
Validated cross-product matrix
Raises
------
ValueError
If input is invalid
"""
V = np.asarray(V, dtype=np.float64)
if V.ndim != 2 or V.shape[0] != 3 or V.shape[1] != 3:
raise ValueError("Expected skew-symmetric matrix with shape (3, 3), "
"got array-like object with shape %s" % (V.shape,))
if not np.allclose(V.T, -V, atol=tolerance):
error_msg = ("Expected skew-symmetric matrix, but it failed the test "
"V.T = %r\n-V = %r" % (V.T, -V))
if strict_check:
raise ValueError(error_msg)
warnings.warn(error_msg)
return V
def check_matrix(R, tolerance=1e-6, strict_check=True):
r"""Input validation of a rotation matrix.
We check whether R multiplied by its inverse is approximately the identity
matrix
.. math::
\boldsymbol{R}\boldsymbol{R}^T = \boldsymbol{I}
and whether the determinant is positive
.. math::
det(\boldsymbol{R}) > 0
Parameters
----------
R : array-like, shape (3, 3)
Rotation matrix
tolerance : float, optional (default: 1e-6)
Tolerance threshold for checks. Default tolerance is the same as in
assert_rotation_matrix(R).
strict_check : bool, optional (default: True)
Raise a ValueError if the rotation matrix is not numerically close
enough to a real rotation matrix. Otherwise we print a warning.
Returns
-------
R : array, shape (3, 3)
Validated rotation matrix
Raises
------
ValueError
If input is invalid
"""
R = np.asarray(R, dtype=np.float64)
if R.ndim != 2 or R.shape[0] != 3 or R.shape[1] != 3:
raise ValueError("Expected rotation matrix with shape (3, 3), got "
"array-like object with shape %s" % (R.shape,))
RRT = np.dot(R, R.T)
if not np.allclose(RRT, np.eye(3), atol=tolerance):
error_msg = ("Expected rotation matrix, but it failed the test "
"for inversion by transposition. np.dot(R, R.T) "
"gives %r" % RRT)
if strict_check:
raise ValueError(error_msg)
warnings.warn(error_msg)
R_det = np.linalg.det(R)
if R_det < 0.0:
error_msg = ("Expected rotation matrix, but it failed the test "
"for the determinant, which should be 1 but is %g; "
"that is, it probably represents a rotoreflection"
% R_det)
if strict_check:
raise ValueError(error_msg)
warnings.warn(error_msg)
return R
def check_axis_angle(a):
"""Input validation of axis-angle representation.
Parameters
----------
a : array-like, shape (4,)
Axis of rotation and rotation angle: (x, y, z, angle)
Returns
-------
a : array, shape (4,)
Validated axis of rotation and rotation angle: (x, y, z, angle)
Raises
------
ValueError
If input is invalid
"""
a = np.asarray(a, dtype=np.float64)
if a.ndim != 1 or a.shape[0] != 4:
raise ValueError("Expected axis and angle in array with shape (4,), "
"got array-like object with shape %s" % (a.shape,))
return norm_axis_angle(a)
def check_compact_axis_angle(a):
"""Input validation of compact axis-angle representation.
Parameters
----------
a : array-like, shape (3,)
Axis of rotation and rotation angle: angle * (x, y, z)
Returns
-------
a : array, shape (3,)
Validated axis of rotation and rotation angle: angle * (x, y, z)
Raises
------
ValueError
If input is invalid
"""
a = np.asarray(a, dtype=np.float64)
if a.ndim != 1 or a.shape[0] != 3:
raise ValueError("Expected axis and angle in array with shape (3,), "
"got array-like object with shape %s" % (a.shape,))
return norm_compact_axis_angle(a)
def check_quaternion(q, unit=True):
"""Input validation of quaternion representation.
Parameters
----------
q : array-like, shape (4,)
Quaternion to represent rotation: (w, x, y, z)
unit : bool, optional (default: True)
Normalize the quaternion so that it is a unit quaternion
Returns
-------
q : array-like, shape (4,)
Validated quaternion to represent rotation: (w, x, y, z)
Raises
------
ValueError
If input is invalid
"""
q = np.asarray(q, dtype=np.float64)
if q.ndim != 1 or q.shape[0] != 4:
raise ValueError("Expected quaternion with shape (4,), got "
"array-like object with shape %s" % (q.shape,))
if unit:
return norm_vector(q)
return q
def check_quaternions(Q, unit=True):
"""Input validation of quaternion representation.
Parameters
----------
Q : array-like, shape (n_steps, 4)
Quaternions to represent rotations: (w, x, y, z)
unit : bool, optional (default: True)
Normalize the quaternions so that they are unit quaternions
Returns
-------
Q : array-like, shape (n_steps, 4)
Validated quaternions to represent rotations: (w, x, y, z)
Raises
------
ValueError
If input is invalid
"""
Q_checked = np.asarray(Q, dtype=np.float64)
if Q_checked.ndim != 2 or Q_checked.shape[1] != 4:
raise ValueError(
"Expected quaternion array with shape (n_steps, 4), got "
"array-like object with shape %s" % (Q_checked.shape,))
if unit:
for i in range(len(Q)):
Q_checked[i] = norm_vector(Q_checked[i])
return Q_checked
def check_rotor(rotor):
"""Input validation of rotor.
Parameters
----------
rotor : array-like, shape (4,)
Rotor: (a, b_yz, b_zx, b_xy)
Returns
-------
rotor : array, shape (4,)
Validated rotor (with unit norm): (a, b_yz, b_zx, b_xy)
Raises
------
ValueError
If input is invalid
"""
rotor = np.asarray(rotor, dtype=np.float64)
if rotor.ndim != 1 or rotor.shape[0] != 4:
raise ValueError("Expected rotor with shape (4,), got "
"array-like object with shape %s" % (rotor.shape,))
return norm_vector(rotor)
def check_mrp(mrp):
"""Input validation of modified Rodrigues parameters.
Parameters
----------
mrp : array-like, shape (3,)
Modified Rodrigues parameters.
Returns
-------
mrp : array, shape (3,)
Validated modified Rodrigues parameters.
Raises
------
ValueError
If input is invalid
"""
mrp = np.asarray(mrp)
if mrp.ndim != 1 or mrp.shape[0] != 3:
raise ValueError(
"Expected modified Rodrigues parameters with shape (3,), got "
"array-like object with shape %s" % (mrp.shape,))
return mrp
|
"""
========================
Plot Straight Line Paths
========================
We will compose a trajectory of multiple straight line paths in exponential
coordinates. This is a demonstration of batch conversion from exponential
coordinates to transformation matrices.
"""
import numpy as np
import matplotlib.pyplot as plt
from pytransform3d.plot_utils import Trajectory, make_3d_axis, remove_frame
from pytransform3d.trajectories import transforms_from_exponential_coordinates
from pytransform3d.transformations import (
exponential_coordinates_from_transform, transform_from)
from pytransform3d.rotations import active_matrix_from_angle
def time_scaling(t, t_max):
"""Linear time scaling."""
return np.asarray(t) / t_max
def straight_line_path(start, goal, s):
"""Compute straight line path in exponential coordinates."""
start = np.asarray(start)
goal = np.asarray(goal)
return (start[np.newaxis] * (1.0 - s)[:, np.newaxis]
+ goal[np.newaxis] * s[:, np.newaxis])
s = time_scaling(np.linspace(0.0, 5.0, 50001), 5.0)
start = transform_from(
R=active_matrix_from_angle(1, -0.4 * np.pi),
p=np.array([-1, -2.5, 0])
)
goal1 = transform_from(
R=active_matrix_from_angle(1, -0.1 * np.pi),
p=np.array([-1, 1, 0])
)
goal2 = transform_from(
R=active_matrix_from_angle(2, -np.pi),
p=np.array([-0.65, -0.75, 0])
)
path1 = straight_line_path(
exponential_coordinates_from_transform(start),
exponential_coordinates_from_transform(goal1),
s
)
path2 = straight_line_path(
exponential_coordinates_from_transform(goal1),
exponential_coordinates_from_transform(goal2),
s
)
H = transforms_from_exponential_coordinates(np.vstack((path1, path2)))
ax = make_3d_axis(1.0)
trajectory = Trajectory(H, n_frames=1000, show_direction=False, s=0.3)
trajectory.add_trajectory(ax)
ax.view_init(azim=-95, elev=70)
ax.set_xlim((-2.2, 1.3))
ax.set_ylim((-2.5, 1))
remove_frame(ax)
plt.show()
|
# Datetime
# Para treinar o uso da biblioteca datetime, execute as funções do código a seguir, tentando prever os seus resultados:
import datetime
d = datetime.date(2001, 9, 11)
tday = datetime.date.today()
print(tday, d)
# datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
tdelta = datetime.timedelta(hours=12)
print(tday + tdelta)
bday = datetime.date(2016, 9, 24)
till_bday = tday - bday
print(till_bday.days)
# strftime - Datetime para String
dt_agora = datetime.datetime.now()
print(dt_agora.strftime('%B %d, %Y'))
# strptime - String para Datetime
dt_str = 'July 24, 2016'
dt = datetime.datetime.strptime(dt_str, '%B %d, %Y')
print(dt)
|
# Dicionario: Um dicionário é uma coleção, assim como as listas e as tuplas. Porém, enquanto as tuplas eram indexadas por um índice, os dicionários são indexados
# por chaves. Todo elemento em um dicionário possui uma chave e um valor. Chaves tipicamente são strings, valores podem ser qualquer tipo de dado.
# Criando um Dicionario:
dados_cidades = {'Nome': 'São Paulo',
'Estado': 'SP',
'area KM': 1521,
'populações_milhoes': 12.18
}
print(dados_cidades)
print()
# Adicionando valores no Dicionario:
dados_cidades['pais'] = 'Brasil'
print(dados_cidades)
print()
# Acessando um valor no dicionario:
print(dados_cidades['Nome'])
print()
# Alterar dados do dicionario:
dados_cidades['area KM'] = 1500
print(dados_cidades)
print()
# Fazendo uma cópia do dicionario:
dados_cidades2 = dados_cidades.copy()
dados_cidades2['Nome'] = 'Santos'
print(dados_cidades)
print(dados_cidades2)
print()
# Atualizando um dicionario:
novos_dados = {
'populações_milhoes': 15,
'Fundação': '25/01/1554'
}
dados_cidades.update(novos_dados)
print(dados_cidades)
print()
# Método get() em um valor que não possui no dicionario, retorna none:
print(dados_cidades.get('Prefeito'))
print()
# Método key() retorna uma lista de chaves de um dicionario ou seja transforma um dicionario em lista:
print(dados_cidades.keys())
print()
# Método values() retorna uma lista de valores de um dicionario ou seja transforma um dicionario em lista:
print(dados_cidades.values())
print()
# Método items() retorna uma lista de tuplas (chave, valor) de um dicionario ou seja transforma um dicionario em lista:
print(dados_cidades.items())
# O dicionário é definido pelos símbolos { e }
dicionario = {}
# O dicionário não possui um "append".
# Adicionamos valores diretamente:
dicionario['cat'] = 'gato'
dicionario['dog'] = 'cachorro'
dicionario['mouse'] = 'rato'
print(dicionario)
print(type(dicionario))
print()
'''
Saída:
{'cat': 'gato', 'dog': 'cachorro', 'mouse': 'rato'}
<class 'dict'>
'''
# Dicionários, assim como as listas, são mutáveis:
dicionario['dog'] = 'cão'
print(dicionario)
print()
# Saída: {'cat': 'gato', 'dog': 'cão', 'mouse': 'rato'}
# Podemos criar o dicionário diretamente também:
dicionario2 = {'Curso': 'Python Pro', 'Linguagem':'Python', 'Módulo':2}
print(dicionario2)
print()
# Saída: {'Curso': 'Python Pro', 'Linguagem': 'Python', 'Módulo': 2}
# Podemos utilizar o operador "in" para verificar se uma chave existe:
if 'cat' in dicionario:
print('cat existe!') # Sim
if 'bird' in dicionario:
print('bird existe!') # Não
if 'gato' in dicionario:
print('gato existe!') # Não
'''
Também podemos utilizar as funções .keys() e .values() para obter listas
com apenas as chaves ou apenas os valores do dicionário.
'''
chaves = dicionario.keys()
print(chaves)
print()
# Saída: dict_keys(['cat', 'dog', 'mouse'])
valores = dicionario.values()
print(valores)
print()
# Saída:dict_values(['gato', 'cão', 'rato'])
# Já a função .items(), retorna uma lista de tuplas (chave, valor) de um dicionário
itens = dicionario.items()
print(itens)
print()
# Saída:dict_items([('cat', 'gato'), ('dog', 'cão'), ('mouse', 'rato')]) |
# Manipulação de Arquivos:
# # Abrir arquivo: 1°) cria uma variavel onde vai receber o retorno do método; 2°) método open() onde passa o parametro o caminho(path) do arquivo se tiver na
# # mesma pasta do projeto entao é so digitar o nome do arquivo; 3°) forma de abertura do arquivo, nesteb exemplo utilizaremos o 'r' de leitura.
# arquivo = open('C:\\Users\\thyci\\PycharmProjects\\Lets_Code\\Lets_code_python\\python_basics', 'r', encoding='utf-8')
# # fazer a leitura do texto do arquivo:
# texto = arquivo.read()
# print(texto)
# # Toda vez que abrir um arquivo ele deve set fechado, para nao dar problemas futuros.7
# arquivo.close()
def leituraArquivo():
'''
-> criada uma variavel chamada de arquivo. Onde arquivo recebe o método ope() e o nome do arquivo como parametro.
-> if (arquivo.mode == 'r'): #Ou seja se o arquivo estiver no mode de leitura 'r'
- > conteudo = arquivo.read() # read() método de leitura. ou seja variavel conteudo recebe variavel arquivo no método de leitura
#OBS: essa maneira é para leitura de arquivos pequenos. Nos casos de leitura de arquivos grandes é na função abaixo.
print(f'Conteudo do arquivo: {conteudo}')
-> arquivo.close() # fechadno o arquivo
:return: sem retorno
'''
arquivo = open('dom_casmurro_cap_1.txt', 'r')
if (arquivo.mode == 'r'):
conteudo = arquivo.read()
print(f'Conteudo do arquivo: {conteudo}')
arquivo.close()
leituraArquivo() |
'''
To delete a file, you must import the OS module, and run its os.remove() function:
'''
import os
#Deleting a file
os.remove("demofile.txt")
#Checking wheather the file exists in directory or not
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")
|
from collections import Counter
inp = input()
hc_hash = {}
for i in inp:
if i not in hc_hash:
hc_hash[i] = 0
hc_hash[i] += 1
print(hc_hash)
values = Counter(hc_hash.values())
print(values)
if len(values) > 2:
print("NO")
elif len(values) == 2:
a, b = values.keys()
t = (values[a] == 1 or values[b] == 1)
x = (abs(a - b) == 1 and t)
y = (a == 1 and values[a] == 1)
z = (b == 1 and values[b] == 1)
if x or y or z:
print("YES")
else:
print("NO")
else:
print("YES")
|
import json
# JSON file
f = open ('data.json', "r")
# Reading from file
data = json.loads(f.read())
# Iterating through the json
# list
for i in data['bmi_details']:
print(i)
# from user response for check the BMI condition
def bmicalculator():
Genter = input("Enter the genter : ")
HeightCM = int(input("Enter your Height in centimeters :"))
WeightKg = int(input("Enter your Weight in kg : "))
bmi = WeightKg / (HeightCM/10 ** 2)
if bmi < 18.4:
print(f"{Genter} is by {bmi} kg/m2 BMI")
print("BMI Category : Underweight")
print("Health risk : Malnutrition risk")
elif bmi == 18.5 - 24.9 :
print(f"{Genter} is Normal weight & Low risk by {bmi} kg/m2 BMI")
print("BMI Category : Overweight")
print("Health risk : Enhanced risk")
elif bmi == 25 - 29.9:
print(f"{Genter} is by {bmi} kg/m2 BMI")
print("BMI Category : Overweight")
print("Health risk : Enhanced risk")
elif bmi == 30 -34.0:
print("f{Genter} is by{bmi} kg/m2 BMI")
print("BMI Category :Moderately obese")
print("Health risk : Medium risk")
elif bmi == 35 - 39.9:
print("f{Genter} is by{bmi} kg/m2 BMI")
print("BMI Category :Severely obese")
print("Health risk : High risk")
else :
print(f"{Genter} is by {bmi} kg/m2 BMI")
print("BMI Category : Very severely obese")
print("Health risk : Very High risk")
if __name__=='__main__':
bmicalculator() |
# Task
# Given a string with a lot of indian phone numbers starting from +91
import re
str = "Hello mere dosto mere pas kuch no. " \
"hain +919425635125, +912534587965 aur batau kya +913265254789, +914587496584 aur +914257865 last wala nahi ana chahiye"
patt = re.compile(r'\b91\d{10}')
matches = patt.finditer(str)
for match in matches:
print(match) |
#Python Morsels
import re
def count_words(sentence):
list_of_words = re.split("[^\w']|\s+", sentence)
dict_words = {}
for word in list_of_words:
if word != "":
if not word in dict_words:
word = word.lower()
dict_words[word] = 1
else:
dict_words[word] += 1
return dict_words |
#Python Morsels
import math
import re
def rounding(grade):
decimal_part = grade - int(grade)
if decimal_part >= 0.5:
grade = math.ceil(grade)
else:
grade = math.floor(grade)
return grade
def percent_to_grade(grade, **ksuffix):
if 'round' in ksuffix and ksuffix['round'] == True:
grade = rounding(grade)
if grade >= 90:
if 'suffix' in ksuffix and ksuffix['suffix'] == True:
if grade >= 97:
return "A+"
elif grade < 93:
return "A-"
return "A"
elif 80 <= grade < 90:
if 'suffix' in ksuffix and ksuffix['suffix'] == True:
if grade >= 87:
return "B+"
elif grade < 83:
return "B-"
return "B"
elif 70 <= grade < 80:
if 'suffix' in ksuffix and ksuffix['suffix'] == True:
if grade >= 77:
return "C+"
elif grade < 73:
return "C-"
return "C"
elif 60 <= grade < 70:
if 'suffix' in ksuffix and ksuffix['suffix'] == True:
if grade >= 67:
return "D+"
elif grade < 63:
return "D-"
return "D"
else:
return "F"
def calculate_gpa(grade_list):
total_value = 0
for value in grade_list:
if value == "A+":
total_value += 4.33
elif value == "A":
total_value += 4.00
elif value == "A-":
total_value += 3.67
elif value == "B+":
total_value += 3.33
elif value == "B":
total_value += 3.00
elif value == "B-":
total_value += 2.67
elif value == "C+":
total_value += 2.33
elif value == "C":
total_value += 2.00
elif value == "C-":
total_value += 1.67
elif value == "D+":
total_value += 1.33
elif value == "D":
total_value += 1.00
elif value == "D-":
total_value += 0.67
elif value == "F":
total_value += 0.00
return total_value/len(grade_list)
print(percent_to_grade(97)) #A
print(percent_to_grade(80)) #B
print(percent_to_grade(60.00001)) #D
print(percent_to_grade(59.9)) #F
print(percent_to_grade(92, suffix=True)) #A-
print(percent_to_grade(98, suffix=True)) #A+
print(percent_to_grade(95, suffix=True)) #A
print(percent_to_grade(100, suffix=True)) #A+
print(percent_to_grade(0, suffix=True)) #F
print(percent_to_grade(89.5, suffix=True, round=True)) #A-
print(percent_to_grade(92.5, suffix=True, round=True)) #A
print(percent_to_grade(72.6, suffix=True)) #C-
print(calculate_gpa(['A', 'B', 'C', 'D', 'F'])) #2.0
print(calculate_gpa(['A-', 'B+', 'C', 'D+', 'F'])) #2.066 |
import random
class InvalidChoice(Exception):
pass
class Choice(class):
""" Describes a question option (choice), its reference code (e.g. Q21a), and the value that
selecting this Choice represents to the test.
"""
def __init__(self, text, code, value):
self.text = text
self.value = value
self.code = code
def select(self):
""" Returns the value of this Choice. """
return self.coded_value
class Question(class):
""" Describes a question and its possible Choices. """
def __init__(self, text, choices):
self.text = text
self.choices = choices
def random_choice(self):
return random.choice(self.choices)
def choose(self, code):
""" Takes the 'code' matching to the desired Choice and returns the 'value' of that Choice. """
for choice in self.choices:
if choice.code == code:
return choice.select()
raise InvalidChoice('Code "%s" does not match a Choice for this Question.' % code)
|
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 24 15:27:59 2020
@author: Li
"""
import math
row_string = ["innermost circle", "second innermost circle", "second outermost circle", "outermost circle"]
col_string = ["5.5 o'clock", "4.5 o'clock", "3.5 o'clock", "2.5 o'clock", "1.5 o'clock", "12.5 o'clock", "11.5 o'clock", "10.5 o'clock", "9.5 o'clock", "8.5 o'clock", "7.5 o'clock", "6.5 o'clock"]
def sample(board):
board[11][0] = 1
board[1][0] = 1
board[2][0] = 1
board[3][0] = 1
board[4][0] = 1
board[0][0] = 1
board[0][1] = 1
board[1][1] = 1
board[2][1] = 1
board[4][1] = 1
board[5][1] = 1
board[2][2] = 1
return
def win_check(matrix):
matrix_check = []
for i in range(12):
matrix_check.append([0] * 4)
for i in range(12):
for j in range(4):
matrix_check[i][j] = matrix[i][j]
row_check = True
for i in range(12):
if matrix_check[i][0] == 1:
for j in range(4):
if matrix_check[i][j] == 0:
row_check = False
if (row_check):
for j in range(4):
matrix_check[i][j] = 0
square_check = True
for i in range(12):
if matrix_check[i][0] == 1:
if matrix_check[i][1] == 0:
square_check = False
if matrix_check[(i+1) % 12][0] == 0:
square_check = False
if matrix_check[(i+1) % 12][1] == 0:
square_check = False
if (square_check):
matrix_check[i][0] = 0
matrix_check[i][1] = 0
matrix_check[(i+1) % 12][0] = 0
matrix_check[(i+1) % 12][1] = 0
clear_check = True
for i in range(12):
for j in range(4):
if matrix_check[i][j] == 1:
clear_check = False
return clear_check
def board_mover(board, no_of_move):
if no_of_move == 0:
return (win_check(board), [0])
for row_move in range(4):
for row_offset in range(12):
movement_code = row_move * 20 + row_offset + 100
result_board = []
for i in range(12):
result_board.append([0] * 4)
for i in range(12):
for j in range(4):
if j == row_move:
result_board[(i+row_offset) % 12][j] = board[i][j]
else:
result_board[i][j] = board[i][j]
result, movement = board_mover(result_board, no_of_move-1)
if (result):
movement.insert(0, movement_code)
return (result, movement)
for col_move in range(6):
for col_offset in range(8):
movement_code = col_move * 10 + col_offset + 200
result_board = []
for i in range(12):
result_board.append([0] * 4)
for i in range(12):
for j in range(4):
if i == col_move:
offset = j + col_offset
idx = i
if offset > 7:
offset = offset % 4
elif offset > 3:
idx = (i + 6) % 12
offset = offset % 4
result_board[idx][offset] = board[i][j]
else:
if ((i+6)%12) == col_move:
offset = j + col_offset
idx = i
if offset > 7:
offset = offset % 4
elif offset > 3:
idx = (i + 6) % 12
offset = offset % 4
result_board[idx][offset] = board[i][j]
else:
result_board[i][j] = board[i][j]
result, movement = board_mover(result_board, no_of_move-1)
if (result):
movement.insert(0, movement_code)
return (result, movement)
return (False, [0])
def main(target_board=None, movement=3):
board = []
for i in range(12):
board.append([0] * 4)
sample(board)
if not (target_board is None):
board = target_board
result, movement = board_mover(board, 3)
if (result):
for move in movement:
if move > 200:
move = move- 200
print("Shift column on " + col_string[(math.floor(move/10))] + " direction by " + str(move % 10) + " tiles outwards.")
elif move > 100:
move = move - 100
print("Rotate " + row_string[math.floor(move/20)] + " by " + str(move % 20) + " tiles anticlockwise.")
|
#day 5 Binary Representation
num=int(input("Enter the Number"))
def bin(i):
if i>1:
bin(i//2)
print(i%2,end=" ")
bin(num)
print()
|
import re
import sys
"""
Assumptions:
all IP addresses are only lowercase alpha characters
TO NOTE: These palindrome functions have been modified from the
originals in palindromes.py - TODO added about consolidating
"""
def check_for_palindromes(strings=[]):
palins = []
for word in strings:
if check_for_palindrome(word):
palins += check_for_palindrome(word)
return palins
# TODO - Move these functions into the `palindromes` file
def check_for_palindrome(word):
"""
For sake of puzzle we consider consecutive letters not a palindrome
e.g. `aaa`
Also we assume palindrome of **three** characters
:return: found three char palindrome or False
"""
palins = []
for i in range(1, len(word)):
# Positive example: `xyx`
# Negative example: `xxx`
try:
# if previous equals next and current isn't same
if word[i-1] == word[i+1] and word[i] != word[i-1]:
# Only append three letter word
palins.append(word[i-1:i+2])
except IndexError:
return palins
return palins
supported_count = 0
# with open(sys.path[0] + '/test_input_2.txt') as file:
with open(sys.path[0] + '/input.txt') as file:
file_data = file.readlines()
for data in file_data:
# Will be lists of all palindromes
outside_ip_palins = []
inside_ip_palins = []
chars = data.rstrip()
# Left-most string (not in brackets)
pre_brk = chars.split('[')[0]
# Strings not in brackets but between bracketed strings
betweens = re.findall('\](.*?)\[', data, re.DOTALL)
post_br_idx = data.rfind(']')
assert post_br_idx > 0
# Right-most string (not in brackets)
post_br = chars[post_br_idx+1:]
# What's in-between brackets
brackets = re.findall('\[(.*?)\]', data, re.DOTALL)
inside_ip_palins = check_for_palindromes(brackets)
outside_ip_palins = check_for_palindromes(betweens)
outside_ip_palins += check_for_palindrome(pre_brk)
outside_ip_palins += check_for_palindrome(post_br)
# Compare palindromes from inside and outside IPs
unsupported = [
not len(inside_ip_palins),
not len(outside_ip_palins),
]
# No palindromes in either
if any(unsupported):
continue
for palin in outside_ip_palins:
if not len(palin):
continue
# Do swapping
word = list(palin)
word[0], word[1], word[2] = word[1], word[0], word[1]
# Check if swapped version inside brackets
if ''.join(word) in inside_ip_palins:
supported_count += 1
# As long as we've found one we can increment, break & move on to next one
break
# Length of valid IPs is `3` for test input
print('Number of IPs supporting SSL is: {}'.format(supported_count))
|
'''
n=input("who are you?")
print("hii",n,"how are you?")
age=int(input("how old are you?"))
print("so you are",age,"good")
'''
'''
# add two numbers type1 prefered
a=int(input(Enter no))
b=int(input(enter second no))
print(a,"+",b,"=",a+b)
'''
# type 2 conventional multiple ip
'''
print("Enter two numbers")
a=int(input())
b=int(input())
print(a,"+",b,"=",a*b)
'''
#1) cal area of rectangle
'''
l=float(input("Enter length"))
b=float(input("enter breadth"))
print("Area of rect is " ,l*b)
'''
#2)accept marks of six sub and cal percent multiple ip so use conventional method
'''
print("Enter marks of six subject")
a=int(input())
b=int(input())
c=int(input())
d=int(input())
e=int(input())
f=int(input())
print("percentage" ,(a+b+c+d+e+f)*100/600)
#print("percentage is" total*0.06)
'''
#3)even oddd
'''
a=int(input("Enter a no"))
if a%2=0:
print
'''
#4) MIN
'''
print("Enter two numbers")
a=int(input())
b=int(input())
print ("min is",min (a,b))
'''
#5) min
'''
print("Enter two numbers")
a=int(input())
b=int(input())
if a<b:
print (a,"is min")
else:
print (b,"is min")
'''
#6)
'''
'''
#7) print in descending order of 2
'''
print("Enter two numbers")
a=int(input())
b=int(input())
if a<b:
print (a,b)
else:
print (b,a)
'''
#
#8)max among 3 nos
'''
print("Enter two numbers")
a=int(input())
b=int(input())
c=int(input())
if a<b<c:
print (c,"is max")
elif a>b>c:
print (a,"is max")
else :
print(b ,"is max")
'''
#9) class
'''
p =float(input("Enter percentage"))
if p>=75:
print("distinction class")
elif 60<=p:
print("first class")
elif 55<=p:
print("higher secondary class")
elif 35<=p :
print("pass class")
else:
print("fail")
'''
#10)while loop 10 to 1
'''
i=10
while i>=1:
print(i)
i-=1
'''
# 1 to n
'''
i=1
print("Enter number")
a=int(input())
while i<=a:
print(i)
i+=1
'''
# a to 1
'''
print("Enter number")
a=int(input())
while a>=1:
print(a)
a-=1
'''
# s to e up
'''
print("Enter two numbers")
s=int(input())
e=int(input())
while s<=e:
print(s)
s+=1
'''
# s to e up and down
'''
print("Enter two numbers")
s=int(input())
e=int(input())
if s<e:
while s<=e :
print(s)
s+=1
else :
while s>=e:
print (s)
s-=1
'''
|
fruits = ['ca', 'at', 'ddd', 'cd', 'ab', 'appl', 'a']
##for i in range(0,15,3):
## print(i)
## print reverse list and reversed text
for i in range(len(fruits)):
index = len(fruits) - i
item = fruits[index - 1];
##print(item)
##print(len(item))
toPrint=''
for b in range(len(item)):
lIndex = len(item) - b - 1
toPrint+=item[lIndex]
print(toPrint)
## hurray
##
##for elem in fruits:
## print(elem)
## if elem == 'appl':
## break
##print('done')
##
##
##
#lists
fruits = ['ca', 'at', 'ddd', 'cd', 'ab',23, 'appl', 'a']
fruits.append('lala') #adding values
print(fruits)
print(fruits)
fruits.insert(2,'lala2')
print(fruits)
fruits.extend(['zz',213])
print(fruits)
ab = fruits.index('appl')
print(ab)
print(fruits[1:4]) # slice
del fruits[1]
print(fruits)
fruits.remove('ab')
print(fruits)
print(fruits.pop())
print(fruits)
print(len(fruits))
#tupple immutable - cant be change only difference
atuple= ('abc',21,'sameer')
print(atuple.index(21))
atpl2 = 12,'ab',21,'ab'
print(atpl2)
print(atpl2.count('ab'))
#loops
fruits = ['ca', 'at', 'ddd', 'cd', 'ab',23, 'appl', 'a']
for elem in fruits:
print(elem)
for it in range(5):
print(fruits[it])
tableNumber = int(input("Enter number:"))
for item in range(1,11):
print(f'{tableNumber} x {item} = {item*tableNumber}')
|
"""
Escribe un programa que nos pida por teclado dos números enteros y que
a continuación muestre en pantalla la suma de los dos números solamente si
son los dos positivos. Si no se cumple que los dos números sean positivos
se visualizará un mensaje indicándolo.
La salida ha de tener el siguiente formato:
“La suma de los dos números es: XXX” o
“No se calcula la suma porque alguno de los números o los dos no son positivos”.
"""
numberOne = int(input("Introduce el primer número:"))
numberTwo = int(input("introduce el segundo número:"))
if numberOne and numberTwo > -1:
print (numberOne + numberTwo)
else:
print ("No se calcula la suma porque alguno de los números o los dos no son positivos")
|
"""
8.Escribe un programa que pida por teclado dos números y que muestre
en pantalla uno de los dos mensajes siguientes en función de los
números leídos:
a) el primer número (valor) es mayor que el segundo(valor)(introduciendo el valor de los números en el mensaje)
b) el primer número (valor) es menor que el segundo (valor;
c) los dos números son iguales (valor).
"""
def comparador(a,b):
if a > b:
print ("%i es mas grande que %i" % (a,b))
elif a == b:
print ("los numeros son iguales:",a)
else:
print ("%i es mas grande que %i" % (b,a))
numberOne = int(input("Por favor introduce el primer número:"))
numberTwo = int(input("Por favor introduce el segundo número:"))
if __name__ == '__main__':
comparador(numberOne,numberTwo)
|
"""
14.Escribe un programa que pida por teclado una cantidad de dinero y que a
continuación muestre la descomposición de dicho importe en el menor número
de billetes y monedas de 100, 50, 20, 10, 5, 2 y 1 euro.
En el caso de que alguna moneda no intervenga en la descomposición no se
tiene que visualizar nada en la pantalla.
Para una cantidad de 2236 euros la salida que generaría el programa sería:
22 billetes de 100 euros
1 billete de 20 euros
1 billete de 10 euros
1 billete de 5 euros
1 moneda de 1 euro
"""
def calc_resto(importe, dinero):
return importe % dinero
def calc_cantidad(importe, dinero):
return importe // dinero
def calc_total_moneda(importe):
moneda = [100, 50, 20, 10, 5, 2, 1]
for elemento in moneda:
if elemento > 2:
print ('%s billetes de %s' % (calc_cantidad(importe,elemento), elemento))
else:
print ('%s monedas de %s' % (calc_cantidad(importe, elemento), elemento))
importe = calc_resto(importe, elemento)
if __name__ == '__main__':
calc_total_moneda(1238) |
"""
10.Modifica el programa anterior para que en vez de mostrar un mensaje genérico
en el caso de que alguno o los dos números sean negativos, escriba una salida
diferenciada para cada una de las situaciones que se puedan producir,
utilizando los siguientes mensajes:
a) No se calcula la suma porque el primer número es negativo.
b) No se calcula la suma porque el segundo número es negativo.
c) No se calcula la suma porque los dos números son negativos.
"""
numberOne = int(input("Introduce el primer número:"))
numberTwo = int(input("introduce el segundo número:"))
if numberOne and numberTwo < 0:
print ("No se calcula la suma porque los dos números son negativos")
elif numberOne < 0:
print ("No se calcula la suma porque el primer número es negativo")
elif numberTwo < 0:
print ("No se calcula la suma porque el segundo número es negativo")
else:
print(numberOne + numberTwo)
|
import pandas as pd
def stat_function():
'''This function take input from user and give output with respect to the input number.
You can select number 1 to read minimum value, number 2 to get maximum value,
number 3 to get mean and mumber 4 for standard deviation.'''
print("Type 1 for minimum value of each column \nType 2 for maximum of each column \nType 3 for mean of each column \nType 4 for standard deviation of each column")
print("*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*")
# read dataset
df = pd.read_csv('iris.csv')
try:
# take input from user
input_value = int(input("Enter number to select: "))
if input_value == 1:
print("You have selected minimum value.")
col1 = round(df.iloc[:,0].min(),2) # use iloc to select all row and column 1 (sepal length) value.
col2 = round(df.iloc[:,1].min(),2) # use iloc to select all row and column 2 (sepal width) value.
col3 = round(df.iloc[:,2].min(),2) # use iloc to select all row and column 3 (petal length) value .
col4 = round(df.iloc[:,3].min(),2) # use iloc to select all row and column 4 (petal width) value.
print("Minimum value of sepal length is {0},sepal width is {1},petal length is {2},petal width is {3}.".format(col1,col2,col3,col4))
elif input_value == 2:
print("You have selected maximum value.")
col1 = round(df.iloc[:,0].max(),2)
col2 = round(df.iloc[:,1].max(),2)
col3 = round(df.iloc[:,2].max(),2)
col4 = round(df.iloc[:,3].max(),2)
print("Maximum value of sepal length is {0},sepal width is {1},petal length is {2},petal width is {3}.".format(col1,col2,col3,col4))
elif input_value == 3:
print("You have selected mean value.")
col1 = round(df.iloc[:,0].mean(),2)
col2 = round(df.iloc[:,1].mean(),2)
col3 = round(df.iloc[:,2].mean(),2)
col4 = round(df.iloc[:,3].mean(),2)
print("Mean of sepal length is {0},sepal width is {1},petal length is {2},petal width is {3}.".format(col1,col2,col3,col4))
elif input_value == 4:
print("You have selected standard deviation value.")
col1 = round(df.iloc[:,0].std(),2)
col2 = round(df.iloc[:,1].std(),2)
col3 = round(df.iloc[:,2].std(),2)
col4 = round(df.iloc[:,3].std(),2)
print("Standard deviation of sepal length is {0},sepal width is {1},petal length is {2},petal width is {3}.".format(col1,col2,col3,col4))
except Exception as e:
print("Exception",e)
stat_function()
|
"""
Summary
---------
Code collection to take collection of csvs and upload to database
Detail
---------
For each exercise:
Load all levels from csvs
For each level, create a hash
See if already exists in database, upload as new entry if not
Create exercise as a list of levels
If exercise is different from everything in DB currently, upload exercise
Note we may have multiple versions of same exercise
When a homework is set, it links to a particular version of an exercise
"""
################################ IMPORTS ###########################################
from pprint import pformat
from hashlib import sha1
import csv, os, datetime, re, collections, json
import mongo as mong
################################ FUNCTIONS ###########################################
def write_structure_to_file(filename, variable_name, dictionary):
"""
Write python dict to a file (used in level tester implementation, not to save to DB)
"""
f = open(filename, 'w')
f.write('{} = {}'.format(variable_name, str(dictionary)))
f.close()
def create_skeleton_fields(filename):
"""
Fill skeleton fields of a dictionary with a csv
"""
output = {}
with open(filename, 'rU') as csvfile:
R = csv.reader(csvfile)
for row in R:
Key = row[0]
Value = row[1]
# Make sure every value is part of a list, even if one item
if Key in output:
output[Key].append(Value)
else:
output[Key] = [Value]
return output
def create_variable_list(filename):
"""
Create a list of dicts, each with variables and answers in
This is ultimately one part of the generator dictionary (one value)
"""
list_of_dicts = []
with open(filename, 'rU') as csvfile:
R = csv.reader(csvfile)
counter = 0
# Each row is a question (except first row)
for row in R:
# First row is headings
if counter==0:
heading = row
# Non first row is actual answers
else:
# Put together a dict for this question
dict_of_vars = {}
i = 0
for value in row:
variable_name = heading[i]
# If wrong answer field, we want to create a mini-dict for wrong answers
if 'wrong' in variable_name:
wrong_var_title = variable_name[0:-3]
if wrong_var_title not in dict_of_vars:
dict_of_vars[wrong_var_title] = {}
dict_of_vars[wrong_var_title][value] = variable_name
# Else we add the value to the dict of variables under the correct name
else:
dict_of_vars[variable_name] = value
i += 1
list_of_dicts.append(dict_of_vars)
counter+=1
return list_of_dicts
def create_level_dict(level_number):
"""
Return a dictionary for a level
"""
level_dict = create_skeleton_fields('skeletons_{}.csv'.format(level_number))
level_dict['variables'] = create_variable_list('variables_{}.csv'.format(level_number))
return level_dict
def create_list_of_levels(dir_path):
"""
Trawl a directory and collect list of level numbers, ordered
Only return those that appear in a list and a skeleton
"""
filenames = os.listdir(dir_path)
skeletons_found, variables_found = [], []
for f in filenames:
skeleton_match = re.match(r'skeletons_(\d+)\.csv', f)
if skeleton_match:
skeletons_found.append(skeleton_match.group(1))
variables_match = re.match(r'variables_(\d+)\.csv', f)
if variables_match:
variables_found.append(variables_match.group(1))
# Check if any skeletons or variables exist without their partner
S_multiset = collections.Counter(skeletons_found)
V_multiset = collections.Counter(variables_found)
overlap = list((S_multiset & V_multiset).elements())
S_remainder = list((S_multiset - V_multiset).elements())
V_remainder = list((V_multiset - S_multiset).elements())
if S_remainder:
print "Warning: Missing the following variables: {}".format(S_remainder)
if V_remainder:
print "Warning: Missing the following skeletons: {}".format(V_remainder)
# Return the overlapping level numbers
return sorted(list(set(overlap)))
def generate_hash(structure):
"""
Generate a sha1 hash of a structure
Note that pformat sorts the level
"""
return str(sha1(pformat(structure)).hexdigest())
def save_hash_and_dict_to_database(_dict, _hash, db_name):
# Check if exists, upload if not
collection = mong.db[db_name]
already_exists = collection.find({"hash": _hash}).count() # either 0 or 1
if not already_exists:
print "Dict appears to be new or modified, uploading new version"
collection.insert({
'hash':_hash,
'dict':_dict,
'upload_time':datetime.datetime.now()
}, check_keys=False)
# TODO: should use insert_one
# but in this case can't do check_keys = False
# Not allowed '.' in key, so 2.9 : ans_1_wrong not allowed for wrong answers
# Need to convert to array of tuples and change logic on exercise html page when checking wrong answers
else:
print "Entry found with hash {} - not uploading new version".format(_hash)
def create_exercise(exercise_name):
"""
Saves exercise and levels to database,
creating a new version if any different to existing
"""
# Shift directory
os.chdir('exercises/{}'.format(exercise_name))
# Create new exercise dictionary
exercise_dict = {
'exercise_name_unique':'Error - information missing',
'exercise_title_visible':'Error - information missing',
'exercise_description_visible':'Error - information missing',
'question_attempts_required':'15',
'level_ids':[]
}
# Open up metadata and fill in for the exercise
with open('exercise_info.csv', 'rU') as csvfile: # TODO, navigate to correct directory
R = csv.reader(csvfile)
for row in R:
Key = row[0]
Value = row[1]
exercise_dict[Key] = Value
# Generate the question numbers to loop through
level_list = create_list_of_levels('.')
# Create each level locally, hash it, save within the new exercise dictionary
for level_number in level_list:
level_dict = create_level_dict(level_number)
level_hash = generate_hash(level_dict)
exercise_dict['level_ids'].append(level_hash)
save_hash_and_dict_to_database(_dict = level_dict, _hash = level_hash, db_name='levels')
# Create exercise hash, upload it if hash doesn't exist
exercise_hash = generate_hash(exercise_dict)
save_hash_and_dict_to_database(_dict = exercise_dict, _hash = exercise_hash, db_name='exercises')
# Shift directory back again
os.chdir('..')
os.chdir('..')
def create_all_exercises():
"""
Loop through folder structure and create an exercise for everything
"""
exercise_folders = os.listdir('exercises')
for name in exercise_folders:
if name[0] != '.': #hidden files:
print "Creating exercise '{}'".format(name)
create_exercise(name)
def delete_all_exercises():
y = raw_input("Are you sure you wish to delete all exercises? Type 'y' to continue: ")
if y != 'y':
print "Cancelling - not deleting anything."
return 0
mong.db['exercises'].remove()
print "Deleted!"
def delete_all_levels():
y = raw_input("Are you sure you wish to delete all levels? Type 'y' to continue: ")
if y != 'y':
print "Cancelling - not deleting anything."
return 0
mong.db['levels'].remove()
print "Deleted!"
################################ CREATE ALL EXERCISES ###########################################
if __name__ == '__main__':
if True:
delete_all_exercises()
delete_all_levels()
create_all_exercises()
|
#Case que separar las variables/constantes de las etiquetas
class VariableOConstante:
#En este diccionario se guardaran todas las variables o constantes
variables = {}
etiquetas = []
etiqfinal={}
i=0
def VarOEtiq(self,sentencia):
#Se mandara a un funcion interna que la procesara la etiqueta
self.Etiqueta(sentencia)
def agregarVariable(self, variable):
self.variables[variable[0]] = variable[1]
def Etiqueta(self,etiqueta):
if (etiqueta != '\x00'):
if ((etiqueta in self.etiquetas) == False):
self.etiquetas.append(etiqueta)
def GettEtiquetas(self):
return self.etiquetas
def GettVariables(self):
return self.variables
def AnadiendoDireccion(self,direccion):
print("self.etiqfinal: "+str(self.etiqfinal))
print("self.i: "+str(self.i))
print("direccion: "+str(direccion))
print("etiquetas[self.i]: "+str(self.etiquetas[self.i]))
self.etiqfinal[self.etiquetas[self.i]]=direccion
self.i=self.i+1
def GettEFinal(self):
return self.etiqfinal |
class Name:
# constructor - instantionation = create an instance of a class
def __init__(self, first, middle, last):
self.first = first
self.middle = middle
self.last = last
# to-string methond
# this def is what is resturned when you call the class on its own
# i.e print(aNme)
def __str__(self):
return self.first + ' ' + self.middle + ' ' + self.last
# this def is what is resturned when you call the class on its own
# i.e print(aNme.functioName())
def lastFirst(self):
return self.last + ', ' + self.first + ' ' + self.middle
def initials(self):
return self.first[0] + self.middle[0] + self.last[0]
aName = Name('Mary', 'Elizabeth', 'Smith')
print(aName)
print(aName.lastFirst())
print(aName.initials())
print("The value of the Name class is " + str(aName))
|
print('This program calculates factorials. What number\'s \
factorial would you like to calculate?')
num = int(input())
fact = 1
if num < 100:
for i in range(1, num + 1):
fact = fact * i
print(str(num) + '! is ' + str(fact) + '.')
else:
print('I\'m a wee computer and can\'t process that high just yet. Bye')
|
# #fpr known sets of data
# # # grades = [71, 81, 77, 84]
# # # # for i in range(len(grades)):
# # # # grades[i] = grades[i] + 5
# # # print(grades)
# # # grades = [grade + 5 for grade in grades]
# # # print(grades)
# # words = ['NOW', 'HELLO', 'IS', 'HOW']
# # print(words)
# # words = [word.lower() for word in words]
# # print(words)
# #
# # list cmp for files
# # #
# # file = open('grade.dat')
# # grades = file.readlines()
# # print(grades)
# # for i in range(len(grades)):
# # grades[i] = grades[i].rstrip()
# grades = [grade.rstrip() for grade in open('grade.dat')]
# print(grades)
# N = range(1,101)
# EN = [x for x in N if x % 2 == 0]
# print(EN)
sent = "here is a sentence of lots of words that are in a single sentence."
words = sent.split(' ')
wlen = [(word, len(word)) for word in words]
for i in wlen:
print(i)
|
def take(num, lyst):
tlist = []
for i in range(0, num, -1):
print(i)
tlist.append(lyst[i])
return tlist
def drop(num, lyst):
dlist = []
for i in range(num, len(lyst), -1):
print(i)
dlist.append(lyst[i])
return dlist
names = ['Ray', 'Martin','Lewis', 'LaBron', 'James']
print(names)
somenames = take(-3, names)
print(somenames)
dnames = drop(3, names)
print(dnames)
|
#!/bin/python3
import math
import os
import random
import re
import sys
from collections import deque
def rotate(lst, x):
x = -x
d = deque(lst)
d.rotate(x)
return d
if __name__ == '__main__':
nd = input().split()
n = int(nd[0])
d = int(nd[1])
a = list(map(int, input().rstrip().split()))
rotatedList = rotate(a,d)
for i in rotatedList:
print(i,end=" ")
|
#DiceGame
import random
import time
roll_again = "YES"
yes_list = ["YES","Y"]
while roll_again in yes_list:
print("\nRolling the dice...")
time.sleep(1)
dice1 = random.randint(1, 6)
dice2 = random.randint(1, 6)
print("The value are :")
print("Dice 1 =", dice1, "\nDice 2 =", dice2)
if dice1 == dice2:
print("=================== # WINNER ! :You rooled a double! # =====================")
else:
print("Keep trying!")
roll_again = input("\nRoll the dice again? (Y/N)").upper()
|
import torch.nn as nn
import torch.nn.functional as F
class ImageClassifier(nn.Module):
def __init__(self):
super(ImageClassifier, self).__init__()
# A convolution layer convolves the input tensors into a more abstract / higher-level representation which help
# to combat overfitting during training which should hopefully yield better results when classifying later on
# For a convolution layer the parameters are respectively:
# 1.) Number of input channels -> RGB (3) | Greyscale (1)
# 2.) Number of output channels -> analogous to the number of hidden neurons in a layer
# 3.) Size of the nxn square convolution "sliding window"
self.conv1 = nn.Conv2d(3, 6, 4)
self.conv2 = nn.Conv2d(6, 15, 4)
# A fully-connected layer is a layer that takes in all the inputs from the layer "before" it in the neural
# network. In this case, we're going to use a Linear Layer which performs a linear transformation to the
# inputs it's receiving from the layers before it. In this case, we're going to perform the linear transform of
# multiplying the inputs from the network by the weight matrix
# The operation we perform here is y = Wx + b -> where x is the input, W is the weight matrix, and b is the bias
self.fc1 = nn.Linear(33135, 64)
self.fc2 = nn.Linear(64, 32)
self.fc3 = nn.Linear(32, 5)
# We only need to define the "forward" operations in our neural network, the "backward" operations where the
# gradients will be computed are automatically computed via autograd which is built-in to the PyTorch library
def forward(self, x):
# After the convolution layer creates a more "abstract" representation of the input, we can use an activation
# function in order to add non-linearity into our network. If all we had is convolution layers without
# interleaved activation functions, our model would always be linear, thus we interleave non-linear activation
# functions between our convolution layer to "learn more" about our network
x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))
x = F.max_pool2d(F.relu(self.conv2(x)), 2)
# -1 means the dimensions are inferred from the other dimensions -> this is just a matrix reshape
x = x.view(-1, self.num_flat_features(x))
# Feed the input through our fully connected layers with non-linear activation functions in between
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
# We could theoretically not have fully-connected layers in our network, because each fully-connected layer
# has an equivalent convolution layer, but it is easier to add fully-connected layers because we can specify
# the number of output neurons (typically the number of classes) more easily, thus we add a fully-connected
# layer at the very end so we get a final num_classes output from our forward operation
x = self.fc3(x)
return x
def num_flat_features(self, x):
size = x.size()[1:]
num_features = 1
for s in size:
num_features *= s
return num_features
|
'''
like a house
HAVC specialist: Type1
Electrician: Type2
new operations
various elements of an existing class hierarchy
'''
import abc
class House: #The class being visited
def accept(self, visitor):
# Trigger the visiting operation!
visitor.visit(self)
def work_on_hvac(self, hvac_specialist):
print(self, "worked on by", hvac_specialist)
def work_on_electricity(self, electrician):
print(self, "worked on by", electrician)
def __str__(self):
return self.__class__.__name__
class Visitor(metaclass=abc.ABCMeta):
def __str__(self):
return self.__class__.__name__
@abc.abstractmethod
def visit(self, house):
pass
class HvacSpecialist(Visitor):
def visit(self, house):
house.work_on_hvac(self)
class Electrician(Visitor):
def visit(self, house):
house.work_on_electricity(self)
hv = HvacSpecialist()
e = Electrician()
home = House()
home.accept(hv)
home.accept(e)
|
num=int(input("enter number"))
for i in range(1,num):
if num%i==0:
print(i)
~
|
a = 5
b = 10
if a > b:
print("Apple is red.")
else:
print("Apple is not red.")
|
clothes = ("t-shirt", "trousers","jeans","shirt")
for x in clothes:
if x == "jeans":
break
print(x)
|
num1 = 20
num2 = 5
quotient = num1 // num2
print("Quotient of a number =" , quotient)
|
""" A program that implements the logic for a Tic-Tac-Toe game
on an arbitrary size square board, e.g. 4x4, 5x5, etc.
author: fizgi
date: 23-Apr-2020
python: v3.8.2
"""
import random
from typing import List
from functions import initializer, print_board, row_checker, col_checker,\
dgn_lr_checker, dgn_rl_checker, result
def initializer():
""" initialize the game values """
size: int = int(input("Enter a number for the board size: "))
board: List[List[str]] = [[random.choice(["X", "O", " "]) for x in range(size)] for y in
range(size)]
return size, board
def print_board(board):
""" print the board """
for row in board:
print(row)
def row_checker(board, size):
""" check rows if there is a winning combination """
for i in range(size):
for j in range(1, size):
if board[i][0] != board[i][j]:
break
else:
yield f"'{board[i][j]}' (Row index: {i})"
def col_checker(board, size):
""" check columns if there is a winning combination """
for i in range(size):
for j in range(1, size):
if board[0][i] != board[j][i]:
break
else:
yield f"'{board[j][i]}' (Col index {i})"
def dgn_lr_checker(board, size):
""" check diagonal left to right if there is a winning combination """
for i in range(0, size):
if board[0][0] != board[i][i]:
break
else:
yield f"'{board[0][0]}' (Diagonal left to right)"
def dgn_rl_checker(board, size):
""" check diagonal right to left if there is a winning combination """
for i, j in zip(range(0, size), reversed(range(0, size))):
if board[0][size - 1] != board[i][j]:
break
else:
yield f"'{board[0][size - 1]}' (Diagonal right to left)"
def result(winner_list):
""" print the result """
try:
print(f"\n\033[4mWinner!! : {winner_list[0]}\033[0m")
if len(winner_list) > 1:
print(f"\n\033[1mThe other winning combination(s):\033[0m")
for winner in winner_list[1:]:
print(winner)
else:
print(f"\n\033[1mNo other winning combination.\033[0m")
except IndexError:
print("\nNo winner!")
size, board = initializer()
winner_list: List[str] = []
print_board(board)
winner_list.extend(list(row_checker(board, size)))
winner_list.extend(list(col_checker(board, size)))
winner_list.extend(list(dgn_lr_checker(board, size)))
winner_list.extend(list(dgn_rl_checker(board, size)))
result(winner_list)
|
# Instructions:
# …… Create a file called comprehensions.py.
# …… Create a list that prompts the user for the names of five people they know.
# Run the provided program. Note that nothing forces you to write the name “properly”—e.g., as “Jane” instead of “jAnE”. You will use list comprehensions to fix this.
# …… First, use list comprehensions to create a new list that contains the lowercase version of each of the names your user provided.
# …… Then, use list comprehensions to create a new list that contains the title-cased versions of each of the names in your lower-cased list.
# Bonuses
# …… Instead of creating a lower-cased list and then a title-cased list, create the title-cased list in a single comprehension.
# Hints
# …… See the documentation for the title method.
names = []
for i in range(5):
names.append(input("put name:"))
print(names)
uppercase = [name.upper() for name in names]
print(uppercase)
lowercase = [name.lower() for name in names]
print(lowercase)
title = [name.title() for name in names]
print(title)
Lower_title= [name.lower().title() for name in names]
print(Lower_title) |
## Counter Controlled Loop ##
counter = 0
while counter < 5:
print counter
counter += 1
## Sentinel Controlled Loop ##
sentinel = ''
while sentinel != "0":
sentinel = input("Enter a number: ")
popup("You entered " + sentinel)
## For Loop ##
for myNum in range(5):
print "For " + str(myNum) |
list1 = []
kolom = input("Masukkan kolom untuk matriks : ")
baris = input("Masukkan baris untuk matriks : ")
i = 0
while (i<int(kolom)):
x = 0
while (x<int(baris)):
list1.append(input("A["+str(i)+"]["+str(x)+"] : "))
x = x + 1
i = i + 1
print ("\n")
print ("Hasil matriks tersebut adalah : ")
print ("\n")
d = 0
a = 1
while (a<=int(kolom)):
print (list1[int(d):d+int(baris)])
d = d + int(baris)
a = a + 1
|
class doubly_linked_list:
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.previous = None
def __init__(self):
self.head = None
def append(self, data):
node = self.Node(data)
if(self.head):
temp = self.head
while(temp.next):
temp = temp.next
temp.next = node
node.previous = temp
else:
self.head = node
def push(self, data):
node = self.Node(data)
if(self.head):
temp = self.head
self.head = node
self.head.next = temp
temp.previous = self.head
else:
self.head = node
def display(self):
temp = self.head
while(temp):
print(temp.data)
temp = temp.next
def pop(self):
if(self.head):
temp = self.head
if(temp.next):
self.head = temp.next
self.head.previous = None
else:
self.head = None
def is_empty(self):
if(self.head):
return False
else:
return True
class driver:
if __name__ == "__main__":
obj = doubly_linked_list()
obj.push(1)
obj.push(2)
obj.push(3)
obj.display()
print('--------------------------------')
obj.append(4)
obj.append(5)
obj.display() |
from collections import deque
def solution(heights):
answer = []
for i in range(len(heights)-1,0,-1):
sent = False
for j in range(i-1,0,-1):
if heights[j] > heights[i]:
sent = True
answer.append(j+1)
break
if sent == False:
answer.append(0)
answer.append(0)
answer = answer[::-1]
return answer
|
from dice import Dice
from random import randrange
class Fuzion(Dice):
def __init__(self):
self.__c_failure = 3
self.__c_success = 18
self.__roll_statistics = []
self.__last_result = 0
self.__margin_of_succ_or_fail = 0
def Rand_method(self, num, sides):
return sum(randrange(sides)+1 for die in range(num))
def Roll(self, num = 3, sides = 6):
self.__dice = self.Rand_method(num, sides)
if self.__dice == self.__c_failure:
#print("critical failure")
failure = self.Rand_method(2, 6)
self.__dice = self.__dice - failure
#if self.__dice < 0:
# self.__dice = 0;
if self.__dice == self.__c_success:
#print("critical success")
#print(self.__dice)
success = self.Rand_method(2, 6)
#print(success)
self.__dice = self.__dice + success
self.__last_result = self.__dice
self.__roll_statistics.append(self.__dice)
return self.__dice
def getStatistics(self):
return self.__roll_statistics
def analyze_statistics(self):
for i in range(60):
a = i
print(int(a), " = ", int(self.__roll_statistics.count(a)))
|
class ngram_mention_extractor(object):
""" Returns all ngrams as a python list"""
def get_mentions(self, query, n = 0):
words = query.split(" ")
if n == 0:
n = len(words)
mentions = []
for length in reversed(range(1, n+1)):
for start_index in range(0, len(words) - length + 1):
mentions.append(" ".join(words[start_index:start_index+length]).lower())
return mentions
if __name__ == "__main__":
extractor = ngram_mention_extractor()
print(extractor.get_mentions("Hello there yoiu bastard")) |
num = int(input('մուտքագրել երկնիշ թիվ՝ '))
print(num//10+num%10)
# #extended version
# while True:
# num = input('Մուտքագրեք երկնիշ թիվ՝ ')
# if len(num)!=2:
# print("Թույլատրվող նիշերի քանակն է ԵՐԿՈՒ:\n")
# else:
# try:
# num = int(num)
# except:
# print("Թույլատրվում են միայն ԹՎԵՐ:\n")
# else:
# print(num//10+num%10)
# break |
num = int(input("enter a nonnegative number: "))
num_str = str(num)
num_str = num_str[-2:]
num_str = int(num_str)
last_two_index = num_str//50*50
num_index = num//50*50
print(num_index+last_two_index) |
def mult(samp_list):
total = 1
for number in samp_list:
total *= number
return total
samp_l = [6, 2, -3, 1, 5]
print(mult(samp_l)) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 31 13:19:42 2019
@author: hoeinnkim
"""
import pandas as pd
df = pd.DataFrame([[15,'남','덕중'],[17,'여','수리']],
index=['호우','헤이'],
columns=['나이','성별','과목'])
print(df)
df.index = ['학생1','학생2']
df.columns = ['연령','남녀','소속']
print(df) |
"""
calc.py
Parser and evaluator for mathematical expressions.
Uses pyparsing to parse. Main function is evaluator().
Heavily modified from the edX calc.py
"""
from __future__ import division
import numbers
import operator
import numpy as np
from pyparsing import (
CaselessLiteral,
Combine,
Forward,
Group,
Literal,
MatchFirst,
Optional,
ParseResults,
Suppress,
Word,
FollowedBy,
ZeroOrMore,
alphanums,
alphas,
nums,
stringEnd,
ParseException
)
class CalcError(Exception):
"""Base class for errors originating in calc.py"""
pass
class UndefinedVariable(CalcError):
"""
Indicate when a student inputs a variable which was not expected.
"""
pass
class UndefinedFunction(CalcError):
"""
Indicate when a student inputs a function which was not expected.
"""
pass
class UnmatchedParentheses(CalcError):
"""
Indicate when a student's input has unmatched parentheses.
"""
pass
class FactorialError(CalcError):
"""
Indicate when factorial is called on a bad input
"""
pass
class CalcZeroDivisionError(CalcError):
"""
Indicates division by zero
"""
class CalcOverflowError(CalcError):
"""
Indicates numerical overflow
"""
class FunctionEvalError(CalcError):
"""
Indicates that something has gone wrong during function evaluation.
"""
class UnableToParse(CalcError):
"""
Indicate when an expression cannot be parsed
"""
pass
# Numpy's default behavior is to raise warnings on div by zero and overflow. Let's change that.
# https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.seterr.html
# https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.seterrcall.html#numpy.seterrcall
def handle_np_floating_errors(err, flag):
"""
Used by np.seterr to handle floating point errors with flag set to 'call'.
"""
if 'divide by zero' in err:
raise ZeroDivisionError
elif 'overflow' in err:
raise OverflowError
elif 'value' in err:
raise ValueError
else: # pragma: no cover
raise Exception(err)
np.seterrcall(handle_np_floating_errors)
np.seterr(divide='call', over='call', invalid='call')
# The following few functions define evaluation actions, which are run on lists
# of results from each parse component. They convert the strings and (previously
# calculated) numbers into the number that component represents.
algebraic = (numbers.Number, np.matrix)
def eval_atom(parse_result):
"""
Return the value wrapped by the atom.
In the case of parenthesis, ignore them.
"""
# Find first number in the list
result = next(k for k in parse_result if isinstance(k, algebraic))
return result
def eval_power(parse_result):
"""
Take a list of numbers and exponentiate them, right to left.
e.g. [ 2, 3, 2 ] -> 2^3^2 = 2^(3^2) -> 512
(not to be interpreted (2^3)^2 = 64)
"""
# `reduce` will go from left to right; reverse the list.
parse_result = reversed(
[k for k in parse_result
if isinstance(k, algebraic)] # Ignore the '^' marks.
)
# Having reversed it, raise `b` to the power of `a`.
def robust_pow(b, a):
try:
# builtin fails for (-4)**0.5, but works better for matrices
return b**a
except ValueError:
# scimath.power is componentwise power on matrices, hence above try
return np.lib.scimath.power(b, a)
power = reduce(lambda a, b: robust_pow(b, a), parse_result)
return power
def eval_parallel(parse_result):
"""
Compute numbers according to the parallel resistors operator.
BTW it is commutative. Its formula is given by
out = 1 / (1/in1 + 1/in2 + ...)
e.g. [ 1, 2 ] -> 2/3
Return NaN if there is a zero among the inputs.
"""
if len(parse_result) == 1:
return parse_result[0]
if 0 in parse_result:
return float('nan')
reciprocals = [1. / e for e in parse_result
if isinstance(e, algebraic)]
return 1. / sum(reciprocals)
def eval_sum(parse_result):
"""
Add the inputs, keeping in mind their sign.
[ 1, '+', 2, '-', 3 ] -> 0
Allow a leading + or -.
"""
total = 0.0
current_op = operator.add
for token in parse_result:
if token == '+':
current_op = operator.add
elif token == '-':
current_op = operator.sub
else:
total = current_op(total, token)
return total
def eval_product(parse_result):
"""
Multiply the inputs.
[ 1, '*', 2, '/', 3 ] -> 0.66
"""
prod = 1.0
current_op = operator.mul
for token in parse_result:
if token == '*':
current_op = operator.mul
elif token == '/':
current_op = operator.truediv
else:
prod = current_op(prod, token)
return prod
class ParserCache(object):
"""Stores the parser trees for formula strings for reuse"""
def __init__(self):
"""Initializes the cache"""
self.cache = {}
def get_parser(self, formula, case_sensitive, suffixes):
"""Get a ParseAugmenter object for a given formula"""
# Check the formula for matching parentheses
count = 0
delta = {
'(': +1,
')': -1
}
for index, char in enumerate(formula):
if char in delta:
count += delta[char]
if count < 0:
msg = "Invalid Input: A closing parenthesis was found after segment " + \
"{}, but there is no matching opening parenthesis before it."
raise UnmatchedParentheses(msg.format(formula[0:index]))
if count > 0:
msg = "Invalid Input: Parentheses are unmatched. " + \
"{} parentheses were opened but never closed."
raise UnmatchedParentheses(msg.format(count))
# Strip out any whitespace, so that two otherwise-equivalent formulas are treated
# the same
stripformula = "".join([char for char in formula if char != " "])
# Construct the key
suffixstr = ""
for key in suffixes:
suffixstr += key
key = (stripformula, case_sensitive, ''.join(sorted(suffixstr)))
# Check if it's in the cache
parser = self.cache.get(key, None)
if parser is not None:
return parser
# It's not, so construct it
parser = ParseAugmenter(stripformula, case_sensitive, suffixes)
try:
parser.parse_algebra()
except ParseException:
msg = "Invalid Input: Could not parse '{}' as a formula"
raise UnableToParse(msg.format(formula))
# Save it for later use before returning it
self.cache[key] = parser
return parser
# The global parser cache
parsercache = ParserCache()
def evaluator(formula, variables, functions, suffixes, case_sensitive=True):
"""
Evaluate an expression; that is, take a string of math and return a float.
-Variables are passed as a dictionary from string to value. They must be
python numbers.
-Unary functions are passed as a dictionary from string to function.
Usage
=====
>>> evaluator("1+1", {}, {}, {}, True)
(2.0, set([]))
>>> evaluator("1+x", {"x": 5}, {}, {}, True)
(6.0, set([]))
>>> evaluator("square(2)", {}, {"square": lambda x: x*x}, {}, True)
(4.0, set(['square']))
>>> evaluator("", {}, {}, {}, True)
(nan, set([]))
"""
if formula is None:
# No need to go further.
return float('nan'), set()
formula = formula.strip()
if formula == "":
# No need to go further.
return float('nan'), set()
# Parse the tree
math_interpreter = parsercache.get_parser(formula, case_sensitive, suffixes)
# If we're not case sensitive, then lower all variables and functions
if not case_sensitive:
# Also make the variables and functions lower case
variables = {key.lower(): value for key, value in variables.iteritems()}
functions = {key.lower(): value for key, value in functions.iteritems()}
# Check the variables and functions
math_interpreter.check_variables(variables, functions)
# Some helper functions...
if case_sensitive:
casify = lambda x: x
else:
casify = lambda x: x.lower() # Lowercase for case insensitive
def eval_number(parse_result):
"""
Create a float out of string parts
Applies suffixes appropriately
e.g. [ '7.13', 'e', '3' ] -> 7130
['5', '%'] -> 0.05
"""
text = "".join(parse_result)
if text[-1] in suffixes:
return float(text[:-1]) * suffixes[text[-1]]
else:
return float(text)
def eval_function(parse_result):
name, arg = parse_result
try:
return functions[casify(name)](arg)
except ZeroDivisionError:
# It would be really nice to tell student the symbolic argument as part of this message,
# but making symbolic argument available would require some nontrivial restructing
msg = ("There was an error evaluating {name}(...). "
"Its input does not seem to be in its domain.").format(name=name)
raise CalcZeroDivisionError(msg)
except OverflowError:
msg = "There was an error evaluating {name}(...). (Numerical overflow).".format(name=name)
raise CalcOverflowError(msg)
except Exception as err: # pylint: disable=W0703
if isinstance(err, ValueError) and 'factorial' in err.message:
# This is thrown when fact() or factorial() is used
# that tests on negative and/or non-integer inputs
# err.message will be: `factorial() only accepts integral values` or
# `factorial() not defined for negative values`
raise FactorialError("Error evaluating factorial() or fact() in input. " +
"These functions can only be used on nonnegative integers.")
else:
# Don't know what this is, or how you want to deal with it
# Call it a domain issue.
msg = ("There was an error evaluating {name}(...). "
"Its input does not seem to be in its domain.").format(name=name)
raise FunctionEvalError(msg)
# Create a recursion to evaluate the tree
evaluate_actions = {
'number': eval_number,
'variable': lambda x: variables[casify(x[0])],
'function': eval_function,
'atom': eval_atom,
'power': eval_power,
'parallel': eval_parallel,
'product': eval_product,
'sum': eval_sum
}
try:
# Return the result of the evaluation, as well as the set of functions used
return math_interpreter.reduce_tree(evaluate_actions), math_interpreter.functions_used
except ZeroDivisionError:
raise CalcZeroDivisionError("Division by zero occurred. Check your input's denominators.")
except OverflowError:
raise CalcOverflowError("Numerical overflow occurred. Does your input contain very large numbers?")
except Exception:
# Don't know what this is, or how you want to deal with it
raise
class ParseAugmenter(object):
"""
Holds the data for a particular parse.
Retains the `math_expr` and `case_sensitive` so they needn't be passed
around method to method.
Eventually holds the parse tree and sets of variables as well.
"""
def __init__(self, math_expr, case_sensitive, suffixes):
"""
Create the ParseAugmenter for a given math expression string.
Do the parsing later, when called like `OBJ.parse_algebra()`.
"""
self.case_sensitive = case_sensitive
self.math_expr = math_expr
self.tree = None
self.variables_used = set()
self.functions_used = set()
self.suffixes = suffixes
def variable_parse_action(self, tokens):
"""
When a variable is recognized, store it in `variables_used`.
"""
self.variables_used.add(tokens[0][0])
def function_parse_action(self, tokens):
"""
When a function is recognized, store it in `functions_used`.
"""
self.functions_used.add(tokens[0][0])
def parse_algebra(self):
"""
Parse an algebraic expression into a tree.
Store a `pyparsing.ParseResult` in `self.tree` with proper groupings to
reflect parenthesis and order of operations. Leave all operators in the
tree and do not parse any strings of numbers into their float versions.
Adding the groups and result names makes the `repr()` of the result
really gross. For debugging, use something like
print OBJ.tree.asXML()
"""
# 0.33 or 7 or .34 or 16.
number_part = Word(nums)
inner_number = (number_part + Optional("." + Optional(number_part))) | ("." + number_part)
# pyparsing allows spaces between tokens--`Combine` prevents that.
inner_number = Combine(inner_number)
# Apply suffixes
number_suffix = MatchFirst(Literal(k) for k in self.suffixes.keys())
# 0.33k or 17
plus_minus = Literal('+') | Literal('-')
number = Group(
Optional(plus_minus) +
inner_number +
Optional(CaselessLiteral("E") + Optional(plus_minus) + number_part) +
Optional(number_suffix)
)
number = number("number")
# Predefine recursive variables.
expr = Forward()
# Handle variables passed in. Variables may be either of two forms:
# 1. front + subscripts + tail
# 2. front + lower_indices + upper_indices + tail
# where:
# front (required):
# starts with alpha, followed by alphanumeric
# subscripts (optional):
# any combination of alphanumeric and underscores
# lower_indices (optional):
# Of form "_{<alaphnumeric>}"
# upper_indices (optional):
# Of form "^{<alaphnumeric>}"
# tail:
# any number of primes
front = Word(alphas, alphanums)
subscripts = Word(alphanums + '_') + ~FollowedBy('{')
lower_indices = Literal("_{") + Word(alphanums) + Literal("}")
upper_indices = Literal("^{") + Word(alphanums) + Literal("}")
tail = ZeroOrMore("'")
inner_varname = Combine(
front +
Optional(
subscripts |
(Optional(lower_indices) + Optional(upper_indices))
) +
tail # optional already by ZeroOrMore
)
varname = Group(inner_varname)("variable")
varname.setParseAction(self.variable_parse_action)
# Same thing for functions
# Allow primes (apostrophes) at the end of function names, useful for
# indicating derivatives. Eg, f'(x), g''(x)
function = Group(inner_varname + Suppress("(") + expr + Suppress(")"))("function")
function.setParseAction(self.function_parse_action)
atom = number | function | varname | "(" + expr + ")"
atom = Group(atom)("atom")
# Do the following in the correct order to preserve order of operation.
pow_term = atom + ZeroOrMore("^" + atom)
pow_term = Group(pow_term)("power")
par_term = pow_term + ZeroOrMore('||' + pow_term) # 5k || 4k
par_term = Group(par_term)("parallel")
prod_term = par_term + ZeroOrMore((Literal('*') | Literal('/')) + par_term) # 7 * 5 / 4
prod_term = Group(prod_term)("product")
sum_term = Optional(plus_minus) + prod_term + ZeroOrMore(plus_minus + prod_term) # -5 + 4 - 3
sum_term = Group(sum_term)("sum")
# Finish the recursion.
expr << sum_term # pylint: disable=pointless-statement
self.tree = (expr + stringEnd).parseString(self.math_expr)[0]
def reduce_tree(self, handle_actions):
"""
Call `handle_actions` recursively on `self.tree` and return result.
`handle_actions` is a dictionary of node names (e.g. 'product', 'sum',
etc&) to functions. These functions are of the following form:
-input: a list of processed child nodes. If it includes any terminal
nodes in the list, they will be given as their processed forms also.
-output: whatever to be passed to the level higher, and what to
return for the final node.
"""
def handle_node(node):
"""
Return the result representing the node, using recursion.
Call the appropriate `handle_action` for this node. As its inputs,
feed it the output of `handle_node` for each child node.
"""
if not isinstance(node, ParseResults):
# Then treat it as a terminal node.
return node
node_name = node.getName()
if node_name not in handle_actions: # pragma: no cover
raise Exception(u"Unknown branch name '{}'".format(node_name))
action = handle_actions[node_name]
handled_kids = [handle_node(k) for k in node]
return action(handled_kids)
# Find the value of the entire tree.
return handle_node(self.tree)
def check_variables(self, valid_variables, valid_functions):
"""
Confirm that all the variables and functions used in the tree are defined.
Otherwise, raise an UndefinedVariable or UndefinedFunction
"""
if self.case_sensitive:
casify = lambda x: x
else:
casify = lambda x: x.lower() # Lowercase for case insens.
# Test if casify(X) is valid, but return the actual bad input (i.e. X)
bad_vars = set(var for var in self.variables_used
if casify(var) not in valid_variables)
if bad_vars:
message = "Invalid Input: {} not permitted in answer as a variable"
varnames = ", ".join(sorted(bad_vars))
raise UndefinedVariable(message.format(varnames))
bad_funcs = set(func for func in self.functions_used
if casify(func) not in valid_functions)
if bad_funcs:
funcnames = ', '.join(sorted(bad_funcs))
message = "Invalid Input: {} not permitted in answer as a function"
# Check to see if there is a corresponding variable name
if any(casify(func) in valid_variables for func in bad_funcs):
message += " (did you forget to use * for multiplication?)"
# Check to see if there is a different case version of the function
caselist = set()
if self.case_sensitive:
for func2 in bad_funcs:
for func1 in valid_functions:
if func2.lower() == func1.lower():
caselist.add(func1)
if len(caselist) > 0:
betternames = ', '.join(sorted(caselist))
message += " (did you mean " + betternames + "?)"
raise UndefinedFunction(message.format(funcnames))
|
#!/usr/bin/env python
# coding: utf-8
# # list
# In[1]:
# list[element1, element2, element3]
# 0 1 2
l1 = [123, 'Bee', 'A.I']
# -3 -2 -1
l1
# In[2]:
#dic[item1, item2, item3]
#item = key:value
d1 = {'id': 2,
'name' : 'Bee',
'course' : 'A.I',
'admission' : '2019-12-15',
'DOB' : '01-01-2000'}
d1
# In[3]:
d1 = {}
d1['id']=1
d1['name']='Bee'
d1['course']='A.I'
d1
# In[ ]:
# Task 1
# store id name and skill in dictionary with input function
info = {} # empty dictionary
user_id = input("Entre your id")
info['id'] = user_id
name = input("Entre your name")
info['name'] = name
skills = 'python' + input("Entre your skills with ',' seprate value")
info['skills'] = skills.split()
info
# In[4]:
# dict[key]
d1 = {'id': 2,
'name' : 'Bee',
'course' : 'A.I',
'admission' : '2019-12-15',
'DOB' : '01-01-2000'}
d1['DOB']
# In[3]:
d1 = {'id': 2,
'name' : 'Bee',
'course' : 'A.I',
'admission' : '2019-12-15',
'DOB' : '01-01-2000'}
d1.clear()
d1
# In[5]:
d1 = {'id': 2,
'name' : 'Bee',
'course' : 'A.I',
'admission' : '2019-12-15',
'DOB' : '01-01-2000'}
d2=d1.copy() # Deep copy
d2["id"] = 5
print(d1)
print(d2)
# In[6]:
d1 = {}
d1['id']=None
d1['name']=None
d1['course']=None
d1
# In[7]:
l1 = ['id','name','course']
print(l1)
d1 = dict.fromkeys(l1)
print(d1)
# In[8]:
d1 = dict.fromkeys(l1,'NA')
print(d1)
# In[10]:
l1 = input("Entry comma seperated value")
l1 = l1.split(",")
print(l1)
# In[ ]:
l1 = input("Entry comma seperated value")
l1 = l1.split(",")
print(l1)
d1 = dict.fromkeys(l1,"NA")
print(d1)
# In[2]:
l1 = ['a','b','c']
l2 = ['x','y','z']
l3 = list(zip(l1,l2))
print(l3)
d1 = dict(l3)
print(d1)
# In[3]:
l1 = input("Entre name")
l1 = l1.split(",")
l2 = input("Entre value")
l2 = l2.split(",")
l3 = list(zip(l1,l2))
d1 = dict(l3)
print(d1)
# In[6]:
print(d1)
print(d1.get('a'))
print(d1.get('s')) #if the key is not present then the error wont be generated- thanks to get function
print(d1.get('h',"value not available"))
# In[8]:
print(d1)
d1.items()
# In[9]:
print(d1)
d1.keys()
# In[10]:
print(d1)
d1.values()
# In[11]:
print(d1)
d1.pop('a') #value
# In[13]:
print(d1)
print(d1.popitem())
# In[14]:
print(d1)
d1.setdefault('b')
# In[17]:
print(d1)
print(d1.setdefault('xyz'))
print(d1.setdefault('mno', 567))
print(d1)
# In[20]:
d1 = {'a':'AA','b':'BB'}
d2 = {'a':'AAAA','c':'CCCC'}
d1.update(d2)
d1
# In[31]:
d1 = {'a':1,
'b':2,
'c':3,
'd':4,
'e':5,
'f':6,
'g':7,
'h':8,
'i':9}
for i,j in sorted(d1.items(),reverse=True):
print(i,j)
# In[35]:
from operator import itemgetter
d1 = {'a':1,
'b':2,
'c':3,
'd':4,
'e':5,
'f':6,
'g':7,
'h':8,
'i':9}
l1 = d1.keys()
l2 = d1.values()
l3 = list(zip(l1,l2))
l3.sort(key=itemgetter(1),reverse=True)
d1 = dict(l3)
print(d1)
# In[36]:
l1 = [('A',0,'Z'),
('B',1,'Y'),
('C',3,'X')]
# In[38]:
def abc(x):
return x[0]
sorted(l1,key=abc)
# In[39]:
def abc(x):
return x[1]
sorted(l1,key=abc)
# In[46]:
d1 = {'a':1,
'b':2,
'c':3,
'd':4}
for k,v in (sorted(d1.items(), key=lambda x:x[1], reverse=True)):
d2[k]=v
print(d2)
# In[ ]:
#list of student one info (id,name,skills)-> then l2,l3,l4...
#press x and all exits
# In[ ]:
lst=[] #simple list to store all studend data
x='' #initialize the exit comand with empty string
while x != 'x':
dict1={}
dict1['ID']=input('Enter ID: ')
dict1['Name']=input('Enter Name: ')
skills=input('Enter your skills') #comma seperated skills
dict1['skills']=skills.split()
lst.append(dict1) #append to lst
x=input('Entre x to exit: ') # if x
lst
# In[ ]:
|
"""Create a Python web crawler"""
#Crawl entire site and gather links
import os
#Each website that is crawled is a separate project (folder)
def createProjectDirectory(directory):
if not os.path.exists(directory):
print 'Creating Project' + directory
os.makedirs(directory)
#Create queue and crawled files (if not created already)
def createDataFiles(projectName, baseURL):
queue = projectName + '/queue.txt'
crawled = projectName + '/crawled.txt'
if not os.path.isfile(queue): #check if the file exist already
write_file(queue, baseURL) #starts at the homepage and starts crawling from there
if not os.path.isfile(crawled):
write_file(crawled, '')
#Create a new file
def write_file(path, data):
f = open(path, 'w')
f.write(data)
f.close()
#Add data onto an existing file
def appendToFile(path,data):
with open(path, 'a') as file: #a mode means append/add onto
file.write(data + '\n')
#Delete the contents of a file
def deleteFileContents(path):
with open(path, 'w'): #do nothing, if a file exists then delete the contents
pass
#convert links and files into a set - Read a file and convert each line to set items
def fileToSet(fileName):
results = set()
with open(fileName, 'r') as f: #'rt' read text-file
for line in f:
results.add(line.replace('\n','')) #deleting the newline part of it
return results
# Iterate through a set, each item will be a new line in the file
def setToFile(links, file):
deleteFileContents(file) #deleting the file, becaue its old data
for link in sorted(links): #loop through links
appendToFile(file, link)
|
#Calculate power by iterative method
def iterPower (base, exp):
'''
base: int or float.
exp: int >= 0
returns: int or float, base^exp
'''
ans = 1
for i in range(exp):
ans *= base
return ans
|
#Importing all math functions from Python's math library
from math import *
# Defining polysum fucntion which calculates the sum of
# area and square of the perimeter of the regular polygon
def polysum (n,s):
'''
n: number of sides of a Polygon
s: length of each side of a Polygon
n and s can be int or float
polysum: sum the area and square of the perimeter of the regular polygon
'''
#Calculating perimeter of polygon
polyPerimeter = n*s
#Caculating area of polygon
polyArea = (0.25*n*s**2)/(tan(pi/n))
#Return the polysum. Rounding it to 4 decimal points.
return round(polyPerimeter**2 + polyArea,4)
|
#following Udemy course: 100 days of code by Angela Yu
import random
print('\n\n----------------Flip a coin------------')
input("If you are ready, type: go\n")
random_int = random.randint(0,1)
if random_int == 0:
print('Heads')
elif random_int == 1:
print('Tails')
else:
print('CHeck your code!')
#---------------------------------------------------------
import random
print('\n\n----------------WHO pays the bill?------------')
names_string = input("Give me everybody's names, separated by a comma followed by a space.\n")
names = names_string.split(", ")
persons = len(names)
x = random.randint(0,(persons-1))
print(f'{names[x]} will be paying the bill today')
#OR shorter, using .choice()
#who = random.choice(names)
#print(f'{who} will be paying the bill today')
#---------------------------------------------------------
print('\n\n----------------TEASURE MAP------------\n')
print('Look, here is your map, you can hide a treasure somewhere here\n')
row1 = ["⬜️","⬜️","⬜️"]
row2 = ["⬜️","⬜️","⬜️"]
row3 = ["⬜️","⬜️","⬜️"]
map = [row1, row2, row3]
print(f"{row1}\n{row2}\n{row3}\n")
position_row = int(input("Where do you want to put the treasure: enter ROW number \n"))
position_column = int(input("Where do you want to put the treasure: enter COLUMN number \n"))
#map[0][1] = ' X'
map[position_column-1][position_row-1] = ' X'
print('\n\nHere you go:\n')
print(f"{row1}\n{row2}\n{row3}\n")
#---------------------------------------------------------
import random
print('\n\n----------------rock paper scissors------------\n')
hands=[
'''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
''',
'''
_______
---' ____)____
______)
_______)
_______)
---.__________)
''',
'''
_______
---' ____)____
______)
__________)
(____)
---.__(___)
''',
]
user=int(input("Ready to play?\n 1 for ROCK\n 2 for PAPER\n 3 for SCISSORS\n When you are ready, enter your choice:\n"))
#prnting your choice
print('*you*:')
if user == 1:
print (hands[0])
elif user == 2:
print (hands[1])
elif user == 3:
print (hands[2])
else:
print ('incorrect entry. Only 1 to 3 is allowed!\n')
#printing computer choice
random_int = random.randint(0,2)
print('*computer*:')
print(hands[random_int])
#printing result:
print('*result*:')
if user == 1:
if random_int == 0:
print('EVEN\nbetter try again')
if random_int == 1:
print('You LOST')
if random_int == 2:
print('You WON')
elif user == 2:
if random_int == 0:
print('You WON')
if random_int == 1:
print('EVEN\nbetter try again')
if random_int == 2:
print('You LOST')
elif user == 3:
if random_int == 0:
print('You LOST')
if random_int == 1:
print('You WON')
if random_int == 2:
print('EVEN\nbetter try again')
'''
-----------------------------------------
another way to work with a list of images:
rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
(____)
---.__(___)
'''
game_images = [rock,paper,scissors]
print(game_images[0])
'''
|
"""
implementation of paper by Sertac Karaman in 2010
http://roboticsproceedings.org/rss06/p34.pdf
"""
import sys, random, math, pygame
from pygame.locals import *
from math import sqrt,cos,sin,atan2
import time
#constants
XDIM = 640
YDIM = 480
WINSIZE = [XDIM, YDIM]
EPSILON = 10.0
NUMNODES = 5000 #samples/iterations
RADIUS = 30.0
TARGET_RADIUS = 200.0
# ===== Dynamic Obstacles =====
"""
For each rectangle obstacle, list with the following:
Start X position (0 starts on left side)
Start Y position (0 starts on top side)
X dimensions of obstacle
Y dimensions of obstacle
"""
# Obstacles
OBS = [[50,50,100,100]]
OBS.append([400,200,100,100])
OBS.append([200,100,100,100])
"""
For each rectangle obstacle, list with the following:
X units to move per tick
Y units to move per tick
X starting direction (1 for right, -1 for left)
Y starting direction (1 for down, -1 for up)
Obstacles will bounce off boder and stay within map
"""
# Motion informatoin
OBS_motion = [[0,10,1,1]]
OBS_motion.append([0,10,1,1])
OBS_motion.append([10,0,1,1])
def dir(obs,obs_motion):
"""
Returns an array to change moving obstacle direction once edge of map is reached
Inputs:
startX: Left-corner X position
startY: Left-corner Y position
lengthX: Length of rectangle
lengthY: Width of rectangle
moveX: Units per tick in X direction
moveY: Units per tick in Y direction
dirX: 1 for left, -1 for right
dirY: 1 for down, -1 for up
Outputs:
[1,1]: Left or top side reached map edge
[-1,-1]: Right or bottom side reached map edge
[1,-1]: Left or bottom side reached map edge
[-1,1]: Right or top side reached map edge
"""
# Input list
startX = obs[0]
startY = obs[1]
lengthX = obs[2]
lengthY = obs[3]
moveX = obs_motion[0]
moveY = obs_motion[1]
dirX = obs_motion[2]
dirY = obs_motion[3]
# Check if obstacle reached edge of map
if (startX + moveX) < 0:
dirX = 1
if (startX + lengthX + moveX) > XDIM:
dirX = -1
if (startY + moveY) < 0:
dirY = 1
if (startY + lengthY + moveY) > YDIM:
dirY = -1
return [dirX,dirY]
def move(obs,obs_motion):
"""
Moves obstacles and returns updated positions
"""
# Input list
startX = obs[0]
startY = obs[1]
lengthX = obs[2]
lengthY = obs[3]
moveX = obs_motion[0]
moveY = obs_motion[1]
# Change direction if obstacle reached end of map
[dirX,dirY] = dir(obs,obs_motion)
startX += moveX*dirX
startY += moveY*dirY
# Output
obs[0] = startX
obs[1] = startY
obs_motion[2] = dirX
obs_motion[3] = dirY
return obs,obs_motion
def obsDraw(pygame, screen):
global white
blue = (0, 0, 255)
for o in OBS:
pygame.draw.rect(screen, blue, o)
def updateObs():
"""
Update moving obstacle location on map
"""
global screen
# Count number of obstacles
numObs = 0
for o in OBS:
numObs += 1 # number of obstacles
# Update moving obstacle position
for i in range(0, numObs):
OBS[i], OBS_motion[i] = move(OBS[i],OBS_motion[i])
screen.fill(white)
pygame.display.update()
class Node:
def __init__(self, xcoord=0, ycoord=0, cost=0, parent=None):
self.x = xcoord
self.y = ycoord
self.cost = cost
self.parent = parent
def obsDraw(pygame, screen):
blue = (0, 0, 255)
for o in OBS:
pygame.draw.rect(screen, blue, o)
def dist(p1, p2):
return sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)
def step_from_to(p1, p2):
if dist(p1, p2) < EPSILON:
return p2
else:
theta = atan2(p2[1] - p1[1], p2[0] - p1[0])
return p1[0] + EPSILON * cos(theta), p1[1] + EPSILON * sin(theta)
def chooseParent(nn, newnode, nodes):
for p in nodes:
if checkIntersect(p, newnode, OBS) and dist([p.x, p.y], [newnode.x, newnode.y]) < RADIUS and p.cost + dist(
[p.x, p.y], [newnode.x, newnode.y]) < nn.cost + dist([nn.x, nn.y], [newnode.x, newnode.y]):
nn = p
newnode.cost = nn.cost + dist([nn.x, nn.y], [newnode.x, newnode.y])
newnode.parent = nn
return newnode, nn
def nearest_neighbor(nodes, q_target):
q_near = nodes[0]
for p in nodes:
if dist([p.x, p.y], [q_target.x, q_target.y]) < dist([q_near.x, q_near.y], [q_target.x, q_target.y]):
q_near = p
return q_near
def ccw(A, B, C):
return (C[1] - A[1]) * (B[0] - A[0]) > (B[1] - A[1]) * (C[0] - A[0])
# Return true if line segments AB and CD intersect
def checkIntersect(nodeA, nodeB, OBS):
A = (nodeA.x, nodeA.y)
B = (nodeB.x, nodeB.y)
for o in OBS:
obs = (o[0], o[1], o[0] + o[2], o[1] + o[3])
C1 = (obs[0], obs[1])
D1 = (obs[0], obs[3])
C2 = (obs[0], obs[1])
D2 = (obs[2], obs[1])
C3 = (obs[2], obs[3])
D3 = (obs[2], obs[1])
C4 = (obs[2], obs[3])
D4 = (obs[0], obs[3])
inst1 = ccw(A, C1, D1) != ccw(B, C1, D1) and ccw(A, B, C1) != ccw(A, B, D1)
inst2 = ccw(A, C2, D2) != ccw(B, C2, D2) and ccw(A, B, C2) != ccw(A, B, D2)
inst3 = ccw(A, C3, D3) != ccw(B, C3, D3) and ccw(A, B, C3) != ccw(A, B, D3)
inst4 = ccw(A, C4, D4) != ccw(B, C4, D4) and ccw(A, B, C4) != ccw(A, B, D4)
if inst1 == False and inst2 == False and inst3 == False and inst4 == False:
# print(A,B)
# input("Press Enter to continue...")
continue
else:
return False
return True
def extend(nodes, screen, black):
rand = Node(random.random() * XDIM, random.random() * YDIM)
nn = nearest_neighbor(nodes, rand)
interpolatedNode = step_from_to([nn.x, nn.y], [rand.x, rand.y])
newnode = Node(interpolatedNode[0], interpolatedNode[1])
if checkIntersect(nn, newnode, OBS):
[newnode, nn] = chooseParent(nn, newnode, nodes)
nodes.append(newnode)
#pygame.draw.line(screen, black, [nn.x, nn.y], [newnode.x, newnode.y])
pygame.display.update()
for e in pygame.event.get():
if e.type == QUIT or (e.type == KEYUP and e.key == K_ESCAPE):
sys.exit("Leaving because you requested it.")
return nodes
def drawPath(nodes, pygame, screen):
last_node = nodes[-1]
start = nodes[0]
red = 255, 10, 10
while last_node != start:
pygame.draw.line(screen, red, [last_node.x, last_node.y], [last_node.parent.x, last_node.parent.y], 5)
last_node = last_node.parent
def main():
pygame.init()
global screen
screen = pygame.display.set_mode(WINSIZE)
pygame.display.set_caption('Bi-directional_RRT_star')
global white
white = 255, 255, 255
black = 20, 20, 40
screen.fill(white)
obsDraw(pygame, screen)
start = Node(0.0, 0.0) # Start in the corner
goal = Node(630.0, 200.0)
start_nodes = []
goal_nodes = []
start_nodes.append(start)
goal_nodes.append(goal)
flag = False
i = 0
start_time = time.time()
while i < NUMNODES and flag != True:
start_nodes = extend(start_nodes, screen, black)
goal_nodes = extend(goal_nodes, screen, black)
q_target = goal_nodes[-1]
# try to connect q_near and q_target if dist is less than a target radius
q_near = nearest_neighbor(start_nodes, q_target)
if (dist([q_target.x, q_target.y], [q_near.x, q_near.y]) < TARGET_RADIUS):
if checkIntersect(q_near, q_target, OBS):
newnode = Node(q_target.x, q_target.y)
[newnode, nn] = chooseParent(q_near, newnode, start_nodes)
start_nodes.append(newnode)
pygame.draw.line(screen, black, [q_near.x, q_near.y], [newnode.x, newnode.y])
flag = True
print("Path found")
break
i += 1
for e in pygame.event.get():
if e.type == QUIT or (e.type == KEYUP and e.key == K_ESCAPE):
sys.exit("Leaving because you requested it.")
if flag == True:
end_time = time.time()
time_taken = end_time - start_time
total_cost = start_nodes[-1].cost + goal_nodes[-1].cost
print("Cost : " + str(total_cost) + ' units')
print("Time Taken : " + str(time_taken) + ' s')
drawPath(start_nodes, pygame, screen)
drawPath(goal_nodes, pygame, screen)
pygame.display.update()
time.sleep(0.01)
# pygame.image.save(screen, "bi_rrt_extend_both.jpg")
else:
print("Path not found. Try increasing the number of iterations")
if __name__ == '__main__':
while True:
main()
updateObs()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
|
#改编了一下这里的20题如下:登陆中国联通网上营业厅 后选择「自助服务」-->「查询」-->「账户余额」,然后输出手机号码和可用额度。
# 参考 http://www.cnblogs.com/LanTianYou/p/6432953.html
from selenium import webdriver
import selenium.webdriver.support.ui as ui
def login_query_10010(username,pwd):
print(username,pwd)
driver=webdriver.PhantomJS()#需要安装PhantomJS,安装方法参考http://www.cnblogs.com/LanTianYou/p/5578621.html
driver.get('http://iservice.10010.com/e4/')
wait=ui.WebDriverWait(driver,30)
login_frame=driver.find_element_by_xpath('html/body/div[5]/div[1]/iframe')
driver.switch_to_frame(login_frame);
wait.until(lambda dr:dr.find_element_by_id('userName').is_displayed())
driver.find_element_by_id('userName').send_keys(username)
driver.find_element_by_id('userPwd').send_keys(pwd)
driver.find_element_by_id('login1').click()
driver.switch_to_default_content()
wait.until(lambda dr:dr.find_element_by_id('menu_query').is_displayed())
driver.find_element_by_id('menu_query').click()
wait.until(lambda dr:dr.find_element_by_id('000100010002').is_displayed())
driver.find_element_by_id('000100010002').click()
wait.until(lambda dr:dr.find_element_by_xpath(".//*[@id='loadPage']/iframe").is_displayed())
account_info_frame=driver.find_element_by_xpath(".//*[@id='loadPage']/iframe")
driver.switch_to_frame(account_info_frame)
wait.until(lambda dr:dr.find_element_by_id('userInfoContent').is_displayed())
wait.until(lambda dr:dr.find_element_by_xpath(".//*[@id='userInfoContent']/dl[3]/dd").is_displayed())
pthone_number=driver.find_element_by_xpath(".//*[@id='userInfoContent']/dl[3]/dd").text
print('电话号码:'+pthone_number)
wait.until(lambda dr:dr.find_element_by_xpath(".//*[@id='userInfoContent']/dl[4]/dd").is_displayed())
available_amount=driver.find_element_by_xpath(".//*[@id='userInfoContent']/dl[4]/dd").text
print('可用余额为:'+available_amount)
if __name__=='__main__':
login_query_10010('186********','********')
|
name = "Gentleman"
print("Hello " + name + " How are you?") #string concatenation
que = "How about you?"
print("Hello " + name + " " + que)
|
n = int(input("Enter n:"))
i = 1
while (i<=n//2+1):
if (i%2==1):
print(i)
i=i+1 |
n = int(input("Enter value of n: "))
i = 1
while (i<=n*2):
if (i%2==0):
print (i)
i=i+1 |
a = 21
b = 7
print(str(a) + " + " + str(b) + " = " + str(a+b)) #addition
print(f"{a} - {b} = {a-b}") #Substraction
print("{} * {} = {}".format(a, b, a*b)) #multiplication
print("{x} / {y} = {div}".format(y=b, x=a, div=a/b)) #Division
print(f"{a} // {b} = {a//b}") #floor divison
print(f"{a} % {b} = {a%b}") #remainder/modulus |
n= int(input("Enter n:"))
for i in range (1,n*2+1,2):
print(i) |
n=int(input("enter a number:"))
if n%400==0:
print("it is a leap year")
elif n%100==0:
print("it is not leap year")
elif n%4==0:
print("it is a leap year")
else:
print("it is not a leap year")
|
class Node:
def __init__(self,data):
self.data=data
self.nxt=None
class LinkedList:
def __init__(self):
self.head=None
def insertatbeg(self,data):
newnode=Node(data)
newnode.nxt=self.head
self.head=newnode
def delete(self):
tmp=self.head
self.head=self.head.nxt
tmp.nxt=None
def printlist(self):
tmp=self.head
while tmp:
print(tmp.data,"==>",end='')
tmp=tmp.nxt
obj=LinkedList()
ch=0
while ch!=4:
print("\n Linked List Implementation \n 1.insertatbeg 2.deletion 3.print 4.exit")
ch=int(input())
if ch==1:
print("enter the data:")
data=input()
obj.insertatbeg(data)
obj.printlist()
elif ch==2:
obj.delete()
obj.printlist()
elif ch==3:
obj.printlist()
else:
print("nothing will happen")
|
str1=str(input("enter a string:"))
a=str1[0:2]
b='Is'
if a==b:
print(str1)
else:
print('Is'+str1)
|
# Created on: 070421
# Author: jasshanK
# Description: Testing pan mechanism of turret
from time import sleep
import pigpio
EN = 6
DIR = 22 # direction GPIO pin
STEP = 27 # step GPIO pin
step = 50
delay = 3000 * (10 ** -6)
CW = 1 # clockwise
CCW = 0 # counter clockwise
yaw = 0 # keep track of relative position of top layer
pi = pigpio.pi()
pi.set_mode(DIR, pigpio.OUTPUT)
pi.set_mode(STEP, pigpio.OUTPUT)
pi.set_mode(EN, pigpio.OUTPUT)
def pan(direction):
# direction of pan
if direction.lower() == "l":
pi.write(DIR, CW)
elif direction.lower() == "r":
pi.write(DIR, CCW)
pi.write(EN, 0)
# stepper moves one rotation
for i in range(step - 1):
pi.write(STEP, 1)
sleep(delay)
pi.write(STEP, 0)
sleep(delay)
pi.write(EN, 1)
try:
while True:
direction = input("Please input direction, l or r. Press enter to continue in previous direction: \n")
pan(direction)
sleep(delay)
except Exception as e:
print(e)
pi.stop()
finally:
pi.write(EN, 1)
pi.stop()
|
print("MENU\n1. Insert a number and ** by 3\n2. Insert 4 IPs to a list and print it\n3. Insert 4 entries to DNS_Dictionary and print it\n4. check if a string is polindrom")
menu_num = int(input("Choose a number between 1 - 4\n"))
if (menu_num == 1):
num = int(input("Choose your number: "))
print ("The new number is: " + str(num**3))
elif (menu_num == 2):
ip_list = []
ip_list.append(input("Enter new IP: "))
ip_list.append(input("Enter new IP: "))
ip_list.append(input("Enter new IP: "))
ip_list.append(input("Enter new IP: "))
print("The IPs you entered are: \n------------\n" + str(ip_list))
elif (menu_num == 3):
dns_dict = {}
dns_dict.update({input("Enter new URL: "): input("Enter its ip: ")})
dns_dict.update({input("Enter new URL: "): input("Enter its ip: ")})
dns_dict.update({input("Enter new URL: "): input("Enter its ip: ")})
dns_dict.update({input("Enter new URL: "): input("Enter its ip: ")})
print("The DNS dictionary is: \n------------\n" + str(dns_dict))
elif(menu_num == 4):
polindrom = input("Enter a string: ")
if (polindrom == polindrom[::-1]):
print("Your string is polindrom")
else:
print("Your string is not polindrom")
else:
print ("Insert a 1-4 number!")
|
#!/usr/bin/env python3
"""
Based off of: http://inst.eecs.berkeley.edu/~cs188/sp09/pacman.html
To run this script, type:
python3 buyLotsOfFruit.py
Once you have correctly implemented the buyLotsOfFruit function,
the script should produce the output:
Cost of [('apples', 2.0), ('pears', 3.0), ('limes', 4.0)] is 12.25
"""
FRUIT_PRICES = {
'apples': 2.00,
'oranges': 1.50,
'pears': 1.75,
'limes': 0.75,
'strawberries': 1.00
}
"""
orderList: List of (fruit, weight) tuples
Returns cost of order
"""
def buyLotsOfFruit(orderList):
# initialized variable to hold total cost
cost = 0
# iterative through the list
for x in orderList:
# if the first elem in each tuple exists in dictionary
if x[0] in FRUIT_PRICES:
# calculates the cost using the price from dict
cost += x[1] * FRUIT_PRICES[x[0]]
# item doesn't exist in dict, prints out error msg and returns none
else:
print("There's an error in your order.")
return None
# returns total cost
return cost
def main():
orderList = [
('apples', 2.0),
('pears', 3.0),
('limes', 4.0)
]
print("Cost of %s is %s." % (orderList, buyLotsOfFruit(orderList)))
if __name__ == '__main__':
main()
|
import os
os.chdir('/Users/Hatim/Desktop/Git Repos/AdventOfCode/Day 5/')
text_file = open('input.txt', 'r')
string = text_file.read().rstrip()
def explosion(string, i):
return string[:i] + string[i+2:]
def reaction(string):
length = len(string)
index = 0
while index < (length - 1):
if index < 0:
index = 0
first = string[index]
second = string[index+1]
if first.lower() == second.lower() and first != second:
string = explosion(string, index)
length -= 2
index -= 2
index += 1
return length
part1 = reaction(string)
part2 = 1e12
alphabets = [chr(i) for i in range(ord('a'),ord('z')+1)]
for alphabet in alphabets:
swaps = {alphabet: '', alphabet.upper(): ''}
string_temp = ''.join(swaps.get(i,i) for i in string)
string_reaction = reaction(string_temp)
part2 = min(part2, string_reaction) |
def prime_number(num):
if (num == 1):
print (1)
elif (num == 0):
print ("input a number larger than 0")
else:
primes = [1]
for i in range(2, num):
for d in range(2, i):
if((i%d) == 0):
break
else:
if(d == (i-1)):
primes.append(i)
print(primes)
prime_number(20)
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
# 0 node in list
if head is None:
return None
# 1 node in list
if head.next is None:
return head
current_node = head
next_node = head.next
# if there's more than 2 nodes in list,
# head node will be the second node in list
head = next_node
# first move
current_node.next = next_node.next
next_node.next = current_node
while current_node.next is not None and current_node.next.next is not None:
previous_node = current_node
current_node = current_node.next
next_node = current_node.next
previous_node.next = next_node
current_node.next = next_node.next
next_node.next = current_node
return head
|
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
is_minus = False
if x < 0:
is_minus = True
answer = ""
x = str(x)
for i in range(len(x)):
if x[len(x) - i - 1] != "-":
answer += x[len(x) - i - 1]
if is_minus:
answer = "-"+answer
answer = int(answer)
if answer > pow(2, 31) - 1 or answer <= -1 * pow(2, 31) :
return 0
return answer |
def addNumber(X,Y):
print(X+Y)
def minusNumber(X,Y):
print(X-Y)
def multiply(X,Y):
print(X*Y)
def divide(X,Y):
print(X/Y)
addNumber(10,20)
minusNumber(20,10)
multiply(20,10)
divide(20,10)
|
def swapFileData():
filename = input("enter the file name: ")
with open(sample1,'r') as a:
data_a = a.read()
with open(sample2,'r') as a:
data_b = b.read
with open(sample1,'w') as a:
a.write(data_b)
with open(sample2,'w') as a:
b.write(data_a)
swapFileData() |
from pymongo import MongoClient
import datetime
ts = datetime.datetime.now().timestamp()
#converting timestamp to proper format
import time
readable = time.ctime(ts)
def insert_data(collection,collection_data): #insert the data in collection
rec_id1 = collection.insert_one(collection_data)
print("Data inserted with record ids",rec_id1)
#rec_id2 = collection.insert_one(temperature2)
#print("Data inserted with record ids",rec_id1," ",rec_id2)
def show_data(collection): #show the data in collection
cursor = collection.find()
for record in cursor:
print(record)
def get_collection_in_database(database_name,collection_name): #Get a particular collection from database
try:
conn = MongoClient() #connect to localhost
print("Connected successfully!!!")
except:
print("Could not connect to MongoDB")
# database
#db = conn.database
db = conn[database_name]
# Created or Switched to collection names: my_temperature_collection
collection = db[collection_name]
return collection
temperature1 = {
"timestamp":readable,
"value":24
}
temperature2 = {
"timestamp":readable,
"value":28
}
database_name="database" #write your database name
collection_name="my_temperature_collection" #collection name
collection=get_collection_in_database(database_name,collection_name) #get your collection for next operations
insert_data(collection,temperature1)
insert_data(collection,temperature2)
show_data(collection)
|
#!/usr/bin/env python
#------------------
# User Instructions
#
# Hopper, Kay, Liskov, Perlis, and Ritchie live on
# different floors of a five-floor apartment building.
#
# Hopper does not live on the top floor.
# Kay does not live on the bottom floor.
# Liskov does not live on either the top or the bottom floor.
# Perlis lives on a higher floor than does Kay.
# Ritchie does not live on a floor adjacent to Liskov's.
# Liskov does not live on a floor adjacent to Kay's.
#
# Where does everyone live?
#
# Write a function floor_puzzle() that returns a list of
# five floor numbers denoting the floor of Hopper, Kay,
# Liskov, Perlis, and Ritchie.
import itertools
def adjacent(a, b):
return abs(a-b)==1
def floor_puzzle():
for hopper, kay, liskov, perlis, ritchie in itertools.permutations([1,2,3,4,5]):
if (hopper is not 5 and
kay is not 1 and
1 < liskov < 5 and
perlis > kay and
not adjacent(ritchie, liskov) and
not adjacent(liskov, kay)):
return [hopper, kay, liskov, perlis, ritchie]
if __name__ == '__main__':
floors = floor_puzzle()
names = ['Hopper', 'Kay', 'Liskov', 'Perlis', 'Ritchie']
for name, floor in zip(names, floors):
print '%s : %d' % (name, floor)
|
def drink(x):
count = x # 喝了多少瓶酒
k1 = x # 多少空瓶子
k2 = x # 多少瓶盖
while k1 >= 3 or k2 >= 7:
while k1 >= 3:
change = k1 // 3
count += change
k1 %= 3
k1 += change
k2 += change
while k2 >= 7:
change = k2 // 7
count += change
k2 %= 7
k1 += change
k2 += change
return count
if __name__ == '__main__':
x_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
for i in x_list:
print(f'x={i}:\t{drink(i)}')
|
#
'''
Class gameProblem, implements simpleai.search.SearchProblem
'''
import simpleai.search
from simpleai.search import SearchProblem, astar
# --------------- GameProblem Definition -----------------
class GameProblem(SearchProblem):
# Object attributes, can be accessed in the methods below
MAP=None
POSITIONS=None
INITIAL_STATE=None
GOAL=None
CONFIG=None
AGENT_START=None
ALGORITHM=None
# --------------- Common functions to a SearchProblem -----------------
def actions(self, state):
'''Returns a LIST of the actions that may be executed in this state
'''
# current state information
actions = []
pos = state[0]
battery = state[2]
# potential moves
pos_east = (pos[0]+1, pos[1])
pos_west = (pos[0]-1, pos[1])
pos_north = (pos[0], pos[1]-1)
pos_south = (pos[0], pos[1]+1)
# append to action list if valid move
if self.can_fly(pos_east) and battery >= self.getAttribute(pos_east, "cost"):
actions.append('East')
if self.can_fly(pos_west) and battery >= self.getAttribute(pos_west, "cost"):
actions.append('West')
if self.can_fly(pos_north) and battery >= self.getAttribute(pos_north, "cost"):
actions.append('North')
if self.can_fly(pos_south) and battery >= self.getAttribute(pos_south, "cost"):
actions.append('South')
return actions
def result(self, state, action):
'''Returns the state reached from this state when the given action is executed
'''
pos = state[0]
goals_left = state[1]
battery = state[2]
# update position
if action is "East":
new_position = (pos[0]+1, pos[1])
elif action is "West":
new_position = (pos[0]-1, pos[1])
elif action is "North":
new_position = (pos[0], pos[1]-1)
elif action is "South":
new_position = (pos[0], pos[1]+1)
#update battery
new_battery = battery - self.getAttribute(new_position, "cost")
if tuple(self.CONFIG.get("station")) == new_position:
new_battery = self.CONFIG.get("capacity")
# if at goal, update goal set
if new_position in goals_left:
s = set()
s.add(new_position)
goals_left -= frozenset(s)
return (new_position, goals_left, new_battery)
def is_goal(self, state):
'''Returns true if state is the final state (ignores battery)
'''
return state[0] == self.GOAL[0] and state[1] == self.GOAL[1]
def cost(self, state, action, state2):
'''Returns the cost of applying `action` from `state` to `state2`.
The returned value is a number (integer or floating point).
By default this function returns `1`.
'''
cost = self.getAttribute(state2[0], "cost")
if cost is not None:
return cost
return sys.maxsize
def heuristic(self, state):
'''Returns the heuristic for `state`
'''
current = state[0]
goals_left = state[1]
# gives priority to paths with fewer goals, based on this weighting
MULTIPLIER = 5
if len(goals_left) > 0:
goal_distances = set()
for location in goals_left:
goal_distances.add(self.dist(current, location))
return min(goal_distances) + (MULTIPLIER * len(goals_left))
else:
return self.dist(current, self.AGENT_START)
def setup (self):
base = self.AGENT_START
goals = frozenset(self.POSITIONS.get("goal"))
battery = self.CONFIG.get("capacity")
initial_state = (base, goals, battery)
final_state = (base, frozenset(), 0)
algorithm = astar
return initial_state,final_state,algorithm
# --------------- Helper Methods ----------------- #
def can_fly(self, position):
if 0 <= position[0] < len(self.MAP) and 0 <= position[1] < len(self.MAP[0]):
return self.MAP[position[0]][position[1]][2].get('blocked') is not True
return False
def dist(self, start, end):
sx, sy = start
ex, ey = end
return abs(ex - sx) + abs(ey - sy)
# -------------------------------------------------------------- #
# --------------- DO NOT EDIT BELOW THIS LINE ----------------- #
# -------------------------------------------------------------- #
def getAttribute (self, position, attributeName):
'''Returns an attribute value for a given position of the map
position is a tuple (x,y)
attributeName is a string
Returns:
None if the attribute does not exist
Value of the attribute otherwise
'''
print(self.CONFIG.get("map_size"))
print(position)
print([position[1]])
print(self.MAP[position[0]][position[1]])
tileAttributes=self.MAP[position[0]][position[1]][2]
if attributeName in tileAttributes.keys():
return tileAttributes[attributeName]
else:
return None
# THIS INITIALIZATION FUNCTION HAS TO BE CALLED BEFORE THE SEARCH
def initializeProblem(self,map,positions,conf,aiBaseName):
# Loads the problem attributes: self.AGENT_START, self.POSITIONS,etc.
if self.mapInitialization(map,positions,conf,aiBaseName):
initial_state,final_state,algorithm = self.setup()
self.INITIAL_STATE=initial_state
self.GOAL=final_state
self.ALGORITHM=algorithm
super(GameProblem,self).__init__(self.INITIAL_STATE)
return True
else:
return False
# END initializeProblem
def mapInitialization(self,map,positions,conf,aiBaseName):
# Creates lists of positions from the configured map
# The initial position for the agent is obtained from the first and only aiBaseName tile
self.MAP=map
self.POSITIONS=positions
self.CONFIG=conf
if 'agentInit' in conf.keys():
self.AGENT_START = tuple(conf['agentInit'])
else:
if aiBaseName in self.POSITIONS.keys():
if len(self.POSITIONS[aiBaseName]) == 1:
self.AGENT_START = self.POSITIONS[aiBaseName][0]
else:
print ('-- INITIALIZATION ERROR: There must be exactly one agent location with the label "{0}", found several at {1}'.format(aiAgentName,mapaPosiciones[aiAgentName]))
return False
else:
print ('-- INITIALIZATION ERROR: There must be exactly one agent location with the label "{0}"'.format(aiBaseName))
return False
return True
|
class MapCharacter:
def __init__(self,str1,str2):
self.str1 = str1
self.str2 = str2
self.can_map =True
def checkcharactermap(self):
if len(self.str1) is not len(self.str2):
return False
else:
charmap = {}
i=0
for i in range(0,len(self.str1)):
if self.str1[i] not in charmap:
charmap[self.str1[i]]=self.str2[i]
else:
self.can_map = False
break
return self.can_map
|
#Look for #IMPLEMENT tags in this file. These tags indicate what has
#to be implemented.
import random
import sys
'''
This file will contain different variable ordering heuristics to be used within
bt_search.
var_ordering == a function with the following template
ord_type(csp)
==> returns Variable
csp is a CSP object---the heuristic can use this to get access to the
variables and constraints of the problem. The assigned variables can be
accessed via methods, the values assigned can also be accessed.
ord_type returns the next Variable to be assigned, as per the definition
of the heuristic it implements.
val_ordering == a function with the following template
val_ordering(csp,var)
==> returns [Value, Value, Value...]
csp is a CSP object, var is a Variable object; the heuristic can use csp to access the constraints of the problem, and use var to access var's potential values.
val_ordering returns a list of all var's potential values, ordered from best value choice to worst value choice according to the heuristic.
'''
'''
ord_random(csp):
A var_ordering function that takes a CSP object csp and returns a Variable object var at random. var must be an unassigned variable.
'''
def ord_random(csp):
var = random.choice(csp.get_all_unasgn_vars())
return var
'''
val_arbitrary(csp,var):
A val_ordering function that takes CSP object csp and Variable object var,
and returns a value in var's current domain arbitrarily.
'''
def val_arbitrary(csp,var):
return var.cur_domain()
def ord_mrv(csp):
#IMPLEMENT
'''
ord_mrv(csp):
A var_ordering function that takes CSP object csp and returns Variable object var,
according to the Minimum Remaining Values (MRV) heuristic as covered in lecture.
MRV returns the variable with the most constrained current domain
(i.e., the variable with the fewest legal values).
'''
smallestDomain = sys.maxsize
smallestV = None;
for v in csp.get_all_unasgn_vars():
if v.cur_domain_size() < smallestDomain:
smallestDomain = v.cur_domain_size()
smallestV = v
return smallestV
def ord_dh(csp):
#IMPLEMENT
'''
ord_dh(csp):
A var_ordering function that takes CSP object csp and returns Variable object var,
according to the Degree Heuristic (DH), as covered in lecture.
Given the constraint graph for the CSP, where each variable is a node,
and there exists an edge from two variable nodes v1, v2 iff there exists
at least one constraint that includes both v1 and v2,
DH returns the variable whose node has highest degree.
'''
highestDegree = -1
highestV = None;
for v in csp.get_all_unasgn_vars():
count = 0
for cons in csp.get_cons_with_var(v):
for variable in cons.get_scope():
if variable in csp.get_all_unasgn_vars():
count += 1
if count > highestDegree:
highestDegree = count
highestV = v
return highestV
def val_lcv(csp,var):
#IMPLEMENT
'''
val_lcv(csp,var):
A val_ordering function that takes CSP object csp and Variable object var,
and returns a list of Values [val1,val2,val3,...]
from var's current domain, ordered from best to worst, evaluated according to the
Least Constraining Value (LCV) heuristic.
(In other words, the list will go from least constraining value in the 0th index,
to most constraining value in the $j-1$th index, if the variable has $j$ current domain values.)
The best value, according to LCV, is the one that rules out the fewest domain values in other
variables that share at least one constraint with var.
'''
possibleValues = var.cur_domain()
ruledOut = []
constraints = csp.get_cons_with_var(var)
for v in possibleValues:
'''
count = 0
for c in constraints:
scope = c.get_scope();
index = 0
for i in range(0, len(scope)):
if scope[i].name == var.name:
index = i
break
for t in c.sat_tuples:
if t[index] != v:
count += 1
ruledOut.append(count)
'''
total_count = 0
for c in constraints:
scope = c.get_scope();
notRuledOutValues = []
for i in range(0, len(scope)):
notRuledOutValues.append([])
index = 0
for i in range(0, len(scope)):
if scope[i].name == var.name:
index = i
break
for t in c.sat_tuples:
if t[index] != v:
for i in range(0, len(scope)):
if i != index and t[i] not in notRuledOutValues[i]:
notRuledOutValues[i].append(t[i])
total_domain = 0
count = 0
for var in scope:
total_domain += var.cur_domain_size()
for tup in notRuledOutValues:
count += len(tup)
total_count += total_domain - count
ruledOut.append(total_count)
for i in range(0, len(possibleValues)):
lowest = i
for j in range(i + 1, len(ruledOut)):
if ruledOut[j] < ruledOut[lowest]:
lowest = j
tempV = possibleValues[i]
tempRuledOut = ruledOut[i]
possibleValues[i] = possibleValues[lowest]
ruledOut[i] = ruledOut[lowest]
possibleValues[lowest] = tempV
ruledOut[lowest] = tempRuledOut
return possibleValues
def ord_custom(csp):
#IMPLEMENT
'''
ord_custom(csp):
A var_ordering function that takes CSP object csp and returns Variable object var,
according to a Heuristic of your design. This can be a combination of the ordering heuristics
that you have defined above.
'''
# ord_mrv
smallestDomain = sys.maxsize
smallestV = None;
allUnasgnVars = csp.get_all_unasgn_vars()
for v in allUnasgnVars:
domainSize = v.cur_domain_size()
if domainSize < smallestDomain:
smallestDomain = domainSize
smallestV = v
if domainSize == smallestDomain:
# ord_dh
highestDegree = -1
highestV = None;
for var in [v, smallestV]:
count = 0
allCons = csp.get_cons_with_var(var)
for cons in allCons:
scope = cons.get_scope()
for variable in scope:
if variable in allUnasgnVars:
count += 1
if count > highestDegree:
highestDegree = count
highestV = var
smallestV = highestV
return smallestV |
##!/usr/bin/python
# Filename: p1.py
import sys
##### ADD YOUR NAME, Student ID, and Section number #######
# NAME:
# STUDENT ID:
# SECTION:
###########################################################
########### ADD YOUR CODE HERE ###############################
def is_float(s):
try:
float(s)
return True
except ValueError:
return False
def convert_miles_to_kilometers():
miles = raw_input("Enter the miles to be converted: ")
if is_float(miles):
#convert miles string to numeric miles
miles = float(miles)
# now apply the conversion km = miles * 1.609344
km = miles * 1.609344
print "{the_miles} are equivalent to {the_km} kilometers".format(the_miles = miles, the_km=km)
else:
print "Illegal unit of conversion. Input miles are not a number."
################################################################
def print_program_menu():
print "\n"
print "Welcome to unit conversion program. Please, choose an option:"
print "1. Miles to kilometers"
print "2. Kilometers to miles"
print "3. Pounds to kilograms "
print "4. Kilograms to pounds"
print "5. Celsius to Fahrenheit"
print "6. Fahrenheit to Celsius"
print "7. Miles/hour to kilometers/hour"
print "8. Kilometers/hour to Miles/hour"
print "9. Exit"
def identify_option(option):
if option.isdigit() : # Verify if this is a number
numeric_option = int(option)
# check if in range
if numeric_option >= 1 and numeric_option <= 9:
return (0, numeric_option)
else:
return (-1, 0) # invalid option
else:
return (-1, 0) # invalid option
def process_conversion(numeric_option):
if (numeric_option == 1):
convert_miles_to_kilometers()
def main():
done = False
while not done:
print_program_menu()
user_option = raw_input("Enter option: ")
option_info_tuple = identify_option(user_option)
if option_info_tuple[0] == 0:
#option was valid
if option_info_tuple[1] == 9:
done = True
print "Thanks for using the unit conversion program"
else:
process_conversion(option_info_tuple[1])
else:
#option invalid
print "Invalid Option\n"
# This line makes python start the program from the main function
if __name__ == "__main__":
main()
sys.exit()
|
def findWord(str1, str2):
for c in str1:
if str2.find(c) < 0:
return "No"
return "Yes"
str1 = input("String 1: ")
str2 = input("String 2: ")
print(findWord(str1,str2)) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sqlite3
conn = sqlite3.connect('proyect.db')
c = conn.cursor()
cant_solitar = 0
def ejecutarQuery(consulta):
c.execute(consulta)
existen = c.fetchall()
#Regresa falso si no hay ordenes que pedir, si no, regresa el arreglo de listas de articulos que requieren ordenes
if not existen:
return False
else:
conn.commit()
return existen
def imprimirListaFilas(lista, encabezadoDefault = ""):
print(encabezadoDefault, end = "")
for fila in lista:
print("|", end = " ")
for valor in fila:
print(valor, end = " | ")
print("")
class InsertarArticulos:
def __init__(self):
self.articuloID = ""
self.Nombre = ""
self.Costo = ""
self.Cantidad = ""
self.Maximo = ""
self.Minimo = ""
self.UbicacionID = ""
def llenarDatosArticulos(self):
x = True
##############################
Nombre = input('Ingrese el nombre del articulo: ')
##############################
while(x == True):
listaFilas = Inventario().mostarFamilia()
Familia = input('Ingrese la familia: ')
for fila in listaFilas:
if int(Familia) == fila[0]:
x = False
if x:
print("Identificador incorrecto")
###########################
costo = input('Ingrese el costo del articulo: ')
############################## CANTIDAD
cantidad = input('Ingrese la cantidad de articulos: ')
############################## MaXIMO
x = True
while(x == True):
max = int(input('Ingrese el max de articulos: '))
if max == '' or max < 5 or max > 100000 :
print ("La cantidad ingresada no esta permitida")
else:
x = False
break
############################## MINIMO
x = True
while(x == True):
min = int(input('Ingrese el minimo de articulos: '))
if min < max and min > 1:
x = False
else:
print("No se puede ingresar esa cantidad")
##############################
x = True
while(x == True):
listaFilas = Inventario().mostrarUbicacion()
ubicacionID = input('Ingrese el ID de la ubicacion: ')
for fila in listaFilas:
if ubicacionID == fila[0]:
x = False
if x:
print("Identificador incorrecto")
##############################
c.execute("INSERT INTO Articulos(UbicacionID, FamiliaID, Nombre, Costo, Cantidad, Maximo, Minimo) VALUES (?, ?, '" + Nombre + "' , '" + costo + "' , '" + cantidad + "' , ? , ?)", (ubicacionID, Familia, max, min))
c.execute("SELECT MAX(ArticuloID) FROM Articulos")
d = c.fetchall()
articuloID = int(d[0][0])
x = True
while(x == True):
listaFilas = Inventario().mostarProveedores()
proveedorID = int(input('Ingrese el ID del proveedor: '))
for fila in listaFilas:
if proveedorID == fila[0]:
x = False
if x:
print("Identificador incorrecto")
c.execute("INSERT INTO ProveedorArt(ProveedorID, ArticuloID) VALUES (?, ?)", (proveedorID, articuloID))
conn.commit()
input()
def eliminarRegistro(self):
x = True
y = True
while(x == True):
artID = input("Ingrese el ID a eliminar\nNo recuerda el ID? Ingrese '?' para mostrar todos los registros.\nSu opcion: ")
if artID == '?':
print("Tabla Articulos")
for row in c.execute('SELECT * FROM Articulos WHERE Estado = 0'):
print (row)
c.execute("SELECT ArticuloID FROM Articulos WHERE ArticuloID= '" + artID +"' ")
for row in c.execute("SELECT ArticuloID FROM Articulos WHERE ArticuloID= '" + artID +"' "):
if row in c.execute("SELECT ArticuloID FROM Articulos WHERE ArticuloID= '" + artID +"' "):
c.execute("UPDATE Articulos SET Estado = 1 WHERE ArticuloID = %s" % (artID))
x = False
input()
conn.commit()
def actualizarRegistro(self):
x = True
self.encabezado = "Articulos\n|ID del Articulo | Nombre | Marca | Modelo | Ubicacion | Costo | Cantidad | Maximo | Minimo|\n"
self.consultaArt = "SELECT * FROM Articulos WHERE ArticuloID = %s"
self.actualizacionCompuesta = "UPDATE Articulos SET %s = %s WHERE ArticuloID = %s"
self.consultaDefault = """ SELECT a.ArticuloID,
a.Nombre,
fa.Marca,
fa.Modelo,
al.NombreAlmacen,
a.Costo,
a.Cantidad,
a.Maximo,
a.Minimo
FROM Articulos a
INNER JOIN Almacenes al
ON al.AlmacenID = a.UbicacionID
INNER JOIN FamiliadeArticulos fa
ON fa.FamiliaID = a.FamiliaID
WHERE a.Estado = 0
ORDER BY a.ArticuloID
"""
while(x == True):
artID = input("Ingrese el ID a actualizar\nNo recuerda el ID? Ingrese '?' para mostrar todos los registros.\nSu opcion: ")
if artID == '?':
listaFilas = ejecutarQuery(self.consultaDefault)
if not listaFilas:
print ("Primero ingrese o active algun articulo")
return
imprimirListaFilas(listaFilas, self.encabezado)
else:
listaFilas = ejecutarQuery(self.consultaArt % (int(artID)))
if not listaFilas:
print ("Ingrese un identificador correcto")
continue
for fila in listaFilas:
if int(artID) == fila[0]:
articulo = int(artID)
x = False
x = True
columna = ""
while(x == True):
opcion = int(input("""Ingrese el numero de la opcion que desea modificar
1)Nombre
2)Costo
3)Cantidad
4)Maximo
5)Minimo
6)Estado
7)Ubicacion
"""))
if opcion == 1:
columna = "Nombre"
if opcion == 2:
columna = "Costo"
if opcion == 3:
columna = "Cantidad"
if opcion == 4:
columna = "Maximo"
if opcion == 5:
columna = "Minimo"
if opcion == 6:
columna = "Estado"
if opcion == 7:
columna = "Ubicacion"
if len(columna) == 0:
print("Ingrese un valor correcto")
continue
x = False
x = True
valor = input("Ingrese el nuevo valor de la columna " + columna + " : ")
if opcion == 2:
valor = float(valor)
elif opcion != 1 and opcion != 2:
valor = int(valor)
else:
valor = "'" + valor + "'"
listaFilas = ejecutarQuery(self.actualizacionCompuesta % (columna, valor, articulo))
class InsertarProveedor:
def __init__(self):
#self.proveedorID = ""
self.proveedorDescripcion = ""
self.eliminadoB = ""
def llenarDatosProveedor(self):
provdesc = input('Ingrese la descricion del proveedor')
elimB = input('Que carajos es esto? No se, ingresa algo')
c.execute("INSERT INTO TablaProveedor (proveedorDescripcion , eliminadoB) VALUES ('" + provdesc + "', '" + elimB + "')")
conn.commit()
input()
class InsertarFamiliaArticulos:
def __init__(self):
self.estado = ""
def llenarDatosFamiliaArticulos(self):
estado = input('Estado: ')
c.execute("INSERT INTO FamiliaArticulos(estado) VALUES ('" + estado + "')")
conn.commit()
input()
class Inventario:
def mostarFamilia(self):
consulta = "SELECT FamiliaID, Nombre FROM FamiliadeArticulos"
encabezado = "|Identificador | Nombre|\n"
lista = ejecutarQuery(consulta)
imprimirListaFilas(lista, encabezado)
return lista
def mostarProveedores(self):
consulta = "SELECT ProveedorID, Nombre FROM Proveedor WHERE Estado = 0"
encabezado = "|Identificador | Nombre|\n"
lista = ejecutarQuery(consulta)
imprimirListaFilas(lista, encabezado)
return lista
def mostrarUbicacionArticulo(self, articuloID):
consulta = "SELECT al.AlmacenID, al.Nombre, a.Nombre FROM Almacenes al INNER JOIN Articulos a ON a.ArticuloID = al.ArticuloID AND a.ArticulosID = %s WHERE al.Estado = 0"
encabezado = "|Identificador Almacen | Nombre Almacen | Nombre Articulo|\n"
lista = ejecutarQuery(consulta)
imprimirListaFilas(lista, encabezado)
def mostrarUbicacion(self):
consulta = "SELECT AlmacenID, NombreAlmacen FROM Almacenes WHERE Estado = 0"
encabezado = "|Identificador | Nombre|\n"
lista = ejecutarQuery(consulta)
imprimirListaFilas(lista, encabezado)
return lista
class Pedidos:
def __init__(self):
self.ProveedorID = ""
self.Nombre = ""
self.ArticuloID = ""
self.encabezado = "|ID del Articulo | Nombre | Marca | Modelo | Ubicacion | Costo | Cantidad | Maximo | Minimo|\n"
self.consultaDefault = """ SELECT a.ArticuloID,
a.Nombre,
fa.Marca,
fa.Modelo,
al.NombreAlmacen,
a.Costo,
a.Cantidad,
a.Maximo,
a.Minimo
FROM Articulos a
INNER JOIN Almacenes al
ON al.AlmacenID = a.UbicacionID
INNER JOIN FamiliadeArticulos fa
ON fa.FamiliaID = a.FamiliaID
WHERE a.Estado = 0
ORDER BY a.ArticuloID
"""
def pedidoProovedor(self):
x = True
consultaArt = "SELECT * FROM Articulos WHERE ArticuloID = %s"
consultaProvArt = "SELECT p.ProveedorID, p.Nombre FROM Articulos a INNER JOIN ProveedorArt pa ON pa.ArticuloID = a.ArticuloID INNER JOIN Proveedor p ON p.ProveedorID = pa.ProveedorID WHERE pa.ArticuloID = %s"
actualizarArt = "UPDATE Articulos SET Cantidad = %s WHERE ArticuloID = %s"
consultaCantMax = "SELECT ArticuloID, Cantidad, Maximo, Minimo FROM Articulos WHERE ArticuloID= %s "
while (x == True ):
pedido = input("Introduzca el ID del articulo al que desea hacer pedido\nSi no recuerda los datos introduzca ? para verlos\nSu opcion: ")
if pedido == '?':
if Consulta().mostrar():
return
else:
listaFilas = ejecutarQuery(consultaArt % (pedido))
if not listaFilas:
print ("Ingrese un identificador correcto")
continue
for fila in listaFilas:
if int(pedido) == fila[0]:
articulo = int(pedido)
x = False
x = True
while (x == True ):
vendor = input("Seleccione el proveedor: \nSi no conoce a los proveedores pulse ? para verlos.\nSu opcion: ")
if vendor == '?':
listaFilas = ejecutarQuery(consultaProvArt % (articulo))
if not listaFilas:
return
imprimirListaFilas(listaFilas)
else:
listaFilas = ejecutarQuery(consultaProvArt % (articulo))
if not listaFilas:
print ("Ingrese un identificador correcto")
continue
for fila in listaFilas:
if int(vendor) == fila[0]:
proveedor = int(vendor)
x = False
x = True
while(x == True):
listaFilas = ejecutarQuery(consultaCantMax % (articulo))
imprimirListaFilas(listaFilas, "| Articulo | Cantidad | Maximo | Minimo |\n")
cantidadDef = int(listaFilas[0][1])
maximo = int(listaFilas[0][2])
minimo = int(listaFilas[0][3])
cantidad = int(input ("Ahora introduzca la cantidad de articulos que desea pedir: "))
if not self.validarCantidad(cantidad, cantidadDef, maximo, minimo):
print ("Vuelva a ingresar la cantidad")
continue
listaFilas = ejecutarQuery(actualizarArt % (cantidadDef + cantidad, articulo))
print("Se ha realizado el pedido al proveedor")
x = False
def validarCantidad(self, cant, cantdef, maximo, minimo):
if(cant > maximo):
return False
elif(cant + cantdef < minimo):
print("Su cantidad insertada no cumple el minimo del articulo")
return False
elif(cant + cantdef > maximo):
print("Su cantidad insertada sobrepasa el maximo del articulo")
return False
else:
return True
class Consulta:
def __init__(self):
self.encabezado = "|ID del Articulo | Nombre | Marca | Modelo | Ubicacion | Costo | Cantidad | Maximo | Minimo|\n"
self.encabezadoProveedor = "|ID del Articulo | Nombre | Nombre Proveedor | Marca | Modelo | Ubicacion | Costo | Cantidad | Maximo | Minimo|\n"
self.consultaDefault = """ SELECT a.ArticuloID,
a.Nombre,
fa.Marca,
fa.Modelo,
al.NombreAlmacen,
a.Costo,
a.Cantidad,
a.Maximo,
a.Minimo
FROM Articulos a
INNER JOIN Almacenes al
ON al.AlmacenID = a.UbicacionID
INNER JOIN FamiliadeArticulos fa
ON fa.FamiliaID = a.FamiliaID
WHERE a.Estado = 0
ORDER BY a.ArticuloID
"""
self.consultaFamilia = """ SELECT a.ArticuloID,
a.Nombre,
fa.Marca,
fa.Modelo,
al.NombreAlmacen,
a.Costo,
a.Cantidad,
a.Maximo,
a.Minimo
FROM Articulos a
INNER JOIN Almacenes al
ON al.AlmacenID = a.UbicacionID
INNER JOIN FamiliadeArticulos fa
ON fa.FamiliaID = a.FamiliaID
AND fa.FamiliaID = %s
WHERE a.Estado = 0
ORDER BY a.ArticuloID, fa.Nombre
"""
self.consultaProveedor = """ SELECT a.ArticuloID,
a.Nombre,
p.Nombre,
fa.Marca,
fa.Modelo,
al.NombreAlmacen,
a.Costo,
a.Cantidad,
a.Maximo,
a.Minimo
FROM Articulos a
INNER JOIN Almacenes al
ON al.AlmacenID = a.UbicacionID
INNER JOIN FamiliadeArticulos fa
ON fa.FamiliaID = a.FamiliaID
INNER JOIN ProveedorArt pa
ON pa.ArticuloID = a.ArticuloID
AND pa.ProveedorID = %s
INNER JOIN Proveedor p
ON p.ProveedorID = pa.ProveedorID
WHERE a.Estado = 0
ORDER BY a.ArticuloID, p.Nombre
"""
def menu(self):
x = True
while(x == True):
os.system("clear")
print ("""Como desea filtrar los articulos?
1.- Familia de articulos
2.- Nombre de proveedor
3.- Sin filtros
4.- Salir
""")
opc = int(input("Ingrese una opcion: "))
if opc == 1:
Inventario().mostarFamilia()
familiaID = int(input("Ingrese el identificador de la familia por la cual desea filtrar: "))
os.system("clear")
listaFilas = ejecutarQuery(self.consultaFamilia % (familiaID))
if not listaFilas:
print("No hay articulos con esa familia")
else:
imprimirListaFilas(listaFilas, self.encabezado)
input()
elif opc == 2:
Inventario().mostarProveedores()
proveedorID = int(input("Ingrese el identificador del proveedor por el cual desea filtrar: "))
os.system("clear")
listaFilas = ejecutarQuery(self.consultaProveedor % (proveedorID))
if not listaFilas:
print("No hay articulos con ese proveedor")
else:
imprimirListaFilas(listaFilas, self.encabezadoProveedor)
input()
elif opc == 3:
self.mostrar()
input()
elif opc == 4:
x = False
def mostrar(self):
print("Inventario")
listaFilas = ejecutarQuery(self.consultaDefault)
if not listaFilas:
print("No hay datos en el inventario")
input()
return False
imprimirListaFilas(listaFilas, self.encabezado)
class Ordenes:
def __init__(self):
self.consultaActualizar = "UPDATE Articulos SET Cantidad = %s WHERE ArticuloID = %s"
def buscarOrdenes(self):
consulta = "SELECT * FROM Articulos WHERE Cantidad < Minimo AND Estado = 0"
existen = ejecutarQuery(consulta)
#Regresa falso si no hay ordenes que pedir, si no, regresa el arreglo de listas de articulos que requieren ordenes
if not existen:
print ("No hay ordenes que pedir")
input()
return False
else:
return existen
def consultarOrdenes(self, lista):
ordenes = []
encabezado = "|ID del Articulo | Nombre | Costo | Cantidad | Maximo | Minimo|\n"
for row in lista:
#0 es ID del Articulo, 3 es Nombre, 5 es Cantidad y 6 es Maximo por lo tanto queda lo faltante para completar el max
ordenes.append([row[0], row[3], row[6] - row[5]])
for orden in ordenes:
print("Identificador: " + str(orden[0]) + "\nNombre de Articulo: " + str(orden[1]) + "\nCantidad requerida: " + str(orden[2]) + "\n")
return ordenes
def mostrarOrdenes(self):
print("Ordenes por realizar:")
ordenes = self.buscarOrdenes()
if not ordenes:
return
self.consultarOrdenes(ordenes)
input()
def reabastecerArticulos(self, pendientes):
articuloID = int(input("Ingrese el identificador del articulo al cual se desea reabastecer hasta el tope: "))
cantidad = 0
for pendiente in pendientes:
if articuloID == pendiente[0]:
cantidad = pendiente[2]
listaFilas = ejecutarQuery(self.consultaActualizar % (cantidad, articuloID))
print (listaFilas)
input()
def mostrar(self):
print("Ordenes por realizar:")
ordenes = self.buscarOrdenes()
if not ordenes:
return
pendientes = self.consultarOrdenes(ordenes)
self.reabastecerArticulos(pendientes)
|
import ticker as yf
from typing import Optional, Tuple, List
def get_price_change(
ticker: str,
lookback: Optional[str] = "2d"
) -> Tuple[float, List]:
"""Gets price change for a particular ticker
Args:
ticker (str): Ticker of interest. E.g., BABA or Y92.SI
lookback (str, optional): Price change period to evaluate on.
Defaults to "2d".
Returns:
Tuple[float, List]: Percentage change in float.
"""
stock = yf.Ticker(ticker)
hist = stock.history(period=lookback).Close.values.tolist()
if len(hist) != int(lookback[0]):
lookback = f"{int(lookback[0])+1}d"
hist = stock.history(period=lookback).Close.values.tolist()
if not hist:
return f"Couldn't find history for ticker {ticker}", None
pct_chng = ((hist[-1] - hist[0]) / hist[0]) * 100
return np.round(pct_chng, 2), hist
|
# Valid Triangle Array
class Solution:
"""
@param nums: the given array
@return: the number of triplets chosen from the array that can make triangles
"""
def triangleNumber(self, nums):
# Write your code here
nums = sorted(nums)
total = 0
for i in range(len(nums)-2):
if nums[i] == 0:
continue
end = i+2
for j in range(i+1, len(nums)-1):
while end < len(nums) and nums[i]+nums[j]>nums[end]:
end += 1
total += end - 1 - j
return total |
class MinStack:
def __init__(self):
# do intialization if necessary
self.stack = []
self.minStack = []
"""
@param: number: An integer
@return: nothing
"""
def push(self, number):
# write your code here
self.stack.append(number)
if len(self.minStack) == 0:
self.minStack.append(number)
else:
self.minStack.append(min(number, self.minStack[-1]))
"""
@return: An integer
"""
def pop(self):
# write your code here
tmp = self.stack[-1]
del(self.stack[-1], self.minStack[-1])
return tmp
"""
@return: An integer
"""
def min(self):
# write your code here
return self.minStack[-1] |
"""Definition of a mock keyboard for use in testing."""
from typing import Optional
from shimmer.keyboard import KeyboardHandler
class MockKeyboard:
"""
A mock of a physical keyboard.
Used to simulate keyboard events in tests.
"""
def press(
self, handler: KeyboardHandler, symbol: int, modifiers: int = 0
) -> Optional[bool]:
"""Press the given key and modifiers and send it to the handler."""
return handler.on_key_press(symbol, modifiers)
def release(
self, handler: KeyboardHandler, symbol: int, modifiers: int = 0
) -> Optional[bool]:
"""Release the given key and modifiers and send it to the handler."""
return handler.on_key_release(symbol, modifiers)
def tap(self, handler: KeyboardHandler, symbol: int, modifiers: int = 0) -> None:
"""Press and release the given key and modifiers and send it to the handler."""
self.press(handler, symbol, modifiers)
# Technically `text` should be called here as well to simulate what actually happens,
# but it's not worth replicating the pyglet behaviour here to map from key+modifiers to
# text.
self.release(handler, symbol, modifiers)
def text(self, handler: KeyboardHandler, text: str) -> Optional[bool]:
"""
Simulate pyglet handling text input and passing it to us as a text character.
Useful for capital vs lowercase testing as SHIFT+a will trigger both an
on_key_press event with MOD_SHIFT and key.A; and an on_text event with "A".
I.e. saves you from having to work out what SHIFT+a means.
"""
return handler.on_text(text)
|
"""A mock mouse for use in testing."""
from typing import Optional, Tuple
from pyglet.window.mouse import LEFT
from shimmer.components.box import Box
class MockMouse:
"""
A mock of a physical mouse.
Used to simulate mouse events in tests.
"""
def box_center_in_world_coord(self, box: Box) -> Tuple[int, int]:
"""Get the center of the box in world coordinate space."""
return box.point_to_world(box.rect.center)
def press(
self,
box: Box,
position: Optional[Tuple[int, int]] = None,
buttons: int = LEFT,
modifiers: int = 0,
) -> Optional[bool]:
"""
Send an on_mouse_press event in the centre of the given Box.
If the Box does not define an `on_mouse_press` then this has no effect.
:param box: Box to send the event to.
:param position: Coordinate to click the mouse at.
:param buttons: Mouse button to simulate. Defaults to Left.
:param modifiers: Keyboard modifiers to include.
:return: True if the event was handled, None if it wasn't.
"""
if position is None:
position = self.box_center_in_world_coord(box)
if hasattr(box, "on_mouse_press"):
return box.on_mouse_press(*position, buttons, modifiers)
return None
def release(
self,
box: Box,
position: Optional[Tuple[int, int]] = None,
buttons: int = LEFT,
modifiers: int = 0,
) -> Optional[bool]:
"""
Send an on_mouse_release event in the centre of the given Box.
If the Box does not define an `on_mouse_release` then this has no effect.
:param box: Box to send the event to.
:param position: Coordinate to click the mouse at.
:param buttons: Mouse button to simulate. Defaults to Left.
:param modifiers: Keyboard modifiers to include.
:return: True if the event was handled, None if it wasn't.
"""
if position is None:
position = self.box_center_in_world_coord(box)
if hasattr(box, "on_mouse_release"):
return box.on_mouse_release(*position, buttons, modifiers)
return None
def move(
self,
box: Box,
start: Optional[Tuple[int, int]] = None,
end: Optional[Tuple[int, int]] = None,
) -> Optional[bool]:
"""
Send an on_mouse_motion event in the centre of the given Box.
If the Box does not define an `on_mouse_motion` then this has no effect.
:param box: Box to send the event to.
:param start: Coordinates to start the motion from. Defaults to the center of the box.
:param end: Coordinates to end the motion at. Defaults to (1, 1) away from the start.
:return: True if the event was handled, None if it wasn't.
"""
if start is None:
start = self.box_center_in_world_coord(box)
if end is None:
end = start[0] + 1, start[1] + 1
dx = end[0] - start[0]
dy = end[1] - start[1]
if hasattr(box, "on_mouse_motion"):
return box.on_mouse_motion(*end, dx, dy)
return None
def drag(
self,
box: Box,
start: Optional[Tuple[int, int]] = None,
end: Optional[Tuple[int, int]] = None,
buttons: int = LEFT,
modifiers: int = 0,
) -> Optional[bool]:
"""
Send an on_mouse_drag event in the centre of the given Box.
If the Box does not define an `on_mouse_drag` then this has no effect.
:param box: Box to send the event to.
:param start: Coordinates to start the motion from. Defaults to the center of the box.
:param end: Coordinates to end the motion at. Defaults to (1, 1) away from the start.
:param buttons: Mouse button to simulate. Defaults to Left.
:param modifiers: Keyboard modifiers to include.
:return: True if the event was handled, None if it wasn't.
"""
if start is None:
start = self.box_center_in_world_coord(box)
if end is None:
end = start[0] + 1, start[1] + 1
dx = end[0] - start[0]
dy = end[1] - start[1]
if hasattr(box, "on_mouse_drag"):
return box.on_mouse_drag(*end, dx, dy, buttons, modifiers)
return None
def click(self, box: Box, buttons: int = LEFT, modifiers: int = 0) -> None:
"""
Simulate a mouse click and release in the centre of the given Box.
:param box: Box to send the event to.
:param buttons: Mouse button to simulate. Defaults to Left.
:param modifiers: Keyboard modifiers to include.
"""
self.press(box, buttons=buttons, modifiers=modifiers)
self.release(box, buttons=buttons, modifiers=modifiers)
def move_onto(self, box: Box) -> Optional[bool]:
"""
Simulate a mouse motion from not on the box, to onto the box.
:param box: Box to move the mouse onto.
:return: True if the event was handled, None if it wasn't.
"""
end = self.box_center_in_world_coord(box)
start = end[0] - box.rect.width, end[1] - box.rect.height
# Move the mouse slightly outside the box to simulate reality of moving onto something.
self.move(box, start)
# Then move the mouse fully onto the box.
return self.move(box, start, end)
def move_off(self, box: Box) -> Optional[bool]:
"""
Simulate a mouse motion from on the box, to off the box.
:param box: Box to move the mouse onto.
:return: True if the event was handled, None if it wasn't.
"""
start = self.box_center_in_world_coord(box)
end = start[0] - box.rect.width, start[1] - box.rect.height
# Move the mouse slightly inside the box to simulate realist of moving off something.
self.move(box, start)
# Then move the mouse fully off the box.
return self.move(box, start, end)
def drag_onto(
self, box: Box, buttons: int = LEFT, modifiers: int = 0
) -> Optional[bool]:
"""
Simulate a mouse drag from not on the box, to onto the box.
:param box: Box to move the mouse onto.
:param buttons: Mouse button to simulate. Defaults to Left.
:param modifiers: Keyboard modifiers to include.
:return: True if the event was handled, None if it wasn't.
"""
end = self.box_center_in_world_coord(box)
start = end[0] - box.rect.width, end[1] - box.rect.height
# Move the mouse slightly outside the box to pretend were moving into it.
self.drag(box, start, buttons=buttons, modifiers=modifiers)
# Then move the mouse fully onto the box.
return self.drag(box, start, end, buttons=buttons, modifiers=modifiers)
def drag_off(
self, box: Box, buttons: int = LEFT, modifiers: int = 0
) -> Optional[bool]:
"""
Simulate a mouse drag from on the box, to off the box.
:param box: Box to move the mouse onto.
:param buttons: Mouse button to simulate. Defaults to Left.
:param modifiers: Keyboard modifiers to include.
:return: True if the event was handled, None if it wasn't.
"""
start = self.box_center_in_world_coord(box)
end = start[0] - box.rect.width, start[1] - box.rect.height
# Drag the mouse slightly inside the box to pretend were moving into it.
self.drag(box, start, buttons=buttons, modifiers=modifiers)
# Then drag the mouse fully off the box.
return self.drag(box, start, end, buttons=buttons, modifiers=modifiers)
def click_and_drag(
self,
box: Box,
start: Tuple[int, int],
end: Tuple[int, int],
buttons: int = LEFT,
modifiers: int = 0,
) -> None:
"""
Click the mouse, drag from start to end, then release the mouse.
:param box: Box to send the event to.
:param start: Coordinates to start the motion from.
:param end: Coordinates to end the motion at.
:param buttons: Mouse button to simulate. Defaults to Left.
:param modifiers: Keyboard modifiers to include.
"""
self.press(box, start, buttons=buttons, modifiers=modifiers)
self.drag(box, start, end, buttons=buttons, modifiers=modifiers)
self.release(box, end, buttons=buttons, modifiers=modifiers)
|
class node:
def __init__(self, value = None, left = None, right = None):
self.value = value
self.left = left
self.right = right
def __str__(self):
return str(self.value)
class b_s_tree:
c = node()
def __init__(self):
self.root = None
def __str__(self):
return str(self.c.value)
def insert_node(self, value):
b = node(value)
if self.root == None:
self.root = b
return b
current = self.root
while 1:
if value < current.value:
if current.left != None:
current = current.left
else:
current.left = b
break
elif value > current.value:
if current.right != None:
current = current.right
else:
current.right = b
break
else:
break
def display(self, root):
if root == None:
return
print root.value
self.display(root.left)
self.display(root.right)
b = b_s_tree()
print b
b.insert_node(10)
b.insert_node(6)
b.insert_node(15)
b.insert_node(3)
b.insert_node(8)
b.insert_node(13)
b.insert_node(20)
b.insert_node(7)
b.insert_node(9)
b.insert_node(14)
b.display(b.root) |
def printer(arg):
print "Hello Anand! %r" %arg
printer("sudhan")
print "Working with files and functions"
from sys import argv
script, fname=argv
def printfile(f):
print f.read()
def rewindfile(f):
f.seek(0)
def printline(line,f):
print line,f.readline()
file1=open(fname)
print "PRINTING FILE..."
printfile(file1)
print "REWINDING FILE..."
rewindfile(file1)
print "PRINTING LINE BY LINE..."
line=1
printline(line,file1)
line+=1
printline(line,file1)
|
mystring=" I wAlK tO sChOoL"
print(mystring.count('o'))
print(mystring.find('o'))
print(mystring.lower())
print(mystring.upper())
print(mystring.replace('o','sno'))
print(mystring.strip()) |
firstList=[1,2,3,4,5,6,1,2,3,4,5,6]
print(firstList)
print(firstList.count(3)) #counts the number of occurrences of '3' in the list
print("this is the out put for the count function")
print(firstList.index(3)) #returns the index of '3' in the list
print("this is the out put for the index function")
print(firstList.pop()) #returns last element then removes it from the list
print("this is the out put for the pop function")
firstList.reverse() #reverses the elements in the list
print("this is the out put for the reverse function")
print(firstList)
firstList.sort() #sorts the list alphabetically in ascending order, or numerical in ascending order
print(firstList)
print("this is the out put for the function")
|
import math
n=int(input())
motu=[]
patlu=[]
for i in range(1,math.floor(n/3)):
patlu.append(i)
motu.append(2*i)
s=int(sum(patlu)+sum(motu))
if s>n:
break
a=patlu[len(patlu)-1]
motu.remove(motu[len(motu)-1])
sum=int(int(sum(patlu))+int(sum(motu)))
motu.append(n-sum)
b=motu[len(motu)-1]
if (a>b or sum<n) and (b>0):
print('Motu')
if (sum>n) and (b<0):
print('Patlu')
|
#linear algebraic operations
import numpy as np
a=input("Enter the 2nd matrix:")
b=input("Enter the 2nd matrix:")
x=np.array(a)
y=np.array(b)
print("matrix algebraic operations")
a=[x,y,np.add(x,y),np.subtract(x,y),np.dot(x,y),np.divide(x,y),np.transpose(x),np.transpose(y),np.linalg.det(x),np.linalg.det(y),np.linalg.inv(x),np.linalg.inv(y),np.linalg.eigvals(x),np.linalg.eigvals(y),np.trace(x),np.trace(y),np.linalg.matrix_rank(x),np.linalg.matrix_rank(y)]
b=["matrix1","matrix2","addition","substraction","multiplication","division","transpose of x","transpose of y","determinant of x","determinant of y","inverse of x","inverse of y","eigen value of x","eigen value of y","trace of x","trace of y","rank of x","rank of y"]
l=len(a)
for i in range(l):
print np.array(a[i])," -----",np.array(b[i])
|
"""
类的静态方法, 私有方法和私有字段
"""
class WhoAreYou(object):
def __init__(self, name, age):
self.name = name
self.__age = age # 私有字段
# 私有方法
def __delete(self):
print('delete %s' % self.name)
def shachu(self):
self.__delete()
def show(self):
print(self.__age)
def select(self):
print('%s login' % self.name)
# 静态方法
@staticmethod
def funv():
print('okk.')
me = WhoAreYou('shiina', 19)
me.select()
# 调用私有方法的两种方式
me.shachu() # 由类中其他的函数从内部调用
me._WhoAreYou__delete() # 强制调用私有方法
# 静态方法
me.show()
WhoAreYou.funv()
|
'''
三级菜单选择, 任何时候输入q 可退出, 输入b 可跳到一级菜单,
question: 输入不存在的值时,没有处理
'''
data = {
'a': {'a1': ['a11','a12','a13'], 'a2': ['a21','a22','a32'], 'a3': ['a31','a32','a33']},
'b': {'b1': ['b11','b12','b13'], 'b2': ['b21','b22','b32'], 'b3': ['b31','b32','b33']},
'c': {'c1': ['c11','c12','c13'], 'c2': ['c21','c22','c32'], 'c3': ['c31','c32','c33']}
}
def choose():
choose_val = input('Please input you choose:')
return choose_val
'''
打印三级列表
'''
def one_list():
for one in data.keys():
print('#:'+one)
def two_list(cho1):
if cho1 in data.keys():
for two in data.get(cho1).keys():
print('#:%s' % two)
def three_list(cho2):
if cho2 in data[cho1].keys():
for three in data.get(cho1).get(cho2):
print('#:%s' % three)
for i in range(3):
one_list()
cho1 = choose()
if cho1 == 'q':exit('qiut')
if cho1 == 'b':print('this is the first level list')
two_list(cho1)
two_list(cho1)
cho2 = choose()
if cho2 == 'q':exit('qiut')
if cho2 == 'b':continue
three_list(cho2)
cho3 = choose()
if cho3 == 'q':exit('qiut')
elif cho3 == 'b':continue
else:break
print('你的选择是:%s' % cho3)
|
data = {
'aaa': 123,
'bbb': 123
}
count = 0
while count < 3:
username = input('Please input your username:')
password = input('Input your password:')
if username in data.keys():
if int(password) == data[username]:
exit('Login OK!')
else:
print('Information Error')
count += 1
else:
exit('Count greater than 3!')
|
"""
装饰器框架: 带参数的装饰器
"""
def before(request, kargs):
print('before')
def after(request, kargs):
print('after')
def filter(before_func, after_func):
def outer(main_func):
def wrapper(request, kargs):
before_result = before_func(request, kargs)
if before_result != None:
return before_result
main_result = main_func(request, kargs)
if main_result != None:
return main_result
after_result = after_func(request, kargs)
if after_result != None:
return after_result
return wrapper
return outer
@filter(before, after)
def Index(request, kargs):
print('index: %s %s' % (request, kargs))
Index('me', 'gy')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.