blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
1fcd42c435dbb422aaa1b5e70dcd5eaf2cad6853
pdspatrick/IT310-Code
/labs/minheightBST.py
806
3.953125
4
class TreeNode: '''Node for a simple binary tree structure''' def __init__(self, value, left, right): self.value = value self.left = left self.right = right def min_height_BST(alist): '''Returns a minimum-height BST built from the elements in alist (which are in sorted order)''' # I think we can just keep finding the middle....right? # and contiunually pass smaller lists recursively. # Trying to do this without try/except ended up with # Zybooks giving me a funny looking stack overflow error. middle = (len(alist) // 2) try: boop = TreeNode(alist[middle], None, None) boop.left = min_height_BST(alist[:middle]) boop.right = min_height_BST(alist[middle+1:]) except: pass return boop
7e19abc5efaf17e647805596b81bf9be3f3c1ea3
Thamaraiselvimurugan/python
/upplwr.py
312
3.96875
4
def upplow(a): up=0 lw=0 for i in range(len(a)): if a[i].isupper(): up=up+1 if a[i].islower(): lw=lw+1 print("No. of uppercase is ="+str(up)) print("No. of lowercase is="+str(lw)) a=raw_input("Enter a string") upplow(a)
0cc2311e0b09f3055b6e85921c3c53f8a1a474f5
JakeVidal/ECE-441-project
/number_format.py
401
3.8125
4
input_value = float(input("enter a decimal value: ")) output_value = "00" adjustment = "0000000000000001" post_decimal = input_value for i in range(0, 14): temp = post_decimal post_decimal = temp*2 - int(temp*2) temp = temp*2 output_value = output_value + str(int(temp)) output_value = int(output_value, 2) + int(adjustment, 2) output_value = hex(output_value) print(output_value)
7c6a6f84e2240e40c9593283083457ff27d78e7f
MiWerner/rAIcer
/Clients/Python-rAIcer-Client/MatrixOps.py
6,900
3.53125
4
import numpy as np import math def multidim_intersect(arr1, arr2): """ Finds and returns all points that are present in both arrays :param arr1: the first array :param arr2: the second array :return: an array of all points that are present in both arrays """ # Remove third dimension from the arrays arr1 = arr1.reshape(len(arr1), 2) arr2 = arr2.reshape(len(arr2), 2) # Change the inner arrays to tuples to compare them arr1_view = arr1.view([('', arr1.dtype)]*arr1.shape[1]) arr2_view = arr2.view([('', arr2.dtype)]*arr2.shape[1]) # Find the intersections and return them intersected = np.intersect1d(arr1_view, arr2_view) return intersected.view(arr1.dtype).reshape(-1, arr1.shape[1]) def multidim_indexof(array, element): """ Finds and returns the index of the first occurrence of element in array :param array: the first array :param element: the element to find :return: the index of the first occurrence of element in array """ # Maybe improve performance later? The numpy variants do not seem to work though for i in range(0, len(array)): if np.array_equal(array[i], element): return i return -1 def convex_combination(point1, point2, factor=0.5, flip=False): """ Calculates the convex combination of two points with a given factor and returns the resulting point which optionally flipped :param point1: the first point :param point2: the second point :param factor: the factor for the first point :param flip: whether the resulting point should be flipped :return: the convex combination of both points """ result = point1*factor + point2*(1-factor) return np.flip(result, axis=0) if flip else result def fast_norm(vector): """ Calculates the norm of the given (numpy) vector(s) using standard math library instead of numpy because it is faster on single vectors :param vector: the vector :return: the norm(s) of the vector(s) """ if hasattr(vector, "ndim") and vector.ndim == 2: n = len(vector) norms = np.zeros(n) for i in range(n): norms[i] = math.sqrt(vector[i][0]**2 + vector[i][1]**2) return norms return math.sqrt(vector[0]**2 + vector[1]**2) def angle_between_vectors(vector1, vector2): """ Calculates the angle in radians between two vectors by taking the dot product of their unit vectors :param vector1: the first vector :param vector2: the second vector :return: the angle in radians between both vectors """ vector1 = vector1 / fast_norm(vector1) vector2 = vector2 / fast_norm(vector2) return np.arccos(np.clip(np.dot(vector1, vector2), -1.0, 1.0)) def find_closest_point_index(point, points): """ Find and return the index of the point closest to the given point from a list of points :param point: the point to find the closest to :param points: the list of points :return: the index of the point closest to the given point """ distances = np.linalg.norm(points - point, axis=1) return np.argmin(distances) def find_closest_point(point, points): """ Find and return the point closest to the given point from a list of points :param point: the point to find the closest to :param points: the list of points :return: the point closest to the given point """ return points[find_closest_point_index(point, points)] def get_perpendicular_vector(point1, point2, direction=0, normalized=True): """ Returns one of the two perpendicular vectors to the vector between the two given points and optionally normalizes it :param point1: the first point :param point2: the second point :param direction: the direction of the resulting vector (either 0 or 1) :param normalized: whether the result should be normalized :return: the perpendicular vector to the vector between the two points """ point1 = point1.reshape(2) point2 = point2.reshape(2) result = np.flip(point2 - point1, axis=0) result[direction] = -result[direction] return result / fast_norm(result) if normalized else result def create_line_iterator(point1, point2, img): """ Produces and array that consists of the coordinates and intensities of each pixel in a line between two points (see https://stackoverflow.com/a/32857432/868291) :param point1: the first point :param point2: the second point :param img: the image being processed :return: a numpy array that consists of the coordinates and an array with the intensities of each pixel in the radii (shape: [numPixels, 3], row = [x,y,intensity]) """ # Define local variables for readability imageH = img.shape[1] imageW = img.shape[0] P1X = point1[0] P1Y = point1[1] P2X = point2[0] P2Y = point2[1] # Difference and absolute difference between points (used to calculate slope and relative location between points) dX = P2X - P1X dY = P2Y - P1Y dXa = np.abs(dX) dYa = np.abs(dY) # Predefine numpy array for output based on distance between points itbuffer = np.empty(shape=(np.maximum(dYa, dXa), 2), dtype=np.float32) itbuffer.fill(np.nan) # Obtain coordinates along the line using a form of Bresenham's algorithm negY = P1Y > P2Y negX = P1X > P2X if P1X == P2X: # Vertical line segment itbuffer[:, 0] = P1X if negY: itbuffer[:, 1] = np.arange(P1Y - 1, P1Y - dYa - 1, -1) else: itbuffer[:, 1] = np.arange(P1Y+1, P1Y+dYa+1) elif P1Y == P2Y: # Horizontal line segment itbuffer[:, 1] = P1Y if negX: itbuffer[:, 0] = np.arange(P1X-1, P1X-dXa-1, -1) else: itbuffer[:, 0] = np.arange(P1X+1, P1X+dXa+1) else: # Diagonal line segment steepSlope = dYa > dXa if steepSlope: slope = dX.astype(np.float32) / dY.astype(np.float32) if negY: itbuffer[:, 1] = np.arange(P1Y-1, P1Y-dYa-1, -1) else: itbuffer[:, 1] = np.arange(P1Y+1, P1Y+dYa+1) itbuffer[:, 0] = (slope*(itbuffer[:, 1]-P1Y)).astype(np.int) + P1X else: slope = dY.astype(np.float32) / dX.astype(np.float32) if negX: itbuffer[:, 0] = np.arange(P1X-1, P1X-dXa-1, -1) else: itbuffer[:, 0] = np.arange(P1X+1, P1X+dXa+1) itbuffer[:, 1] = (slope*(itbuffer[:, 0]-P1X)).astype(np.int) + P1Y # Remove points outside of image colX = itbuffer[:, 0] colY = itbuffer[:, 1] itbuffer = itbuffer[(colX >= 0) & (colY >= 0) & (colX < imageW) & (colY < imageH)] # Get intensities from img ndarray intensities = img[itbuffer[:, 0].astype(np.uint), itbuffer[:, 1].astype(np.uint)] return itbuffer, intensities
f53dec941f3422e8731285a1f3a375ea45121c41
ifeedtherain/Python_Stepik
/02-07_stringm.py
244
3.515625
4
s = str(input()) t = str(input()) cnt = 0 def cnt_occur(s, t, cnt): i = -1 while True: i = s.find(t, i+1) if i == -1: return cnt cnt += 1 if t in s: print(cnt_occur(s,t, cnt)) else: print(cnt)
b367f9a09739b87aef87a011a5e9454b87c3b6fe
ArielAyala/python-conceptos-basicos-y-avanzados
/Unidad 4/Tuplas.py
338
4.09375
4
tupla = (100, "Hola", [1, 2, 3], -50) for dato in tupla: print(dato) # Funciones de tuplas print("La cantidad de datos que tiene esta posicion (Solo si son listas) en la tupla es :",len(tupla[1])) print("El índice del valor 100 es :", tupla.index(100)) print("El índice del valor 'Hola' es :", tupla.index("Hola")) print("454")
eb65ff92ef8086781e3657ca6f543dc2edadc228
ArielAyala/python-conceptos-basicos-y-avanzados
/Unidad 4/Listas.py
737
4.21875
4
numeros = [1, 2, 3, 4, 5] datos = [5, "cadena", 5.5, "texto"] print("Numeros", numeros) print("Datos", datos) # Mostramos datos de la lista por índice print("Mostramos datos de la lista por índice :", datos[-1]) # Mostramos datos por Slicing print("Mostramos datos por Slicing :", datos[0:2]) # Suma de Listas listas = numeros + datos print("La suma de las listas es :", listas) # Mutabilidad pares = [0, 2, 4, 5, 8, 10] pares[3] = 6 print("Lista de pares, mutando un valor :", pares) # Funciones o métodos de Listas c = len(pares) print("La función 'len' cuenta cuandos datos tiene la lista, ejemplo la lista pares :", c) pares.append(12) print("La función 'append' agregar un dato al final de la lista, ejemplo :", pares)
5d86707b669cf0fcf7c822473de137649d5a228e
ArielAyala/python-conceptos-basicos-y-avanzados
/Unidad 8/MetodosEspeciales.py
669
3.84375
4
class Pelicula: # Contructor de la clase def __init__(self, titulo, duracion, lanzamiento): self.titulo = titulo self.duracion = duracion self.lanzamiento = lanzamiento print("Se creó la película", self.titulo) # Destructor de la lcase def __del__(self): print("Se está borrando la película", self.titulo) # Redefiniendo el método string def __str__(self): return "{} lanzando el {} con duración de {} minutos.".format(self.titulo, self.lanzamiento, self.duracion) def __len__(self): return self.duracion pelicula = Pelicula("El Padrino", 175, 1973) print(str(pelicula))
745b9f249e9c21f26fc2a4c9f04f4aa604c2293e
valerocar/geometry-blender
/gblend/geometry.py
10,000
4.1875
4
""" Geometry classes """ from gblend.variables import x, y, z, rxy from sympy.algebras.quaternion import Quaternion from sympy import symbols, cos, sin, sqrt, N, lambdify, exp def sigmoid(s, k): """ The sigmoid function. :param s: independent variable :param k: smoothing parameter :return: """ return 1 / (1 + exp(-(s / k))) class Geometry: """ The Geometry class is used to encapsulate the concept of a region defined by the set of point at which a function is greater or equal to 1/2. """ def __init__(self, f, dim): """ Creates a geometrical object defined by the inequality f(p) >= 1/2 :param f: a function :param dim: the number of independent variable of the function """ self.dim = dim self.f = f def __geometry(self, f): if self.dim == 2: return Geometry2D(f) elif self.dim == 3: return Geometry3D(f) return Geometry(self, f) def __and__(self, b): """ Returns an object that is the intersection of this object with b :param b: :return: """ return self.__geometry(self.f * b.f) def __or__(self, b): """ Returns an object that is the union of this object with b :param b: :return: """ return self.__geometry(self.f + b.f - self.f * b.f) def __invert__(self): """ Returns the complement (in the set theoretical sense) of this object :return: """ return self.__geometry(1 - self.f) def __sub__(self, b): """ Returns an object that is the difference of this object with b :param b: :return: """ return self.__geometry(self.f * (1 - b.f)) def get_lambda(self): """ Returns the lambda function of the function f, so that it can be used for numerical evaluation :return: """ if self.dim == 3: return lambdify((x, y, z), self.f, 'numpy') elif self.dim == 2: return lambdify((x, y), self.f, 'numpy') return None class Geometry3D(Geometry): def __init__(self, f): Geometry.__init__(self, f, 3) @staticmethod def subs_3d(f, x_new, y_new, z_new): xx, yy, zz = symbols("xx yy zz", real=True) xx_new = x_new.subs({x: xx, y: yy, z: zz}) yy_new = y_new.subs({x: xx, y: yy, z: zz}) zz_new = z_new.subs({x: xx, y: yy, z: zz}) tmp = f.subs({x: xx_new, y: yy_new, z: zz_new}) return tmp.subs({xx: x, yy: y, zz: z}) def translated(self, dx, dy, dz): """ Returns a translated version of this object :param dx: distance translates in the x-direction :param dy: distance translates in the y-direction :param dz: distance translates in the z-direction :return: a translated version of this object """ return Geometry3D(Geometry3D.subs_3d(self.f, x - dx, y - dy, z - dz)) def displaced(self, f, axis='z'): """ Returns this object displaced by one of the formulas (x,y,z) -> (x+f(y,z),y,z) (x,y,z) -> (x,f(x,z),z) (x,y,z) -> (x,y,z+f(x,y)) depending on whether axis is "x", "y" or "z". :param f: a function in 2-variables none of which is the axis variable :param axis: the axis along which the object will be displaced :return: the displaced object """ # TODO: Check for f variables dependencies if axis == 'x': return Geometry3D(self.subs_3d(self.f, x - f, y, z)) elif axis == 'y': return Geometry3D(self.subs_3d(self.f, x, y - f, z)) elif axis == 'z': return Geometry3D(self.subs_3d(self.f, x, y, z - f)) return None def scaled(self, sx: float, sy: float, sz: float): """ Returns a scaled version of this object :param sx: scale factor in the x-direction :param sy: scale factor in the y-direction :param sz: scale factor in the y-direction :return: a scaled version of this object """ return Geometry3D(Geometry3D.subs_3d(self.f, x / sx, y / sy, z / sz)) def rotated(self, nx: float, ny: float, nz: float, theta: float): """ Returns a rotated version of this object :param nx: x-component of the rotation axis :param ny: y-component of the rotation axis :param nz: z-component of the rotation axis :param theta: rotation angle :return: a rotated version of this object """ nrm = N(sqrt(nx ** 2 + ny ** 2 + nz ** 2)) sn2 = N(sin(theta / 2)) cs2 = N(cos(theta / 2)) q = Quaternion(cs2, sn2 * nx / nrm, sn2 * ny / nrm, sn2 * nz / nrm) q_inv = q.conjugate() r = q_inv * Quaternion(0, x, y, z) * q return Geometry3D(self.subs_3d(self.f, r.b, r.c, r.d)) def displace(self, f, axis='z'): self.f = self.displaced(f, axis).f def translate(self, dx: float, dy: float, dz: float): self.f = self.translated(dx, dy, dz).f def scale(self, sx, sy, sz): self.f = self.scaled(sx, sy, sz).f def rotate(self, nx, ny, nz, theta): self.f = self.rotated(nx, ny, nz, theta).f ################################### # # # Concrete Geometry Types # # (sigmoid functions here! # # # ################################### class HalfSpace3D(Geometry3D): """ Defines the half space as the set of points (x,y,z) satisfying nx*x + ny*y + nz*z >= 0 """ def __init__(self, nx=0, ny=0, nz=1, k=1 / 2): """ Defines the half space as the set of points (x,y,z) satisfying nx*x + ny*y + nz*z >= 0 :param nx: x-component of the normal vector to the plane :param ny: y-component of the normal vector to the plane :param nz: z-component of the normal vector to the plane :param k: smoothing parameter """ Geometry3D.__init__(self, sigmoid(nx * x + ny * y + nz * z, k)) class FunctionGraph3D(Geometry3D): def __init__(self, fxy, k=1 / 2): """ Defines the region that consists of the set of point (x,y,z) such that z >= f_xy(x,y) :param fxy: function dependent of the variables (x,y) and independent of z :param k:smoothing parameter """ Geometry3D.__init__(self, sigmoid(z - fxy, k)) class Ball3D(Geometry3D): def __init__(self, x0=0, y0=0, z0=0, r_val=1, k=1 / 2): """ A ball in 3-dimensional space :param x0: the x-component of the center of the ball :param y0: the y-component of the center of the ball :param z0: the z-component of the center of the ball :param r_val: the radius of the ball :param k: smoothing factor """ Geometry3D.__init__(self, sigmoid(r_val ** 2 - (x - x0) ** 2 - (y - y0) ** 2 - (z - z0) ** 2, k)) class Cylinder3D(Geometry3D): def __init__(self, x0=0, y0=0, r_val=1, k=1 / 2): """ A cylinder in 3-dimensional space :param x0: the x-component of the cylinder's center :param y0: the y-component of the cylinder's center :param r_val: the y-component of the cylinder's center :param k: the smoothing factor """ Geometry3D.__init__(self, sigmoid(r_val ** 2 - (x - x0) ** 2 - (y - y0) ** 2, k)) class RevolutionSurface3D(Geometry3D): def __init__(self, curve_eq, k=1 / 2): """ A surface obtained by rotating a curve around the z-axis :param curve_eq: equation of curve in the r and z variables :param k: smoothing parameter """ Geometry3D.__init__(self, sigmoid(RevolutionSurface3D.compute_f(curve_eq), k)) @staticmethod def compute_f(curve_eq): return curve_eq.subs({rxy: sqrt(x ** 2 + y ** 2)}) class Torus3D(RevolutionSurface3D): def __init__(self, r_min=1, r_max=2, k=1 / 2): """ A torus in 3-dimensional space :param r_min: radius of the torus circular cross sections :param r_max: radius to the center of the torus circular cross section :param k: smoothing parameter """ RevolutionSurface3D.__init__(self, r_min ** 2 - (rxy - r_max) ** 2 - z ** 2, k) ########################## # # # Geometry 2D # # # ########################## class Geometry2D(Geometry): def __init__(self, f): Geometry.__init__(self, f, 2) def translated(self, dx, dy): return Geometry2D(self.subs_2d(self.f, x - dx, y - dy)) def scaled(self, sx, sy): return Geometry2D(self.subs_2d(self.f, x / sx, y / sy)) def rotated(self, theta): return Geometry2D(self.subs_2d(self.f, x * cos(theta) + y * sin(theta), -x * sin(theta) + y * cos(theta))) def translate(self, dx, dy): self.f = self.translated(dx, dy).f def scale(self, sx, sy): self.f = self.scaled(sy, sx).f def rotate(self, theta): self.f = self.rotated(theta).f @staticmethod def subs_2d(f, x_new, y_new): xx, yy = symbols("xx yy", real=True) xx_new = x_new.subs({x: xx, y: yy}) yy_new = y_new.subs({x: xx, y: yy}) tmp = f.subs({x: xx_new, y: yy_new}) return tmp.subs({xx: x, yy: y}) class Disk2D(Geometry2D): def __init__(self, x0=0, y0=0, r=1, k=1 / 2): Geometry2D.__init__(self, sigmoid(r ** 2 - (x - x0) ** 2 - (y - y0) ** 2, k)) class HalfPlane2D(Geometry2D): def __init__(self, x0, y0, x1, y1, k=1 / 2): Geometry2D.__init__(self, sigmoid(HalfPlane2D.compute_f(x0, y0, x1, y1), k)) @staticmethod def compute_f(x0, y0, x1, y1): dx = x1 - x0 dy = y1 - y0 return -dy * (x - x0) + dx * (y - y0)
e129e980c58a0c812c96d4d862404361765cbaa6
rafiqulislam21/python_codes
/serieWithValue.py
660
4.1875
4
n = int(input("Enter the last number : ")) sumVal = 0 #avoid builtin names, here sum is a built in name in python for x in range(1, n+1, 1): # here for x in range(1 = start value, n = end value, 1 = increasing value) if x != n: print(str(x)+" + ", end =" ") #this line will show 1+2+3+............ # end = " " means print will show with ount line break sumVal = sumVal + x #this line will calculate sum 1+2+3+............ else: print(str(x) + " = ", end=" ")#this line will show last value of series 5 = ............ sumVal = sumVal + x print(sumVal) #this line will show final sum result of series............
33d35100498e40f3e2e2b175bb08908764795180
Ascarik/Checkio
/Scientific_Expedition/14.py
1,256
3.71875
4
import re def checkio(line: str) -> int: # your code here gl = ('A', 'E', 'I', 'O', 'U', 'Y') sl = ('B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'X', 'Z') line = line.upper() line = re.sub("[.,!?]", " ", line) words = line.split(sep=" ") count = 0 for word in words: w1 = [word[i] for i in range(0, len(word), 2)] w2 = [word[i] for i in range(1, len(word), 2)] if len(w1) > 0 and len(w2) > 0: count = method_name(count, gl, sl, w1, w2) print(count) return count def method_name(count, gl, sl, w1, w2): if all(elem in sl for elem in w1) and all(elem in gl for elem in w2): count += 1 elif all(elem in sl for elem in w2) and all(elem in gl for elem in w1): count += 1 return count if __name__ == "__main__": print("Example:") print(checkio("My name is ...")) # These "asserts" are used for self-checking and not for an auto-testing assert checkio("My name is ...") == 3 assert checkio("Hello world") == 0 assert checkio("A quantity of striped words.") == 1 assert checkio("Dog,cat,mouse,bird.Human.") == 3 print("Coding complete? Click 'Check' to earn cool rewards!")
5fe9f18569a4428aaa121c5090e53b65b820900b
Ascarik/Checkio
/home/21.py
733
3.859375
4
from collections.abc import Iterable def duplicate_zeros(donuts: list[int]) -> Iterable[int]: # your code here l = list() for v in donuts: if v == 0: l += [0, 0] else: l.append(v) return l print("Example:") print(list(duplicate_zeros([1, 0, 2, 3, 0, 4, 5, 0]))) # These "asserts" are used for self-checking assert list(duplicate_zeros([1, 0, 2, 3, 0, 4, 5, 0])) == [ 1, 0, 0, 2, 3, 0, 0, 4, 5, 0, 0, ] assert list(duplicate_zeros([0, 0, 0, 0])) == [0, 0, 0, 0, 0, 0, 0, 0] assert list(duplicate_zeros([100, 10, 0, 101, 1000])) == [100, 10, 0, 0, 101, 1000] print("The mission is done! Click 'Check Solution' to earn rewards!")
6b0e7d8b19429a89e3efb5e3fd1ed23a01cb08a4
Ascarik/Checkio
/Scientific_Expedition/2.py
871
3.671875
4
def yaml(a): # your code here result = {} list_values = a.split("\n") for value in list_values: if not value: continue key, value = value.split(":") key, value = key.strip(), value.strip() if value.isnumeric(): value = int(value) result[key] = value return result if __name__ == '__main__': print("Example:") print(yaml("""name: Alex age: 12""")) # These "asserts" are used for self-checking and not for an auto-testing assert {'name': 'Alex', 'age': 12} == {'age': 12, 'name': 'Alex'} assert yaml("""name: Alex age: 12""") == {'age': 12, 'name': 'Alex'} assert yaml("""name: Alex Fox age: 12 class: 12b""") == {'age': 12, 'class': '12b', 'name': 'Alex Fox'} print("Coding complete? Click 'Check' to earn cool rewards!")
222fde26ceeabe38f9af3ff6da73fa3328a0ce44
idrishkhan/IDRISHKHAN
/idrish 10.py
71
3.546875
4
x=int(input()) count=0 while(x>1): x=x/10 count=count+1 print(count)
f390a3bee6b5ef187a5c8ab9c60091cb289862bb
MatusMaruna/Transformers
/4DV507.rd222dv.A4/ofp_example_programs/while.py
182
3.625
4
def sumUpTo(n): i=1 ofp_sum=0 while i<n+1: ofp_sum=ofp_sum+i i=i+1 return ofp_sum # # Program entry point - main # n=10 res=sumUpTo(n) print(res)
378377ffb254db27a2e823bd282124a63dfba06c
mmore500/conduit
/tests/netuit/arrange/scripts/make_ring.py
772
3.671875
4
#!/usr/bin/python3 """ Generate ring graphs. This script makes use of NetworkX to generate ring graphs (nodes are connected in a ring). This tool creates adjacency list files (.adj) whose filename represent the characteristics of the graph created. """ from keyname import keyname as kn import networkx as nx dims = [3, 10, 15, 27, 56, 99] def make_filename(dim): return kn.pack({ 'name' : 'ring', 'ndims' : '1', 'dim0' : str(dim), 'ext' : '.adj', }) for dim in dims: ring = [edge for edge in zip(range(dim), range(1, dim))] + [(dim - 1, 0)] G_ring = nx.DiGraph(ring) with open("assets/" + make_filename(dim), "w") as file: for line in nx.generate_adjlist(G_ring): file.write(line + '\n')
407ae0b9bd3004e0655b747f9f5ffda563ae8cae
anooptrivedi/workshops-python-level2
/list2.py
338
4.21875
4
# Slicing in List - more examples example = [0,1,2,3,4,5,6,7,8,9] print(example[:]) print(example[0:10:2]) print(example[1:10:2]) print(example[10:0:-1]) #counting from right to left print(example[10:0:-2]) #counting from right to left print(example[::-3]) #counting from right to left print(example[:5:-1]) #counting from right to left
ca7c8607e41db501f958a746028fb28040133d54
anooptrivedi/workshops-python-level2
/guessgame.py
460
4.125
4
# Number guessing game import random secret = random.randint(1,10) guess = 0 attempts = 0 while secret != guess: guess = int(input("Guess a number between 1 and 10: ")) attempts = attempts + 1; if (guess == secret): print("You found the secret number", secret, "in", attempts, "attempts") quit() elif (guess > secret): print("Your guess is high, try again") else: print("Your guess is low, try again")
c5dae743955e135a879799766903fe1e9a6d4b1f
abhinavk99/rubik-solver
/src/solver.py
8,055
3.546875
4
from tkinter import Tk, Label, Button, Canvas, StringVar, Entry from cube import Cube class RubikSolverGUI: def __init__(self, master): """Creates the GUI""" self.master = master master.title('Rubik Solver') self.label = Label(master, text='Rubik Solver') self.label.pack() self.rand_string_button = Button(master, text='Enter randomizer string', command=self.randStringEntry) self.rand_string_button.pack() self.rand_scramble_button = Button(master, text='Randomly scramble cube', command=self.startRandScramble) self.rand_scramble_button.pack() self.solved_button = Button(master, text='Start with solved cube', command=self.startSolved) self.solved_button.pack() self.canvas = Canvas(master, width=400, height=350) self.canvas.pack() def randStringEntry(self): """Sets up GUI for entering the randomizer string""" self.destroyInitButtons() self.showEntry(self.randStringCreate) def randStringCreate(self): """Creates the cube with the randomizer string""" self.string_entry.destroy() self.create_button.destroy() self.rubik = Cube(self.string.get()) self.showOptions() self.drawCube() def startRandScramble(self): """Creates a randomly scrambled cube""" self.destroyInitButtons() self.rubik = Cube() scramble_str = self.rubik.scramble() self.canvas.create_text(120, 300, fill='black', font='Helvetica 13', text=scramble_str) self.showOptions() self.drawCube() def startSolved(self): """Starts the cube to solved state""" self.destroyInitButtons() self.rubik = Cube() self.showOptions() self.drawCube() def showOptions(self): """Shows options for acting on cube""" self.solve_button = Button(self.master, text='Solve cube', command=self.solveCube) self.solve_button.pack() self.new_scramble_button = Button(self.master, text='Enter move string for new cube', command=self.newCubeEntry) self.new_scramble_button.pack() self.add_moves_button = Button(self.master, text='Add moves to current cube', command=self.addMovesEntry) self.add_moves_button.pack() self.check_solved_button = Button(self.master, text='Check if cube is solved', command=self.checkCubeSolved) self.check_solved_button.pack() self.reset_button = Button(self.master, text='Reset cube', command=self.resetCube) self.reset_button.pack() self.rand_scramble_button = Button(self.master, text='Randomly scramble cube', command=self.randScramble) self.rand_scramble_button.pack() def solveCube(self): """Solves the cube""" self.rubik.solve() self.canvas.delete('all') self.drawCube() def newCubeEntry(self): """Sets up GUI to create a new cube with randomizer string""" self.destroyOptions() self.canvas.delete('all') self.showEntry(self.randStringCreate) def addMovesEntry(self): """Sets up GUI to add moves to current cube with randomizer string""" self.destroyOptions() self.canvas.delete('all') self.showEntry(self.addMoves) def addMoves(self): """Add moves to current cube with randomizer string""" self.string_entry.destroy() self.create_button.destroy() self.canvas.delete('all') try: self.rubik.parse_randomizer(self.string.get()) except ValueError as e: self.canvas.create_text(120, 300, fill='black', font='Helvetica 13', text=str(e)) self.showOptions() self.drawCube() def showEntry(self, method): """Sets up GUI for entering randomizer string""" self.string = StringVar() self.canvas.delete('all') self.string_entry = Entry(self.master, width=100, textvariable=self.string) self.string_entry.pack() self.create_button = Button(self.master, text='Create', command=method) self.create_button.pack() def checkCubeSolved(self): """Checks if cube is solved""" res = 'Cube is ' + ('' if self.rubik.check_solved() else 'not ') + 'solved.' self.canvas.delete('all') self.canvas.create_text(120, 300, fill='black', font='Helvetica 13', text=res) self.drawCube() def resetCube(self): """Resets the cube to solved state""" self.rubik.reset() self.canvas.delete('all') self.canvas.create_text(120, 300, fill='black', font='Helvetica 13', text='Reset cube to solved state.') self.drawCube() def randScramble(self): """Randomly scrambles the cube""" self.rubik = Cube() scramble_str = self.rubik.scramble() self.canvas.delete('all') self.canvas.create_text(120, 300, fill='black', font='Helvetica 13', text=scramble_str) self.drawCube() def destroyInitButtons(self): """Destroys initial buttons""" self.rand_string_button.destroy() self.rand_scramble_button.destroy() self.solved_button.destroy() def destroyOptions(self): """Destroys options buttons""" self.solve_button.destroy() self.new_scramble_button.destroy() self.add_moves_button.destroy() self.check_solved_button.destroy() self.reset_button.destroy() self.rand_scramble_button.destroy() def drawCube(self): """Displays cube in unfolded format (cross on its side)""" colors = { 'o': 'orange', 'g': 'green', 'r': 'red', 'b': 'blue', 'w': 'white', 'y': 'yellow' } mat = self.rubik.faces['u'] for i in range(3): self.canvas.create_rectangle(90, 30 * i, 120, 30 + 30 * i, fill=colors[mat[i][0]]) self.canvas.create_rectangle(120, 30 * i, 150, 30 + 30 * i, fill=colors[mat[i][1]]) self.canvas.create_rectangle(150, 30 * i, 180, 30 + 30 * i, fill=colors[mat[i][2]]) arr = ['l', 'f', 'r'] for j in range(3): for i in range(3): mat = self.rubik.faces[arr[i]] self.canvas.create_rectangle(90 * i, 90 + 30 * j, 30 + 90 * i, 120 + 30 * j, fill=colors[mat[j][0]]) self.canvas.create_rectangle(30 + 90 * i, 90 + 30 * j, 60 + 90 * i, 120 + 30 * j, fill=colors[mat[j][1]]) self.canvas.create_rectangle(60 + 90 * i, 90 + 30 * j, 90 + 90 * i, 120 + 30 * j, fill=colors[mat[j][2]]) mat = self.rubik.faces['b'] self.canvas.create_rectangle(270, 90 + 30 * j, 300, 120 + 30 * j, fill=colors[mat[2 - j][2]]) self.canvas.create_rectangle(300, 90 + 30 * j, 330, 120 + 30 * j, fill=colors[mat[2 - j][1]]) self.canvas.create_rectangle(330, 90 + 30 * j, 360, 120 + 30 * j, fill=colors[mat[2 - j][0]]) mat = self.rubik.faces['d'] for i in range(3): self.canvas.create_rectangle(90, 180 + 30 * i, 120, 210 + 30 * i, fill=colors[mat[i][0]]) self.canvas.create_rectangle(120, 180 + 30 * i, 150, 210 + 30 * i, fill=colors[mat[i][1]]) self.canvas.create_rectangle(150, 180 + 30 * i, 180, 210 + 30 * i, fill=colors[mat[i][2]]) top = Tk() my_gui = RubikSolverGUI(top) top.minsize(600, 450) top.mainloop()
00fb14c2e66e3c49102c223d3ec95266ab15cd2d
drvinceknight/agent-based-learn
/ablearn/population/agents.py
593
3.875
4
class Agent: """ A generic class for agents that will be used by the library """ """ INITIALIZATION """ def __init__(self, strategies=False, label=False): # The properties each agent will have. self.strategies = strategies # Strategy the agent will use. self.utility = 0 # Utility the agent will obtain. self.label = label # If required a label to track a specific agent. def increment_utility(self, amount=1): # How much their utility will increase self.utility += float(amount) # Utility for each agent will increase in this amount.
ab8cacb11a83b66b3754303ddbd8b8532130f590
igoreduardo/teste_python_junior
/teste_1240.py
217
3.515625
4
ncasos = int(input()) while ncasos > 0: a,b = list(input().split()) if (len(a) >= len(b)): if a[-len(b):] == b: print("encaixa") else: print("não encaixa") else: print('') ncasos -=1
1325e94c27e1a70f6ccaa8d12ab54900a351504e
harshajk/advent-of-code-2020
/day01.py
1,103
3.53125
4
import unittest import itertools def day1p1(filename): f = open(filename, "r") entries = [int(ent) for ent in set(f.read().split("\n"))] for ent in entries: reqrd = 2020 - ent if reqrd in entries: f.close() return reqrd * ent return -1 def day1p2(filename): f = open(filename, "r") entries = [int(ent) for ent in set(f.read().split("\n"))] permutations = itertools.permutations(entries,3) for a, b, c in permutations: if a + b + c == 2020: f.close() return a * b * c return -1 class TestDay1(unittest.TestCase): def test_day1p1_example(self): result = day1p1("input/day01test.txt") self.assertEqual(514579, result) def test_day1p1_actual(self): result = day1p1("input/day01.txt") self.assertEqual(864864, result) def test_day1p2_actual(self): result = day1p2("input/day01.txt") self.assertEqual(281473080, result) if __name__ == '__main__': unittest.main()
4d4336b3a33831a4a0f48faa84051ba3233aba0e
ppnbb/Python
/list.py
119
3.5
4
s = [1, 'four', 9, 16, 25] print(s) print(s[0]) print(len(s)) s[1] = 4 print(s) del s[2] print(s) s.append(36) print(s)
f7c99be0a3edde23c91d40edbe184d7f7f6a89ca
INFOPAUL/DeepLearning_Proj2
/activations/Tanh.py
838
3.59375
4
from Module import Module class Tanh(Module): """Applies the element-wise function: Tanh(x) = \tanh(x) = \frac{\exp(x) - \exp(-x)} {\exp(x) + \exp(-x)} Shape ----- - Input: `(N, *)` where `*` means, any number of additional dimensions - Output: `(N, *)`, same shape as the input Examples -------- >>> l = nn.Tanh() >>> input = torch.randn(2) >>> output = l.forward(input) """ def __init__(self): super().__init__() self.input = None def forward(self, input): """Forward pass for the Tanh activation function""" self.input = input.clone() return self.input.tanh() def backward(self, grad): """Backward pass for the Tanh activation function""" return grad.t().mul(1 - (self.input.tanh() ** 2))
4047cddfa36d495357e8cbe9d890406446c888ae
INFOPAUL/DeepLearning_Proj2
/weight_initialization/xavier_uniform.py
662
4
4
import math def xavier_uniform(tensor): """Fills the input tensor with values according to the method described in `Understanding the difficulty of training deep feedforward neural networks` - Glorot, X. & Bengio, Y. (2010), using a uniform distribution. The resulting tensor will have values sampled from Uniform(-a, a) where a = \sqrt{\frac{6}{\text{fan\_in} + \text{fan\_out}}} Parameters ---------- tensor: an n-dimensional tensor Examples: >>> w = torch.empty(3, 5) >>> xavier_uniform(w) """ std = math.sqrt(6.0 / float(tensor.size(0) + tensor.size(1))) return tensor.uniform_(-std, std)
21947c14f2c2f197853704ac0fad4f42022be6d4
x4nth055/pythoncode-tutorials
/machine-learning/image-transformation/reflection.py
934
3.5625
4
import numpy as np import cv2 import matplotlib.pyplot as plt # read the input image img = cv2.imread("city.jpg") # convert from BGR to RGB so we can plot using matplotlib img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # disable x & y axis plt.axis('off') # show the image plt.imshow(img) plt.show() # get the image shape rows, cols, dim = img.shape # transformation matrix for x-axis reflection M = np.float32([[1, 0, 0 ], [0, -1, rows], [0, 0, 1 ]]) # transformation matrix for y-axis reflection # M = np.float32([[-1, 0, cols], # [ 0, 1, 0 ], # [ 0, 0, 1 ]]) # apply a perspective transformation to the image reflected_img = cv2.warpPerspective(img,M,(int(cols),int(rows))) # disable x & y axis plt.axis('off') # show the resulting image plt.imshow(reflected_img) plt.show() # save the resulting image to disk plt.imsave("city_reflected.jpg", reflected_img)
a1b6068223e0aaaab6976e0c06c48171254c3fbc
x4nth055/pythoncode-tutorials
/python-standard-library/using-threads/multiple_threads_using_threading.py
1,561
3.609375
4
import requests from threading import Thread from queue import Queue # thread-safe queue initialization q = Queue() # number of threads to spawn n_threads = 5 # read 1024 bytes every time buffer_size = 1024 def download(): global q while True: # get the url from the queue url = q.get() # download the body of response by chunk, not immediately response = requests.get(url, stream=True) # get the file name filename = url.split("/")[-1] with open(filename, "wb") as f: for data in response.iter_content(buffer_size): # write data read to the file f.write(data) # we're done downloading the file q.task_done() if __name__ == "__main__": urls = [ "https://cdn.pixabay.com/photo/2018/01/14/23/12/nature-3082832__340.jpg", "https://cdn.pixabay.com/photo/2013/10/02/23/03/dawn-190055__340.jpg", "https://cdn.pixabay.com/photo/2016/10/21/14/50/plouzane-1758197__340.jpg", "https://cdn.pixabay.com/photo/2016/11/29/05/45/astronomy-1867616__340.jpg", "https://cdn.pixabay.com/photo/2014/07/28/20/39/landscape-404072__340.jpg", ] * 5 # fill the queue with all the urls for url in urls: q.put(url) # start the threads for t in range(n_threads): worker = Thread(target=download) # daemon thread means a thread that will end when the main thread ends worker.daemon = True worker.start() # wait until the queue is empty q.join()
650fae3372e044e73b1bed85128889758ae1f885
x4nth055/pythoncode-tutorials
/machine-learning/shape-detection/circle_detector.py
1,117
3.59375
4
import cv2 import numpy as np import matplotlib.pyplot as plt import sys # load the image img = cv2.imread(sys.argv[1]) # convert BGR to RGB to be suitable for showing using matplotlib library img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # make a copy of the original image cimg = img.copy() # convert image to grayscale img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # apply a blur using the median filter img = cv2.medianBlur(img, 5) # finds the circles in the grayscale image using the Hough transform circles = cv2.HoughCircles(image=img, method=cv2.HOUGH_GRADIENT, dp=0.9, minDist=80, param1=110, param2=39, maxRadius=70) for co, i in enumerate(circles[0, :], start=1): # draw the outer circle in green cv2.circle(cimg,(i[0],i[1]),i[2],(0,255,0),2) # draw the center of the circle in red cv2.circle(cimg,(i[0],i[1]),2,(0,0,255),3) # print the number of circles detected print("Number of circles detected:", co) # save the image, convert to BGR to save with proper colors # cv2.imwrite("coins_circles_detected.png", cimg) # show the image plt.imshow(cimg) plt.show()
4cb9aea7093ea178b506ef4b522e6c8fd7bf7444
x4nth055/pythoncode-tutorials
/python-standard-library/logging/logger_handlers.py
630
3.609375
4
import logging # return a logger with the specified name & creating it if necessary logger = logging.getLogger(__name__) # create a logger handler, in this case: file handler file_handler = logging.FileHandler("file.log") # set the level of logging to INFO file_handler.setLevel(logging.INFO) # create a logger formatter logging_format = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s") # add the format to the logger handler file_handler.setFormatter(logging_format) # add the handler to the logger logger.addHandler(file_handler) # use the logger as previously logger.critical("This is a critical message!")
b579ca7d200ccf359ddaddbfc63bcb2523f0b3ab
x4nth055/pythoncode-tutorials
/machine-learning/image-transformation/translation.py
768
3.65625
4
import numpy as np import cv2 import matplotlib.pyplot as plt # read the input image img = cv2.imread("city.jpg") # convert from BGR to RGB so we can plot using matplotlib img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # disable x & y axis plt.axis('off') # show the image plt.imshow(img) plt.show() # get the image shape rows, cols, dim = img.shape # transformation matrix for translation M = np.float32([[1, 0, 50], [0, 1, 50], [0, 0, 1]]) # apply a perspective transformation to the image translated_img = cv2.warpPerspective(img, M, (cols, rows)) # disable x & y axis plt.axis('off') # show the resulting image plt.imshow(translated_img) plt.show() # save the resulting image to disk plt.imsave("city_translated.jpg", translated_img)
a36caeefcb4d3981e146ec5be64caae06d2d8e39
x4nth055/pythoncode-tutorials
/general/simple-math-game/simple_math_game.py
1,015
3.953125
4
# Imports import pyinputplus as pyip from random import choice # Variables questionTypes = ['+', '-', '*', '/', '**'] numbersRange = [num for num in range(1, 20)] points = 0 # Hints print('Round down to one Number after the Comma.') print('When asked to press enter to continue, type stop to stop.\n') # Game Loop while True: # Deciding and generating question currenType = choice(questionTypes) promptEquation = str(choice(numbersRange)) + ' ' + currenType + ' ' + str(choice(numbersRange)) solution = round(eval(promptEquation), 1) # Getting answer from User answer = pyip.inputNum(prompt=promptEquation + ' = ') # Feedback and Points if answer == solution: points += 1 print('Correct!\nPoints: ',points) else: points -= 1 print('Wrong!\nSolution: '+str(solution)+'\nPoints: ',points) # Stopping the Game if pyip.inputStr('Press "Enter" to continue', blank=True) == 'stop': break # Some Padding print('\n\n')
556a1ee02b0e41c666f2ded73fe84d46d177ccd0
x4nth055/pythoncode-tutorials
/ethical-hacking/ftp-cracker/simple_ftp_cracker.py
1,153
3.5625
4
import ftplib from colorama import Fore, init # for fancy colors, nothing else # init the console for colors (for Windows) init() # hostname or IP address of the FTP server host = "192.168.1.113" # username of the FTP server, root as default for linux user = "test" # port of FTP, aka 21 port = 21 def is_correct(password): # initialize the FTP server object server = ftplib.FTP() print(f"[!] Trying", password) try: # tries to connect to FTP server with a timeout of 5 server.connect(host, port, timeout=5) # login using the credentials (user & password) server.login(user, password) except ftplib.error_perm: # login failed, wrong credentials return False else: # correct credentials print(f"{Fore.GREEN}[+] Found credentials:", password, Fore.RESET) return True # read the wordlist of passwords passwords = open("wordlist.txt").read().split("\n") print("[+] Passwords to try:", len(passwords)) # iterate over passwords one by one # if the password is found, break out of the loop for password in passwords: if is_correct(password): break
4eaba11433ea548d2f95f8e5515c1b2c5bfaf3ce
x4nth055/pythoncode-tutorials
/gui-programming/chess-game/data/classes/Piece.py
1,897
3.6875
4
import pygame class Piece: def __init__(self, pos, color, board): self.pos = pos self.x = pos[0] self.y = pos[1] self.color = color self.has_moved = False def move(self, board, square, force=False): for i in board.squares: i.highlight = False if square in self.get_valid_moves(board) or force: prev_square = board.get_square_from_pos(self.pos) self.pos, self.x, self.y = square.pos, square.x, square.y prev_square.occupying_piece = None square.occupying_piece = self board.selected_piece = None self.has_moved = True # Pawn promotion if self.notation == ' ': if self.y == 0 or self.y == 7: from data.classes.pieces.Queen import Queen square.occupying_piece = Queen( (self.x, self.y), self.color, board ) # Move rook if king castles if self.notation == 'K': if prev_square.x - self.x == 2: rook = board.get_piece_from_pos((0, self.y)) rook.move(board, board.get_square_from_pos((3, self.y)), force=True) elif prev_square.x - self.x == -2: rook = board.get_piece_from_pos((7, self.y)) rook.move(board, board.get_square_from_pos((5, self.y)), force=True) return True else: board.selected_piece = None return False def get_moves(self, board): output = [] for direction in self.get_possible_moves(board): for square in direction: if square.occupying_piece is not None: if square.occupying_piece.color == self.color: break else: output.append(square) break else: output.append(square) return output def get_valid_moves(self, board): output = [] for square in self.get_moves(board): if not board.is_in_check(self.color, board_change=[self.pos, square.pos]): output.append(square) return output # True for all pieces except pawn def attacking_squares(self, board): return self.get_moves(board)
5c420b7d6d0efc40dcff469f8a130259aff0ac75
x4nth055/pythoncode-tutorials
/python-standard-library/print-variable-name-and-value/print_variable_name_and_value.py
153
4.0625
4
# Normal way to print variable name and value name = "Abdou" age = 24 print(f"name: {name}, age: {age}") # using the "=" sign print(f"{name=}, {age=}")
6b6dd3b2a888029cf3f1e9dd43f9710421778b8d
x4nth055/pythoncode-tutorials
/gui-programming/currency-converter-gui/currency_converter.py
4,166
3.59375
4
# importing everything from tkinter from tkinter import * # importing ttk widgets from tkinter from tkinter import ttk import requests # tkinter message box for displaying errors from tkinter.messagebox import showerror API_KEY = 'put your API key here' # the Standard request url url = f'https://v6.exchangerate-api.com/v6/{API_KEY}/latest/USD' # making the Standard request to the API response = requests.get(f'{url}').json() # converting the currencies to dictionaries currencies = dict(response['conversion_rates']) def convert_currency(): # will execute the code when everything is ok try: # getting currency from first combobox source = from_currency_combo.get() # getting currency from second combobox destination = to_currency_combo.get() # getting amound from amount_entry amount = amount_entry.get() # sending a request to the Pair Conversion url and converting it to json result = requests.get(f'https://v6.exchangerate-api.com/v6/{API_KEY}/pair/{source}/{destination}/{amount}').json() # getting the conversion result from response result converted_result = result['conversion_result'] # formatting the results formatted_result = f'{amount} {source} = {converted_result} {destination}' # adding text to the empty result label result_label.config(text=formatted_result) # adding text to the empty time label time_label.config(text='Last updated,' + result['time_last_update_utc']) # will catch all the errors that might occur # ConnectionTimeOut, JSONDecodeError etc except: showerror(title='Error', message="An error occurred!!. Fill all the required field or check your internet connection.") # creating the main window window = Tk() # this gives the window the width(310), height(320) and the position(center) window.geometry('310x340+500+200') # this is the title for the window window.title('Currency Converter') # this will make the window not resizable, since height and width is FALSE window.resizable(height=FALSE, width=FALSE) # colors for the application primary = '#081F4D' secondary = '#0083FF' white = '#FFFFFF' # the top frame top_frame = Frame(window, bg=primary, width=300, height=80) top_frame.grid(row=0, column=0) # label for the text Currency Converter name_label = Label(top_frame, text='Currency Converter', bg=primary, fg=white, pady=30, padx=24, justify=CENTER, font=('Poppins 20 bold')) name_label.grid(row=0, column=0) # the bottom frame bottom_frame = Frame(window, width=300, height=250) bottom_frame.grid(row=1, column=0) # widgets inside the bottom frame from_currency_label = Label(bottom_frame, text='FROM:', font=('Poppins 10 bold'), justify=LEFT) from_currency_label.place(x=5, y=10) to_currency_label = Label(bottom_frame, text='TO:', font=('Poppins 10 bold'), justify=RIGHT) to_currency_label.place(x=160, y=10) # this is the combobox for holding from_currencies from_currency_combo = ttk.Combobox(bottom_frame, values=list(currencies.keys()), width=14, font=('Poppins 10 bold')) from_currency_combo.place(x=5, y=30) # this is the combobox for holding to_currencies to_currency_combo = ttk.Combobox(bottom_frame, values=list(currencies.keys()), width=14, font=('Poppins 10 bold')) to_currency_combo.place(x=160, y=30) # the label for AMOUNT amount_label = Label(bottom_frame, text='AMOUNT:', font=('Poppins 10 bold')) amount_label.place(x=5, y=55) # entry for amount amount_entry = Entry(bottom_frame, width=25, font=('Poppins 15 bold')) amount_entry.place(x=5, y=80) # an empty label for displaying the result result_label = Label(bottom_frame, text='', font=('Poppins 10 bold')) result_label.place(x=5, y=115) # an empty label for displaying the time time_label = Label(bottom_frame, text='', font=('Poppins 10 bold')) time_label.place(x=5, y=135) # the clickable button for converting the currency convert_button = Button(bottom_frame, text="CONVERT", bg=secondary, fg=white, font=('Poppins 10 bold'), command=convert_currency) convert_button.place(x=5, y=165) # this runs the window infinitely until it is closed window.mainloop()
96ec108cb0ac2c756220ac07685f16e393ef7706
x4nth055/pythoncode-tutorials
/general/url-shortener/cuttly_shortener.py
589
3.5625
4
import requests import sys # replace your API key api_key = "64d1303e4ba02f1ebba4699bc871413f0510a" # the URL you want to shorten url = sys.argv[1] # preferred name in the URL api_url = f"https://cutt.ly/api/api.php?key={api_key}&short={url}" # or # api_url = f"https://cutt.ly/api/api.php?key={api_key}&short={url}&name=some_unique_name" # make the request data = requests.get(api_url).json()["url"] if data["status"] == 7: # OK, get shortened URL shortened_url = data["shortLink"] print("Shortened URL:", shortened_url) else: print("[!] Error Shortening URL:", data)
2dbadce9d4d45885537755e69599f7774af7142a
x4nth055/pythoncode-tutorials
/gui-programming/platformer-game/world.py
4,383
3.5625
4
import pygame from settings import tile_size, WIDTH from tile import Tile from trap import Trap from goal import Goal from player import Player from game import Game class World: def __init__(self, world_data, screen): self.screen = screen self.world_data = world_data self._setup_world(world_data) self.world_shift = 0 self.current_x = 0 self.gravity = 0.7 self.game = Game(self.screen) # generates the world def _setup_world(self, layout): self.tiles = pygame.sprite.Group() self.traps = pygame.sprite.Group() self.player = pygame.sprite.GroupSingle() self.goal = pygame.sprite.GroupSingle() for row_index, row in enumerate(layout): for col_index, cell in enumerate(row): x, y = col_index * tile_size, row_index * tile_size if cell == "X": tile = Tile((x, y), tile_size) self.tiles.add(tile) elif cell == "t": tile = Trap((x + (tile_size // 4), y + (tile_size // 4)), tile_size // 2) self.traps.add(tile) elif cell == "P": player_sprite = Player((x, y)) self.player.add(player_sprite) elif cell == "G": goal_sprite = Goal((x, y), tile_size) self.goal.add(goal_sprite) # world scroll when the player is walking towards left/right def _scroll_x(self): player = self.player.sprite player_x = player.rect.centerx direction_x = player.direction.x if player_x < WIDTH // 3 and direction_x < 0: self.world_shift = 8 player.speed = 0 elif player_x > WIDTH - (WIDTH // 3) and direction_x > 0: self.world_shift = -8 player.speed = 0 else: self.world_shift = 0 player.speed = 3 # add gravity for player to fall def _apply_gravity(self, player): player.direction.y += self.gravity player.rect.y += player.direction.y # prevents player to pass through objects horizontally def _horizontal_movement_collision(self): player = self.player.sprite player.rect.x += player.direction.x * player.speed for sprite in self.tiles.sprites(): if sprite.rect.colliderect(player.rect): # checks if moving towards left if player.direction.x < 0: player.rect.left = sprite.rect.right player.on_left = True self.current_x = player.rect.left # checks if moving towards right elif player.direction.x > 0: player.rect.right = sprite.rect.left player.on_right = True self.current_x = player.rect.right if player.on_left and (player.rect.left < self.current_x or player.direction.x >= 0): player.on_left = False if player.on_right and (player.rect.right > self.current_x or player.direction.x <= 0): player.on_right = False # prevents player to pass through objects vertically def _vertical_movement_collision(self): player = self.player.sprite self._apply_gravity(player) for sprite in self.tiles.sprites(): if sprite.rect.colliderect(player.rect): # checks if moving towards bottom if player.direction.y > 0: player.rect.bottom = sprite.rect.top player.direction.y = 0 player.on_ground = True # checks if moving towards up elif player.direction.y < 0: player.rect.top = sprite.rect.bottom player.direction.y = 0 player.on_ceiling = True if player.on_ground and player.direction.y < 0 or player.direction.y > 1: player.on_ground = False if player.on_ceiling and player.direction.y > 0: player.on_ceiling = False # add consequences when player run through traps def _handle_traps(self): player = self.player.sprite for sprite in self.traps.sprites(): if sprite.rect.colliderect(player.rect): if player.direction.x < 0 or player.direction.y > 0: player.rect.x += tile_size elif player.direction.x > 0 or player.direction.y > 0: player.rect.x -= tile_size player.life -= 1 # updating the game world from all changes commited def update(self, player_event): # for tile self.tiles.update(self.world_shift) self.tiles.draw(self.screen) # for trap self.traps.update(self.world_shift) self.traps.draw(self.screen) # for goal self.goal.update(self.world_shift) self.goal.draw(self.screen) self._scroll_x() # for player self._horizontal_movement_collision() self._vertical_movement_collision() self._handle_traps() self.player.update(player_event) self.game.show_life(self.player.sprite) self.player.draw(self.screen) self.game.game_state(self.player.sprite, self.goal.sprite)
78ce0accceb722296ce623a1887aba4c258145a4
x4nth055/pythoncode-tutorials
/general/mouse-controller/control_mouse.py
1,004
3.75
4
import mouse # left click mouse.click('left') # right click mouse.click('right') # middle click mouse.click('middle') # get the position of mouse print(mouse.get_position()) # In [12]: mouse.get_position() # Out[12]: (714, 488) # presses but doesn't release mouse.hold('left') # mouse.press('left') # drag from (0, 0) to (100, 100) relatively with a duration of 0.1s mouse.drag(0, 0, 100, 100, absolute=False, duration=0.1) # whether a button is clicked print(mouse.is_pressed('right')) # move 100 right & 100 down mouse.move(100, 100, absolute=False, duration=0.2) # make a listener when left button is clicked mouse.on_click(lambda: print("Left Button clicked.")) # make a listener when right button is clicked mouse.on_right_click(lambda: print("Right Button clicked.")) # remove the listeners when you want mouse.unhook_all() # scroll down mouse.wheel(-1) # scroll up mouse.wheel(1) # record until you click right events = mouse.record() # replay these events mouse.play(events[:-1])
c2f3c2f4f9e5f4d6fcba4789bdcfcb0982167d1b
x4nth055/pythoncode-tutorials
/general/video-to-audio-converter/video2audio_moviepy.py
457
3.5
4
import os import sys from moviepy.editor import VideoFileClip def convert_video_to_audio_moviepy(video_file, output_ext="mp3"): """Converts video to audio using MoviePy library that uses `ffmpeg` under the hood""" filename, ext = os.path.splitext(video_file) clip = VideoFileClip(video_file) clip.audio.write_audiofile(f"{filename}.{output_ext}") if __name__ == "__main__": vf = sys.argv[1] convert_video_to_audio_moviepy(vf)
502aeeb7cc94fca111d0597f863a2d09528a525a
aravind9643/Python_Programs
/Aravind/Practice_2_14112018.py
428
3.703125
4
#String Handling methods s1 = "aravind" s2 = "Aravind" s3 = "ARAVIND" s4 = " " s5 = "A5" s6 = " Aravind " print "Upper : ",s1.upper() print "Lower : ",s2.lower() print "Capitalize",s1.capitalize() print "Is Upper : ",s3.isupper() print "Is Lower : ",s1.islower() print "Is Space : ",s4.isspace() print "Is Alpha : ",s1.isalpha() print "Is AlNum : ",s5.isalnum() print "lstrip : ",s6.lstrip() print "rstrip : ",s6.rstrip()
25b8baaafb486e6018eb9290bbddfa67740cb882
aravind9643/Python_Programs
/Aravind/Practice_3_14112018.py
77
3.875
4
#String Operations (Slicing) str = "Aravind" print str[1:5] print str[-6:-2]
2b96b7dd86cc485189f87f81fae1f875f3c76d19
swaraj1999/python
/chap 3 if_and_loop/for_loop_string.py
293
3.640625
4
# for i in range(len(name)): # print(name(i)) #old process name="swaraj" for i in name: print(i) #python #1256= 1+2+5+6 num=input("enter name ::") total=0 for i in num: total+=int(i) print(total) #python spl
4ecfc694f1652d1f3ecc2b3cc6addff325126ab8
swaraj1999/python
/chap 3 if_and_loop/exercise6.py
313
4.0625
4
#ask user for name and age,if name starts with (a or A) and age is above 10 can watch mpovie otherwise sorry name,age=input("enter \t name \n \t age ((separated by space)::").split() age=int(age) if (age>=10) and (name[0]=='a' or name[0]=='A'): print("you can watch movie") else: print("sorry")
1d68a3df1eabd82b222b90a1ce2ef85556cff033
swaraj1999/python
/chap 2 string/more_inputs_in_one_line.py
514
3.9375
4
#input more than one input in one line name,age= input("enter your name and age(separated by space)").split() #.split splits the string in specific separator and returns a list print(name) print (age) #during giving name and age,a space will be provided into name and age,other wise it will be error,swaraj19 will not be accepted,swaraj 19 is correct nm,ag=input("enter your name and age(separated by comma)").split(",") print(nm) print(ag) # here space not required,you need to use a comma b/w name age
be1df6b6d7690e3e55bf9a7c50b7d496707c22fa
swaraj1999/python
/chap 7 dictionary/more.py
304
3.9375
4
# more about get method user={'name':'swaraj','age':19} print(user.get('names','not found')) # it will print not found instead of none cz names is not key,other wise print value #more than two same keys user={'name':'swaraj','age':19,'age':12} # it will overwrite 12 print(user)
06d831bdfe88c48846a0230006e81c439890eeb2
swaraj1999/python
/chap 2 string/variable_more.py
253
3.75
4
# taking one or more variables in one line name, age=" swaraj","19" #dont take 19, take 19 as string "19",otherwise it will give error print("hello " + name + " your age is " + age) # hello swaraj your age is 19 XX=YY=ZZ=1 print(XX+YY+ZZ) #ANS 3
8f8e8651d25ac8333692a5aa18bc26589f3fefe4
swaraj1999/python
/chap 8 set/set_intro.py
1,092
4.1875
4
# set data type # unordered collection of unique items s={1,2,3,2,'swaraj'} print(s) # we cant do indexing here like:: s[1]>>wrong here,UNORDERED L={1,2,4,4,8,7,0,9,8,8,0,9,7} s2=set(L) # removes duplicate,unique items only print(s2) s3=list(set(L)) print(s3) # set to list # add data s.add(4) s.add(10) print(s) # remove method s.remove(1) #key not present in set,it will show error && IF ONE KEY IS PRESENT SEVERAL TIME,IT WILL NOT REMOVE print(s) # discard method s.discard(4) # key not present in set,it will not set error print(s) # copy method s1=s.copy() print(s1) #we cant store list tuple dictionary , we can store float,string # we can use loop for item in s: print(item) # we can use if else if 'a' in s: print('present') else: print('false') # union && intersection s1={1,2,3} s2={4,5,6} union_set=s1|s2 # union | print(union_set) intersection_set=s1&s2 # intersection using & print(intersection_set)
4b4ced98150d913d22ec9ce39a21f21dcdd8faa8
swaraj1999/python
/chap 7 dictionary/in_itterations.py
889
4.03125
4
# in keyword and iterations in dictionary user_info = { 'name':'swaraj', 'age':19, 'fav movies':['ggg','hhh'], 'fav tunes':['qqq','www'], } # check if key in dictionary if 'name' in user_info: # check any key word print('present') else: print('not present') # check if value exists in dictionary if 24 in user_info: print('present') else: print('not present') # loopps in dictionary for i in user_info: print(i) # print keys print(user_info[i]) # value # value method user_info_values=user_info.values() print(user_info_values) print(type(user_info_values)) # keys method user_info_keys=user_info.keys() print(user_info_keys) print(type(user_info_keys)) # item method user_items = user_info.items() print(user_items) print(type(user_items))
15c3309d2d94b809fccc1c1aaaa0cd66cdfd3954
swaraj1999/python
/chap 4 function/exercise11.py
317
4.375
4
# pallindrome function like madam, def is_pallindrome(name): return name == name[::-1] #if name == reverse of name # then true,otherwise false # print(is_pallindrome(input("enter name"))) #not working for all words print(is_pallindrome("horse")) #working for all words
aa200cf39c63f65b74bf0490391a048be026dc6f
swaraj1999/python
/chap 5 list/function.py
226
3.796875
4
#min and max function numbers=[6,60,2] def greatest_diff(l): return max(l)-min(l) print(greatest_diff(numbers)) #print diff of two no print(min(numbers)) # min print(max(numbers)) #max
5334cf3288c199a6f4d943541d318a14e6ad1d56
fsandhu/qrCode-gen
/main.py
1,042
3.609375
4
__author__ = "Fateh Sandhu" __email__ = "fatehkaran@huskers.unl.edu" """ Takes in a weblink or text and converts it into qrCode using a GUI Built using Tkinter library. """ import sys import tkinter as tk import qrcode as qr from PIL import Image from tkinter import messagebox qrCode = qr.make("welcome") qrCode.save("qr.png") # define function that updates qrCode when <generateQR> button is clicked. def gen_code(): text = ent_val.get() qrCode = qr.make(text) qrCode.save("qrUpdate.png") ent_val.delete(0, tk.END) qrImg1 = tk.PhotoImage(file="qrUpdate.png") display.configure(image=qrImg1) display.image = qrImg1 window = tk.Tk() window.title("QR Code Generator") lbl_insert = tk.Label(text="Enter text or weblink: ") lbl_insert.pack() ent_val = tk.Entry(lbl_insert, width=30, bg="white", fg="black", text="Enter text/weblink") ent_val.pack() qrImg = tk.PhotoImage(file="qr.png") display = tk.Label(image=qrImg) display.pack(side=tk.BOTTOM) btn = tk.Button(text="Generate QR", command=gen_code) btn.pack() window.mainloop()
36a7847a50d3af04b66455750f93a9a731db9c4b
raullopezgonzalez/Artificial-Intelligence
/Lab5/src/pca_utils.py
1,899
3.5
4
#!/usr/bin/python # -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt from sklearn.decomposition import PCA def toy_example_pca(): rng = np.random.RandomState(1) X = np.dot(rng.rand(2, 2), rng.randn(2, 200)).T # do the plotting plt.scatter(X[:, 0], X[:, 1]) plt.xlabel('$x_1$', fontsize=16) plt.ylabel('$x_2$', fontsize=16) plt.axis('equal'); return X def draw_vector(v0, v1, ax=None): ax = ax or plt.gca() arrowprops=dict(arrowstyle='->', linewidth=2, shrinkA=0, shrinkB=0) ax.annotate('', v1, v0, arrowprops=arrowprops) def plot_pca_toy_example(X): #pca = PCA(n_components=2, whiten=True).fit(X) pca = PCA(n_components=2).fit(X) X_pca = pca.transform(X) fig, ax = plt.subplots(1, 3, figsize=(20, 5)) fig.subplots_adjust(left=0.0625, right=0.95, wspace=0.1) # plot data ax[0].scatter(X[:, 0], X[:, 1], alpha=0.2) for length, vector in zip(pca.explained_variance_, pca.components_): v = vector * 3 * np.sqrt(length) draw_vector(pca.mean_, pca.mean_ + v, ax=ax[0]) ax[0].axis('equal'); ax[0].set(xlabel='x', ylabel='y', title='input') # plot principal components ax[1].scatter(X_pca[:, 0], X_pca[:, 1], alpha=0.2) draw_vector([0, 0], [0, 1], ax=ax[1]) draw_vector([0, 0], [3, 0], ax=ax[1]) ax[1].axis('equal') ax[1].set(xlabel='component 1', ylabel='component 2', title='principal components', xlim=(-5, 5), ylim=(-3, 3.1)) # plot principal components pca = PCA(n_components=2, whiten=True).fit(X) X_pca = pca.transform(X) ax[2].scatter(X_pca[:, 0], X_pca[:, 1], alpha=0.2) draw_vector([0, 0], [0, 3], ax=ax[2]) draw_vector([0, 0], [3, 0], ax=ax[2]) ax[2].axis('equal') ax[2].set(xlabel='component 1', ylabel='component 2', title='principal components (whiten: unit variance)', xlim=(-5, 5), ylim=(-3, 3.1)) return pca
6443de5f4faef205aa7cb2b213f262b625cea272
chelosilvero78/small-projects
/exercises-python/AutomateTheBoringStuff/ch9-3-1b.py
1,791
3.734375
4
###Automate tbs. ''' Filling in the Gaps Write a program that finds all files with a given prefix, such as spam001.txt, spam002.txt, and so on, in a single folder and locates any gaps in the numbering (such as if there is a spam001.txt and spam003.txt but no spam002.txt). Have the program rename all the later files to close this gap. As an added challenge, write another program that can insert gaps into numbered files so that a new file can be added. ''' import os, shutil from os import path as p, listdir from shutil import move def debugP(*var): print('dbg',var) d = input('...enter to continue ') def create_subfolder(new_dest): new_sub = new_dest if os.path.exists(new_sub) is False: os.makedirs(new_sub) return new_sub # spampath should exist if using this function for real userPath = input('Input a path to create "spam" subfolder.') spampath = create_subfolder(userPath) # create spam00x files (unnecessary if files exist) for i1 in range(12): if i1 == 6: continue #we're skipping spam006.txt num000 = ('{num:03d}'.format(num=i1)) # create formatted 00x numbers spamfile = open(''.join((spampath, 'spam', num000, '.txt')), 'w') spamfile.close() ''' # pause (only for testing) print('Pause - check if files were created.') pause = input('...enter to continue ') ''' #initialize num0 = 0 num000 = ('{num:03d}'.format(num=num0)) spamlist = listdir(spampath) for i2, file in enumerate(spamlist): if file.startswith('spam'): spamnew = ''.join((file[:-7], num000, '.txt')) if spamnew != file: move(p.join(spampath, file), p.join(spampath, spamnew)) num0 += 1 num000 = ('{num:03d}'.format(num=num0)) print('Files were successfully renumbered.') ''' '''
d0beb6ea25578dadd9859a79955980e6f42f0436
chelosilvero78/small-projects
/small-projects-python/ClearDone-3.py
1,652
3.6875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created 4/19/17, 11:34 AM @author: davecohen Title: Clear Done Input: text file that has lines that begin with 'x ' (these are done files) Output: text file that moves those lines to the end of the file with date stamp at top. USAGE: Run file with terminal - copy your todo items to clipboard. Check your directory, "sorted files" for output. CREATE A CONFIG FILE AS SUCH: #config.py myConfig = {'outputdir': 'my/output/path/'} OR Simply replace the outputdir line with your output path. """ import sys, os from datetime import datetime #NON-STANDARD LIBRARY import pyperclip #LOCAL MODULE - SEE ABOVE from config import * def debugP(var,num=1): print('dbg',num,':',var) d = input('...enter to continue ') # MAIN print('Please copy your todo list text to clipboard. Hit enter when done.') pause = input('') #use pyperclip to get clipboard tododata = pyperclip.paste() #create a list with clipboard content. todolist = tododata.split('\n') donelist = [] tasklist = [] outputdir = myConfig['outputdir'] #configure in a separate file taskoutput = os.path.join(outputdir, 'sorted-tasks.txt') doneoutput = os.path.join(outputdir, 'sorted-done.txt') nowtime = str(datetime.now()) for line in todolist: if line.startswith('x '): donelist.append(line) else: tasklist.append(line) with open(taskoutput, 'a') as f2: for taskline in tasklist: f2.write(taskline + '\n') with open(doneoutput, 'a') as f2: f2.write(nowtime + '\n') for doneline in donelist: f2.write(doneline + '\n') print('Files output to:', taskoutput, '\n', doneoutput)
f586137284403932a921fe86453e8894c40fcc17
chelosilvero78/small-projects
/exercises-python/MIT-6-0001/tests-hangman2.py
2,906
3.546875
4
''' testing helper functions before committing to main file ''' from hangman_no_hints import * wordlist = load_words() def reduceList(myList, num): return [word for word in wordlist if len(word) == num] # print('>>> reduceList tests') # print(reduceList(wordlist, 2)) # print(reduceList(wordlist, 3)) # print(reduceList(wordlist, 4)) # print(reduceList(wordlist, 5)) def matchLetter(l1, l2): l1 = l1.lower() if l1 == l2: return True elif l1 == '_': return True else: return False print('>>> matchLetter tests') print(matchLetter('-', 'a')) #True print(matchLetter('a', 'a')) #True print(matchLetter('b', 'a')) #False # def getIndices(word): # # indices = [] # # for i, letter in enumerate(word): # # if letter != '_': # # indices.append(i) # # return indices # # return [i for i, letter in enumerate(word) if letter != '_'] # # print(getIndices('___nk')) twoList = reduceList(wordlist, 2) guessWord = '_i' def letterTally(word): #count the letters in w1 and w2, check for match #only count letters present in w1 wordCount = {} for letter in word: if letter != '_' and letter not in wordCount: wordCount.setdefault(letter, 1) elif letter != '_' and letter in wordCount: wordCount[letter] += 1 return wordCount def removeSpaces(word): return word.replace(' ', '').strip() def removeUnderscores(word): word = removeSpaces(word) return word.replace('_', '') def match_with_gaps(my_word, other_word): my_word = removeSpaces(my_word) other_word = removeSpaces(other_word) for i, letter in enumerate(my_word): if not matchLetter(my_word[i], other_word[i]): return False # https://stackoverflow.com/questions/9323749/python-check-if-one-dictionary-is-a-subset-of-another-larger-dictionary/41579450#41579450 if not letterTally(my_word).items() <= letterTally(other_word).items(): return False return True print('>>> match_with_gaps tests') print(match_with_gaps("a_ _ le", "apple")) #True print(match_with_gaps("te_ t", "tact")) #False print(match_with_gaps("a_ _ le", "banana")) # False print(match_with_gaps("a_ ple", "apple")) # False def show_possible_matches(my_word): my_word = removeSpaces(my_word) myList = reduceList(wordlist, len(my_word)) possible_matches = [other_word for other_word in myList if match_with_gaps(my_word, other_word)] if len(possible_matches) > 0: for match in possible_matches: print(match, end=" ") print() else: print('No matches found') print('>>> match_with_gaps tests') show_possible_matches("t_ _ t") # tact tart taut teat tent test text that tilt tint toot tort tout trot tuft twit show_possible_matches("abbbb_ ") #No matches found show_possible_matches("a_ pl_ ") # ample amply # len(secret_word) = max value for reduceList
424325f5f0d12aaf1de6c1ed351cf647e63de4d7
chelosilvero78/small-projects
/small-projects-python/Game-Hangman-3.py
2,228
3.625
4
#pythontemplate #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on 3/1/17, 12:31 PM @author: davecohen Title: Hangman ===TODO able to restart the game? word list graphics """ ############ ###GAME SETUP ############ import re import getpass #Word is prompted by non-game player. This may only work in bash terminal? word=getpass.getpass("Type a word or phrase for someone else to guess: ") print("Let's play Hangman!") prompt = 'Have someone put in a word or phrase for you to guess: ' word = word.upper() word = re.sub(r'[^\w\s]','',word) censored = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' hanged = 0 hangman = [ 'The post is built.', 'The head appears.', 'The body appears.', 'First arm up.', 'Now, the other arm.', 'First leg up. ONLY ONE MORE GUESS LEFT!', '''Now, the other leg. Sorry, you lose. GAME OVER''', ] guessed = [] valid = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' ############ ###FUNCTIONS ############ def dashword_call(): '''print dashword from censored''' dashword = '' for letter in word: if letter in censored: dashword = dashword + '-' else: dashword = dashword + letter return dashword ############ ###GAME ############ print('{} wrong guesses and you get taken to the gallows!!!'.format(len(hangman))) print(dashword_call()) while hanged < len(hangman): guess = str(input('guess a letter: ')) #in function? guess = guess.upper() guess = re.sub(r'[^\w\s]','',guess) #edit censored without guess: if (len(guess) != 1) or (guess not in valid) : print('invalid input.') print(dashword_call()) continue if guess in guessed: print('already guessed.') print(dashword_call()) continue if guess in word and guess in censored: censored = censored.replace(guess,'') print(dashword_call()) if word == dashword_call(): print('YOU WIN!!') break if (guess not in word) and (guess not in guessed): print('WRONG GUESS ({}/{}). {}'.format(hanged+1,len(hangman),hangman[hanged])) hanged += 1 if hanged == len(hangman): break print(dashword_call()) guessed.append(guess) ''' '''
924837c49470fc6971c1593e5f09712409368779
chelosilvero78/small-projects
/notes-python/PythonForEverybody/10-tuples.py
3,055
3.953125
4
#python3 print('Ch10.1 -\nTuples are immutable') t_no = 'a', 'b', 'c', 'd', 'e' t_paren = ('a', 'b', 'c', 'd', 'e') print(t_no == t_paren) print(t_no is t_paren) t1 = ('a',) print(type(t1)) s1 = ('a') print(type(s1),'<-always include the final comma in a tuple of len 1!') t_emp = tuple() print(t_emp) t_lup = tuple('lupins') print(t_lup,'<-a string in a tuple function is iterated over the chars of the string') t5 = ('a', 'b', 'c', 'd', 'e') print(t5[0],'<- this is like get item 0') print(t5[1:3]) #t5[0] = 'A' #this yields an error t5 = ('A',) + t5[1:] print(t5,'<-this replaced the old t5') print('\nCh10 -\nComparing tuples') t012 = (0, 1, 2) t034 = (0, 3, 4) print(t012 < t034) t012 = (0, 1, 200000) print(t012 < t034) #--- '''This function sorts text from longest to shortest.''' txt = 'but soft what light in yonder window breaks' words = txt.split() t = list() #empty list for word in words: t.append((len(word), word)) #create a tuple of 2 as list item t.sort(reverse=True) res = list() #list of tuples for length, word in t: res.append(word) #appends words in order of length print(res) #--- print('\nCh10 -\nTuple assignment') m = [ 'have', 'fun' ] x, y = m print(x,'<- x is roughly equiv to m[0]') print(y,'<- y is roughly equiv to m[1]') a, b = 1,2 a, b = b, a print(a,'<- we swapped the variables') #--- addr = 'monty@python.org' uname, domain = addr.split('@') print(uname) print(domain) #--- print('\nCh10 -\nDictionaries and tuples') d = {'a':10, 'b':1, 'c':22} t = list(d.items()) #here, we made a list of d.items print(t) #--- d = {'a':10, 'b':1, 'c':22} t = list(d.items()) t.sort() print(t,'<-sorted!') print('\nCh10.5 -\nMultiple assignment with dictionaries') for key, val in list(d.items()): print(val, key) print('^this is what\'s up!') d = {'a':10, 'b':1, 'c':22} l = list() #--- """The function below creates a reverse sorted tuple from dictionary.""" for key, val in d.items() : l.append( (val, key) ) #print(l) l.sort(reverse=True) print(l) #--- print('\nCh10 -\nUsing tuples as keys in dictionaries') first = 'd' #input('enter first name: ') last = 'e' #input('enter last name: ') number = 3 #input('enter number: ') directory = {} directory[last,first] = number #creates the dictionary syntax for last, first in directory: print(first, last, directory[last,first]) print('\nCh10 -\nSo many data types') print('.sorted: sorted(iterable[, key][, reverse])') print(sorted([5, 2, 3, 1, 4])) print(sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'})) student_tuples = [('john', 'A', 15),('jane', 'B', 12),('dave', 'B', 10)] print(sorted(student_tuples, key=lambda student: student[2])) # sort by age print('^woah wtf is lamda?') #--- print('reversed: reversed(seq) \n Return a reverse iterator. seq must be an object which has a __reversed__() method or supports the sequence protocol (the __len__() method and the __getitem__() method with integer arguments starting at 0).') student_list = ['jim','sally','greg'] new_list = list(reversed(student_list)) print(reversed(new_list)) print('^I\'m so confused.')
6d08454da7f8c3b15ec404505a6b77b9192e570e
breschdleng/Pracs
/fair_unfair_coin.py
1,307
4.28125
4
import random """ Given an unfair coin, where probability of HEADS coming up is P and TAILS is (1-P), implement a fair coin from the given unfair coin Approach: assume an unfair coin that gives HEADS with prob 0.3 and TAILS with 0.7. The objective is to convert this to a fair set of probabilities of 0.5 each Solution: use bayes theorem flip the coins twice, if HH or TT then p(HH) == 0.49, p(TT) = 0.09, p(HT) = p(TH) = 0.21 1) flip two coins 2) if HH or TT repeat 1) 3) if different then heads if HT and tails if TH Bayes' Theorem: p(head on the first flip / diff results) = p(diff results / head on the first flip)*p(head on the first flip) / p(diff results) p(diff results / head on the first flip) = p(tails/heads) = 0.3 p(heads on first flip) = 0.7 p(diff results) = p(HT)+p(TH) = 0.21*2 p(head on the first flip / diff results) = 0.3*0.7/0.42 = 0.5 ---answer for a fair coin flip! """ """ 1: heads 0: tails """ def unfair_coin(): p_heads = random.randint(0, 100)/100 if p_heads > 0.5: return 1 else: return 0 def unfair_to_fair(a,b): p, q = unfair_coin() print(b*p, a*q) if __name__ == '__main__': a = unfair_coin() b = unfair_coin() if a==b: unfair_coin() if a == 1: print("heads") else: print("tails")
c841e0852e4f1874f392065d0a21b32dfe9262e4
AndrewZhang1996/DFSandBFS
/node.py
347
3.546875
4
class node(): def __init__(self, name, hasPrevious, hasNext): self.name = name self.previous = None self.next = None self.hasPrevious = hasPrevious self.hasNext = hasNext def set_previous(self, _previous): if self.hasPrevious==1: self.previous = _previous def set_next(self, _next): if self.hasNext==1: self.next = _next
5b6fc5dbfa1e7d85d4c80642ecb2822c23d5a6be
ShainaJordan/thinkful_lessons
/fibo.py
282
4.15625
4
#Define the function for the Fibonacci algorithm def F(n): if n < 2: return n else: print "the function is iterating through the %d function" %(n) return (F(n-2) + F(n-1)) n = 8 print "The %d number in the Fibonacci sequence is: %d" %(n, F(n))
556ba64f9a8ac34fae4876547d44e2d990582742
DL-py/python-notebook
/001基础部分/015函数.py
1,548
4.34375
4
""" 函数: """ """ 函数定义: def 函数名(参数): 代码 """ """ 函数的说明文档: 1.定义函数说明文档的语法: def 函数名(参数): """ """内部写函数信息 代码 2.查看函数的说明文档方法: help(函数名) """ # 函数说明文档的高级使用: def sum_num3(a, b): """ 求和函数sum_num3 :param a:参数1 :param b:函数2 :return:返回值 """ return a + b """ 返回值:可以返回多个值(默认是元组),也可以返回列表、字典、集合等 """ """ 函数的参数: 1.位置参数:调用函数时根据函数定义的参数位置来传递参数 注意:传递和定义参数的顺序和个数必须一致 2.关键字参数:函数调用时,通过“键=值”形式加以指定,无先后顺序 注意:如果有位置参数时,位置参数必须在关键字参数的前面,但关键字参数之间不存在先后顺序 3.缺省参数(默认参数):用于定义函数,为参数提供默认值,调用时可不传入该默认参数的值。 注意:所有位置参数必须出现在默认参数前,包括函数定义和调用 """ """ 不定长参数: 不定长参数也叫可变参数,用于不确定调用的时候会传递多少个参数(不传参数也可以)的场景, 此时可以用包裹位置参数,或包裹关键字参数,来进行参数传递,会显得非常方便。 包裹位置传递:*args args是元组类型,则就是包裹位置传递 包裹关键字传递:**kwargs """
85d74879093a2041af2b2457d8f144a0df9e4bb5
DL-py/python-notebook
/001基础部分/006元组.py
230
3.78125
4
""" 元组: 1.元组与列表的区别: 元组中的数据不能修改(元组中的列表中的数据可以修改);列表中的数据可以修改 """ # 创建元组: tuple1 = (1, 2, 3, 4) tuple2 = (1,) # 逗号不能省
2f6b959205e4761ab4147d1369f214ba7b81fad3
changyubiao/myalgorithm-demo
/leetcode/leetcode215.py
2,274
3.609375
4
# -*- coding: utf-8 -*- """ 在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。 示例 1: 输入: [3,2,1,5,6,4] 和 k = 2 输出: 5 示例 2: 输入: [3,2,3,1,2,4,5,5,6] 和 k = 4 输出: 4 说明: 你可以假设 k 总是有效的,且 1 ≤ k ≤ 数组的长度。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/kth-largest-element-in-an-array 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 1 方法1 :排序 解决 ,比较傻 """ from typing import List class Solution: def findKthLargest(self, nums: List[int], k: int) -> int: left, right = 0, len(nums) - 1 while True: pos = self.partition(nums, left=left, right=right) current_m_large = pos + 1 if k == current_m_large: # 刚好 第k 大 return nums[pos] elif k < current_m_large: # 在前面继续找 right = pos - 1 else: # 在 后面 继续 找 left = pos + 1 pass @staticmethod def partition(array: List[int], left: int, right: int) -> int: """ 把 大的元素 放在 前面 ,小的元素 放到 后面. array partition xxx >= array[left] > xxxx 返回 这个 数组的小标 :param array: :param left: :param right: :return: """ # 临时变量 temp = array[left] while left < right: while left < right and array[right] < temp: right = right - 1 array[left] = array[right] while left < right and array[left] >= temp: left = left + 1 # 把大的数字 放到右边 array[right] = array[left] array[left] = temp return left if __name__ == '__main__': nums = [3, 2, 3, 1, 2, 4, 5, 5, 6] s = Solution() ret = s.findKthLargest(nums, k=4) print(f"ret:{ret}") nums = [3, 2, 1, 5, 6, 4] rt = s.findKthLargest(nums, k=2) print(f"ret:{rt}") pass
9ce8a31ed3cedb1f9f097f1df67eb1b26eff07e7
changyubiao/myalgorithm-demo
/classthree/5.py
3,694
3.890625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @Time : 2019/1/1 13:21 @File : 5.py @Author : frank.chang@shoufuyou.com 转圈打印矩阵 【 题目5 】 给定一个整型矩阵matrix, 请按照转圈的方式打印它。 例如: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 array=[ [ 1 2 3 4] [ 5 6 7 8] [ 9 10 11 12] [13 14 15 16] ] 打印结果为: 1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9,5, 6, 7, 11, 10 【要求】 额外空间复杂度为O(1) 按顺时针方向 每一圈 进行遍历,之后 , 在内圈 也这样遍历, 最后结果就是 按照 顺时针的方向 进行遍历. ----- | """ import numpy as np class Point: """ Point 定义一个辅助的 数据结构 point """ def __init__(self, x, y): self.x = x self.y = y def __str__(self): return f"{self.__class__.__name__}({self.x},{self.y})" __repr__ = __str__ def print_edge_old(matrix, a, b): """ first version :param matrix: 矩阵 :param a: point a :param b: point b :return: """ X, Y = a.x, a.y m, n = b.x, b.y if X == m: for i in range(Y, n + 1): # 水平 方向 print(matrix[X][i], end=' ') elif Y == n: for i in range(X, m + 1): # 竖直 方向 print(matrix[i][Y], end=' ') else: # 构成一个矩形 while a.y < b.y and Y < b.y: print(matrix[a.x][Y], end=' ') Y += 1 while a.x < b.x and X < b.x: print(matrix[X][b.y], end=' ') X += 1 # 重置 y 坐标 Y = n while a.y < b.y and Y > a.y: print(matrix[b.x][Y], end=' ') Y -= 1 X = m while a.x < b.x and X > a.x: print(matrix[X][a.y], end=' ') X -= 1 def print_edge(matrix, a, b): """ 打印 最外围的 一圈 的边 :param matrix: 矩阵 :param a: point a :param b: point b :return: """ cur_index = a.x cur_column = a.y if a.x == b.x: for i in range(a.y, b.y + 1): # 水平 方向 [a.y,b.y] 进行打印 print(matrix[a.x][i], end=' ') elif a.y == b.y: for i in range(a.x, b.x + 1): # 竖直 方向 print(matrix[i][a.y], end=' ') else: # 构成一个矩形 的情况 # --- 从左向右 while cur_column != b.y: print(matrix[a.x][cur_column], end=' ') cur_column += 1 # | 从上到下 while cur_index != b.x: print(matrix[cur_index][b.y], end=' ') cur_index += 1 # --- 从右向左 while cur_column != a.y: print(matrix[b.x][cur_column], end=' ') cur_column -= 1 # | 从下向上 while cur_index != a.x: print(matrix[cur_index][a.y], end=' ') cur_index -= 1 def print_matrix(matrix, a, b): """ :param matirx: :param a: point :param b: point :return: """ while a.x <= b.x and a.y <= b.y: print_edge(matrix, a, b) a.x += 1 a.y += 1 b.x -= 1 b.y -= 1 def test_one(): matrix = np.arange(1, 16).reshape((5, 3)) A = Point(0, 0) B = Point(4, 2) print_matrix(matrix, A, B) print(f"\nmatrix:\n{matrix}") def test_two(): matrix = np.arange(1, 17).reshape((4, 4)) A = Point(0, 0) B = Point(3, 3) print_matrix(matrix, A, B) print(f"\nmatrix:\n{matrix}") if __name__ == '__main__': test_one() test_two() pass
dac2fa508d94199d6b188da9c78742a2b6de26c6
changyubiao/myalgorithm-demo
/classfour/1.py
6,251
4.21875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @Time : 2019/2/10 22:16 @File : 1.py @Author : frank.chang@shoufuyou.com 二叉树相关练习 实现 二叉树的先序、中序、后序遍历,包括递归方式和非递归方式 """ from util.stack import Stack class Node: """ 二叉树 结点 """ def __init__(self, data): self.value = data self.left = None self.right = None def main(): """ 5 3 8 2 4 7 10 1 6 9 11 三种遍历方式如下: 5 3 2 1 4 8 7 6 10 9 11 ========pre-order =========== 1 2 3 4 5 6 7 8 9 10 11 ========in-order =========== 1 2 4 3 6 7 9 11 10 8 5 ========post-order=========== :return: """ head = Node(5) head.left = Node(3) head.right = Node(8) head.left.left = Node(2) head.left.right = Node(4) head.left.left.left = Node(1) head.right.left = Node(7) head.right.left.left = Node(6) head.right.right = Node(10) head.right.right.left = Node(9) head.right.right.right = Node(11) print("\npre_order: ") pre_order(head) pre_order_stack(head) # print("\nin_order: ") # in_order(head) # # print("\npost_order: ") # post_order(head) pass def pre_order(head: Node): if head is None: return print(head.value, end=' ') pre_order(head.left) pre_order(head.right) def in_order(head: Node): if head is None: return in_order(head.left) print("{}".format(head.value), end=' ') in_order(head.right) def post_order(head: Node): if head is None: return post_order(head.left) post_order(head.right) print("{}".format(head.value), end=' ') def pre_order_stack(head: Node): """ 非递归的实现版本. 先序遍历 用辅助栈来实现 先序遍历 ,先压 head,之后, 循环条件: 栈不为空 把孩子的结点的 右边孩子有的话,压入栈中. 如果 有左孩子的话 , 也把结点压入栈中. 这样 之后 从栈中弹出的时候,就会先出栈的是做孩子, 之后 之后才是右孩子. 这样就可以实现先序遍历. :param head: :return: """ if head is not None: print("\npre_order_stack: ") stack = Stack() stack.push(head) while not stack.is_empty(): head = stack.pop() print("{}".format(head.value), end=' ') # 注意这里一定要先压右孩子,后压左孩子. if head.right is not None: stack.push(head.right) if head.left is not None: stack.push(head.left) print("") def in_order_stack(head: Node): """ 中序遍历 非递归实现 left root right 中序遍历,首先呢,先要找到左边界,就是最左边的孩子, 如果不用递归实现,还是要用辅助栈来完成这个事情. 首先有一个 循环 来 控制 如何退出: 循环条件是: 栈不为空, 或者 head 不是空的. 两者 成立一个就可以了. 首先 如果 head 不为空,就把 head 压入 栈中, 之后 head 往左走一步,继续这样直到走到没有左孩子,开始把栈中的元素弹出.然后 打印出来. 之后 把 弹出结点的 的 右孩子压入栈中. 继续循环. left root right 其实意思就是 先把 左边的左子树 压入栈中, 之后弹出,开始压入 右边的 孩子,如果 右孩子没有值, 栈中 弹一个元素出来. 当前结点 为空, 从栈中取一个元素,然后当前 结点开始向右走, 如果当前结点 不为空, 把当前结点 压入栈中, 结点开始向左走. :return: """ if head is not None: stack = Stack() while not stack.is_empty() or head is not None: if head is not None: stack.push(head) head = head.left else: # head is None,从栈中取结点,其实这个时候就是上一层结点. head = stack.pop() print("{}".format(head.value), end=' ') head = head.right print(" ") def post_order_stack(head: Node): """ 后序遍历 非递归的实现 可以借助 两个栈来实现: help_stack 用来存放 结点的顺序为 root right left 可以借助先序遍历 思想 中 左右 ---> 中右左 ---> 之后借助 一个辅助栈,编程 左右中,这个就是后续遍历. 首先把 head 入栈, 之后进入循环,只要栈不为空, 取出栈顶元素, 压入到print_stack 中, 之后 在依次出栈就可以了. help_stack 的作用 和先序遍历一个意思, 只是 先 压入左孩子, 之后 压入右孩子. :param head: :return: """ print_stack = Stack() help_stack = Stack() if head is not None: print("post_order_stack: ") help_stack.push(head) while not help_stack.is_empty(): head = help_stack.pop() print_stack.push(head) # 先放入左边, 之后放右边的节点. if head.left is not None: help_stack.push(head.left) if head.right is not None: help_stack.push(head.right) # end while while not print_stack.is_empty(): cur = print_stack.pop() print("{}".format(cur.value), end=' ') def create_three(): head = Node(5) head.left = Node(3) head.right = Node(8) head.left.left = Node(2) head.left.right = Node(4) head.left.left.left = Node(1) head.right.left = Node(7) head.right.left.left = Node(6) head.right.right = Node(10) head.right.right.left = Node(9) head.right.right.right = Node(11) return head if __name__ == '__main__': head = create_three() # pre_order(head) # print('===================') # in_order(head) # # print('===================') # post_order(head) # print('===================') # post_order_stack(head) # # print("\npost_order: ") # post_order(head) pass
eb07b756e4de5cda92741b93630997f9cbff01e5
changyubiao/myalgorithm-demo
/classthree/1.py
3,591
4
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @Time : 2018/12/16 14:48 @File : 1.py @Author : frank.chang@shoufuyou.com 用数组结构 实现大小固定的队列和栈 1.实现 栈结构 2.实现 队列结构 """ class ArrayToStack: def __init__(self, init_size): if init_size < 0: raise ValueError("The init size is less than 0") self.arr = [None] * init_size # size 表示栈的容量,同时表示 将要 插入位置的index. self.size = 0 def peek(self): if self.size == 0: return return self.arr[self.size - 1] def push(self, item): """ :param item: :return: """ if self.size == len(self.arr): raise IndexError("The stack is full") # 入栈 self.arr[self.size] = item self.size += 1 def pop(self): if self.size == 0: raise IndexError("The stack is empty") self.size -= 1 return self.arr[self.size] class ArrayQueue: """ end 做为入队列的索引 , 当end 达到 最大长度 的时候, 返回 0 位置,循环这样进行 start 做为出队列的索引, 当 start 达到 最大长度 的时候, 返回 0 位置,循环这样进行 put(self, item) 入队列 get 出队列 peek 返回队列 首元素 is_empty 判断队列 是否为空的, True , False """ def __init__(self, init_size): if init_size < 0: raise ValueError("The init size is less than 0") self.end = 0 self.start = 0 self.arr = [None] * init_size # 队列 当前 size self.size = 0 def put(self, item): """ 删除并返回队首的元素。如果队列为空则会抛异常. :param item: :return: """ if self.size == len(self.arr): raise IndexError("The queue is full") self.size += 1 self.arr[self.end] = item self.end = 0 if self.end == self.length - 1 else self.end + 1 def is_empty(self): return self.size == 0 @property def length(self): return len(self.arr) def get(self): """ 删除并返回队首的元素。如果队列为空则会抛异常。 Remove and return an item from the queue. :return: """ if self.size == 0: raise IndexError("The stack is empty") # 这里要把队列的长度减1 self.size -= 1 tmp = self.start self.start = 0 if self.start == self.length - 1 else self.start + 1 return self.arr[tmp] def peek(self): """ 返回队列 首 的元素 :return: """ if self.size == 0: raise IndexError("The queue is empty") return self.arr[self.start] def test_stack(): stack = ArrayToStack(5) stack.push(1) stack.push(2) stack.push(3) stack.pop() stack.pop() stack.pop() stack.pop() def test_quque(): queue = ArrayQueue(4) queue.put(1) queue.put(2) queue.put(3) queue.get() print(queue.peek()) queue.put(4) print(queue.peek()) # while not queue.is_empty(): # print(queue.get()) if __name__ == '__main__': pass queue = ArrayQueue(4) queue.put(1) queue.put(2) queue.put(3) queue.get() print(queue.peek()) queue.put(4) print(queue.peek()) # while not queue.is_empty(): # print(queue.get()) # queue.put(1)
2e5e728e42819ca386083f2dbd9ce51055d73fc6
Clearyoi/adventofcode
/2020/6/part2.py
438
3.703125
4
def overallTotal( groups ): return sum ( [ groupTotal( group ) for group in groups ] ) def groupTotal( group ): people = group.split( '\n' ) answers = people[0] for person in people: for answer in answers: if answer not in person: answers = answers.replace( answer, '' ) return len( answers ) groups = [ x for x in open( "input.txt" ).read().strip().split( '\n\n' ) ] print( 'Total: {}'.format( overallTotal ( groups ) ) )
135aec9f9fa998bda9a1782d1091dba08fa5b7e6
Clearyoi/adventofcode
/2020/7/part1.py
833
3.53125
4
def parseBags( bagsRaw ): bags = [] for bag in bagsRaw: bags.append( ( bag[0].split()[0] + bag[0].split()[1], [ x.split()[1] + x.split()[2] for x in bag[1] ] ) ) return bags def findOuterBagsInner( bags, seeking ): newSeeking = seeking.copy() for bag in bags: for seek in seeking: if seek in bag[1]: newSeeking.add(bag[0]) if newSeeking == seeking: return len(newSeeking) - 1 return findOuterBagsInner( bags, newSeeking ) def findOuterBags( bagsRaw, goal ): bags = parseBags ( bagsRaw ) seeking = set() seeking.add(goal) return findOuterBagsInner( bags, seeking ) bagsRaw = [ ( x.split( 'contain' )[0], x.split( 'contain' )[1].split( ',' ) )for x in open( "input.txt" ).read().strip().split( '\n' ) ] print( "Number of bags which can contain my bag: {}".format( findOuterBags( bagsRaw, "shinygold" ) ) )
8d852b9ba3fb4403dc783cc6c703c451ee0197f7
Pranav-Tumminkatti/Python-Turtle-Graphics
/Turtle Graphics Tutorial.py
979
4.40625
4
#Turtle Graphics in Pygame #Reference: https://docs.python.org/2/library/turtle.html #Reference: https://michael0x2a.com/blog/turtle-examples #Very Important Reference: https://realpython.com/beginners-guide-python-turtle/ import turtle tim = turtle.Turtle() #set item type tim.color('red') #set colour tim.pensize(5) #set thickness of line tim.shape('turtle') tim.forward(100) #turtle moves 100 pixels forward tim.left(90) #turtle turns left 90 degrees tim.forward(100) tim.right(90) tim.forward(100) tim.penup() #lifts the pen up - turtle is moving but line is not drawn tim.left(90) tim.forward(100) tim.right(90) tim.pendown() #puts the pen back down tim.forward(100) tim.left(90) tim.penup() tim.forward(50) tim.left(90) tim.pendown() tim.color('green') #changes the colour of the line to green tim.forward(100) #Making a new object named dave dave = turtle.Turtle() dave.color('blue') dave.pensize(10) dave.shape('arrow') dave.backward(100) dave.speed(1)
ec2c17082037d296706d9659c6a56709b4027d48
namitanair0201/leetcode
/rotateMatrix.py
759
3.875
4
class Solution(object): def rotate(self, matrix): """ :type matrix: List[List[int]] :rtype: None Do not return anything, modify matrix in-place instead. [ [1,2,3], [4,5,6], [7,8,9] ], rotate the input matrix in-place such that it becomes: [ [7,4,1], [8,5,2], [9,6,3] ] """ n= len(matrix) for i in range(n): for j in range(n): if i<j: matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] for i in matrix: i.reverse() if __name__ == "__main__": Solution().rotate([[1,2,3],[4,5,6,],[7,8,9]])
78f4b8b8aa2eb93a5daf00dfb0e3077df20a217e
sAnjali12/BsicasPythonProgrammas
/python/if1.py
123
4.03125
4
number = input("enter your no.") num = int(number) if num<10: print "small hai" elif num>10 or num<20: print "yeeeeeeee"
d58cd85ebb232f5540e8cde005f1352d9fb8e2e4
sAnjali12/BsicasPythonProgrammas
/python/reportAvarage.py
386
3.5625
4
marks = [ [78, 76, 94, 86, 88], [91, 71, 98, 65, 76], [95, 45, 78, 52, 49]] index = 0 total_sum=0 while index<len(marks): j = 0 sum=0 count = 0 while j<len(marks[index]): sum = sum+marks[index][j] count = count+1 average = sum/count j = j+1 print sum print average total_sum=total_sum+sum index = index+1 print total_sum #print average
b68c9db55ce6af793f0fc36505e12e741c497c31
sAnjali12/BsicasPythonProgrammas
/python/userInput_PrimeNum.py
339
4.1875
4
start_num = int(input("enter your start number")) end_num = int(input("enter your end number")) while (start_num<=end_num): count = 0 i = 2 while (i<=start_num/2): if (start_num): print "number is not prime" count = count+1 break i = i+1 if (count==0 and start_num!=1): print "prime number" start_num = start_num+1
0c2c3eaca985cb68fc6a58e24ffaea257dbb89ad
sAnjali12/BsicasPythonProgrammas
/python/sum.py
421
3.75
4
elements = [23, 14, 56, 12, 19, 9, 15, 25, 31, 42, 43] index = 0 sum1 = 0 sum2 = 0 count1 = 0 count2 = 0 while index<len(elements): if elements[index]%2==0: count1 = count1+1 sum1 = sum1+elements[index] else: count2 = count2+1 sum2 = sum2+elements[index] index = index+1 even_average = sum1/count1 odd_averae = sum2/count2 print "EVEN AVERAGE:)___",even_average print "ODD AVERAGE:)_______",odd_aerage
932faa7f15b06df9c922ff7b84c74853d869a93a
isaacgs95/Kata1
/kata2/programa_2_4.py
270
4
4
''' Escribir un programa que pida al usuario un número entero positivo y muestre por pantalla la cuenta atrás desde ese número hasta cero separados por comas. ''' numero = int(input("Introduce un número: ")) for i in range(numero, -1, -1): print(i, end=", ")
3750e8f1fc7137dddda348c755655db99026922b
xilaluna/web1.1-homework-1-req-res-flask
/app.py
1,335
4.21875
4
# TODO: Follow the assignment instructions to complete the required routes! # (And make sure to delete this TODO message when you're done!) from flask import Flask app = Flask(__name__) @app.route('/') def home(): """Shows a greeting to the user.""" return f'Are you there, world? It\'s me, Ducky!' @app.route('/frog') def my_favorite_animal(): """shows user my favorite animal""" return f'Frogs are cute!' @app.route('/dessert/<users_dessert>') def favorite_dessert(users_dessert): return f'How did you know I liked {users_dessert}' @app.route('/madlibs/<adjective>/<noun>') def mad_libs(adjective, noun): return f'That is one {adjective} {noun}' @app.route('/multiply/<number1>/<number2>') def multiply(number1, number2): if (number1.isdigit() == True) & (number2.isdigit() == True): answer = int(number1) * int(number2) return answer else: return "Invalid inputs. Please try again by entering 2 numbers!" @app.route('/sayntimes/<word>/<number>') def sayntimes(word, number): if number.isdigit() == True: string = "" for word in range(int(number)): string += str(word) return else: return f"Invalid input. Please try again by entering a word and a number!" if __name__ == '__main__': app.run(debug=True)
9d0241b8b9a5d399ca4334a5cd95caefd6284651
ecoBela/flask_app_game_wk3_wkend_hw
/app/tests/test_game.py
1,709
3.875
4
import unittest from app.models.game import Game from app.models.games import * from app.models.player import Player class TestGame(unittest.TestCase): def setUp(self): self.player1 = Player("Socrates", "Rock") self.player2 = Player("Plato", "Paper") self.player3 = Player("Aristotle", "Scissors") self.player4 = Player("Captain Marvel", "Rock") self.game1 = Game([self.player1, self.player2]) def test_game_has_players(self): self.assertEqual([], self.game1.players) def test_choose_rock_over_scissors(self): # result = choose_winner(self.player1, self.player3) # self.assertEqual(self.player1, result) result = choose_winner(self.player1, self.player3) self.assertEqual(f"{player1.name} chose Rock and is the winner!", result) result = choose_winner(self.player1, self.player2) self.assertEqual(f"{player2.name} chose {player2.move} and is the winner!", result) result = choose_winner(self.player3, self.player1) self.assertEqual(f"{player1.name} chose {player1.move} and is the winner!", result) def test_choose_scissors_over_paper(self): result = choose_winner(self.player3, self.player2) self.assertEqual(f"{self.player3.name} chose {player3.move} and is the winner!", result) result = choose_winner(self.player3, self.player1) self.assertEqual(f"{player1.name} chose {player1.move} and is the winner!", result) def test_it_is_a_draw(self): result = choose_winner(self.player1, self.player4) self.assertEqual(f"{player1.name} and {player4.name} made the same move. It's a draw!", result)
71e703749e9420528dd2dc48e8d89d4f5d7da8ce
Davidrbl/python-6
/Room.py
1,129
3.53125
4
class Room: def __init__(self, _name, _exits=[], _items=[], _people=[]): self.exits = _exits self.items = _items self.people = _people self.name = _name def add_exit(self, room): self.exits.append(room) def describe(self, game): game.printHeader() #Naam generaten game.printRegel("Je bent nu in: " + self.name) #Zeggen wat erin is game.printRegel(game.show_list(self.items, "Items in this room")) game.printRegel(game.show_list(self.people, "People in this room")) game.printRegel(game.show_list(self.exits, "Exits")) game.printFooter() def add_item(self, item): self.items.append(item) def add_person(self, person): self.people.append(person) def getExits(self): return self.exits def setExits(self, exits): self.exits = exits def getItems(self): return self.items def setItems(self, items): self.items = items def getPeople(self): return self.people def setPeople(self, people): self.people = people
d0beb6a3f23b2a9337b60dd68d6083c1c60873ed
DanielFlores23/Tareas
/multiplicacion2.py
536
3.84375
4
for indice in range (32,36): print("Tabla de ", inndice for elemento in range(1,11): resultado = indice * elemento print("{2} x {0} = {1}".format(elemento,resultado,indice)) print() print() print("Otros Valores") print() tablas= [21, 34, 54, 65, 76] for indice in tablas: print("Tabla del ", indice) for elemento in range(1,11): resultado = indice * elemento print("{2} x {0} = {1}".format(elemento,resultado,indice)) print()
715634e01c2a166e581c9fa0554218ef11072444
terryjungtj/OpenCV_Practice
/04-shapesAndTexts.py
1,212
3.671875
4
# Shapes and Texts import cv2 import numpy as np print("Package Imported") img = np.zeros((512, 512, 3), np.uint8) # matrix of 0 (black) # img[:] = 255, 0, 0 # change all the pixels in the matrix to blue cv2.line(img, (0,0), (300,300), (0,255,0), 3) # draw a line (image, starting point, ending point(user defined), colour, thickness) # cv2.line(img, (0,0), (img.shape[1],img.shape[0]), (0,255,0), 3) # draw a line (image, starting point, ending point, colour, thickness) cv2.rectangle(img, (0,0), (250,350), (0,0,255), 3) # draw a rectangle (image, starting point, ending point(user defined), colour, thickness) # cv2.rectangle(img, (0,0), (250,350), (0,0,255), cv2.FILLED) # draw a rectangle (image, starting point, ending point(user defined), colour, filled) cv2.circle(img, (400, 50), 30, (255, 0, 0), 3) # draw a circle (image, centre point, radius(user defined), colour, thickness) cv2.putText(img, "OPENCV", (300,100), cv2.FONT_ITALIC, 1, (0,250,0), 1) # insert text (image, text, position, font, scale, colour, thickness) cv2.imshow("Image", img) cv2.waitKey(0)
21fbb16cd1da3148922030c29f5f6f0563d12463
Ahmedatef-09/machine_learning
/python_files/ML_English/logistic_regreesion/logistic_regression.py
1,681
3.578125
4
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import statsmodels.api as sm sns.set() from sklearn.linear_model import LinearRegression from sklearn.feature_selection import f_regression from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split raw_data = pd.read_csv('2.02. Binary predictors.csv') # print(raw_data) data = raw_data.copy() data['Admitted'] = data['Admitted'].map({'Yes':1,'No':0}) data['Gender'] = data['Gender'].map({'Female':1,'Male':0}) # print(data) y = data['Admitted'] x1 = data[['SAT','Gender']] # print(x1) # '''lets create the regression using stats model''' x = sm.add_constant(x1) # # print(x) reg_log = sm.Logit(y,x) #this is logistic_regression code line result_log = reg_log.fit() # # print(reg_log) # print(reg_log.summary()) '''if we take np.exp(gender_coef) it will result 7 which mean in the same sat score female has 7 times higher odd than males''' #if we want to predict values the use reg_log.predict() np.set_printoptions(formatter={'float':lambda x: "{0:0.2f}".format(x)}) #format output # print(result_log.predict()) '''if you want to compare result predicted with actual you use this method''' # print(result_log.pred_table()) '''lets try to show the table in gopod look ''' df = pd.DataFrame(result_log.pred_table(),columns=['predicted 0 ','predicted 1'],index=['actual 0 ','actual 1']) # print(df) '''to calculate the accuracy ''' accuracy_df = np.array(df) accuracy_final = (accuracy_df[0,0]+accuracy_df[1,1])/accuracy_df.sum() # print(accuracy_final) '''now lets test our model ''' # print(x)
266cb9b64f570b1262f7bfd62d9d81892ced05fe
Ahmedatef-09/machine_learning
/python_files/ML_Arabic/pandas_groupby.py
618
3.546875
4
import numpy as np import pandas as pd dic = {'a':[1,2,3], 'b':[4,5,6], 'c':[7,8,9], 'key':'a b c'.split()} dic2 = {'a':[10,20,30], 'b':[40,50,60], 'c':[70,80,90], 'key':'a b c'.split()} df = pd.DataFrame(dic,index=[0,1,2]) df2 = pd.DataFrame(dic2,index=[0,1,2]) df3 = pd.concat([df,df2],axis=0) #paste dataframe,df2 under each other df4 = pd.merge(df,df2,how= 'inner',on='key')#inner join df,df2 u can merge more than one ke #df.join(df2)( in this case merge by index index df = index df2 ) but in .merge merge done by column print(df)
6e825fd8dbd70ac20d3502995a7a1efa4da77ab9
shivangsoni/NLP
/HW/ShivangSoni_HW1/CustomLanguageModel
2,439
3.546875
4
import math from collections import Counter from collections import defaultdict class CustomLanguageModel: def __init__(self, corpus): """Initialize your data structures in the constructor.""" self.unigram_count = Counter() self.bigram_count = Counter() self.trigram_count = Counter() self.vocabulary_size = 0 self.num_words = 0 self.backoff_multiplier = 0.4 self.train(corpus) def train(self, corpus): """ Takes a corpus and trains your language model. Compute any counts or other corpus statistics in this function. """ for sentence in corpus.corpus: prev_word1 = None prev_word2 = None for datum in sentence.data: word = datum.word self.unigram_count[tuple([word])] += 1 if prev_word1 != None: self.bigram_count[tuple([prev_word1,word])] += 1 if prev_word2 != None: self.trigram_count[tuple([prev_word2,prev_word1,word])] += 1 prev_word2 = prev_word1 prev_word1 = word self.vocabulary_size = len(self.unigram_count) self.num_words = sum(self.unigram_count.values()) def score(self, sentence): """ Takes a list of strings as argument and returns the log-probability of the sentence using your language model. Use whatever data you computed in train() here. """ score = 0.0 prev_word1 = None prev_word2 = None for word in sentence: three_words_count = self.trigram_count[tuple([prev_word2, prev_word1, word])] two_words_count = self.bigram_count[tuple([prev_word2, prev_word1])] # Use the trigram if it exists if (three_words_count > 0): score += math.log(three_words_count) score -= math.log(two_words_count) else: two_words_count = self.bigram_count[tuple([prev_word1, word])] one_word_count = self.unigram_count[tuple([prev_word1])] # Use the bigram if it exists if (two_words_count > 0): score += math.log(self.backoff_multiplier) score += math.log(two_words_count) score -= math.log(one_word_count) # Use the unigram in case all else fails else: score += 2 * math.log(self.backoff_multiplier) score += math.log(self.unigram_count[tuple([word])] + 1.0) score -= math.log(self.num_words + self.vocabulary_size) prev_word2 = prev_word1 prev_word1 = word return score
26a5cbe6f6590d875069427d1b72cf5f7d6a86c1
nikolajjsj/IntoToCSPython
/week2/tower_of_hanoi.py
418
3.8125
4
def printMove(from_stack, to_stack): print('Move from ' + str(from_stack) + ' to ' + str(to_stack)) def towers_of_hanoi(n, from_stack, to_stack, spare_stack): if n == 1: printMove(from_stack, to_stack) else: towers_of_hanoi(n-1, from_stack, spare_stack, to_stack) towers_of_hanoi(n, from_stack, to_stack, spare_stack) towers_of_hanoi(n-1, spare_stack, to_stack, from_stack)
dfabde0a7eddb09e12accbde3198111ff9f0cfa0
770847573/Python_learn
/Hello/正则/3.边界匹配.py
2,098
3.890625
4
""" --------------锚字符(边界字符)------------- ^ 行首匹配,和在[]里的^不是一个意思 [^xxxxx] $ 行尾匹配 \A 匹配字符串开始,它和^的区别是,\A只匹配整个字符串的开头,即使在re.M模式下也不会匹配它行的行首 \Z 匹配字符串结束,它和$的区别是,\Z只匹配整个字符串的结束,即使在re.M模式下也不会匹配它行的行尾 \b 匹配一个单词的边界,也就是值单词和空格间的位置 \B 匹配非单词边界 """ import re # search():使用指定的正则在指定的字符串中从左往右依次进行搜索,只要找到一个符合条件的子字符串,则立即停止查找,返回一个对象 # search函数的底层调用的是match # findall():使用指定的正则在指定的字符串中匹配所有符合条件的子字符串,返回一个列表 print(re.search(r"^this","this is a text")) # startswith() print(re.search(r"text$","this is a text")) # endswith() print("this is a text\nthis is a text\nthis is a text\nthis is a text") # 默认情况下,即使字符串有多行,使用^和$进行行首和行尾的匹配,都将字符串当做一行处理 print(re.findall(r"^this","this is a text\nthis is a text\nthis is a text\nthis is a text")) # ['this'] print(re.findall(r"text$","this is a text\nthis is a text\nthis is a text\nthis is a text")) # ['text'] # 如果需要匹配每个行的行首和行尾,需要设置flags=re.M,表示多行模式 print(re.findall(r"^this","this is a text\nthis is a text\nthis is a text\nthis is a text",flags=re.M)) # ['this', 'this', 'this', 'this'] print(re.findall(r"text$","this is a text\nthis is a text\nthis is a text\nthis is a text",flags=re.M)) # ['text', 'text', 'text', 'text'] # \A和\Z即使在re.M模式下也不会匹配它行的行首和行尾 print(re.findall(r"\Athis","this is a text\nthis is a text\nthis is a text\nthis is a text",flags=re.M))# ['this'] print(re.findall(r"text\Z","this is a text\nthis is a text\nthis is a text\nthis is a text",flags=re.M))# ['text']
d4509f58c0d0721b86336e567946646df9431717
770847573/Python_learn
/Hello/错误和异常/抛出异常raise.py
391
4.15625
4
# 产生异常的形式 # 形式一:根据具体问题产生异常【异常对象】 try: list1 = [12, 3, 43, 34] print(list1[23]) except IndexError as e: print(e) #形式2:直接通过异常类创建异常对象, # raise异常类(异常描述)表示在程序中跑出一个异常对象 try: raise IndexError("下标越界~~~") except IndexError as e: print(e)
fdc709509a4898c4be7205c77a5f0a7c3a3f029e
770847573/Python_learn
/Hello/正则/1.数量词匹配.py
1,759
3.875
4
""" -------------------匹配多个字符------------------------ 说明:下方的x、y、z均为假设的普通字符,n、m(非负整数),不是正则表达式的元字符 (xyz) 匹配小括号内的xyz(作为一个整体去匹配) x? 匹配0个或者1个x x* 匹配0个或者任意多个x(.* 表示匹配0个或者任意多个字符(换行符除外)) x+ 匹配至少一个x x{n} 匹配确定的n个x(n是一个非负整数) x{n,} 匹配至少n个x x{n,m} 匹配至少n个最多m个x。注意:n <= m x|y |表示或,匹配的是x或y """ """ () 表示分组,其中的内容可以当做一个整体处理 {} 数量匹配,限定指定的字符出现的次数 | 表示或,,语法:正则一|正则二,表示只要其中一个正则能够匹配上,则就可以得到结果 ? 匹配0个或者1个,非贪婪匹配 * 匹配0个或者多个,贪婪匹配 + 匹配1个或者多个【匹配至少1个】,贪婪匹配 """ import re # findall():使用指定的正则在指定的字符串中匹配所有符合条件的子字符串,返回一个列表 print(re.findall(r"a+","aaaaaaaaaaaaaaaaaaaaa")) # ['aaaaaaaaa'],至少匹配1个,尽可能多的匹配 print(re.findall(r"a?","aaaaaaaaa")) # ['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', ''],优先匹配1个,最后必定有一个"" print(re.findall(r"a*","aaaaaaaaa")) # ['aaaaaaaaa', ''],尽可能多的匹配,最后必定有一个"" print(re.findall(r"a{3}","aaaaaaaaaa")) # ['aaa', 'aaa', 'aaa'],一次只能匹配3个 print(re.findall(r"a{3,}","aaaaaaaaa")) # ['aaaaaaaaa'],尽可能多的匹配 print(re.findall(r"a{3,5}","aaaaaaaaa")) # ['aaaaa', 'aaaa'],尽可能多的匹配
df37cd6d0c236e8f92f0892484ea4d63bfcd1d93
770847573/Python_learn
/Hello/Day13Code/4.装饰器使用一.py
2,245
4
4
# 1.闭包 def func1(): n = 45 def func2(): print(n) return func2 # 方式一 f = func1() f() # 方式二 func1()() # 2. """ 假设我们要增强某个函数的功能,但又不希望修改原函数的定义, 这种在代码运行期间动态增加功能的方式,称之为“装饰器”(Decorator) """ # 装饰器的本质:实际上是一个闭包 # 闭包的书写形式 # 方式一 def outter1(a): def inner1(b): print(a,b) return inner1 f1 = outter1(3) f1(4) # 方式二 def outter1(a): def inner1(b): print(a,b) inner1(79) outter1(3) # 实现装饰器,使用方式一 # 3.装饰器的语法 def now(): # 7 print("拼搏到无能为力,坚持到感动自己") # 需求:给now函数增加一个新的功能,但是要求不能修改now函数 # 装饰器的书写步骤 # a.书写一个闭包,外部函数的函数名其实就是装饰器的名称 # b.给外部函数设置参数,该参数表示需要被装饰的函数,一般命名为func,fun,f... def outter(func): # 2 def inner(): # 3,5 # c.调用原函数 func() # 在内部函数中调用了外部函数中的变量 6 # d.新增功能 print("new~~~~") # 8 # e.inner中包含了原函数的功能和新的功能,也就是原函数被装饰器之后的结果, 所以必须将装饰之后的结果返回 return inner # 3 # f.调用外部函数【装饰器】,将原函数作为参数传递 f = outter(now) # func = now f = inner 1 f() # 4 """ 掌握: a.语法 b.执行顺序 使用场景: 在实际项目开发中,有ABC三个人同时开发同一个项目 对于整个项目中的公共文件,一个公共文件有可能在多个地方 如果其中一个人需要使用公共文件中的功能,但是还需要增加新的功能,一定不能直接修改文件,可以使用装饰器 """ """ 注意: a.好处:在不修改原函数的基础上增加新的功能 b.调用原函数和增加新功能没有绝对的先后顺序,根据具体的需求进行调整 c.装饰器实际上还是普通的函数,所以一定要注意参数的匹配 """
7b756c270d420e1256cfe977fb7576833a54b4d5
770847573/Python_learn
/Hello/简单排序算法/1.作业讲解.py
900
3.796875
4
# 需求:利用列表推导式将已知列表中的整数提取出来 list1 = [True, 17, "hello", "bye", 98, 34, 21] # 注意:isdigit()是字符串的功能,其他类型的变量无法使用 # 方式一:str() list2 = [ele for ele in list1 if str(ele).isdigit()] print(list2) # 方式二:type() # [17, 98, 34, 21] list2 = [ele for ele in list1 if type(ele) == int] print(list2) # 方式三:isinstance(变量,类型)判断一个变量是否是指定的数据类型 list2 = [ele for ele in list1 if isinstance(ele,int) and not isinstance(ele,bool)] print(list2) # [17, 98, 34, 21] # 需求:利用列表推导式存放指定列表中字符串的长度 # 注意:列表,元组,字符串,字典和集合都可以使用len()统计元素的个数或者计算容器的长度 list1 = ["good", "nice", "see you", "bye"] # print(len("good")) list2 = [len(word) for word in list1] print(list2)
69ecb5fe76a1dee7a56808755922d0a942c069cb
770847573/Python_learn
/shopcar1/storage.py
2,479
3.65625
4
""" 仓库类:【信息保存在本地磁盘:程序刚启动时把列表先存储到文件中,之后使用再读取出来】 商品列表 商品名称 价格 剩余量 Mac电脑 20000 100 PthonBook 30 200 草莓键盘 80 60 iPhone 7000 70 """ import os,pickle from shopcar1.goods import Goods # 注意:导入类和导入函数以及变量的方式相同 # 假设存储仓库中商品列表的文件名为goodslist.txt path = r"goodslist.txt" # 任何用户,任何一次访问到仓库的时候应该访问的都是同一个仓库,所以需要将仓库类定义为单例类 def singleton(cls): instance = None def getinstance(*args,**kwargs): nonlocal instance if not instance: instance = cls(*args,**kwargs) return instance return getinstance @singleton class Storage(object): __slots__ = ("goods_list",) # 如果程序第一次启动:文件不存在,需要商品列表先存储到文件中 # 如果程序第二次以上启动:文件存在,则需要将文件中的内容读取出来 def __init__(self): # 注意:在实际项目开发中,建议早构造函数中的代码尽量简洁 self.__load_goods() # 加载商品,对于其中的操作,只在当前类中可以进行 def __load_goods(self): if os.path.exists(path): # 存在,说明程序不是第一次运行 self.get_goods() else: # 不存在,说明程序是第一次运算 # a.定义商品列表,用于存储仓库中的商品对象 self.goods_list = [] # b.模拟商品信息 name_list = ["Mac电脑","food","book","kindle"] price_list = [130000,20,78,500] num_list = [100,100,100,100] # c.遍历上述三个列表,将对应的信息获取出来,然后创建商品对象并添加到商品列表中 for i in range(len(name_list)): goods = Goods(name_list[i],price_list[i],num_list[i]) self.goods_list.append(goods) # d.将商品列表存储到文件中【对象的序列化和反序列化】 self.save_goods() def save_goods(self): with open(path, "wb") as f: pickle.dump(self.goods_list, f) def get_goods(self): with open(path, "rb") as f: self.goods_list = pickle.load(f)
7bbf2b2e59d035278ed1512201e70391af6c2e8a
770847573/Python_learn
/day19/4.多态的应用.py
1,664
4.4375
4
# 1.多态的概念 # a. class Animal(object): pass class Cat(Animal): pass # 在继承的前提下,一个子类对象的类型可以是当前类,也可以是父类,也可以是祖先类 c = Cat() # isinstance(对象,类型)判断对象是否是指定的类型 print(isinstance(c,object)) # True print(isinstance(c,Animal)) # True print(isinstance(c,Cat)) # True a = Animal() print(isinstance(a,Cat)) # False # b. class Animal(object): def show(self): print("父类") class Cat(Animal): def show(self): print("cat") class Dog(Animal): def show(self): print("dog") class Pig(Animal): def show(self): print("pig") # 定义a的时候不确定a的类型,所以不能确定a.show()调用的是哪个类中的函数 def func(a): a.show() c = Cat() d = Dog() p = Pig() # 当运行程序的时候,才能确定a的类型 func(c) func(d) func(p) # 2.多态的应用 # 好处:简化代码 # 需求:人喂养动物 class Animal(object): def __init__(self,name): self.name = name def eat(self): print("eating") class Cat(Animal): pass class Dog(Animal): pass class Pig(Animal): pass class Person(object): """ def feed_cat(self,cat): cat.eat() def feed_dog(self,dog): dog.eat() def feed_pig(self,pig): pig.eat() """ # 定义的时候ani的类型并不确定,只有当函数被调用,传参之后才能确定他的类型 def feed_animal(self,ani): ani.eat() per = Person() c = Cat("小白") d = Dog("旺财") p = Pig("小黑") per.feed_animal(c) per.feed_animal(d) per.feed_animal(p)
37cb9c59405d6f6c92945782ff7c68b5adff0388
770847573/Python_learn
/Hello/Day15/day15作业.py
504
3.609375
4
#获取当前时间,判断是否是元旦,如果不是,计算和元旦差了多少天 import datetime def get_time(): time_now = datetime.datetime.now() time_now_day = time_now.strftime('%Y/%m/%d') if time_now_day == '2021/01/01': print('今天是是元旦') else: yuandan_date =datetime.datetime(2021,1,1,0,0,0) days1= time_now - yuandan_date days2 = days1.days print('今天不是元旦,距元旦相差了{}天'.format(days2)) get_time()
bccdae6959d7354f0a68014f753b98a6e7075dc0
770847573/Python_learn
/Hello/抽象类的使用.py
400
4.125
4
import abc class MyClass(metaclass=abc.ABCMeta): @abc.abstractmethod def mymethod(self): pass class My1(MyClass): def mymethod(self): print('Do something!!!') my = My1()#如果一个类继承自抽象类,而未实现抽象方法,仍然是一个抽象类 my.mymethod() #my1 = MyClass() TypeError: Can't instantiate abstract class MyClass with abstract methods mymethod
a5fc666c80858fc0a3f313bfe562b0e25115e840
770847573/Python_learn
/Hello/Day13Code/5.装饰器使用二.py
1,517
3.875
4
# 1.需求:书写一个装饰器,对年龄进行校验 def get_age(age): print("年龄:%d" % (age)) def check_age(func): def inner(n): # 新的功能:校验传进来的年龄是否是负数,如果是负数,则改为相反数 if n < 0: n = -n # 调用原函数 func(n) return inner f = check_age(get_age) f(-6) # 使用场景:如果原函数有参数,而且在装饰器中需要对原函数中的参数做出操作,则在装饰器的内部函数中设置参数 print("*" * 30) # 2.使用 @xxx 简化装饰器的使用 # 注意1:@xxx表示将一个指定的装饰器直接作用于需要装饰的函数,xxx表示装饰器的名称 # 注意2:使用@xxx装饰函数,则装饰器必须先存在,然后才能使用 def check_age1(func): print("外部函数被执行了~~~~~~") def inner1(n): print("内部函数被执行了~~~~~") if n < 0: n = -n # 调用原函数 func(n) return inner1 # @xxx会调用装饰器的外部函数,同时将外部函数的返回值返回,原函数的函数名指向了内部函数的引用 @check_age1 # @xxx的作用相当于 check_age(get_age) def get_age1(age): print("年龄:%d" % (age)) # get_age1(-18)调用的将不再是原函数,而是装饰器的内部函数 get_age1(-18) """ 工作原理: 假设: 原函数:a 装饰器:wrapper(func) @wrapper:func = a原 a------》inner a() : inner() """
7a61d100ca4bd6b29b7642691b09b1de68709424
770847573/Python_learn
/Hello/正则/7.正则练习一.py
551
3.609375
4
# 1.要求从控制台输入用户名和密码,如果用户名和密码都输入合法,则注册成功 """ 要求: 用户名:只能由数字或字母组成,长度为6~12位 密码:只能由数字组成,长度必须为6位 """ import re username = input("请输入用户名:") pwd = input("请输入密码:") # 匹配上,返回一个对象,匹配不上,返回None r1 = re.match(r"^[0-9a-zA-Z]{6,12}$",username) r2 = re.match(r"^\d{6}$",pwd) if r1 and r2: print("注册成功") else: print("注册失败")
b10c4327168a5edd2d50a588ac0731f3b67bc4c9
KurinchiMalar/DataStructures
/DynamicProgramming/MaximumSumContiguousSubsequence.py
3,855
3.78125
4
''' Given a sequence of n numbers A(1)....A(n) give an algorithm for finding a contiguous subsequence A(i)....A(j) for which the sum of elements in the subsequence is maximum. Example : {-2, 11,-4, 13, -5, 2} --> 20 (11 + -4 + 13) {1, -3, 4, -2, -1, 6} --> 7 (4 + -2,+ -1 + 6) ''' # Time Complexity : O(n) # Space Complexity : O(1) ''' Kadane's Algorithm: Look at all positive contiguous segments of the array and keep track of the maximum sum contiguous segment(sum_end_here) among all the positvite segments(sum_so_far). Each time we get a positive sum , update sum_so_far accordingly. ''' def max_sum_contiguous_subseq_KadaneAlgorithm(Ar): sum_end_here = 0 sum_so_far = 0 for i in range(0,len(Ar)): sum_end_here = sum_end_here + Ar[i] if sum_end_here < 0: sum_end_here = 0 continue if sum_so_far < sum_end_here: sum_so_far = sum_end_here return sum_so_far # Time Complexity : O(n) # Space Complexity : O(n) # M[i] indicates maximum sum of all windows ending at i. def max_sum_contiguous_subseq_dynamic(Ar): M = [0]*(len(Ar)+1) result = [] if Ar[0] > 0: M[0] = Ar[0] else: M[0] = 0 for i in range(0,len(Ar)): if M[i-1]+Ar[i] > 0 : M[i] = M[i-1]+Ar[i] else: M[i] = 0 max_sum = 0 max_index = 0 for i in range(0,len(M)): # one complete scan to find the max value. if M[i] > max_sum: max_sum = M[i] max_index = i for i in range(0,max_index+1): if M[i] == 0: result = [] else: result.append(Ar[i]) print "The maxsum_contiguous_subseq_fromlefttoright:"+str(result) # to print the maximum seq return max_sum # Time Complexity : O(n) # Space Complexity : O(n) # M[i] indicates maximum sum of all windows starting at i. def max_sum_contiguous_subseq_dynamic_fromrighttoleft(Ar): n = len(Ar) M = [0]*(n+1) result = [] if Ar[n-1] > 0: M[n-1] = Ar[n-1] else: M[n-1] = 0 for i in range(n-2,-1,-1): if M[i+1]+Ar[i] > 0 : M[i] = M[i+1]+Ar[i] else: M[i] = 0 max_sum = 0 max_index = 0 for i in range(0,len(M)): # one complete scan to find the max value. if M[i] > max_sum: max_sum = M[i] max_index = i for i in range(n-1,max_index-1,-1): if M[i] == 0: result = [] else: result.append(Ar[i]) print "The maxsum_contiguous_subseq_fromrighttoleft:"+str(result) # to print the maximum seq return max_sum # Time Complexity : O(nlogn) # Divide and Conquer approach # Recurrence : 2T(n/2) + O(n) import sys def max_crossing_sum(Ar,l,m,hi): left_max = -sys.maxint-1 left_sum = 0 for i in range(m,l-1,-1): left_sum += Ar[i] if left_sum > left_max: left_max = left_sum right_max = -sys.maxint-1 right_sum = 0 for i in range(m+1,hi+1): right_sum += Ar[i] if right_sum > right_max: right_max = right_sum return left_max + right_max def max_value_contiguous_subsequence(Ar,low,high): if low == high: return Ar[low] mid = (low + high) // 2 return max( max_value_contiguous_subsequence(Ar,low,mid),\ max_value_contiguous_subsequence(Ar,mid+1,high),\ max_crossing_sum(Ar,low,mid,high)) Ar = [2, 3, 4, 5, 7] Ar = [-2, 11,-4, 13, -5, 2] print "max_Recursive_O(nlogn):"+str(max_value_contiguous_subsequence(Ar,0,5)) print "max_DP_O(n):"+str(max_sum_contiguous_subseq_dynamic(Ar)) print "max_DP_O(n):"+str(max_sum_contiguous_subseq_dynamic_fromrighttoleft(Ar)) print "max_Kadane's Algorithm_O(n):"+str(max_sum_contiguous_subseq_KadaneAlgorithm(Ar))
9e97f5a89008686e2f7317b30441b7f2eeffe933
KurinchiMalar/DataStructures
/Sorting/CountingSort.py
1,053
3.671875
4
# Time Complexity : O(n+k) # Space Complexity : O(n+k) def counting_sort(Ar,k): B = [0 for el in Ar] C = [0 for el in range(0,k+1)] print "Ar :"+str(Ar) print "B :"+str(B) print "C :"+str(C) for j in range(0,len(Ar)): #Build the counting array...how many times current index has occured in original Ar C[Ar[j]] = C[Ar[j]] + 1 print "C now :"+str(C) # Build array such that each index says "I have x number of smaller elements in result array less than or equal to x" for j in range(1,k+1): C[j] = C[j-1] + C[j] print "C new :" + str(C) #Put element 5 in input array = C[5] - 1 th position in Result array B. # In this eg) 5 in input array = 6th position (C[5] - 1) in B # Then subtract 1 since one occurence is captured in result already now. for i in range(len(Ar)-1,-1,-1): B[C[Ar[i]]-1] = Ar[i] C[Ar[i]] = C[Ar[i]] - 1 #print B[C[Ar[i]]-1] print "Result :" + str(B) if __name__ == '__main__': Ar = [5,2,3,1,2,3,0] counting_sort(Ar,5)
9a97498c8f5dfe49b5a0118718c8e6b81dbd97f2
KurinchiMalar/DataStructures
/Strings/RemoveAdjacentDuplicatesRecursively.py
1,016
3.890625
4
''' Recursively remove all adjacent duplicates. Given a string of characters, recursively remove adjacent duplicate characters from string. The output string should not have any adjacent duplicates. ''' # Time Complexity : O(n) # Space Complexity : O(1) ... inplace, no stack. def remove_adj_duplicates(mystring): result = [] res_idx = 0 mystring[res_idx] = mystring[0] i = 1 while i < len(mystring): if mystring[i] != mystring[res_idx]: res_idx = res_idx + 1 mystring[res_idx] = mystring[i] i = i + 1 else: while i < len(mystring) and mystring[i] == mystring[res_idx]: # recursively remove all equals. res_idx = res_idx - 1 i = i + 1 print "mystring:"+str(mystring[0:res_idx+1]) # our desired chars are only upto res_idx. mystring = "azxxzy" mystring = "geeksforgeeks" mystring = "careermonk" mystring = "mississippi" mystring = list(mystring) remove_adj_duplicates(mystring)
6b1dc96656928464dc9fd37109885b88c9560134
KurinchiMalar/DataStructures
/Searching/FirstRepeatingElement.py
2,180
3.578125
4
#https://ideone.com/daLlg9 #Time Complexity = O(n) (Building hash_ar and finding max of negatives) #Space Complexity = O(k) ---- k is the range of numbers in the input array. Here 0 to 5. Hence k = 5 ''' Solution: 1) Store the position of occurence in input array in hash_ar 2) On second occurence negate 3) If already negated just skip 4) Index of the largest negative value is the first repeating element ''' def first_repeating_element_hashing_withpositions(Ar,n): hash_ar = [0] * (n+1) for i in range(0,len(Ar)): position = hash_ar[Ar[i]] if position == 0: # first occurence hash_ar[Ar[i]] = i+1 #Array index starts from zero. hence index 0 == position 1 elif position > 0: # repeating for the first time hash_ar[Ar[i]] = -(hash_ar[Ar[i]]) # if position is negative .... just skip and move to next element. we have already registered it's repetition. print hash_ar # Find the largest negative value and return the index of it from hash_ar. result_val = 0 result_index = -1 for i in range(0,len(hash_ar)): if hash_ar[i] < 0: # seeing oly negatives if result_val == 0 or hash_ar[i] > result_val: result_val = hash_ar[i] result_index = i print "first repeating element is:"+ str(result_index) print "result_val:"+str(result_val) return result_index #YET TO UNDERSTAND THIS IMPLEMENTATION '''def FirstRepeatedElementAmongRepeatedElementsWithHash(A): table = {} # hash max = 0 for element in A: if element in table and table[element] == 1: table[element] = -2 elif element in table and table[element] < 0: table[element] -= 1 elif element != " ": table[element] = 1 else: table[element] = 0 for element in A: if table[element] < max: max = table[element] maxRepeatedElement = element print maxRepeatedElement, "repeated for ", abs(max), " times" ''' #A = [3,2,1,2,3] #FirstRepeatedElementAmongRepeatedElementsWithHash(A) #Ar = [3,2,1,2,3] Ar = [3, 2, 1, 1, 2, 1, 2, 5, 5] first_repeating_element_hashing_withpositions(Ar,5) #FirstRepeatedElementAmongRepeatedElementsWithHash(Ar)
d15a8a84b1a7e7ac54f74d47180757109a17782a
KurinchiMalar/DataStructures
/Medians/FindLargestInArray.py
505
4.28125
4
__author__ = 'kurnagar' import sys # Time Complexity : O(n) # Worst Case Comparisons : n-1 # Space Complexity : O(1) def find_largest_element_in_array(Ar): max = -sys.maxint - 1 # pythonic way of assigning most minimum value #print type(max) #max = -sys.maxint - 2 #print type(max) for i in range(0,len(Ar)): if Ar[i] > max: max = Ar[i] return max Ar = [2, 1, 5, 234, 3, 44, 7, 6, 4, 5, 9, 11, 12, 14, 13] print ""+str(find_largest_element_in_array(Ar))