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
e77fa8624d18fc83c991cc75ed4fd7a91d55167c
zbnmoura/python-demo
/py_json.py
401
3.890625
4
# JSON is commonly used with data APIS. Here how we can parse JSON into a Python dictionary import json #sample json user_json = '{"name":"bruno", "age":27}' #parse to dict user = json.loads(user_json) print(user, type(user)) print(user['name']) #dict to json(str) car = {'color':'gray', 'make':'toyota', 'model':'yaris', 'year':2019} car_json = json.dumps(car) print(car_json, type(car_json))
ebd053e13774a318fc462af8bebc3f7234a254a7
FloatingFowl/ValueIterationMDP
/value_iteration.py
5,461
3.859375
4
def move_up(A,i,j,walls): '''Utility function if you move up''' final = 0.0 try: if (i+1,j) not in walls: val = A[i+1][j] final += 0.8*val else: raise IndexError except IndexError: final += 0.8*A[i][j] try: if (i,j+1) not in walls: val = A[i][j+1] final += 0.1*A[i][j+1] else: raise IndexError except IndexError: final += 0.1*A[i][j] try: if (i,j-1) not in walls: if j==0: final += 0.1*A[i][j] else: val = A[i][j-1] final+=0.1*A[i][j-1] else: raise IndexError except IndexError: final += 0.1*A[i][j] return final def move_down(A,i,j,walls): '''Utility function if you move down''' final=0.0 try: if (i-1,j) not in walls: val=A[i-1][j] # ask about this!!! TODO if i==0: final+=0.8*A[i][j] else: final+=0.8*A[i-1][j] else: raise IndexError except IndexError: final+=0.8*A[i][j] try: if (i,j+1) not in walls: val=A[i][j-1] final+=0.1*A[i][j+1] else: raise IndexError except IndexError: final+=0.1*A[i][j] try: if (i,j-1) not in walls: val=A[i][j-1] if j==0: final+=0.1*A[i][j] else: final+=0.1*A[i][j-1] else: raise IndexError except IndexError: final+=0.1*A[i][j] return final def move_right(A,i,j,walls,flag=False): '''Utility function if you move right''' final=0.0 try: if (i,j+1) not in walls: val=A[i][j+1] final+=0.8*A[i][j+1] if flag: print(final) else: raise IndexError except IndexError: final+=0.8*A[i][j] try: if (i+1,j) not in walls: val=A[i+1][j] final+=0.1*A[i+1][j] if flag: print(final) else: raise IndexError except IndexError: final+=0.1*A[i][j] try: if (i-1,j) not in walls: val=A[i-1][j] if i==0: final+=0.1*A[i][j] else: final+=0.1*A[i-1][j] else: raise IndexError except IndexError: final+=0.1*A[i][j] return final def move_left(A,i,j,walls): '''Utility function if you move left''' final=0.0 try: if (i,j-1) not in walls: val=A[i][j-1] if j==0: final+=0.8*A[i][j] else: final+=0.8*A[i][j-1] else: raise IndexError except IndexError: final+=0.8*A[i][j] try: if (i+1,j) not in walls: val=A[i+1][j] final+=0.1*A[i+1][j] else: raise IndexError except IndexError: final+=0.1*A[i][j] try: if (i-1,j) not in walls: val=A[i-1][j] if i==0: final+=0.1*A[i][j] else: final+=0.1*A[i-1][j] else: raise IndexError except IndexError: final+=0.1*A[i][j] return final def VI(A, start_state, end_states, walls, step_reward): '''Value Iteration Algortihm''' # actions = {0:"north", 1:"east", 2:"south", 3:"west"} U = [[0 for i in range(len(A[0]))] for j in range(len(A))] tolerance = 0.01 iter = 0 while 1: #Run Until Convergance iter += 1 new = [[0 for i in range(len(A[0]))] for j in range(len(A))] for i in range(len(A)): for j in range(len(A[i])): # print "& ", if (i,j) in end_states or (i,j) in walls: new[i][j] = A[i][j] # if (i,j) in walls: # print 100, # else: # print "%.3f" % (new[i][j] + 52), else: #Add step reward new[i][j] = step_reward + A[i][j] v1 = move_up(U,i,j,walls) v2 = move_down(U,i,j,walls) v3 = move_right(U,i,j,walls) v4 = move_left(U,i,j,walls) #Pick max of 4 options new[i][j] += max([v1,v2,v3,v4]) # if max([v1,v2,v3,v4]) == v1: # print "%.3f" % (new[i][j] + 42), # elif max([v1,v2,v3,v4]) == v3: # print "%.3f" % (new[i][j] + 32), # elif max([v1,v2,v3,v4]) == v2: # print "%.3f" % (new[i][j] + 22), # elif max([v1,v2,v3,v4]) == v4: # print "%.3f" % (new[i][j] + 12), # print to_stop=True for i in range(len(U)): for j in range(len(U[i])): if abs(U[i][j]-new[i][j]) > 0.01 * abs(U[i][j]): to_stop=False U[i][j]=new[i][j] if to_stop==True: break return U if __name__ == "__main__": '''Input''' first_inp=raw_input() n, m = int(first_inp.split()[0]), int(first_inp.split()[1]) A = [] start_states = [] end_states = {} walls = {} for i in range(n): s = [float(i) for i in raw_input().split()] A.append(s) second_inp=raw_input() E = int(second_inp.split()[0]) W = int(second_inp.split()[1]) for i in range(E): temp = raw_input().split() end_states[int(temp[0]), int(temp[1])] = 1 for i in range(W): temp=raw_input().split() walls[int(temp[0]), int(temp[1])] = 1 temp = raw_input().split() start_state = (int(temp[0]), int(temp[1])) step_reward = float(raw_input()) for i in range(n): walls[i, -1] = 1; walls[i, m] = 1; for i in range(m): walls[-1, i] = 1; walls[n, i] = 1; ans = VI(A, start_state, end_states, walls, step_reward) for i in range(len(ans)): for j in range(len(ans[i])): print "%.3f" % ans[i][j], print
7d60bd6fda2d94da3cebbf66d07b9564591dd089
rajputarun/machine_learning_intern
/keras_bottleneck_multiclass.py
6,828
3.578125
4
''' Using Bottleneck Features for Multi-Class Classification in Keras We use this technique to build powerful (high accuracy without overfitting) Image Classification systems with small amount of training data. The full tutorial to get this code working can be found at the "Codes of Interest" Blog at the following link, http://www.codesofinterest.com/2017/08/bottleneck-features-multi-class-classification-keras.html Please go through the tutorial before attempting to run this code, as it explains how to setup your training data. The code was tested on Python 3.5, with the following library versions, Keras 2.0.6 TensorFlow 1.2.1 OpenCV 3.2.0 This should work with Theano as well, but untested. ''' import numpy as np import pandas as pd from keras.utils import np_utils from keras.preprocessing.image import ImageDataGenerator, img_to_array, load_img from keras.models import Sequential from keras.layers import Dense, Dropout, Activation, Flatten from keras.layers import Conv2D, MaxPooling2D, ZeroPadding2D, GlobalAveragePooling2D from keras import applications from keras import optimizers from keras import regularizers from keras.layers.normalization import BatchNormalization from keras.utils.np_utils import to_categorical import matplotlib.pyplot as plt import math import cv2 # dimensions of our images. img_width, img_height = 224, 224 top_model_weights_path = 'bottleneck_fc_model.h5' train_data_dir = 'data/train' validation_data_dir = 'data/validation' # number of epochs to train top model epochs = 50 # batch size used by flow_from_directory and predict_generator batch_size = 16 ####################################################################### def save_bottlebeck_features(): # build the VGG16 network model = applications.VGG16(include_top=False, weights='imagenet') datagen = ImageDataGenerator(rescale=1. / 255) generator = datagen.flow_from_directory( train_data_dir, target_size=(img_width, img_height), batch_size=batch_size, class_mode=None, shuffle=False) print(len(generator.filenames)) print(generator.class_indices) print(len(generator.class_indices)) nb_train_samples = len(generator.filenames) num_classes = len(generator.class_indices) predict_size_train = int(math.ceil(nb_train_samples / batch_size)) bottleneck_features_train = model.predict_generator( generator, predict_size_train) np.save('bottleneck_features_train.npy', bottleneck_features_train) generator = datagen.flow_from_directory( validation_data_dir, target_size=(img_width, img_height), batch_size=batch_size, class_mode=None, shuffle=False) nb_validation_samples = len(generator.filenames) predict_size_validation = int( math.ceil(nb_validation_samples / batch_size)) bottleneck_features_validation = model.predict_generator( generator, predict_size_validation) np.save('bottleneck_features_validation.npy', bottleneck_features_validation) save_bottlebeck_features() ####################################################################### def train_top_model(): datagen_top = ImageDataGenerator(rescale=1. / 255, rotation_range=40, width_shift_range=0.2, height_shift_range=0.2, shear_range=0.2, zoom_range=0.2, horizontal_flip=True, fill_mode='nearest') generator_top = datagen_top.flow_from_directory( train_data_dir, target_size=(img_width, img_height), batch_size=batch_size, class_mode='categorical', shuffle=False) nb_train_samples = len(generator_top.filenames) num_classes = len(generator_top.class_indices) # save the class indices to use use later in predictions np.save('class_indices.npy', generator_top.class_indices) # load the bottleneck features saved earlier train_data = np.load('bottleneck_features_train.npy') # get the class lebels for the training data, in the original order train_labels = generator_top.classes # https://github.com/fchollet/keras/issues/3467 # convert the training labels to categorical vectors train_labels = to_categorical(train_labels, num_classes=num_classes) generator_top = datagen_top.flow_from_directory( validation_data_dir, target_size=(img_width, img_height), batch_size=batch_size, class_mode=None, shuffle=False) nb_validation_samples = len(generator_top.filenames) validation_data = np.load('bottleneck_features_validation.npy') validation_labels = generator_top.classes validation_labels = to_categorical( validation_labels, num_classes=num_classes) model = Sequential() model.add(Flatten(input_shape=train_data.shape[1:])) model.add(Dense(512, activation='relu')) model.add(Dropout(0.3)) model.add(Dense(num_classes, activation='softmax')) model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy']) # history = model.fit(train_data, train_labels, # epochs=epochs, # batch_size=batch_size, # validation_data=(validation_data, validation_labels)) history = model.fit_generator(datagen_top.flow(train_data, train_labels, batch_size=batch_size), steps_per_epoch=int(np.ceil(train_data.shape[0] / float(batch_size))), epochs=epochs, validation_data=(validation_data, validation_labels), workers=4) model.save_weights(top_model_weights_path) (eval_loss, eval_accuracy) = model.evaluate( validation_data, validation_labels, batch_size=batch_size, verbose=1) print("[INFO] accuracy: {:.2f}%".format(eval_accuracy * 100)) print("[INFO] Loss: {}".format(eval_loss)) plt.figure(1) # summarize history for accuracy plt.subplot(211) plt.plot(history.history['acc']) plt.plot(history.history['val_acc']) plt.title('model accuracy') plt.ylabel('accuracy') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper left') # summarize history for loss plt.subplot(212) plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('model loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper left') plt.show() train_top_model() #######################################################################
b772d28d9f6ec808e4fc417b1487ced30b19b1ec
NguyenVuNhan/cpp
/solution/Week5/matrix.py
2,927
3.59375
4
class Matrix(): def __init__(self): self.setPoint = [] self.setPointLen = 0 pass def refresh(self): self.setPoint = [] self.setPointLen= 0 def addSetPoint(self, x, y): self.setPoint.append([x,y]) self.setPointLen += 1 def createMatrix(self): m = [] for i in range(self.setPointLen): r = [] for j in range(self.setPointLen): r.append(self.setPoint[i][0]**j) m.append(r) return m def inverseMatrix(self, matrix): def matrixMinor(matrix, i, j): return [row[:j] + row[j+1:] for row in (matrix[:i]+matrix[i+1:])] def getDeterminant(matrix): if ( len(matrix) == 2 ): return matrix[0][0]*matrix[1][1] - matrix[0][1]*matrix[1][0] determinant = 0 for i in range(len(matrix)): determinant += ((-1)**i)*matrix[0][i]*getDeterminant(matrixMinor(matrix, 0, i)) return determinant determinant = getDeterminant(matrix) inverseMatrix = [] for i in range(len(matrix)): row = [] for j in range(len(matrix)): minor = matrixMinor(matrix, i, j) row.append(((-1)**(i+j)) * getDeterminant(minor)) inverseMatrix.append(row) inverseMatrix = list(map(list, zip(*inverseMatrix))) # Transpose matrix for i in range(len(inverseMatrix)): for j in range(len(inverseMatrix)): inverseMatrix[i][j] /= determinant return inverseMatrix def matrixMul(self, matrixA, matrixB): zip_b = list(zip(*matrixB)) return [[sum(ele_a*ele_b for ele_a, ele_b in zip((row_a if type(row_a) == list else [row_a]), col_b)) for col_b in zip_b] for row_a in matrixA] def getVector(self, method="Gaussian"): if (method == "Gaussian"): m = self.createMatrix() for i in range(len(m)): m[i].append(self.setPoint[i][1]) # Gaussian for j in range(len(m)): for i in range(len(m)): if ( i != j ): try: quotion = m[i][j] / m[j][j] except: print(m[i][j], m[j][j]) for k in range(len(m)+1): m[i][k] -= quotion*m[j][k] try: vector = [ m[i][len(m)]/m[i][i] for i in range(len(m)) ] return vector except ZeroDivisionError: return [0] elif (method == "Normal"): inverseMatrix = self.inverseMatrix(self.createMatrix()) y = [ [point[1]] for point in self.setPoint ] return [m[0] for m in self.matrixMul(inverseMatrix, y)] return []
6f8020d3159ccb6190cf4f57d7c85cadd34e4dcd
gauravssnl/python3-network-programming
/dns_mx.py
1,975
3.84375
4
#!/usr/bin/env python3 # Looking up a mail domain - the part of an email address after the `@` import dns.resolver def resolve_hostname(hostname, indent=''): """ print an A or AAAA record for hostname; follow CNAME if necessary """ indent = indent + ' ' answer = dns.resolver.query(hostname, 'A') if answer.rrset is not None: for record in answer: print(indent, hostname, 'has A address', record.address) return answer = dns.resolver.query(hostname, 'AAAA') if answer.rrset is not None: for record in answer: print(indent, hostname, 'has AAAA address', record.address) return answer = dns.resolver.query(hostname, 'CNAME') if answer.rrset is not None: record = answer[0] cname = record.address print(indent, hostname, 'is an alias for', cname) resolve_hostname(cname, indent) return print(indent, 'ERROR: no A, AAAA, or CNAME records for', hostname) def resolve_email_domain(domain): """ For an email address `name@domain` , find its mail server IP address """ try: answer = dns.resolver.query(domain, 'MX') except dns.resolver.NXDOMAIN: print('Error: No such domain', domain) return if answer.rrset is not None: records = sorted(answer, key=lambda record: record.preference) for record in records: name = record.exchange.to_text(omit_final_dot=True) print('Priority', record.preference) resolve_hostname(name) else: print(domain, 'has no explicit MX records') print('Attempting to resolve domain as an a A, AAAA, or CNAME') resolve_hostname(domain) if __name__ == '__main__': import argparse parser = argparse.ArgumentParser(description='Find mailserver IP address') parser.add_argument('domain', help='domain that you want to send mail to') resolve_email_domain(parser.parse_args().domain)
dcbb89d1234dbba6acc1d3439df4dea019e50235
josepdecid/MAI-IML
/labs/w2/algorithms/pca.py
9,763
3.765625
4
import logging from typing import Union, Tuple import matplotlib.pyplot as plt import numpy as np from utils.plotting import mat_print class PCA: """Principal component analysis (PCA) Algorithm to transform multi-dimensional observations into a set of values of linearly uncorrelated variables called principal components. The first principal component has the largest possible variance (that is, accounts for as much of the variability in the data as possible), and each succeeding component in turn has the highest variance possible under the constraint that it is orthogonal to the preceding components. The resulting vectors (each being a linear combination of the variables and containing n observations) are an uncorrelated orthogonal basis set. PCA is sensitive to the relative scaling of the original variables. Parameters ---------- n_components : int, float, None Number of components to keep. - If parameter is an int `n_components` >= 1, it is the number of selected components. - If parameter is a float 0 < `n_components` < 1, it selects the number of components that explain at least a variance equivalent to this value. - If `n_components` is None, all components are kept: n_components == n_features. name: str Identifiable name of the dataset used for plotting and printing purposes. solver: str Solving method for extracting eigenvalues. It may take three different values: - `eig`: Uses `np.linalg.eig` to compute the eigenvalues and right eigenvectors of the covariance matrix. - `hermitan`: Uses `np.linalg.eigh` which assumes the matrix is Hermitan (i.e. symmetric) By default takes only the lower triangular part of the matrix and assumes that the upper triangular part is defined by the symmetry of the matrix. This one is faster to compute. - `svd`: Uses `np.linalg.svd` which is exactly the same for Hermitan matrices. However it's faster and numerically more stable than calculate the eigenvalues and eigenvectors as it uses a Divide and Conquer approaches instead of a plain QR factorization, which are less stable. Attributes ---------- components_ : np.array, shape (`n_components`, `d_features`) Principal axes in feature space of directions with maximum variance in the data. The components are sorted from largest to smallest associated eigenvalue, which is equivalent to sort descending by explained variance. cov_mat_ : np.array, shape (`d_features`, `d_features`) Covariance matrix of the training data. explained_variance_ : np.array The amount of variance explained by each of the selected `n_components`. Equivalent to n_components largest eigenvalues of `cov_mat`. explained_variance_ratio_ : np.array, shape (`n_components`,) Percentage of the amount of variance explained by each of the selected `n_components`. If all the components are stored, this sum of all ratios is equal to 1.0. eigen_values_ : np.array, shape(`n_components`,) Singular values associated to each of the selected `n_components` (eigenvectors). mean_: np.array, shape(`d_features`,) Mean vector for all features, estimated empirically from the training data. n_components_ : int Number of components selected to use: - Equivalent to parameter `n_components` if it is an int. - Estimated from the input data if it is a float. - Equivalent to d_features if not specified. """ def __init__(self, n_components: Union[int, float, None], name: str, solver='eig'): if solver not in ['eig', 'hermitan', 'svd']: raise ValueError('Solver must be "eig", "hermitan", "svd"') # Parameters self._n_components = n_components self._name = name self._solver = solver # Attributes self.components_: np.ndarray = None self.cov_mat_: np.ndarray = None self.explained_variance_ = None self.explained_variance_ratio_ = None self.eigen_values_ = None self.mean_ = None self.n_components_ = None def fit(self, X: np.ndarray) -> 'PCA': """Fit the model with X. Parameters ---------- X : np.ndarray, shape (n_samples, d_features) Training data where: - n_samples is the number of rows (samples). - d_features is the number of columns (features). Returns ------- self : PCA object Returns the instance itself. """ self.mean_ = np.mean(X, axis=0) phi_mat = (X - self.mean_).T self.cov_mat_ = np.cov(phi_mat) if self._solver == 'eig': # Using Eigenvalues and Eigenvectors eig_values, eig_vectors = np.linalg.eig(self.cov_mat_) eig_values, eig_vectors = PCA.__sort_eigen(eig_values.real, eig_vectors.real) elif self._solver == 'hermitan': # Using Eigenvalues and Eigenvectors assuming Hermitan matrix eig_values, eig_vectors = np.linalg.eigh(self.cov_mat_) eig_values, eig_vectors = PCA.__sort_eigen(eig_values.real, eig_vectors.real) else: # TODO: Check # Using Singular Value Decomposition _, eig_values, eig_vectors = np.linalg.svd(self.cov_mat_, compute_uv=True) # PCA.__display_eig(singular_values, singular_vectors) # self.explained_variance_ = (eig_values ** 2) / (X.shape[0] - 1) self.explained_variance_ = eig_values self.explained_variance_ratio_ = self.explained_variance_ / self.explained_variance_.sum() if type(self._n_components) == int: k = self._n_components elif type(self._n_components) == float: k = np.searchsorted(self.explained_variance_ratio_.cumsum(), self._n_components) + 1 else: k = X.shape[1] self.explained_variance_ = self.explained_variance_[:k] self.explained_variance_ratio_ = self.explained_variance_ratio_[:k] self.components_ = eig_vectors[:k, :] self.eigen_values_ = eig_values[:k] self.n_components_ = k logging.info(f'Original Matrix:\n{mat_print(X)}') logging.info(f'Covariance Matrix:\n{mat_print(self.cov_mat_)}') logging.info(f'Eigenvalues:\n{mat_print(self.eigen_values_)}') logging.info(f'Eigenvectors:\n{mat_print(self.components_)}') logging.info(f'Explained Variance:\n{mat_print(self.explained_variance_ratio_)}') logging.info(f'Cumulative Explained Variance:\n{mat_print(np.cumsum(self.explained_variance_ratio_))}') return self def transform(self, X: np.ndarray) -> np.ndarray: """Apply the dimensionality reduction on X. Parameters ---------- X : np.ndarray, shape (n_samples, d_features) Test data where: - n_samples is the number of rows (samples). - d_features is the number of columns (features). Returns ------- X_transformed : np.ndarray, shape (n_samples, self.n_components) """ if self.components_ is None: raise Exception('Fit the model first before running a transformation') X_transformed = (self.components_ @ (X - self.mean_).T).T logging.info(f'Transformed X:\n{mat_print(X_transformed)}') return X_transformed def fit_transform(self, X: np.ndarray) -> np.ndarray: """Fit the model with X and then apply the dimensionality reduction on X. Parameters ---------- X : np.ndarray, shape (n_samples, d_features) Training data where: - n_samples is the number of rows (samples). - d_features is the number of columns (features). Returns ------- X_transformed : np.ndarray, shape (n_samples, self.n_components) """ self.fit(X) return self.transform(X) def inverse_transform(self, X_transformed: np.ndarray) -> np.ndarray: """Reconstruct X_original from X which would be its transformation. Parameters ---------- X_transformed : np.ndarray, shape (`n_shape`, `n_components`) Transformed X from original data obtained with `transform` or `fit_transform`. Returns ------- X_original : np.ndarray, shape (n_samples, d_features) """ if self.components_ is None: raise Exception('Fit the model first before running a transformation') return X_transformed @ self.components_ + self.mean_ def get_cov_matrix(self, dataset_name: str) -> Tuple[plt.Figure, plt.Axes]: """Create covariance matrix Matplotlib figure. Parameters ---------- dataset_name : str Dataset name used in the figure title. Returns ------- Cov_figure : plt.Axes """ f, ax = plt.subplots(1, 1) im = ax.matshow(self.cov_mat_, cmap=plt.get_cmap('coolwarm')) ax.set_title(f'Covariance matrix for {dataset_name} dataset', y=1.08, fontsize=18) plt.colorbar(im, ax=ax) return f, im @staticmethod def __display_eig(values, vectors): for i in range(len(values)): print(f'{i}) {values[i]}: {vectors[i, :]}') @staticmethod def __sort_eigen(values, vectors): eig = list(zip(values, vectors.T)) eig.sort(key=lambda x: x[0], reverse=True) values, vectors = zip(*eig) values, vectors = np.array(values), np.array(vectors) return values, vectors
3b1132a97a381abd155d82d061d7cff1ef065133
madfrogsec/id0-rsa
/caesar.py
632
3.53125
4
#!/usr/bin/env python2.7 # coding: utf-8 import string cipher = "ZNKIGKYGXIOVNKXOYGXKGRREURJIOVNKXCNOINOYXKGRRECKGQOSTUZYAXKNUCURJHKIG\ AYKOSZUURGFEZURUUQGZZNKCOQOVGMKGZZNKSUSKTZHAZOLOMAXKOZYMUZZUHKGZRKGYZROQKLOLZEE\ KGXYURJUXCNGZKBKXBGPJADLIVBAYKZNUYKRGYZZKTINGXGIZKXYGYZNKYURAZOUT" charsetlen = len(string.uppercase) ascii_offset = 65 for i in xrange(charsetlen): print '[+] Key : {}'.format(chr(i + ascii_offset)) print ''.join(map(lambda x:chr(((ord(x)-ascii_offset+i)%charsetlen)+ascii_offset),cipher)) print '\n' # THE CAESAR CIPHER IS A REALLY OLD CIPHER WHICH IS REALLY WEAK IM NOT SURE HOW # OLD BECAUSE IM TOO LAZY TO LOOK AT THE WIKI PAGE AT THE MOMENT BUT I FIGURE ITS # GOT TO BE AT LEAST LIKE FIFTY YEARS OLD OR WHATEVER VAJDUXFCPV USE THOSE LAST # TEN CHARACTERS AS THE SOLUTION
87e0c4f5b7335390da9274aedad193cbdb99d5ce
Ghelpagunsan/classes
/lists.py
2,473
4.15625
4
class manipulate: def __init__(self, cars): self.cars = cars def add(self): self.cars.append("Ford") self.cars.sort() return self.cars def remove(self): print("Before removing" + str(self.cars)) self.cars.remove("Honda") return str("After removing" + str(self.cars)) def update(self, car): car.update(["Pajero", "Mitzubishi"]) sorted(car) return car class show: def __init__(self, num): self.num = num def getvalue(self): return str(self.num.index(4)) def popval(self): self.num.pop() return self.num def reversing(self): self.num.reverse() return self.num def counting(self): i = 0 for j in self.num: i+=1 return i class change: def __init__(self,year): self.year = year def deletingval(self): del self.year[3] return self.year def looping(self): for x in self.year: print(x) def check(self): if 2001 in self.year: return str("Found!") class compare: def __init__(self, a, b): self.a = a self.b = b def length(self, n): return str("The length of the list is " + str(len(n))) def multipleset(self, n): return str(n) y = n[0] return str(y) x = y[0] return str(x) z = x[1] return str(z) def intersections(self): c = self.a.intersection_update(self.b) return str(c) def differences(self): c = self.b.difference(self.a) return str(c) def symmetric(self): c = self.a.symmetric_difference(self.b) sorted(c) return str(c) def unions(self, a, b, c, d): e = a.union(b, c, d) return str(e) def extends(self, x, y): y.extend(x) return str(y) class order: def __init__(self, a): self.a = a def whileloop(self): i = 0 while i<5: i+=2 print(i) def sorting(self): self.a.append(7) self.a.sort() return str(self.a) def forloop(self): i = 0 for i in self.a: print(i) i+=1 # print(add()) # print(remove()) # print(update()) # print(getvalue([1, 2, 3, 4 ,5])) # print(popval(['a', 'b', 'c', 'd'])) # print(reversing([2, 4, 6, 8])) # print(counting([1, 2, 3, 4, 5, 6, 7, 8])) # print(deletingval(["Davao", "Cebu", "Manila", "Butuan"])) # looping() # print(check()) # print(length([1, 2, 3, 4, 5, 6])) # print(multipleset()) # print(intersections({"a", "b", "c", "d"}, {"a", "d", "f"})) # print(differences({"a", "b", "c", "d"}, {"a", "d", "f"})) # print(symmetric({"a", "b", "c", "d"}, {"a", "d", "f"})) # print(unions()) # print(extends()) # whileloop() # print(sorting([8, 4, 5, 6])) # forloop()
2f12b3b8b93d24222a5856b78c6b3c335139c8ab
iKanae/ML_algorithm
/24.py
1,444
3.765625
4
#-*- coding: utf-8 -*- import random #输入目标数字 def FirstInput(): num=[] while len(num)<4: temp=raw_input("Enter the number:") if temp.isdigit(): if int(temp)>=14 or int(temp)<=0: print("This number is out of range!") else: num.append(int(temp)) else: print("It is not a valid number!") return num #计算24点 def Count24(num): di={"1":"+","2":"-","3":"*","4":"/"} value=0 for i in range(4): num[i]=str(float(num[i])) while value<>24: list=num[:] result = [] while len(list)>1: index=int(random.choice(range(0,len(list)))) a=list[index] list.pop(index) if len(list)==1: index=0 else: index = int(random.choice(range(0, len(list)))) b=list[index] list.pop(index) #计算值 oc=int(random.choice(range(1,5))) eq = str(a)+di[str(oc)]+str(b) try: value=eval(eq) except ZeroDivisionError: oc = int(random.choice(range(1, 4))) eq = str(a) + di[str(oc)] + str(b) value=eval(eq) #存公式 list.append(str(value)) result.append([eq]) return value,result print Count24(FirstInput()) #一个bad case 7 7 2 10
849f89ad2affd58959e659ecc9e04ade09a538bd
Vitalius1/Python_OOP_Assignments
/math_dojo.py
2,046
3.5625
4
# PART 1 Support only for integerspy class MathDojo(object): def __init__(self): self.result = 0 def add(self, *num_a): self.add_result = 0 for value in num_a: self.add_result += value self.result += self.add_result return self def subtract(self, *num_s): self.sub_result = 0 for value in num_s: self.sub_result += value self.result -= self.sub_result return self md = MathDojo().add(2).add(2, 5).subtract(3, 2).result print md # PART 2 Support for lists and integers class MathDojo2(object): def __init__(self): self.result = 0 def add(self, *num_a): for value in num_a: if type(value) == list: for el in value: self.result += el elif type(value) == int: self.result += value return self def subtract(self, *num_s): for value in num_s: if type(value) == list: for el in value: self.result += el elif type(value) == int: self.result -= value return self md2 = MathDojo2().add([1],3,4).add([3, 5, 7, 8], [2, 4.3, 1.25]).subtract(2, [2,3], [1.1, 2.3]).result print md2 # PART 3 Support for lists, tuples and integers class MathDojo3(object): def __init__(self): self.result = 0 def add(self, *num_a): for value in num_a: if isinstance(value, (list, tuple)): for el in value: self.result += el elif isinstance(value, int): self.result += value return self def subtract(self, *num_s): for value in num_s: if isinstance(value, (list, tuple)): for el in value: self.result -= el elif isinstance(value, int): self.result -= value return self md3 = MathDojo3().add((1,2,3,4),[5,8,12,4],14).subtract((2,3),[6,9],7).result print md3
8411166d3b4014fc9e41599512aa1b964e53cc0b
Vitalius1/Python_OOP_Assignments
/Hospital/register.py
1,148
3.734375
4
from hospital import Hospital from patient import Patient # creating 6 instances of Patient class p1 = Patient("Vitalie", "No allergies") p2 = Patient("Diana", "No allergies") p3 = Patient("Galina", "Yes") p4 = Patient("Nicolae", "Yes") p5 = Patient("Ion", "No allergies") p6 = Patient("Olivia", "Yes") # Create the hospital giving it a name and a capacity hospital1 = Hospital("Braga", 5) # Admiting the patients into the hospital hospital1.admit(p1) hospital1.admit(p2) hospital1.admit(p3) hospital1.admit(p4) hospital1.admit(p5) hospital1.admit(p6) # this patient will receive a message that hospital is full (capacity = 5) and will not be admited to it. print # Discharge a patient by his name and setting it's bed attribute to None, but he still keeps his ID in case he returns. hospital1.discharge("Galina") print # When the patient is discharged he gives the bed back to be reused by new patients. hospital1.discharge("Nicolae") print hospital1.admit(p3) # Testing the admition of 2 previous patients in case they come back they still have the same ID hospital1.admit(p4) # but reusing beds left by other users
18bad60ca2d5f57a9864b9885cdea01fca19e3a3
DangerousCode/DAM-2-Definitivo
/Python/Funciones/Ejercicio1.py
459
3.9375
4
#-*-coding:utf-8-*- __author__ = 'AlumnoT' from math import sqrt '''Crea una funcin que nos haga la raz cuadrada de un nmero que habremos elevado antes al cuadrado. Lo que si debemos tener claro y ese es el objetivo del ejercicio es que debemos importar directamente la funcin que nos haga la raz cuadrada''' def raiz(num): return sqrt(num) num=int(raw_input("Introduce el numero: ")); num=num**2 print "El numero introducido es: ",raiz(num)
265049dd5c7273612076608f805ee6f00e3f2430
DangerousCode/DAM-2-Definitivo
/Python/Funciones de Alto orden/Ejemplo4.py
1,256
4.3125
4
__author__ = 'AlumnoT' '''Funcion dada una lista de numeros y un numero cota superior, queremos devolver aquellos elementos menores a dicha cota''' lista=list(range(-5,5)) '''1)Modificar la sintaxis anterior para que solo nos muestre los numeros negativos''' print filter(lambda x:x<0,lista) '''2)Crear funcion a la que le vamos a pasar una lista de los valores 0,1,2,3,4 y esa funcion tiene que devolvernos una lista formada por el cuadrado del primer valor con el cubo del primer valor (con todos los valores)''' print map(lambda x:[x*x,x*x*x],[0,1,2,3,4]) '''3)Generar dos listas una con valores numericos del 0 al 5 y otra con tres cadenas cuando ejecutemos la funcion queremos que nnos muestre la media de la lista que contiene los numeros y que las tres cadenas de la segunda lista aparezcan como una sola frase''' lista=list(range(0,6)) listacad=["hola","que","tal"] print (reduce(lambda x,z:x+z,lista))/len(lista) print reduce(lambda a,b:a+" "+b,listacad) '''4)Se nos va a facilitar una lista y una tupla con numeros debemos realizar una funcion que sume cada numero de la lista con el correspondiente numero de su misma posicion en la tupla todo ello usando map,reduce,filter, lambda''' lis=[1,2,3] tup=(3,2,1) print map(lambda x,y:x+y,lis,tup)
9120d38a16996a33341e5dc748b331694a03ebee
DangerousCode/DAM-2-Definitivo
/Python/Recursividad/Invertir.py
189
3.609375
4
__author__ = 'AlumnoT' def invertir(l,m): if l==[]: return m else: m.append(l[len(l)-1]) return invertir(l[:len(l)-1],m) #main m=[] print invertir([1,2,3],m)
dfdd7c21112d4354fbbcce108399dcaf2374d537
ytreeshan/BeginnerPython
/IMAGE.py
804
3.9375
4
#Name: Treeshan Yeadram #Date: Sept -24 -2018 #This program loads an image, displays it, and then creates, displays, # and saves a new image that has only the red channel displayed. #Import the packages for images and arrays: import matplotlib.pyplot as plt import numpy as np i =input("Enter the name of an input file: ") out = input("Enter the name of an output file") img = plt.imread(i) #Read in image from csBridge.png #plt.im show(img) #Load image into pyplot img2 = img.copy() #make a copy of our image img2[:,:,1] = 0 #Set the green channel to 0 img2[:,:,0] = 0 #Set the blue channel to 0 plt.imshow(img2) #Load our new image into pyplot plt.show() #Show the image (waits until closed to continue) plt.imsave(out, img2)
6de79716bba3f70746d3b0383cec3cf5d318670e
ytreeshan/BeginnerPython
/Flower.py
260
3.921875
4
#Name: Treeshan Yeadram #Date: August 27, 2018 #This program draws a flower import turtle tia = turtle.Turtle() for i in range(36): tia.forward(100) tia.left(145) tia.forward(10) tia.right(90) tia.forward(10) tia.left(135) tia.forward(100)
6ba11745ac18a6684b494920a5c04cea1bdb6ec7
ProTrickstar/Python-Classes
/main.py
903
3.8125
4
from typing import Collection class Car(object): def __init__(self, name, color, speed, weight, model): self.name = name self.color = color self.speed = speed self.weight = weight self.model = model def start(self): print("Started") def stop(self): print("Stopped") def changeGear(self,gear_type): print("Gear Changed") "Gear Related Functionality Is Here" def speed(self): print("Speed Has Been Boosted By 100 KM/h") "accelerator functionality is here" # Define some students john = Car("Nexon", "black", "120 KM/h", 520, "XZA+") jane = Car("BMW", "white","120 KM/h", 580, "Q3") audi = Car("Audi", "Black","120 KM/h", 220, "Q10" ) audi.color # Now we can get to the grades easily print(john.start()) print(jane.start()) print(audi.color) print(audi.model)
171561d4d9db4d191b834ba2a1ab1ddba5bd102a
Souvikns/NPTL
/Assignment/week2.py
2,786
4.0625
4
# to check whether a number can be expressed as the sum of three squares import math def isSquare(n: int): root = math.sqrt(n) if int(root + 0.5) ** 2 == n: return True else: return False def threesquares(n: int): for a in range(n): for b in range(n): if n == pow(4, a) * (4 * b + 7): return False return True # ============================================================================================= # Write a function repfree(s) that takes as input a string s and checks whether any character appears more than once. # The function should return True if there are no repetitions and False otherwise. def repfree(s: str): check = [] # we make a empty list for i in s: if i in check: # we check that if that element already exists in the list if it exists then it return false return False else: check.append(i) # if the elemement is not present then we insert into the list return True # A list of numbers is said to be a hill if it consists of an ascending sequence followed by a descending sequence, # where each of the sequences is of length at least two. Similarly, a list of numbers is said to be a valley hill if # it consists of an descending sequence followed by an ascending sequence. You can assume that consecutive numbers in # the input sequence are always different from each other. # # Write a Python function hillvalley(l) that takes a list l of integers and returns True # if it is a hill or a valley, and False otherwise. # ============================================================================================= def hillvalley(l: list): pos = -1 if l[0] < l[1]: for i in range(len(l) - 1): if l[i] > l[i + 1]: pos = i break if pos == -1: return False for i in range(pos, len(l) - 1): if l[i] < l[i + 1]: return False return True elif l[0] > l[1]: for i in range(len(l) - 1): if l[i] < l[i + 1]: pos = i break if pos == -1: return False for i in range(pos, len(l) - 1): if l[i] > l[i + 1]: return False return True return False # ============================================================================================= if __name__ == '__main__': # print(hillvalley([1, 2, 3, 5, 4])) # print(hillvalley([1, 2, 3, 4, 5])) # print(hillvalley([1, 2, 3, 4, 5, 3, 2, 4, 5, 3, 2, 1])) # print(repfree(input("Enter a string: "))) # print(threesquares(int(input("Enter a number: ")))) # print(threesquares(int(input("Enter a number: ")))) pass
f49c4a5e794cb8b565e74cc65cb7abcd1319cb81
LenouarMiloud/data-preprocessing-miloudLenouar
/data_preprocessing_assignement.py
1,545
3.921875
4
""" Do not delete this section, Please Commit your changes after implementing the necessary code. - The data file called Social_Network_Ads.csv. - Your Job is to preprocess this data because we gonna use it later one in the course. The Features of this dataset are: - UserID: Which represent id of user in the database. - Gender: Can be male or female. - EstimatedSalary: The salary of the user. - Purchased: An integer number {1 if the user purshased something, 0 otherwise} The target variable for this data is the purshased status. Happy coding.""" # Step 0: import the necessary libraries: pandas, matplotlib.pyplot, and numpy. import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split # Step 1: load your dataset using pandas data = pd.read_csv('Social_Network_Ads.csv') x = data.drop(['User ID', 'Purchased'], axis = 1) y = data['Purchased'] # Step 2: Handle Missing data if they exist. X.isnull().sum() # Step 3: Encode the categorical variables. df = pd.get_dummies(data,prefix="",columns=['Gender']) encoder = LabelEncoder() x['Gender'] = encoder.fit_transform(X['Gender']) # Step 4: Do Feature Scaling if necessary. scaler = StandardScaler() x = scaler.fit_transform(X) # Final Step: Train/Test Splitting. x_train, x_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 19)
b61bd2fb18af6e022e1fcf22645d6d871e22c93b
Erimus-Koo/utility
/coudan_order_for_min_cost.py
2,499
3.671875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'Erimus' # 商品凑单算法 # 计算有限个商品,达到指定价格的所有排列组合。 import logging as log # ═══════════════════════════════════════════════ class Order(): def __init__(self, itemList, targetPrice): self.r = {} self.itemList = itemList # 商品字典{price:nume} self.targetPrice = targetPrice # 凑单目标价格 def orderNum(self, itemList, prevOrder='', prevPrice=0): log.debug(f'>> prevOrder: {prevOrder} | prevPrice: {prevPrice}') for num in range(999): price, name = itemList[0] thisOrder = prevOrder + (f' + {num} {name}' if num else '') thisPrice = prevPrice + price * num log.debug(f'{thisOrder} = {prevPrice} + {price} * {num}') # 如果当前价格超了 就不再增加数量 if thisPrice >= self.targetPrice: self.r[thisOrder.strip('+ ')] = thisPrice [log.debug(f'>>> {k} = {v}') for k, v in self.r.items()] return # 如果价格没超 就往下一位 if len(itemList) > 1: self.orderNum(itemList[1:], prevOrder=thisOrder, prevPrice=thisPrice) def calc(self): # 格式化商品数据 itemDict = {} for name, price in self.itemList.items(): itemDict.setdefault(price, '') itemDict[price] += f'/{name}' itemDict[price] = itemDict[price].lstrip('/') itemList = sorted(itemDict.items(), key=lambda x: x[1]) print('\nITEMLIST\n========') [print(f'{price:8.2f} | {name}') for price, name in itemList] print(f'\nTraget Price: {targetPrice:.2f}') self.orderNum(itemList) # 按总价升序 r = sorted(self.r.items(), key=lambda d: d[1]) print('\nRESULT\n======') [print(f'{total:>8.2f} | {order}') for order, total in r] # ═══════════════════════════════════════════════ if __name__ == '__main__': # log.basicConfig(level=log.DEBUG, format=('pid:%(process)d | %(message)s')) itemList = {'短裤': 59, 'T1': 44, 'T2': 39} targetPrice = 300 # 目标价格(满减/包邮/等) minOrder = Order(itemList, targetPrice) minOrder.calc()
9314d79806a7272dfddf71b958b2b1088cf57410
mahdibny/Python_ML
/ch06_Write_Read.py
2,250
3.6875
4
# -*- coding: utf-8 -*- """ Created on Thu Dec 29 02:25:30 2016 Chapter 6: Data Loading, Storage, and File Formats inputs and outputs with panda objects @author: Mahdi """ """ Reading and Writing Data in Text Format pg 155 Parsing Function in pandas read_csv Load delimited data from a file, URL, or file-like object. Use comma as default delimiter read_table Load delimited data from a file, URL, or file-like object. Use tab ('\t') as default delimiter read_fwf Read data in fixed-width column format (that is, no delimiters) read_clipboard Version of read_table that reads data from the clipboard. Useful for converting tables from web pages """ from pandas import Series, DataFrame import pandas as pd df=pd.read_csv('../pydata-book/ch06/ex1.csv') #or use read_table and use delimeter pd.read_table('../pydata-book/ch06/ex1.csv',sep=',') #consider a file you can create column names df1=pd.read_csv('../pydata-book/ch06/ex2.csv',header=None) df2=pd.read_csv('../pydata-book/ch06/ex2.csv',names=['a','b','c','d','message']) # above line we ccreate and choose specific column names names=['a','b','c','d','message'] df3=pd.read_csv('../pydata-book/ch06/ex2.csv',names=names,index_col='message') #format data so messages become columns #Hierachical indexing parse=pd.read_csv('../pydata-book/ch06/csv_mindex.csv',index_col=['key1','key2']) print(parse) #whitespace delimiter result=pd.read_table('../pydata-book/ch06/ex3.txt',sep='\s+') print(result) #skip rows df4=pd.read_csv('../pydata-book/ch06/ex4.csv',skiprows=[0,2,3]) print(df4) #handling missing data result_1=pd.read_csv('../pydata-book/ch06/ex5.csv') print(result_1) #do things that we talk about in pandas ''' Table 6.2 pg 160 ''' """ Reading Text Files in Pieces """ results_2=pd.read_csv('../pydata-book/ch06/ex6.csv') print(results_2) #read out a small numbers of rows results_3=pd.read_csv('../pydata-book/ch06/ex6.csv',nrows=5) print(results_3) #to read in pieces specify a chunksize as a number of rows chunker=pd.read_csv('../pydata-book/ch06/ex6.csv',chunksize=1000) #text parser object tot=Series([]) for pieces in chunker: tot=tot.add(pieces['key'].value_counts(),fill_value=0) tot=tot.order(ascending=False) """ Writing Data Out to Text Format """
1b5ce70200e871bc8c00df5b011d72410c73981a
abhishek98as/30-Day-Python-DSA-Challenge
/oops-Code/oops2.py
317
3.84375
4
class Laptop: def __init__(self,brand,model_name,price): #instance veriable self.brand=brand self.model_name=model_name self.price=price self.laptop_name= brand + ' '+model_name laptop1=Laptop('hp','ld758',60000) print(laptop1.brand) print(laptop1.laptop_name)
17d9da227eaebcddf62a7c7fdc105b4a630c2d37
abhishek98as/30-Day-Python-DSA-Challenge
/Tkinter/files1.py
112
4.0625
4
lst=[] for i in range(3): name=input("enter name:") lst.append(name) for i in lst: print(i)
4f8ec851f83e7149a418a6b51d1f6a5db39bc7dd
abhishek98as/30-Day-Python-DSA-Challenge
/list inbuilt 2.py
194
4.0625
4
a=[] for i in range(10): x=input("enter item to add in the list:") a.append(x) x=input("enter the value whose frequency you want") f=a.count(x) print("frequency of ",x,"is=",f)
d33d729641934f15a3890017dd8b1ce577a49f83
abhishek98as/30-Day-Python-DSA-Challenge
/n start print.py
230
3.8125
4
n=int(input("enter the rows")) i=1 while(n>0): b=1 while(b<i): print(" ",end="") b=b+1 j=1 while(j<=(n*2)-1): print("*",end="") j=j+1 print() n=n-1 i=i+1
56df3b34dc4446dcbdd480e74851d75cfae53cae
abhishek98as/30-Day-Python-DSA-Challenge
/reverse string.py
179
4.375
4
#program to find reverse of a string # a=input("enter the string") # print(a[-1::-1]) a=input("enter the string") for i in rnage((len(a)-1),-1,-1): print(a[i],end='')
3d86264c9fe1870958e35659a0fcc8ebd9d50fb7
abhishek98as/30-Day-Python-DSA-Challenge
/square.py
108
3.765625
4
n=int(input("enter the no.")) i=1 sum=0 while(i<=n): sum=sum+(i*i) i=i+1 print("sum=",sum)
7b58be538dd3c1812c10b375b5ed392e7c46c8fc
abhishek98as/30-Day-Python-DSA-Challenge
/marks of subject.py
456
3.9375
4
a=int(input("enter the 1st marks")) b=int(input("enter the 2nd marks")) c=int(input("enter the 3rd marks")) d=int(input("enter the 4rth marks")) e=int(input("enter the 5th marks")) total= a+b+c+d+e percentage=(total/500)*100 print("total marks",total,"total percentage",percentage) if percentage>=80: print("Grade A") elif percentage>=60: print("grade B") elif percentage>=40: print("grade C") else: print("your Grade D")
3dfce3bc28489d24728b25c6f1eeb76d76157952
rscsam/Evolve
/spawner.py
9,546
4
4
"""This module defines a series of spawners capable of spawning occupants into their world""" from creature import * from plant import * class Spawner: """A superclass that defines a spawner capable of keeping track of its own occupants and deciding when to spawn a new one in the world it is created in""" def __init__(self, timer, height, width, x, y): """Initialization logic Args: timer: the time in update cycles between each attempted spawn height: the height of the spawner width: the width of the spawner x: the x-value of the spawner in its world y: the y-value of the spawner in its world""" self.__timer = 100 self.__current_time = 0 self.__height = 0 self.__width = 0 self.__x = 0 self.__y = 0 self.spawning = False self.__spawn_x = 0 self.__spawn_y = 0 self.__special_id = 0 self.__occupants = [] self.__position_rlt = {} self.__init_special_id() self.__timer = timer self.__current_time = timer self.__height = height self.__width = width self.__x = x self.__y = y self.special_request = -1 def __init_special_id(self): """Initializes a special id used to keep track of occupants by the world""" self.__special_id = random.random() * 999999999 def update(self): """The primary logic loop that is run during every cycle of the program""" self.__current_time -= 1 if self.__current_time <= 0: self.spawning = True self.__current_time = self.__timer def timer(self): """Getter for the timer Return: the spawner's timer""" return self.__timer def get_current_time(self): """Getter for the current state of the timer. If it is zero, it is time to spawn Return: the current time of the timer""" return self.__current_time def gct(self): """Getter for the current state of the timer. If it is zero, it is time to spawn Return: the current time of the timer""" return self.get_current_time() def set_current_time(self, o): """Sets the current state of the timer to a specified value Args: o: the new current time of the timer""" self.__current_time = o def countdown(self): """Decrements the current state of the timer by 1""" self.__current_time -= 1 def getx(self): """Getter for the x-value of the spawner Return: The x-value of the spawner""" return self.__x def gety(self): """Getter for the y-value of the spawner Return: The y-value of the spawner""" return self.__y def get_height(self): """Getter for the height of the spawner Return: The height of the spawner""" return self.__height def get_width(self): """Getter for the width of the spawner Return: The width of the spawner""" return self.__width def add(self, o): """Adds an occupant to its list of occupants to keep track of as well as the rlt Args: o: A triple (occupant to add, occupant x, occupant y)""" self.__occupants.append(o[0]) self.__position_rlt[o[0]] = (o[1], o[2]) def remove(self, occupant): """Removes an occupant from its list of occupants to keep track of Args: occupant: the occupant to remove from the list of occupants""" if occupant in self.__occupants: self.__occupants.remove(occupant) def occupants(self): """Getter for the list of occupants the spawner is tracking Return: the list of occupants the spawner is tracking""" return self.__occupants def find_occupant_x(self, o): """Uses the rlt to find the x-position of a tracked occupant Args: o: the occupant whose x-location is needed Return: the x-position of the occupant requested""" return self.__position_rlt[o][0] def find_occupant_y(self, o): """Uses the rlt to find the y-position of a tracked occupant Args: o: the occupant whose y-location is needed Return: the y-position of the occupant requested""" return self.__position_rlt[o][1] def set_spawnx(self, x): """Sets the x-location of the next spawn Args: x: the next x-location for the spawn""" self.__spawn_x = x def spawnx(self): """Getter for x-location of the next spawn Return: the x-value of the next spawn""" return self.__spawn_x def spawny(self): """Getter for y-location of the next spawn Return: the y-value of the next spawn""" return self.__spawn_y def set_spawny(self, y): """Sets y-location of the next spawn Args: the y-value of the next spawn""" self.__spawn_y = y def set_spawning(self, tf): """Sets the spawning trigger to a specified value Args: tf: whether or not the spawner will now be spawning""" self.spawning = tf def spawn(self): """Sets spawning trigger and creates the spawned occupant Return: an Occupant that is to be spawn""" self.__spawn_x = random.random() * self.__width + self.__x self.__spawn_y = random.random() * self.__height + self.__y self.spawning = True return Occupant('#696969', 5, 1) def get_spawn_x(self): """Getter for x-location of the next spawn Return: the x-value of the next spawn""" return self.__spawn_x def get_spawn_y(self): """Getter for y-location of the next spawn Return: the y-value of the next spawn""" return self.__spawn_y def get_special_id(self): """Getter for the special id, used to keep track of occupants in the world Return: the special id for this spawner""" return self.__special_id def process_special_request(self, data): """If a special request number is initialized, process it Args: data: any data that will be passed in as part of the request""" class PlantSpawner(Spawner): """A spawner that only spawns plants""" def spawn(self): """Creates a plant to spawn, and adds it to its tracked occupants Return: a plant to be spawned in the world""" self.set_spawning(False) p = Plant(random.random()*10000) self.add((p, self.get_spawn_x(), self.get_spawn_y())) return p def update(self): """The primary logic loop that is run during every cycle of the program Only selectively spawns based on shade in the area""" self.countdown() if self.get_current_time() <= 0: spawnx = ((random.random() * (self.get_width())) + self.getx()) spawny = ((random.random() * (self.get_height())) + self.gety()) rand = random.random() shade = self._calculate_shade(spawnx, spawny, rand) if rand > shade: self.set_spawnx(spawnx) self.set_spawny(spawny) self.set_spawning(True) self.set_current_time(self.timer()) def _calculate_shade(self, x, y, target): """Calculates the shade for a new potential plant Args: x: the new x-value of the potential plant y: the new y-value of the potential plant""" shade = 0 for plant in self.occupants(): size = plant.get_size() px = self.find_occupant_x(plant) py = self.find_occupant_y(plant) distance = int(math.sqrt((((x-px)*(x-px))+((y-py)*(y-py))))) if distance != 0: shade += (size/distance) else: return 2 if shade > target: return shade return shade class SpecialSpawner(Spawner): """A spawner that spawns objects using a provided template""" def __init__(self, timer, height, width, x, y, occupant): """Initialization logic Args: timer: the time in update cycles between each attempted spawn height: the height of the spawner width: the width of the spawner x: the x-value of the spawner in its world y: the y-value of the spawner in its world occupant: the template occupant to base spawns off of""" Spawner.__init__(self, timer, height, width, x, y) self.__model = occupant def spawn(self): """Spawns an instance of the provided model Return: an instance of the template occupant""" self.set_spawnx((random.random() * (self.get_width())) + self.getx()) self.set_spawny((random.random() * (self.get_height())) + self.gety()) self.set_spawning(False) return self.__model
f14b52073894e095f4540d58eee77ff0aa4930fa
acanizares/advent_of_code
/day01.py
504
3.625
4
from functools import reduce from itertools import cycle file = "input01.txt" with open(file, 'rt') as f: lines = f.readlines() # Part 1 def sum_str(a: str, b: str): return int(a) + int(b) res1 = reduce(sum_str, lines) print(f"The result is: {res1}") # Part 2 lines_int = map(lambda x: int(x), lines) freqs = {0: 1} freq = 0 for x in cycle(lines_int): freq += x if freqs.get(freq, None) is not None: break freqs[freq] = 1 print(f"First repeated frequency: {freq}\n")
f258b3e7709eefaf83d7cb62d1965af0bbfa7803
MaxRozendaal/AoC2020
/day11/puzzle.py
1,870
3.625
4
import copy, string def box(coordinate: tuple, height: int, width: int) -> list: x, y = coordinate return [(x + i, y + j) for i in range(-1,2) for j in range(-1,2) if all([ x + i >= 0, y + j >= 0, x + i < height, y + j < width, (x + i, y + j) != coordinate ])] def iteration(layout: list) -> list: stable = False layout_copy = copy.deepcopy(layout) while not stable: # Iterate over seats in layout for id_row, row in enumerate(layout): for id_seat, seat in enumerate(row): # Evaluate if current position is a seat if seat != ".": # Generate evaluation box around current position evaluation_box = box((id_row, id_seat), len(layout), len(row)) rule_seat_count = 0 # Iterate over positions to evaluate around current position for evaluated_position in evaluation_box: i, j = evaluated_position if layout[i][j] == "#": rule_seat_count += 1 if layout[id_row][id_seat] == "#" and rule_seat_count >= 4: layout_copy[id_row][id_seat] = "L" elif layout[id_row][id_seat] == "L" and rule_seat_count == 0: layout_copy[id_row][id_seat] = "#" if layout == layout_copy: stable = True layout = copy.deepcopy(layout_copy) return layout def main(): with open("test.txt", "r") as f: layout = [list(line) for line in f.read().split("\n")] occupied_seats = 0 for row in iteration(layout): occupied_seats += row.count("#") print(f"Part 1 answer: {occupied_seats}") if __name__ == "__main__": main()
3cac0579ed84aaeeb6cd68e8dba63fbfa5caefee
brentirwin/automate-the-boring-stuff
/ch7/regexStrip.py
1,091
4.6875
5
#! python3 # regexStrip.py ''' Write a function that takes a string and does the same thing as the strip() string method. If no other arguments are passed other than the string to strip, then whitespace characters will be removed from the beginning and end of the string. Otherwise, the characters specified in the second argument to the function will be removed from the string. ''' import re def regexStrip(string, substring = None): # No substring if substring == None: # Find whitespace at beginning and/or end startSpaceRegex = re.compile(r'^\w+') endSpaceRegex = re.compile(r'\w+$') # Remove whitespace at beginning and/or end string = startSpaceRegex.sub('', string) string = endSpaceRegex.sub('', string) return string # Yes substring else: substringRegex = re.compile(substring) return substringRegex.sub('', string) string = input("String: ") substring = input("Substring: ") if substring == '': print(regexStrip(string)) else: print(regexStrip(string, substring))
c86a09cf6d893b85a67cf094b8fcf3e1b1e22e9b
realdavidalad/python_algorithm_test_cases
/longest_word.py
325
4.375
4
# this code returns longest word in a phrase or sentence def get_longest_word(sentence): longest_word="" for word in str(sentence).split(" "): longest_word=word if len(word) > len(longest_word) else longest_word return longest_word print get_longest_word("This is the begenning of algorithm")
359bb72cb48016ffc26ac72b81a607df7bf62bc3
emilydowgialo/hackbright_coding_challenges
/graph-practice.py
1,427
4.09375
4
class PersonNode(object): """ Node in a graph representing a person """ def __init__(self, name, adjacent=None): """ Create a person node with friends adjacent """ adjacent = adjacent or set() self.name = name self.adjacent = set(adjacent) def __repr__(self): """ Debugging-friendly representation """ return "PersonNode: %s" % self.name class FriendGraph(object): """ Create a graph of friends and adjacent friends """ def __init__(self): """ Create an empty graph """ self.nodes = set() def __repr__(self): return "FriendGraph: %s" % [n.node for n in self.nodes] def add_person(self, person): """ Add a person to the graph """ self.nodes.add(person) def add_adjacent(self, person1, person2): """ Set two people as friends """ person2.adjacent.add(person1) person1.adjacent.add(person2) class CheckIfFriends(object): def are_they_friends(self, person1, person2, seen=None): """ Recursively check to see if two people are friends on a graph """ if not seen: seen = set() if person1 is person2: return True # Keep track of the person node that we've seen before seen.add(person1) for person in person1.adjacent - seen: if self.are_they_friends(person, person2, seen): return True return False
7aa5652177d2beb2f1e29d63a2d5c44e4cd1980f
paulofranciscon/courses-class-python
/LeituraPython.py
265
3.703125
4
with open("first_file.txt", "r") as arquivo: """ ## Nesta forma lê o aquivo inteiro conteudo = arquivo.read() """ ### Nesta forma lê a primeira linha conteudo = arquivo.readline() for linha in arquivo.readlines(): print(linha)
bed4536a9e45ea5bbe4e437abf0eb8df23c389c9
PaoloLRinaldi/read_write_binary_python_dummies
/readwritebin.py
8,579
3.90625
4
from struct import pack, unpack def dtype_str_to_char(type_name): ''' Convert the name of the type to a character code to be interpreted by the "struct" library. ''' if not (type(type_name) is str): raise TypeError("You must insert a string.") if type_name == 'unsigned char': return 'B' elif type_name == 'char': return 'c' elif type_name == 'signed char': return 'b' elif type_name == '_Bool': return '?' elif type_name == 'short': return 'h' elif type_name == 'unsigned short': return 'H' elif type_name == 'int': return 'i' elif type_name == 'unsigned int': return 'I' elif type_name == 'long': return 'l' elif type_name == 'unsigned long': return 'L' elif type_name == 'long long': return 'q' elif type_name == 'unsigned long long': return 'Q' elif type_name == 'float': return 'f' elif type_name == 'double': return 'd' elif type_name == 'char[]': return 's' elif type_name == 'char *': return 'p' elif type_name == 'void *': return 'p' else : raise ValueError("Unknown type name: " + type_name) def type_size(type_name): ''' Get the size of a type in bytes. ''' if not (type(type_name) is str): raise TypeError("You must insert a string.") if type_name == 'unsigned char': return 1 elif type_name == 'char': return 1 elif type_name == 'signed char': return 1 elif type_name == '_Bool': return 1 elif type_name == 'short': return 2 elif type_name == 'unsigned short': return 2 elif type_name == 'int': return 4 elif type_name == 'unsigned int': return 4 elif type_name == 'long': return 4 elif type_name == 'unsigned long': return 4 elif type_name == 'long long': return 8 elif type_name == 'unsigned long long': return 8 elif type_name == 'float': return 4 elif type_name == 'double': return 8 else : raise ValueError("Unknown type name: " + type_name) class Bin: ''' The class that manages a binary file. ''' def __init__(self, filename, truncate = False, little_endian = True): try: # Does the file already exist? self._f = open(filename, "r+" + "b") except: # If it doesn't exist craete it. self._f = open(filename, "wb") self._f.close() self._f = open(filename, "r+" + "b") self._f.seek(0) self._endian_char = "<" if little_endian else ">" self._filename = filename if truncate: self._f.truncate(0) def write(self, val, type_str = "unsigned char"): ''' Write a value in the current position. param: val The value you want to write param: type_str The type of the value ''' self._f.write(pack(self._endian_char + dtype_str_to_char(type_str), val)) def write_many(self, vals, type_str = "unsigned char"): ''' Write multiple values in the current position. param: vals The container containing the values you want to write. E.g.: bin_instance.write_many((6, 8, -1), "int") param: type_str The type of the values ''' self._f.write(pack(self._endian_char + dtype_str_to_char(type_str) * len(vals), *vals)) def write_at(self, point, val, type_str = "unsigned char"): ''' Write a value in the specified position. param: point The point where to write. It must be espressed in bytes. param: val The value you want to write param: type_str The type of the value ''' self.jump_to(point) self.write(type_str, val) def write_many_at(self, point, vals, type_str = "unsigned char"): ''' Write multiple values in the current position. param: point The point where to write. It must be espressed in bytes. param: vals The container containing the values you want to write. E.g.: bin_instance.write_many((6, 8, -1), "int") param: type_str The type of the values ''' self.jump_to(point) self.write_many(type_str, vals) def write_string(self, s): ''' Write a string in the current position. param: s The string you want to write ''' self._f.write(s.encode("ascii")) def write_string_at(self, point, s): ''' Write a string in the current position. param: point The point where to write. It must be espressed in bytes. param: s The string you want to write ''' self.jump_to(point) self.write_string(s) def get_value(self, type_str = "unsigned char"): ''' Get the value in the current position. param: type_str The type of the value ''' return unpack(self._endian_char + dtype_str_to_char(type_str), self._f.read(type_size(type_str)))[0] def get_values(self, num, type_str = "unsigned char"): ''' Get multiple values starting from the current position. param: num The number of values you want to read param: type_str The type of the value ''' return unpack(self._endian_char + dtype_str_to_char(type_str) * num, self._f.read(num * type_size(type_str))) def get_value_at(self, point, type_str = "unsigned char"): ''' Get the value in the specified position. param: point The point from where to read. It must be expressed in bytes. param: type_str The type of the value ''' self.jump_to(point) return self.get_value(type_str) def get_values_at(self, point, num, type_str = "unsigned char"): ''' Get multiple values starting from the specified position. param: point The point from where to read. It must be expressed in bytes. param: num The number of values you want to read param: type_str The type of the value ''' self.jump_to(point) return self.get_values(num, type_str) def get_string(self, sz): ''' Read a string from the current position. param: sz The size of the string ''' ret = str() s = unpack(self._endian_char + "c" * sz, self._f.read(sz)) for a in s: ret += str(a)[2:-1] return ret def get_string_at(self, point, sz): ''' Read a string from the specified position. param: point The point from where to read. It must be expressed in bytes. param: sz The size of the string ''' self.jump_to(point) return self.get_string(sz) def jump_to(self, point): ''' Move the current position. param: point The point where to move. It must be expressed in bytes. ''' self._f.seek(point) def pos(self): ''' Get the position you are currently on. It is expressed in bytes. ''' return self._f.tell() def move_by(self, size, type_str = "char"): ''' Move from your current position by a certain quantity. E.g: You have just written 3 integers and you want to move back to the first one: bin_instance.move_by(-3, "int") or bin_instance.move_by(-12) since the size of "int" is 4 bytes. param: size The number of steps param: type_str The type to deduce the size of the step ''' self.jump_to(self.pos() + size * type_size(type_str)) def size(self): ''' Get the size of the file in bytes ''' p = self.pos() self._f.seek(0, 2) ret = self.pos() self.jump_to(p) return ret def flush(self): ''' Flush the buffer ''' self._f.flush() def close(self): ''' Close the file ''' self._f.close()
eac9e099603de5785fc9c0d0e533fb5cfb39aa90
ant0ndk/autocost
/src/main.py
404
3.59375
4
from functions import Dialog Dialog.clear() while True: answer = input('>>> ') if answer == '/help': Dialog.help() elif answer == '/clear': Dialog.clear() elif answer == '/donate': Dialog.donate() elif answer == '/exit': exit() elif answer == '/autocost': Dialog.autocost() else: print('Неизвестная команда')
f25a009feace4cd5c587bbcda8af72afa281fafc
peterFran/CryptoHashAttacks
/BruteForce.py
2,420
3.515625
4
#!/usr/bin/env python # encoding: utf-8 """ BruteForce.py Created by Peter Meckiffe on 2013-02-15. Copyright (c) 2013 UWE. All rights reserved. """ import sys import os import unittest from hashlib import sha1 class BruteForce: def __init__(self, hashtuple, salt): self.alphabet = "abcdefghijklmnopqrstuvwxyz0123456789" self.salt = salt self.hashtuple = hashtuple self.passwordList = ["No password found"]*self.tupleLength self.hashesMatched = 0 def badBruteAttack(self): try: self.depthFirst("",i) except Exception as e: pass return self.finaliseOutput() def bruteAttack(self): try: for i in range(0,6): self.levelCascade("",i) except Exception as e: pass return self.finaliseOutput() def levelCascade(self, previous, level): if level==0: for i in self.alphabet: digest = sha1(self.salt+previous+i).hexdigest() if digest in self.hashtuple: print "Found: %s matches %s" % (previous+i,digest) self.passwordList[self.hashtuple.index(digest)] = "Password %s = %s\n" % (previous+i, digest) self.hashesMatched += 1 if self.hashesMatched == len(self.hashtuple): raise Exception() else: for i in self.alphabet: self.levelCascade(previous+i, level-1) def finaliseOutput(self): if "No password found" in self.passwordList: output = "%d passwords not matched, apologies...\n" % (len(self.hashtuple) - self.hashesMatched) else: output = "All hashes cracked. Take that!\n" output = "List of passwords:\n" for x in self.passwordList: output += x return output if __name__ == '__main__': hashes = ("c2543fff3bfa6f144c2f06a7de6cd10c0b650cae", "b47f363e2b430c0647f14deea3eced9b0ef300ce", "e74295bfc2ed0b52d40073e8ebad555100df1380", "0f7d0d088b6ea936fb25b477722d734706fe8b40", "77cfc481d3e76b543daf39e7f9bf86be2e664959", "5cc48a1da13ad8cef1f5fad70ead8362aabc68a1", "4bcc3a95bdd9a11b28883290b03086e82af90212", "7302ba343c5ef19004df7489794a0adaee68d285", "21e7133508c40bbdf2be8a7bdc35b7de0b618ae4", "6ef80072f39071d4118a6e7890e209d4dd07e504", "02285af8f969dc5c7b12be72fbce858997afe80a", "57864da96344366865dd7cade69467d811a7961b") saltedHashes = ("2cb3c01f1d6851ac471cc848cba786f9edf9a15b", "a20cdc214b652b8f9578f7d9b7a9ad0b13021aef", "76bcb777cd5eb130893203ffd058af2d4f46e495", "9208c87b4d81e7026f354e63e04f7a6e9ca8b535", "d5e694e1182362ee806e4b03eee9bb453a535482", "120282760b8322ad7caed09edc011fc8dafb2f0b" ) #a = BruteForce(saltedHashes,"uwe.ac.uk") a = BruteForce(hashes,"") print a.bruteAttack()
69015c173899ac3b237d2e7ce00c3503182717bc
EnGinear87/Python
/Romeos_Dictionary_Email.py
5,477
4.4375
4
# -*- coding: utf-8 -*- """ Created on Fri Jun 4 16:31:09 2021 @author: Melvin Wayne Abraham | Module 4_Python Assignment """ #Question 1: Using the Romeo data file download, write a program to open the file and read it line by line. #For each line, split the line into a list of words using the split function. #When the program completes, sort and print the resulting words in alphabetical order. #Need to figure out how to maintain the same order for capital or non-capital words print(' Question 1: ') #Import the data from the folder and then assign it over to a variable called romeo_data data = "buad5802-m4-python-assignment-data-file-romeo.txt" #print(data) romeo_data = open(data) oh_romeo = list() #Creates an empty list for line in romeo_data: #Iterates through each line of the data file mentioned above find_words = line.split() #Splits the strings into a list of words per line #print(find_words) #Verify all the words within the list for word in find_words: #Finds each new word in the new list and iterates through if word not in oh_romeo: #If the word is not in the original list, append the new one oh_romeo.append(word) #print(oh_romeo) else: #This will ensure it continually loops through all the words and continues continue #Now print the results from the list sorted in alphabetical order print('The words in alphabetical order (capital or not) are: ', sorted(oh_romeo, key=lambda v: (v.upper(), v[0].islower()))) print(' ') #Question 2: Using the data file from the M3 Python assignment download, #write a program that categorizes each email message by which day of the week the email was sent. #To do this, look for lines that start with "From," then look for the third word #and keep a running count of each of the days of the week. #At the end of the program, print out the contents of your dictionary (order does not matter). print(' Question 2: ') days_dict = {} #Creates an empty dictionary dayslist = [] #Creates an empty list with open("buad5802-m3-python-assignment-data-file.txt") as day_of_week: #Open the file and set it to day_of_week for line in day_of_week: #Create a for loop and iterate each line dayslist = line.split() #Split the strings into a list of words per line #If the length of words is greater than 3 and the line starts with "From" then keep a running count if len(dayslist) > 3 and line.startswith('From'): day = dayslist[2] if day not in days_dict: #If it is not in the days dictionary, the value equals 1 days_dict[day] = 1 else: #Unless it is, then you would count it and then add one as well days_dict[day] += 1 #Print out the remaining information for the dictionary in no particular order print ('The contents of the dictionary are: ', days_dict) print(' ') #Question 3: Revise the program you wrote in Item 2 above, as follows: #Read and parse the “From” lines and pull out the email addresses from the line. #Count the number of messages from each person using a dictionary. #After all the data has been read, print the person with the most emails #sent by creating a list of (count, email) tuples from the dictionary. #Sort the list in reverse order (Z–A) and print out the person with the most emails sent. print(' Question 3: ') #Read the filename or if null use the standard name name = "buad5802-m3-python-assignment-data-file.txt" if len(name) < 1 : name = "buad5802-m3-python-assignment-data-file.txt" data_start = open(name) count = 0 #Set the original count value to zero email_list = list() #Creates an empty list person = dict() #Creates an empty dictionary most_emails = 0 #Set the original count value to zero quantity_emails = 0 #Set the original count value to zero for line in data_start: #Create a for loop and iterate each line email_list = line.split() #Split the strings into a list of words per line #print(email_list) #Verify the email list is correct #If From is in the email list, then the person equals the previous value plus 1 if "From" in email_list: person[email_list[1]] = person.get(email_list[1],0) + 1 else: continue for key in person: #Create a for loop through each key in the person's email if person[key] > quantity_emails : #If the persons email is the greatest quantity most_emails = key #Then it equals the most emails quantity_emails = person[key] #And the quantity equals the person in the key print('The following emails have been sorted in reverse order (Z-A)', sorted(person, reverse=True)) print('The person with the most emails is registered to', most_emails, 'in the amount of', quantity_emails, 'emails sent.') print(' ') print ('Here is another method finding the solution to Question #3 with less coding than above:' ) data_file = open('buad5802-m3-python-assignment-data-file.txt') #Opens the data file counts = dict() #Create an empty dictionary for line in data_file: #Iterate through each line of the file if line.startswith('From:'): #If the line starts with "From" then split it and add the first line to an email line = line.split() email = line[1] counts[email] = counts.get(email,0)+1 #Count the emails from each sender into a dictionary per person print('The following emails have been sorted in reverse order (Z-A)', sorted(counts, reverse=True)) print('The person with the most emails is registered to', email, 'in the amount of', max(counts.values()), 'emails sent.')
06f270d632cfd5007e9dffa79348605cd4e94bc2
sebbycake/HackerRank
/Data_Structures/2D Array - DS.py
1,008
3.65625
4
# link to problem description # https://www.hackerrank.com/challenges/2d-array/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=arrays def get_max_sum_hourglass(arr): num_rows = len(arr) num_cols = len(arr[0]) hourglass_sum_list = [] # to iterate through each row and col for row in range(num_rows): for col in range(num_cols): try: top = arr[row][col] + arr[row][col+1] + arr[row][col+2] mid = arr[row+1][col+1] btm = arr[row+2][col] + arr[row+2][col+1] + arr[row+2][col+2] hour_glass_sum = top + mid + btm hourglass_sum_list.append(hour_glass_sum) except IndexError: pass max_sum = max(hourglass_sum_list) return max_sum # test case test_matrix = [ [1,1,1,0,0,0], [0,1,0,0,0,0], [1,1,1,0,0,0], [0,0,0,0,0,0], [0,0,0,0,0,0], [0,0,0,0,0,0] ] max_s = get_max_sum_hourglass(test_matrix) print(max_s)
fa0c8bc224b3c091276166cd426bd5153edb0b73
Lynkdev/Python-Projects
/shippingcharges.py
508
4.34375
4
#Jeff Masterson #Chapter 3 #13 shipweight = int(input('Enter the weight of the product ')) if shipweight <= 2: print('Your product is 2 pounds or less. Your cost is $1.50') elif shipweight >= 2.1 and shipweight <= 6: print('Your product is between 2 and 6 pounds. Your cost is $3.00') elif shipweight >= 6.1 and shipweight <= 10: print('Your product is between 6 and 10 pounds. Your cost is $4.00') elif shipweight > 10: print('Your product is over 10 pounds. Your cost is $4.75')
6d678659bf552174f4fbda373d079ae25b9c3a79
Shivani-Y/Assignment_6
/fibonacci.py
1,562
4.09375
4
""" This is a Fibonacci Iterator """ class Fibonacci: """The class accepts a sinlge agrument which should be a integer""" def __init__(self, limit): self.limit = limit self.number_1 = 0 #setting defaults self.number_2 = 1 #setting defaults self.iteration_count = 0 #setting defaults self.sum_of_last_two_digits = 1 #setting defaults def __iter__(self): if not isinstance(self.limit, int):#raising a value error if limit not int raise ValueError if self.limit < 0:#if limit is negative the value is empty pass return self def __next__(self): if self.iteration_count > self.limit:#if the iterations add up tp more #than the limit the iterator stops raise StopIteration if self.iteration_count == 0:#if limit is 0 then return 0 and add to counter self.iteration_count += 1 return self.number_1 if self.iteration_count == 1:#if limit is 1 then return 1 and add to counter self.iteration_count += 1 return self.number_2 if self.iteration_count > 1:#if limit is a +int (not 0 0r 1) and iteration_count #is more than 1 then add to counter and return sum of last 2 digits self.sum_of_last_two_digits = self.number_1 + self.number_2 self.number_1 = self.number_2 self.number_2 = self.sum_of_last_two_digits self.iteration_count += 1 return self.sum_of_last_two_digits return None
3647c4684453494b07d2000b1f7d2a9cfd7eaef0
ching-yi-hsu/practice_python
/6_String_Lists/string_lists.py
206
4.3125
4
str_word = str(input("enter a string : ")) str_word_rev = str_word[::-1] if str_word == str_word_rev : print(str_word , " is a palindrome word") else : print(str_word, " isn't a palindrome word")
46131795cbfb5c47dfab2f3f6adeed58106b8f45
GaryChen10128/bblcg
/thread.py
489
3.609375
4
# -*- coding: utf-8 -*- """ Created on Sat May 15 15:11:24 2021 @author: DIAMO """ import threading import time # 子執行緒的工作函數 def job(): for i in range(5): print("Child thread:", i) time.sleep(1) # 建立一個子執行緒 t = threading.Thread(target = job) # 執行該子執行緒 t.start() # 主執行緒繼續執行自己的工作 for i in range(3): print("Main thread:", i) time.sleep(1) # 等待 t 這個子執行緒結束 t.join() print("Done.")
964dbd05aba2232c55aea32b45ae7f254d8575ee
selece/aoc2020-python
/day01.py
641
3.53125
4
from util.filereader import FileReader data = FileReader('inputs/01.txt').parseInt() found = False for index_1, data_1 in enumerate(data): for index_2, data_2 in enumerate(data): if not found and index_1 != index_2 and data_1 + data_2 == 2020: print("part1: ", data_1, data_2, data_1 * data_2) found = True found = False for index_1, data_1 in enumerate(data): for index_2, data_2 in enumerate(data): for index_3, data_3 in enumerate(data): if not found and data_1 + data_2 + data_3 == 2020: found = True print("part2:", data_1 * data_2 * data_3)
ec31e6c3c5eb2b9d3233e31330e60b3e5c715d60
mandarwarghade/Python3_Practice
/ch10ex11.py
833
3.953125
4
""" Exercise 11 Two words are a “reverse pair” if each is the reverse of the other. Write a program that finds all the reverse pairs in the word list. Solution: http://thinkpython2.com/code/reverse_pair.py. """ import bisect from ch10ex10 import listWords2 if __name__ == '__main__': word_list = listWords2() print(word_list) """def listWords2(): fin = open("words.txt") t = [] for line in fin: words = line.strip() t += [words] return t def in_bisect(word_list, word): y = bisect.bisect_left(word_list, word) if y == len(word_list): return False if word_list[y] == word: print(word) def reverse_pair(): list1 = listWords2() for firstword in list1: firstword = firstword[::-1] in_bisect(list1, firstword) reverse_pair() """
bf07fa0385b64213f01583fe22a86deb00ea65d2
mandarwarghade/Python3_Practice
/ThinkPython_Ex3.py
1,035
4.1875
4
#Exercise 3 #Note: This exercise should be done using only the statements and other features we have learned so far. #Write a function that draws a grid like the following: #+ - - - - + - - - - + #| | | #| | | #| | | #| | | #+ - - - - + - - - - + #| | | #| | | #| | | #| | | #+ - - - - + - - - - + def do_twice(f, arg): f(arg) f(arg) def print_twice(arg): print(arg,end="") print(arg,end="") def print_twice_newline(arg): print(arg) print(arg) def do_four(f, arg): do_twice(f,arg) do_twice(f,arg) # do_twice(print_twice, "natasha") # do_four(print_twice, "natasha") def make_grid(): print_twice("+" + "----") print("+") do_twice(print_twice_newline, "|" + " " + "|" + " " + "|") print_twice("+" + "----") print("+") do_twice(print_twice_newline, "|" + " " + "|" + " " + "|") print_twice("+" + "----") print("+") make_grid()
0c64a84dd309c60d67983f471a8e9e7b222deafe
mandarwarghade/Python3_Practice
/ch10.py
4,755
4.125
4
""" Chapter 10 short exercises, # 1 - #7 Exercises""" from __future__ import print_function, division import time # (for Ex. 9 exercises ) # Exercise 1 # Write a function called nested_sum that takes a list of lists of integers and # adds up the elements from all of the nested lists. For example: # >>> t = [[1, 2], [3], [4, 5, 6]] # >>> nested_sum(t) # 21 t = [[1, 2], [3], [4, 5, 6]] def nested_sum(t): count = 0 for nestedList in t: count += sum(nestedList) return count # nested_sum(t) """ Exercise 2 Write a function called cumsum that takes a list of numbers and returns the cumulative sum; that is, a new list where the ith element is the sum of the first i+1 elements from the original list. For example: >>> t = [1, 2, 3] >>> cumsum(t) [1, 3, 6] """ t = [1, 2, 3] def cumsum(t): t2 = [] count = 0 for i in t: count += i t2.append(count) return t2 # cumsum(t) """Exercise 3 Write a function called middle that takes a list and returns a new list that contains all but the first and last elements. For example: >>> t = [1, 2, 3, 4] >>> middle(t) [2, 3] """ t = [1, 2, 3, 4] def middle(t): t2 = t[1:-1] return t2 # middle(t) """Exercise 4 Write a function called chop that takes a list, modifies it by removing the first and last elements, and returns None. For example: >>> t = [1, 2, 3, 4] >>> chop(t) >>> t [2, 3] """ t = [1, 2, 3, 4] def chop(t): t.pop(0) t.pop() #chop(t) """ Exercise 5 Write a function called is_sorted that takes a list as a parameter and returns True if the list is sorted in ascending order and False otherwise. For example: >>> is_sorted([1, 2, 2]) True >>> is_sorted(['b', 'a']) False """ t = [1, 2, 3] def is_sorted(t): return t == sorted(t) #is_sorted(t) """ Exercise 6 Two words are anagrams if you can rearrange the letters from one to spell the other. Write a function called is_anagram that takes two strings and returns True if they are anagrams. """ t = "cinema" t2 = "iceman" def is_anagram(firstString, secondString): return sorted(firstString) == sorted(secondString) # is_anagram(t, t2) """ Exercise 7 Write a function called has_duplicates that takes a list and returns True if there is any element that appears more than once. It should not modify the original list. """ def has_duplicates(listName): t = listName[:] t.sort() for i in range(len(t) - 1): if t[i] == t[i + 1]: return True return False """ Exercise 8 This exercise pertains to the so-called Birthday Paradox, which you can read about at http://en.wikipedia.org/wiki/Birthday_paradox. If there are 23 students in your class, what are the chances that two of you have the same birthday? You can estimate this probability by generating random samples of 23 birthdays and checking for matches. Hint: you can generate random birthdays with the randint function in the random module.""" def birthday_paradox(trial=1000): import random total = 0 for trialNum in range(trial): bDayList = [] for i in range(23): bDay = random.randint(0, 365) bDayList.append(bDay) bDayList.sort() sameDay = False for i in range(len(bDayList) - 1): if bDayList[i] == bDayList[i + 1]: sameDay = True if sameDay: total += 1 prop = (total / trial) * 100 print("The propability is ", prop, "percent" ) # birthday_paradox(50) # I know I can seperate this into different functions to avoid bugs. The book has a different answer: #http://greenteapress.com/thinkpython2/code/birthday.py """ Exercise 9 Write a function that reads the file words.txt and builds a list with one element per word. Write two versions of this function, one using the append method and the other using the idiom t = t + [x]. Which one takes longer to run? Why? Solution: http://thinkpython2.com/code/wordlist.py. """ def listWords(): fin = open("words.txt") t = [] for line in fin: words = line.strip() t.append(words) return t # listWords() def listWords2(): fin = open("words.txt") t = [] for line in fin: words = line.strip() t += [words] return t # listWords2() def timeWords(): startTime = time.time() listWords() endTime = time.time() totalTime = endTime - startTime startTime2 = time.time() listWords2() endTime2 = time.time() totalTime2 = endTime2 - startTime2 if totalTime > totalTime2: print("The append method takes longer!") elif totalTime2 > totalTime: print("The t = t + [x] method takes longer!") else: print("I must have written this with a bug!") timeWords()
8a71ab1b2ab89fcc2296be219571a80408c0b726
Valoderah/Python-Play
/final-project-keal-master/final-project-keal-master/gui_setup.py
2,141
3.796875
4
from tkinter import * # test of function called by button and passed values def test_func(entry, value): print("Testing grabbing from text box:", entry, value) # test of pop up window def popup(): #Window root = Tk() #Closes popup button = Button(root, text="Close", command=root.destroy) button.pack() from itertools import permutations perm = permutations('1234567890', 6) count = 0 f = open("unused919.txt", "w+") n = open("test1.txt", "w+") for i in set(perm): k = ",".join(i) k = k.replace(",", "") print(k) d = dict() r = input("Enter your name:") if (r == 'q'): break d[r] = k count += 1 f.write(str(k) + "\n") for kp in sorted(d.keys()): n.write("'%s':'%s', \n" % (kp, d[kp])) f.close() n.close() root.mainloop() #width and height of window WIDTH = 500 HEIGHT = 300 # Window root = Tk() root.title("919# Generator!") #Sets v to what the radiobuttons will be v = IntVar() v.set(1) # Sets the options of the window canvas = Canvas(root, height=HEIGHT, width=WIDTH) canvas.pack() # Square of the window (Can make multiple in future) frame = Frame(root) frame.place(relwidth=1, relheight=1) # Sets label of program label = Label(frame, text="919# Generator") label.pack() # Label before user input nameLabel = Label(frame, text="Please enter your name") nameLabel.pack() # User input (Their name userName = Entry(frame) userName.pack() # First radio button, undergraduate underGrad = Radiobutton(frame, text="Undergraduate", variable=v, value=1) underGrad.pack() # Second radio button, graduate grad = Radiobutton(frame, text="Graduate", variable=v, value=2) grad.pack() # Ok button, currently test to make sure to grab from user input and send it to def button = Button(frame, text="OK", command=lambda: test_func(userName.get(), v.get())) button.pack() # pop up button, currently test to make a pop up window popbtn = Button(frame, text="pop", command=popup) popbtn.pack() # makes sure window does not close before user wants it root.mainloop()
bec5623135d5387e7bb16e3f63d93522a2a6f69a
sbuffkin/python-toys
/stretched_search.py
1,172
4.15625
4
import sys import re #[^b]*[b][^o]*[o][^a]*[a][^t]*[t](.?) #([^char]*[char])*(.?) <- general regex #structure of regex, each character is [^(char)]*[(char)] #this captures everything that isn't the character until you hit the character then moves to the next state #you can create a "string" of these in regex to see if you can find the given string within a larger document, #perhaps hidden somewhere #this will find the first such occurance. #takes in a string as input """ If any group is captured (even an empty one) that means we got a hit! It might been stretched across the entire document but YAY. """ def regexBuild(string): regex = "" for char in string: regex += "[^{0}]*[{0}]".format(char) regex += "(.)" p = re.compile(regex) return p def find(reg): try: filename = sys.argv[2] except: print('Need filename arg') try: f = open(filename,'r') words = f.read() m = reg.match(words) print(m) if m: print('Found Match') else: print('No Match') except: print("File not found") reg = regexBuild(sys.argv[1]) find(reg)
de2c4ac7bfbd1eb42659b496dbb5cef33937bba4
berkbenzer/Python
/user_delete_in_mysqldb.py
2,426
3.5625
4
import mysql.connector import getpass # Get database credentials from user raw_input #password = getpass.getpass("Enter database password: ") # Connect to database def establish_connection(): conn = mysql.connector.connect( database='mysql', user='root', password='password' ) return conn def close_connection(conn): # Close the database connection conn.close() def delete_user(conn, user_name, user_host): # Create a cursor for executing the DROP USER query cursor = conn.cursor() drop_query = "DROP USER %s@%s" cursor.execute(drop_query, (user_name, user_host)) # Commit the changes to the database conn.commit() cursor.close() def prompt_confirmation(user_name, user_host): # Prompt for confirmation to delete the user confirm = raw_input("Are you sure you want to delete %s@'%s'? (Y/N): " % (user_name, user_host)) return confirm.lower() == "y" def delete_usernames(conn, usernames): # Delete each username from the database for username in usernames: # Check if the user exists in the database query = "SELECT user, host FROM mysql.user WHERE user = %s" cursor = conn.cursor() cursor.execute(query, (username,)) results = cursor.fetchall() if results: for result in results: user_name = result[0] user_host = result[1] print("%s@'%s' found in the database" % (user_name, user_host)) if prompt_confirmation(user_name, user_host): delete_user(conn, user_name, user_host) print("%s@'%s' deleted from the database" % (user_name, user_host)) else: print("%s@'%s' deletion canceled" % (user_name, user_host)) else: print("%s not found in the database" % username) def main(): # Prompt the user for a comma-separated list of usernames to delete usernames_input = raw_input("Enter comma-separated list of usernames to delete: ") usernames = [username.strip() for username in usernames_input.split(",")] # Establish a database connection conn = establish_connection() # Delete the usernames from the database delete_usernames(conn, usernames) # Close the database connection close_connection(conn) # Entry point of the script if __name__ == "__main__": main()
eb67725e6d7dd3d94fdb42cf8e1bfee5459c38aa
alexandrumeterez/MLlibrary
/steepest_descent.py
604
3.78125
4
import numpy as np def steepest_descent(A, b, x, max_iterations = 49, eps = 0.001): """ Gives the solution to Ax = b via the steepest descent method. """ i = 0 r = b - np.dot(A, x) delta = np.dot(r, r) delta_zero = delta while i < max_iterations and delta > (eps**2) * delta_zero: q = np.dot(A, r) alpha = delta / np.dot(r, q) x = x + np.multiply(alpha, r) if i % 50 == 0: r = b - np.dot(A, x) else: r = r - np.multiply(alpha, q) delta = np.dot(r, r) i = i + 1 return x
b8b78d051aac3047317b0374ce7eb596b0bccd96
singmyr/project-euler
/Python/problem17/main.py
1,867
3.984375
4
""" If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used? NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of "and" when writing out numbers is in compliance with British usage. """ LANGUAGE_DEFINITIONS = { 0: { 0: "zero", 1: "one", 2: "two", 3: "three", 4: "four", 5: "five", 6: "six", 7: "seven", 8: "eight", 9: "nine", 10: "ten", 11: "eleven", 12: "twelve", 13: "thirteen", 14: "fourteen", 15: "fifteen", 16: "sixteen", 17: "seventeen", 18: "eighteen", 19: "nineteen" }, 1: { 2: "twenty", 3: "thirty", 4: "forty", 5: "fifty", 6: "sixty", 7: "seventy", 8: "eighty", 9: "ninety" }, 2: {i:(lambda i=i: LANGUAGE_DEFINITIONS[0][i]+ "hundred") for i in range(10)}, 3: {i:(lambda i=i: LANGUAGE_DEFINITIONS[0][i]+ "thousand") for i in range(10)} } SUM = 0 for i in range(1, 1001): # Check if we should add 3 digits for "and" if i > 100 and i % 100 > 0: SUM += 3 i = str(i) l = list(i)[::-1] for k, v in enumerate(l): v = int(v) if v == 0: continue if k == 0 and len(i) > 1: if int(l[k+1]) == 1: continue if k == 1 and v < 2: c = LANGUAGE_DEFINITIONS[0][(v*10) + int(l[k-1])] else: c = LANGUAGE_DEFINITIONS[k][v] SUM += len(c() if callable(c) else c) print(SUM)
4f557ded70a629951844921d64fbea421a4d729d
Jaaga/project_sphere
/searchv2.py
851
3.625
4
#!/bin/python import pickle def main(): data = pickle.load( open('alldata.pickle', 'rb') ) def search(data, phrase): results = {} for stakeholder in data: for question in data[stakeholder]: for response in data[stakeholder][question]: count = 0 if all(word in response.lower() for word in phrase.lower().split()): count += 1 code = stakeholder+'-'+question+'-'+str(count) results[code]=response return(results) while True: phrase = raw_input("Search phrase: ") if phrase is 'exit': break else: for key,value in search(data, phrase).iteritems(): print key+': '+value if __name__ == "__main__": main()
615bd2cd21a24f313ec38f841fe467411cf2d0f0
mthompson-CU/Thompson_CSCI3202_Assignment1
/Node.py
370
3.6875
4
# Author: Matthew Thompson # IdentiKey: math1906 # Date: August 25, 2015 # Programming Assignment 1 # Implements a Node to be used in a Binary Tree # Inspired by https://www.ics.uci.edu/~pattis/ICS-33/lectures/treesi.txt class Node(): def __init__(self, key, left=None, right=None, parent=None): self.key = key self.left = left self.right = right self.parent = parent
19f4c2bc73df0fe69092b3ec9510c90b1e6a7f53
nickbonne/code_wars_solutions
/num_ppl_on_bus.py
221
3.75
4
# https://www.codewars.com/kata/number-of-people-in-the-bus/train/python def number(bus_stops): riders = 0 for stop in bus_stops: riders = riders + stop[0] - stop[1] return riders
389627cb58aab2830218f281631d9dbd4258e83b
nickbonne/code_wars_solutions
/decode_morse_code.py
538
3.671875
4
# https://www.codewars.com/kata/54b724efac3d5402db00065e decodeMorse(morseCode): solution = '' if len(morseCode.split(' ')) == 1: return ''.join([MORSE_CODE[char] for char in morseCode.split()]) for item in morseCode.split(' '): for char in item.split(): if char == item.split()[-1]: solution = solution + MORSE_CODE[char] + ' ' else: solution = solution + MORSE_CODE[char] return solution.strip()
f99b74da1df3867190d6d81f396d3126cd7c2d7a
nickbonne/code_wars_solutions
/get_middle_char.py
225
3.8125
4
# https://www.codewars.com/kata/get-the-middle-character/train/python def get_middle(s): s_len = len(s) mid = int(s_len / 2) if s_len % 2 == 0: return s[mid-1:mid+1] else: return s[mid]
6f46ac550d63f7aeb3658a5e508a9a361f5dc698
Kodoh/Edabit
/boolList.py
450
3.640625
4
def to_boolean_list(word): word = word.lower() valuelist = [] bina = [] YesNo = [] for i in word: valuelist.append(ord(i)-96) for x in valuelist: if x % 2 != 0: bina.append(1) else: bina.append(0) for e in bina: if e == 0: YesNo.append(False) else: YesNo.append(True) return YesNo print(to_boolean_list("rat"))
f9d47f85762c6f41b58d0c364c99daed2cbb712b
sagarchand9/Multiuser_Chat
/client/client.py
2,428
3.984375
4
# Python program to implement client side of chat room. import socket import select import sys server1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if len(sys.argv) != 4: print "Correct usage: script, IP address, port number, username:password" exit() userpass = str(sys.argv[3]) #passname = str(sys.argv[4]) if not len(userpass.split(":",1)) == 2: print "wrong format for user name and password" exit(0) IP_address = str(sys.argv[1]) Port = int(sys.argv[2]) server1.connect((IP_address, Port)) server1.send(userpass) #print server1 #i = 1 while True: # maintains a list of possible input streams sockets_list = [sys.stdin, server1] """ There are two possible input situations. Either the user wants to give manual input to send to other people, or the server is sending a message to be printed on the screen. Select returns from sockets_list, the stream that is reader for input. So for example, if the server wants to send a message, then the if condition will hold true below.If the user wants to send a message, the else condition will evaluate as true""" read_sockets,write_socket, error_socket = select.select(sockets_list,[],[]) for socks in read_sockets: #print str(socks) + " " + str(i) if socks == server1: message = socks.recv(2048) #print "message length" + str(len(message)) if len(message) == 0: print "Connection closed\n" server1.close() exit(0) elif message == "-1##": print "Authentication failure\n" server1.close() exit(0) elif(len(message)<5): print "Try after " + str(message) + " seconds" server1.close() exit(0) elif(message=="logout"): print "User logged out" server1.close() exit(0) elif(message=="User is already online"): print "User is already online" server1.close() exit(0) print message else: #server1.send(userpass) message = sys.stdin.readline() server1.send(message) sys.stdout.write("<You>") sys.stdout.write(message) sys.stdout.flush() #i += 1 server1.close()
91a5122f9957141be0966121bf67ac11ae2a2f22
Pranitha-J-20/Fibonacci
/Fibonacci series.py
306
4.21875
4
num=int(input("enter the number of terms: ")) n1=0 n2=1 count=0 if num<=0: print("enter a positive integer") elif num==1: print('fibonacci seies: ',n1) else: print("fibonacci series: ") while count<num: print(n1) nth=n1+n2 n1=n2 n2=nth count=count+1
cd3b754dbe9309c766f99833b8f7e41da6ea4702
Martoxdlol/programacion
/algo1/parcial1/ej2.py
1,814
3.6875
4
# Escribir una funcion `dar_vuelta` que reciba una lista de tuplas de numeros y que # devuelva una nueva lista de tuplas, donde la primer tupla tendra el primer elemento # de todas las tuplas originales; la segunda, los segundos, etc. # Ejemplo: # [(1,2,3), (4,5), (6,), (7,8,9,10)] # => # [(1,4,6,7), (2,5,8), (3,9), (10,)] # Nota: las tuplas originales no tienen todas la misma cantidad de elementos entre sí. # Ayuda: Una tupla de un solo elemento se puede crear de la forma `t = (elem,)` # Escribir debajo de este comentario el código del ejercicio def dar_vuelta(lista): maxlen = max(map(len, lista)) resultado = [] for posicion_en_tupla in range(maxlen): lista_temporal = [] for tupla in lista: if posicion_en_tupla < len(tupla): lista_temporal.append(tupla[posicion_en_tupla]) resultado.append(tuple(lista_temporal)) return resultado # Pruebas l_inicial = [(1,2,3), (4,5), (6,), (7,8,9,10)] l_esperada = [(1,4,6,7), (2,5,8), (3,9), (10,)] l_resultado = dar_vuelta(l_inicial) for i in range(len(l_esperada)): assert list(l_esperada[i]) == list(l_resultado[i]) # Explicacion de pensamiento # La lista resultante va a tener de largo lo mismo que la cantidad maxima de valores que tenga alguna de las tuplas. # Ej: [(1,2,3),(4,5),(6,7,8,9)] ; la lista resultante va a tener 4 items de largo porque la tercer tupla tiene 4 valores y es la que mas tiene # Cada item de la lista resultante va a tener un indice (la posicion en la que esta en la lista). Este indice corresponde al indice en cada tupla de la lista original # Ej: entada = [ ( 1 , 2 ) , ( 3 , 4 ) ] resultante = [ (1,3) , (3,4) ] # indice 0 ^ ^ indice 1 indice 0 ^ ^ indice 1 indice 0 ^ ^ indice 1
1ade809b4e80d779f5b09cf5b03bf018519f2788
Martoxdlol/programacion
/algo1/tp1/main.py
11,350
3.59375
4
import sudoku import random from mapas import MAPAS TEST_MODE = False #Esta linea sirve para desactivar test (ver final del archivo) <<<<<<<<<<<<<<<<<<<<<<< COLOR_REST = "\x1b[0m" COLOR_INPUT = "\x1b[36m" COLOR_ROJO = "\x1b[31m" COLOR_VERDE = "\x1b[32m" INSTRUCCIONES = ('','valor','borrar','salir') DESACTIVAR_COLORES = False #Esta linea sirve para desactivar los colores (no esta bien modificar constantes pero 🤷‍♂️) <<<<<<<<<<<<<<<<<<<<<<< if DESACTIVAR_COLORES: COLOR_REST = "" COLOR_INPUT = "" COLOR_ROJO = "" COLOR_VERDE = "" #Estoy modificando constantes pero en realidad este comportamiento no depende en absoluto de la ejecucion del programa #y no hay ninguna logica del mismo arriba tampoco asi que no me parece mal hacerlo #Solo se estan cambiando al inicio de todo una sola vez antes de que pase nada MENSAJE_INICIAL = COLOR_INPUT+"¿Qué desea hacer?"+COLOR_REST MENSAJE_SIN_MOVIMIENTOS = COLOR_ROJO+"¡Cuidado, no hay movimientos posibles! Vas a tener que cambiar algo"+COLOR_REST MENSAJE_TERMINO = COLOR_VERDE+"¡Terminó el sudoku!"+COLOR_REST INSTRUCCIONES_DEL_JUEGO = f"""{COLOR_VERDE}Reglas del sudoku{COLOR_REST} Regla 1: hay que completar las casillas vacías con un solo número del 1 al 9 Regla 2: en una misma fila no puede haber números repetidos Regla 3: en una misma columna no puede haber números repetidos Regla 4: en una misma región no puede haber números repetidos Regla 5: la solución de un sudoku es única ¿Como jugar? Ingrese la acción a realizar con el nombre de la accion ej: 'instruccion: {COLOR_INPUT}valor{COLOR_REST}' o el número ej: 'instruccion: {COLOR_INPUT}1{COLOR_REST}': Ej: {COLOR_INPUT}valor a2 8{COLOR_REST} Ej: {COLOR_INPUT}valor{COLOR_REST}, posicion: {COLOR_INPUT}8B{COLOR_REST} valor: {COLOR_INPUT}5{COLOR_REST} Ej: {COLOR_INPUT}1 A1{COLOR_REST}, valor: {COLOR_INPUT}4{COLOR_REST} """ PLANTILLA_SUDOKU = """ 1 2 3 4 5 6 7 8 9 ╔═══════╦═══════╦═══════╗ a ║ {} {} {} ║ {} {} {} ║ {} {} {} ║ a b ║ {} {} {} ║ {} {} {} ║ {} {} {} ║ b c ║ {} {} {} ║ {} {} {} ║ {} {} {} ║ c ╠═══════╬═══════╬═══════╣ d ║ {} {} {} ║ {} {} {} ║ {} {} {} ║ d e ║ {} {} {} ║ {} {} {} ║ {} {} {} ║ e f ║ {} {} {} ║ {} {} {} ║ {} {} {} ║ f ╠═══════╬═══════╬═══════╣ g ║ {} {} {} ║ {} {} {} ║ {} {} {} ║ g h ║ {} {} {} ║ {} {} {} ║ {} {} {} ║ h i ║ {} {} {} ║ {} {} {} ║ {} {} {} ║ i ╚═══════╩═══════╩═══════╝ 1 2 3 4 5 6 7 8 9 """ PREGUNTA_INPUT_EN_JUEGO = """Instrucciones 1. valor | Ingresar un valor 2. borrar | Borar un valor 3. salir | Salir del programa Instrucción: """ PREGUNTA_INPUT_INICIAL = """Instrucciones 1. nuevo | Iniciar nuevo juego 2. salir | Salir del programa Instrucción: """ def borrar_consola(): print('\033c') #lo saqué de internet, imprime un caracter especial en unicode que supongo limpia la consola print(COLOR_REST) def obtener_texto_sudoku(sudoku_actual, sudoku_inicial): lista_numeros = [] for fila in range(0,9): for columna in range(0,9): numero_cadena = '' if sudoku_inicial[fila][columna] == sudoku.VACIO: #Agregar color si es un valor nuevo que NO está en el original numero_cadena += COLOR_INPUT if sudoku_actual[fila][columna] != sudoku.VACIO: #Agregar numero a la lista numero_cadena += str(sudoku_actual[fila][columna]) else: numero_cadena += ' ' numero_cadena += COLOR_REST lista_numeros.append(numero_cadena) return PLANTILLA_SUDOKU.format(*lista_numeros) def obtener_input_inicial(): return input(PREGUNTA_INPUT_INICIAL).strip().lower() def obtener_input_en_juego(): return input(PREGUNTA_INPUT_EN_JUEGO).strip().lower() def es_del_original(sudoku_inicial, fila, columna): if sudoku_inicial[fila][columna]: return True return False def obtener_valor_posicion(valor = None): #Ej b4 -> 1,3 #Ej A1 -> 0,0 #Ej 5a -> 1,4 #Es lo mismo mayuscula/minuscula y si primero letra o primero número posicion = valor or input("Valor a modificar (ej: A1): ").strip().lower() fila = -1 columna = -1 if len(posicion) != 2: return False if posicion[0].isdigit(): columna = int(posicion[0]) - 1 fila = ord(posicion[1]) - 97 #Convierte el valor de la letra en la tabla ascii a numero y le resta lo necesario para que quede la 'a' en la posicion 0 elif posicion[1].isdigit(): columna = int(posicion[1]) - 1 fila = ord(posicion[0]) - 97 if fila < 0 or fila > 8: return False if columna < 0 or columna > 8: return False return (fila,columna) def obtener_numero(s, valor = None): valor = valor or input(s).strip() if len(valor) != 1 or not valor.isdigit() or valor == '0': return False return int(valor) def procesar_instruccion(instruccion,sudoku_actual,sudoku_inicial): instruccion_lista = instruccion.split(' ') instruccion = instruccion_lista[0] parametro1 = len(instruccion_lista) > 1 and instruccion_lista[1] parametro2 = len(instruccion_lista) > 2 and instruccion_lista[2] if len(instruccion) == 1 and instruccion.isdigit(): instruccion = INSTRUCCIONES[int(instruccion)] if instruccion == 'salir': exit() elif instruccion == 'valor': return instruccion_insertar(instruccion,sudoku_actual,sudoku_inicial,parametro1,parametro2) elif instruccion == 'borrar': return instruccion_borrar(instruccion,sudoku_actual,sudoku_inicial,parametro1,parametro2) else: return sudoku_actual,COLOR_ROJO+'Ingrese una instrucción válida'+COLOR_REST def instruccion_insertar(instruccion,sudoku_actual,sudoku_inicial,parametro1,parametro2): posicion = obtener_valor_posicion(parametro1) #Obtener/pedir posicion if posicion == False: #Comprobar posicion validad return sudoku_actual,COLOR_ROJO+'Posición incorrecta'+COLOR_REST if es_del_original(sudoku_inicial, *posicion): #Comprobar posicion que no sea del original return sudoku_actual,COLOR_ROJO+'Posición incorrecta'+COLOR_REST nuevo_valor = obtener_numero("Nuevo valor: ", parametro2) if nuevo_valor == False: return sudoku_actual,COLOR_ROJO+'Valor inválido'+COLOR_REST if not sudoku.es_movimiento_valido(sudoku_actual,posicion[0],posicion[1],nuevo_valor): return sudoku_actual,COLOR_ROJO+'Movimiento inválido'+COLOR_REST nuevo_sudoku = sudoku.insertar_valor(sudoku_actual,posicion[0],posicion[1],nuevo_valor) return nuevo_sudoku,MENSAJE_INICIAL def instruccion_borrar(instruccion,sudoku_actual,sudoku_inicial,parametro1,parametro2): posicion = obtener_valor_posicion(parametro1) #Obtener/pedir posicion if posicion == False: #Comprobar posicion validad return sudoku_actual,COLOR_ROJO+'Posición incorrecta'+COLOR_REST if es_del_original(sudoku_inicial, *posicion): #Comprobar posicion que no sea del original return sudoku_actual,COLOR_ROJO+'Posición incorrecta'+COLOR_REST nuevo_sudoku = sudoku.borrar_valor(sudoku_actual,posicion[0],posicion[1]) return nuevo_sudoku,MENSAJE_INICIAL def mapa_ramdom(): return random.choice(MAPAS) def crear_sudokus(): mapa = mapa_ramdom() if TEST_MODE: mapa = MAPAS[29] sudoku_inicial = sudoku.crear_juego(mapa) sudoku_actual = sudoku.crear_juego(mapa) return sudoku_inicial,sudoku_actual def main(): sudoku_inicial = None sudoku_actual = None jugando = False mensaje = MENSAJE_INICIAL while True: borrar_consola() if sudoku_actual: texto_sudoku = obtener_texto_sudoku(sudoku_actual,sudoku_inicial) print(texto_sudoku) #Mostrar sudoku else: print(INSTRUCCIONES_DEL_JUEGO) #Mostrar instrucciones del juego por única vez #Comprobar si se terminó el sudoku if jugando and sudoku.esta_terminado(sudoku_actual): mensaje = MENSAJE_TERMINO jugando = False #Comprobar si hay movimientos posibles elif jugando and not sudoku.hay_movimientos_posibles(sudoku_actual): if mensaje == MENSAJE_INICIAL: mensaje = "" else: mensaje += "\n" mensaje += MENSAJE_SIN_MOVIMIENTOS print(mensaje) #Mostrar mensaje if jugando: instruccion = obtener_input_en_juego() #Mostrar y pedir instruccion nuevo_sudoku,mensaje = procesar_instruccion(instruccion,sudoku_actual,sudoku_inicial) sudoku_actual = nuevo_sudoku else: instruccion = obtener_input_inicial().lower().strip() #Mostrar y pedir instruccion if instruccion == 'nuevo' or instruccion == '1': sudoku_inicial,sudoku_actual = crear_sudokus() jugando = True mensaje = MENSAJE_INICIAL if instruccion == 'salir' or instruccion == '2': exit() main() """ TEST Solucion MAPAS[29] #nota: para probar si no hay movimientos posibles usar valor A2 8 valor A2 9 valor A3 8 valor A4 1 valor A5 7 valor A6 5 valor A7 6 valor A8 4 valor A9 3 valor B1 6 valor B2 5 valor B3 7 valor B4 3 valor B5 9 valor B6 4 valor B7 1 valor B8 2 valor B9 8 valor C1 1 valor C2 3 valor C3 4 valor C4 2 valor C5 8 valor C6 6 valor C7 5 valor C8 7 valor C9 9 valor D1 8 valor D2 2 valor D3 1 valor D4 6 valor D5 4 valor D6 9 valor D7 7 valor D8 3 valor D9 5 valor E1 5 valor E2 7 valor E3 3 valor E4 8 valor E5 2 valor E6 1 valor E7 4 valor E8 9 valor E9 6 valor F1 4 valor F2 6 valor F3 9 valor F4 7 valor F5 5 valor F6 3 valor F7 2 valor F8 8 valor F9 1 valor G1 3 valor G2 1 valor G3 2 valor G4 4 valor G5 6 valor G6 8 valor G7 9 valor G8 5 valor G9 7 valor H1 7 valor H2 8 valor H3 5 valor H4 9 valor H5 1 valor H6 2 valor H7 3 valor H8 6 valor H9 4 valor I1 9 valor I2 4 valor I3 6 valor I4 5 valor I5 3 valor I6 7 valor I7 8 valor I8 1 // JAVASCRIPT // PROBADOR AUTOMATICO DE SUDOKUS // ENTRAR A: http://www.sudokumania.com.ar/sm1/sudoku-solucionar/solucionar.php // LLENAR Y RESOLVER // TOCAR F12 o click derecho inspeccionar elemento // Buscar la opcion que dice Console // Pegar este código y darle a enter //(si, lo hice yo el código) let rows = document.querySelector('table.tabla').children[0].children let instructions = '' let y = 0 let letras = ['A','B','C','D','E','F','G','H','I'] for(const row of rows){ let x = 1 for(cell of row.children){ const valor = cell.children[0].value const fila = y+"" const columna = x+"" const letra_fila = letras[y] const letra_columna = letras[x] //ESTA LINEA ES LA QUE HAY QUE CAMBIAR PARA QUE ANDE SEGUN EL MODELO DE SUDOKU instructions += "valor "+letra_fila+columna+" "+valor //FIN DE ESA LINEA instructions += '\n' x++ } y++ } console.log(instructions) """
3945a03fd8a7ee3aeddafb8ea7e6297be0ea720e
maigahurairah15/Hurairah-GWC-2018
/data_2.py
508
3.546875
4
import json from pprint import pprint # Open a json file and append entries to the file. f = open("allanswers.json", "r") data = json.load(f) print(type(data)) print(data) f.close() count = 0 oppcount = 0 count_2 = 0 for d in data: if d['color'] == "red": count += 1 elif d['color'] == "blue": count_2 += 1 else: oppcount += 1 print("number of red:" + str(count)) print("number of blue:" + str(count_2)) print("number of others:" + str(oppcount))
8a611b9924a63e2184b0476e88e2b3298a5468f8
sayan1995/Trees-2
/problem2.py
1,097
3.625
4
''' Time Complexity: O(n) Space Complexity: O(n) Did this code successfully run on Leetcode : Yes Explanation: Iterate through the tree until you reach the leaf node, while iterating through till the leaf create the number. Once you reach the leaf node add the number to the variable sum. Do this for left and right, return sum ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def __init__(self): self.sum = 0 def helper(self, root: TreeNode, sum1: int, val: int) -> int: if root == None: self.sum = self.sum + 0 return if root.left == None and root.right == None: self.sum = self.sum + ((val * 10) + root.val) else: self.helper(root.left, self.sum, (val * 10) + root.val) self.helper(root.right, self.sum, (val * 10) + root.val) def sumNumbers(self, root: TreeNode) -> int: result = 0 self.helper(root, result, 0) return self.sum
fbf0c2db1a6db137d0248bcde62f2df6f0a88124
WorleyD/Small-Scripts
/pauleigon.py
174
3.546875
4
N, paul, opp = input().split() N, paul, opp = int(N), int(paul), int(opp) turn = (paul + opp) // N if turn % 2 == 0: print("paul") else: print("opponent")
557dd823f5842595cf89e5913043fe2de6b19efb
vishwasbeede/Python3-Programs-examples
/Guess_number.py
1,052
3.9375
4
#Used random module to select a number from your input and this will match to yours input import random list_int = [] char_sep='-' for i in range(0,6): list_int.append(i) print ("{:<30} {} ".format(" ",(char_sep*100))) print ("\n\n{:<30} Enter charecters for input to stop execution\n\n".format(" ")) print ("{:<30} Enter numbers in range of 1 to 5 \n\n".format(" ")) print ("{:<30} {} \n\n".format(" ",(char_sep*100))) while True: # user_input = input("Would you like to play? (Y/n):") user_number = random.choice(list_int) # if user_input == "n": # break try: user_input_guess=int(input("Enter the number you guess: ")) except: print ("{:<30}Enter only numbers as input charecters".format("")) print ("{:<30}Stopping execution".format("")) exit(1) if user_number == user_input_guess: print ("{:<30}Congratulations guessed number correctly!!!!".format(" ")) else: print ("{:<30}Sorry!!, you need to guess {}".format(" ",user_number))
15e37aae65af448243383d67e58968662a563b11
kaczy-code/qpbe3e
/exercise_answers/word_count/cleaning.py
592
3.625
4
# cleaning.py from word_count.exceptions import EmptyStringError punct = str.maketrans("", "", "!.,:;-?") def clean_line(line): """changes case and removes punctuation""" # raise exception if line is empty if not line.strip(): raise EmptyStringError() # make all one case cleaned_line = line.lower() # remove punctuation cleaned_line = cleaned_line.translate(punct) return cleaned_line def get_words(line): """splits line into words, and rejoins with newlines""" words = line.split() return "\n".join(words) + "\n"
36c2198e5cd512b4fd029ee0c0ca148ffec6ca74
FDELTA/data-investments-analysis
/src/operaciones.py
1,907
3.609375
4
def price_distribution(df, x): ''' Esta función esta diseñada para recibir uno de los cinco barrios de NY y te devuelve su distribución por precios ''' import seaborn as sns import matplotlib.pyplot as plt print('Please select the neighbourhodod: ') x=input() df1 = df[df.neighbourhood_group == x][["neighbourhood","price"]] d = df1.groupby("neighbourhood").mean() sns.distplot(d) return plt.show() def data_zone(df, x, y): ''' Esta función esta diseñada para recibir o bien price o bien avialablity_365 y retornar un gráfico térmico ''' import seaborn as sns import matplotlib.pyplot as plt card = df[df[x]< y] card.plot(kind='scatter', x='longitude', y='latitude',c=x, cmap=plt.get_cmap('jet'), colorbar=True, alpha=0.4) def pie_chart_price_availability(df, x): ''' Esta función esta diseñada para recibir o bien price o bien availability_365 y devolver el porcentaje en sus rangos ''' import seaborn as sns import matplotlib.pyplot as plt a = df[df[x]<=90].count()[0] b = df[(df[x]>90) & (df[x]<=180)].count()[0] c = df[(df[x]>180) & (df[x]<=270)].count()[0] d = df[(df[x]>270)].count()[0] labels = 'Less than 90','Between 90 & 180','Between 180 & 270','Greater than 270' sizes = a,b,c,d explode = (.1,.1,.1,.1) availability_pie = plt.pie(sizes,labels=labels,explode=explode,shadow=True,startangle=90,autopct='%1.1f%%',radius=1.1) plt.title('Calendar Year 2019') def plot_bar(df,y): ''' Esta función recibe un DataFrame y devuelve un plot bar al que puedes nombrar tanto los ejes como el título ''' import seaborn as sns import matplotlib.pyplot as plt plt.bar(x=y.index, height=y, alpha=.7) print('Enter the title of the chart: ') z= input() print('Enter the ylabel: ') n= input() print('Enter the xlabel: ') h= input() plt.title(z, color='red', fontsize=15) plt.ylabel(n, color='blue', fontsize=13) plt.xlabel(h,color='blue', fontsize=13)
f116c26e1ee37fb0b6418ca6391c606f1dba882f
helen5haha/pylee
/string/StringtoInteger.py
2,132
4.0625
4
''' Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. Requirements for atoi: The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value. The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function. If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed. If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned. ''' max_int_bits = 32 max_int_str = str(pow(2, max_int_bits - 1) - 1) min_int_str = str(pow(2, max_int_bits - 1)) # abs value, without sign max_int_len = len(max_int_str) min_int_len = len(min_int_str) def atoi(str): len_s = len(str) if 0 == len_s: return 0 index = 0 while index < len_s and ' ' == str[index]: index += 1 sign = 1 if index < len_s: if '+' == str[index]: sign = 1 index += 1 elif '-' == str[index]: sign = -1 index += 1 value = 0 val_str = '' for i in range(index, len_s): ch = str[i] if ch >= '0' and ch <= '9': val_str += ch if len(val_str) > max_int_len or len(val_str) > min_int_len: return int(max_int_str) if 1 == sign else -int(min_int_str) if len(val_str) >= max_int_len and val_str > max_int_str: return int(max_int_str) if 1 == sign else -int(min_int_str) value = value * 10 + ord(ch) - ord('0') index += 1 else: break return value * sign atoi("1234")
523de77dc6cfa1910c76b666b90ef7dd7795d609
helen5haha/pylee
/number/PlusOne.py
676
3.84375
4
# Given a non-negative number represented as an array of digits, plus one to the number. # The digits are stored such that the most significant digit is at the head of the list. ''' Use a int array to represent the number, leftest is the highest bit. Space complexity O(1) - Time complexity O(N) Like 99, 999, please remember to insert 1 in the leftest position ''' def plusOne(digits): len_s = len(digits) carry = 1 for i in range(len_s - 1, -1, -1): total = digits[i] + carry digit = int(total % 10) carry = int(total / 10) digits[i] = digit if 1 == carry: digits.insert(0,1) return digits n = [9,0,9] plusOne(n)
3e687a4ef9403cd1ab70b4d5e7a349f9d8dfb1cb
helen5haha/pylee
/game/EditDistance.py
1,039
3.984375
4
# Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. # Each operation(insert/delete/replace a character is counterd as 1 step) # Classical Dynamical Planning. Most DP problems can be optimized for space complexity. def minDistance(word1, word2): if "" == word1 and "" == word2: return 0 elif "" == word1: return len(word2) elif "" == word2: return len(word1) len1 = len(word1) len2 = len(word2) arr1 = [0 for y in range(0, len1 + 1)] arr2 = [0 for y in range(0, len1 + 1)] arr1[0] = 0 for y in range(1, len1 + 1): arr1[y] = y for x in range(1, len2 + 1): arr2[0] = x for y in range(1, len1 + 1): arr2[y] = min(arr1[y - 1] + (0 if (word1[y - 1] == word2[x - 1]) else 1), arr1[y] + 1, arr2[y - 1] + 1) tmp = arr1 arr1 = arr2 arr2 = tmp for y in range(0, len1 + 1): arr2[y] = 0 return arr1[len1] w1 = "hello" w2 = "world" minDistance(w1, w2)
4e8bd8aaa604889745c461244c773a9ca8fc24b4
helen5haha/pylee
/game/Candy.py
1,238
3.921875
4
''' There are N children standing in a line. Each child is assigned a rating value. You are giving candies to these children subjected to the following requirements: Each child must have at least one candy. Children with a higher rating get more candies than their neighbors. What is the minimum candies you must give? Greedy Algorithm: Initialize an array with size N, all elements are 1, indicating every has at least one candy. Then perform two round greedy processes: First traverse from left to right, if one ranks higher than its left, then it has one more candy than its left Second traverse from right to left, if one ranks higher than its right, then it has at least one more candy than its right. (If one already has more candies than its right, then we need to do nothing) ''' def candy(ratings): len_r = len(ratings) if len_r <= 1: return len_r candys = [1] * len_r candys[0] = 1 candys[len_r - 1] = 1 for i in range(1, len_r): if ratings[i] > ratings[i - 1]: candys[i] = candys[i - 1] + 1 for i in range(len_r - 2, -1, -1): if ratings[i] > ratings[i + 1]: candys[i] = max(candys[i + 1] + 1, candys[i]) return sum(candys) r = [1,2,3,4] candy(r)
11e398caeba36ad2cf970e7e9d96067ebc9c203d
helen5haha/pylee
/game/GasStation.py
1,358
3.953125
4
''' There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations. Return the starting gas station's index if you can travel around the circuit once, otherwise return -1. Note: The solution is guaranteed to be unique. Greedy Algorithm: we keep an array to record the remaining(current + added - to consume) gas for each station. For a ok route, whatever station car is at, its remaining gas should not be less than 0 ''' def canCompleteCircuit(gas, cost): len_remain = len(gas) remain = [x for x in gas] # init for i in range(0, len_remain): remain[i] -= cost[i] total = 0 start = 0 prefix_min = 0 prefix_tot = 0 is_find = False for i in range(0, len_remain): prefix_tot += remain[i] if prefix_tot < prefix_min: prefix_min = prefix_tot total += remain[i] if total < 0: start = i + 1 total = 0 continue elif len_remain - 1 == i and total + prefix_min >= 0: is_find = True break return start if is_find else -1 gas = [1,3,5,1] cost = [1,1,1,1] canCompleteCircuit(gas,cost)
d7712ac2adbb87b2fa2e55da4608bbb8a27d095d
helen5haha/pylee
/tree/SumRoottoLeafNumbers.py
2,119
4.09375
4
# Given a binary tree containing digits from 0-9 only, each root-to-lead path could represent a number. # An example is the root-to-leaf path 1->2->3 which represents the number 123. Find the total sum of all root-to-leaf numbers ''' For example, 1 / \ 2 3 The root-to-leaf path 1->2 represents the number 12. The root-to-leaf path 1->3 represents the number 13. Return the sum = 12 + 13 = 25. Search Algorithm can be used to find at least one solution(DFS or BFS) or all solutions. To find all solutions, there are two ways: from bottom to top and from top to bottom ''' class TreeNode: def __init__(self, value): self.val = value self.left = None self.right = None def insertLeft(self, node): if self.left == None: self.left = TreeNode(node) else: t = TreeNode(node) t.left = self.left self.left = t def insertRight(self, node): if self.right == None: self.right = TreeNode(node) else: t = TreeNode(node) t.right = self.right self.right = t # From bottom to top def doSumNumbers1(root, val): if None == root.left and None == root.right: return val * 10 + root.val left = 0 right = 0 if None != root.left: left = doSumNumbers1(root.left, val * 10 + root.val) if None != root.right: right = doSumNumbers1(root.right, val * 10 + root.val) return left + right def sumNumbers1(root): if None == root: return 0 return doSumNumbers1(root, 0) # From top to bottom sum = 0 def doSumNumbers2(root, val): global sum if None == root.left and None == root.right: sum += val * 10 + root.val if None != root.left: doSumNumbers2(root.left, val * 10 + root.val) if None != root.right: doSumNumbers2(root.right, val * 10 + root.val) def sumNumbers2(root): if None == root: return 0 doSumNumbers2(root, 0) return sum r = TreeNode(3) r.insertLeft(9) r.insertRight(20) r.right.insertLeft(15) r.right.insertRight(7) sumNumbers2(r)
b82e275828c10a818ba3c653e59f76ab12a128f5
helen5haha/pylee
/array/RemoveDuplicatesfromSortedArray.py
721
4
4
''' Given a sorted array, remove the duplicates in place such that each element appear onlyonce and return the new length. Do not allocate extra space for another array, you must do this in place with constant memory. For example, Given input array A = [1,1,2], Your function should return length = 2, and A is now [1,2]. Note the operation on index to avoid removing all later elements everytime ''' def removeDuplicates(A): if None == A: return 0 len_A = len(A) if len_A <= 1: return len_A m = 0 n = 1 while n < len_A: if A[m] != A[n]: m += 1 if m != n: A[m] = A[n] n += 1 return m + 1 A = [1,1,2] removeDuplicates(A)
b4c8c18405a914afecee69a0d7f55f57bca6aed5
helen5haha/pylee
/game/CountandSay.py
1,012
4.15625
4
''' The count-and-say sequence is the sequence of integers beginning as follows: 1, 11, 21, 1211, 111221, ... 1 is read off as "one 1" or 11. 11 is read off as "two 1s" or 21. 21 is read off as "one 2, then one 1" or 1211. Given an integer n, generate the nth sequence. Note: The sequence of integers will be represented as a string. Every round, when encounter a different char then stop the count of this round. Please note that the last round, because it encounters the end of the string, so we have to force stop the round ''' def doCountAndSay(src): char = src[0] num = 0 result = "" for c in src: if char == c: num += 1 else: result += (str(num) + char) char = c num = 1 result += (str(num) + char) return result def countAndSay(n): if 0 == n: return "" elif 1 == n: return "1" result = "1" for i in range(1,n): result = doCountAndSay(result) return result countAndSay(4)
84806db8304b6bb9b25f9aced5bcb078492bae2a
helen5haha/pylee
/matrix/SpiralMatrix.py
827
4.21875
4
''' Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. For example, Given the following matrix: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] You should return [1,2,3,6,9,8,7,4,5]. ''' def spiralOrder(matrix): m = len(matrix) if 0 == m: return [] n = len(matrix[0]) if 0 == n: return [] arr = [] round = (min(m,n) + 1) / 2 for x in range(0, round): for y in range(x, n-x): arr.append(matrix[x][y]) for y in range(x+1, m-x-1): arr.append(matrix[y][n-x-1]) if m - 2*x > 1: for y in range(n-x-1, x-1, -1): arr.append(matrix[m-x-1][y]) if n - 2*x > 1: for y in range(m-x-2, x, -1): arr.append(matrix[y][x]) return arr
2f9bec07df890c4216fa7d1c54b4213bd31a22e4
Keerthanavikraman/Luminarpythonworks
/data collections/List/duplicate_elements.py
116
3.671875
4
a=[4,5,7,8,7,9,5,4,90,86,2] b=[] for i in a: if i not in b: b.append(i) else: print( i )
0b7d12e99bbad7b7b9b528ed1983782b2e756027
Keerthanavikraman/Luminarpythonworks
/recursion/pattern_prgming4.py
358
3.890625
4
# 1 # 1 2 # 1 2 3 # 1 2 3 4 # 1 2 3 4 5 # n=int(input("enter the number of rows")) # for i in range(0,n+1): # for j in range(1,i+1): # print(j,end="") # print() # def pattern(n): num=1 for i in range(0,n): num=1 for j in range(0,i+1): print(num,end="") num=num+1 print() pattern(5)
4ec2b5c6f100707445748efb5d938974db71abe7
Keerthanavikraman/Luminarpythonworks
/functional_prgming/filter_lessthan250.py
476
3.640625
4
#print all product details available below 250 products=[ {"item_name":"boost","mrp":290,"stock":50}, {"item_name":"complan","mrp":280,"stock":0}, {"item_name":"horlicks","mrp":240,"stock":40}, {"item_name":"nutrella","mrp":230,"stock":30}, {"item_name":"chocos","mrp":250,"stock":80} ] # for product in products: # if product["mrp"]<250: # print(product) # lessthan=list(filter(lambda product:product["mrp"]<250,products)) print(lessthan)
d0618c2aed8bfbf1c657d1448b09ca6d4467cbb5
Keerthanavikraman/Luminarpythonworks
/recursion/pattern_prgming5.py
155
3.828125
4
# 1 # 22 # 333 # 4444 # 55555 n=int(input("enter the number of rows")) for i in range(n+1): for j in range(i): print(i,end="") print()
5005b088869cc007756d7d590cb1d6e79537f086
Keerthanavikraman/Luminarpythonworks
/flowofcontrols/decision_making.py
107
3.515625
4
# if(condition): # code1 # else: # code2 a=-10 if a>0: print("hello") else: print("in else")
d4c77a5c80995e28f9e9a8f73fba025e8c8bee1f
Keerthanavikraman/Luminarpythonworks
/data collections/dictionary/count.py
622
3.734375
4
# def word_count(str): # counts=dict() # words=str.split() # # for word in words: # if word in counts: # counts[word]+=1 # else: # counts[word]=1 # return counts # print(word_count("hhy hy hlo hlo hy")) count={} data="hello hai hello" words=data.split(" ") for i in words: if i not in count: count.update({i:1}) else: val=int(count[i]) val+=1 count.update({i:val}) print(count) str=input(" >") words=str.split(" ") dict={} for i in words: count=words.count(i) dict.update({i:count}) #print(i,count) print(dict)
a739553149e1cc887b9f6508bee62fde6472fdc3
Keerthanavikraman/Luminarpythonworks
/data collections/List/diff_btw_append_extend.py
126
4.15625
4
lst=[1,2,3] b=[4,5,6] lst.append(b) print(lst) #output is a nested element lst=[1,2,3] b=[4,5,6] lst.extend(b) print(lst)
d87fc10983d97f15e84252a5155f5c0a850d69f8
Keerthanavikraman/Luminarpythonworks
/data collections/tuple/basics_tuple.py
505
4.03125
4
# tup=(1,2,3,4,5,6,7,8,9) # print(tup) # print(type(tuple)) ## tuple is immutable #### heterogeneous ## indexing possible ## updation not possible ## tuple unpacking is also possible # empty tuple # tup2=() # print(tup2) # print(type(tup2)) # tup=(1,2,3,4,5,6,7,8,9) # print(tup) # print("max value",max(tup)) # print("min value",min(tup)) # print("len",len(tup)) #heterogeneous # tup=1,"hello",5.9 # print(tup) # indexing possible # tup=1,"hello",5.9 # print(tup) # print(tup[1]) # print(tup[-1])
4ce0c09c5ab4259249dd4e70d6f52f4eb54795a8
Keerthanavikraman/Luminarpythonworks
/exception/exception_rise.py
153
3.859375
4
no1=int(input("enter")) #6 no2=int(input("enter")) #6 if no1==no2: raise Exception("two numbers are same") else: print(no1+no2) #error
651e3f37f2518814b84f00267e6050bf29870030
Keerthanavikraman/Luminarpythonworks
/data collections/sets/prime_noprime.py
291
3.859375
4
sett={1,2,3,4,5,6,7,8,9,23,44,56} prime=set() nonprime=set() for i in sett: if i>1: for j in range(2,i): if(i%j)==0: nonprime.add(i) break else: prime.add(i) print("prime set",prime) print("nonprime set",nonprime)
e85f71a5945dae83f2dc0228d4c7e8727d9eb708
Keerthanavikraman/Luminarpythonworks
/oop/ex1.py
621
3.84375
4
#create a child class that will inherit all of the variables and methods of vehicle class class Vehicle: def vdetails(self, model, mileage, max_speed): self.model = model self.mileage = mileage self.max_speed = max_speed print(self.model, self.mileage, self.max_speed) class Car(Vehicle): def cdetails(self,color,regno): self.color = color self.regno = regno print(self.color, self.regno) car1 = Car() car1.vdetails("jeep", 20, 100) car1.cdetails("black","KL25J6201") car2=Car() car2.vdetails("range rover",30,150) car2.cdetails("white","KL25K3838")
6a411b630b2bc9e408e32f659dbeddc4a9539672
Keerthanavikraman/Luminarpythonworks
/regular_expression/validnumberss.py
187
3.5
4
import re n= input("enter the number to validate") x='[+][9][1]\d{10}' #x='[+][9][1]\d{10}$' match = re.fullmatch(x,n) if match is not None: print("valid") else: print("invalid")
acc576db7a4d5719d99183a63b4a3765a74a27f2
Keerthanavikraman/Luminarpythonworks
/oop/polymorphism/overriding.py
294
3.703125
4
class Employee: def printval(self,company): self.company=company print("inside employee method",self.company) class Parent(Employee): def printval(self,job): self.job=job print("inside parent method",self.job) pa=Parent() pa.printval("software engineer")
40ae0cbd5a8c49c631f06d5da36cb9e0bd2630f4
Keerthanavikraman/Luminarpythonworks
/pythonprgm/evennbr1,10.py
275
3.96875
4
# for i in range(2,10,2): # print(i) # for num in range(1,10): # if num%2==0: # print(num) # num=num+1 min=int(input("enter the initial range")) max=int(input("enter the maximum range")) for num in range(min,max): if num % 2 == 0: print(num)
5cffad649c630930892fb1bbe38c7c8b6c177b60
Keerthanavikraman/Luminarpythonworks
/oop/polymorphism/demo.py
1,028
4.28125
4
### polymorphism ...many forms ##method overloading...same method name and different number of arguments ##method overriding...same method name and same number of arguments ###method overloading example # class Operators: # def num(self,n1,n2): # self.n1=n1 # self.n2=n2 # print(self.n1+self.n2) # # class Display(Operators): # def num(self,n3): # self.n3=n3 # print(self.n3) # d=Display() # d.num(3) # # class Operators: # def num(self,n1,n2): # self.n1=n1 # self.n2=n2 # print(self.n1+self.n2) # # class Display(Operators): # def num(self,n3): # self.n3=n3 # print(self.n3) # d=Display() # d.num(3,4) ## donot support # ###method overriding example class Person: def printval(self,name): self.name=name print("inside person method",self.name) class Child(Person): def printval(self,class1): self.class1=class1 print("inside child method",self.class1) ch=Child() ch.printval("abc")
f07f7e851fe9d5554686094ba2eaf09d05861ad5
Keerthanavikraman/Luminarpythonworks
/regular_expression/quantifier_valid5.py
263
3.71875
4
#starting with a upper case letter #numbers,lowercase,symbols #Abv5< G6 R. Tt Dhgfhjkhg6t667":';; import re n= input("enter ") x="(^[A-Z]{1}[a-z0-9\W]+)" match = re.fullmatch(x,n) if match is not None: print("valid") else: print("invalid")
f67e50de1830bab59d56667dd875288fa6500a5e
Keerthanavikraman/Luminarpythonworks
/flowofcontrols/switching.py
474
4.0625
4
# string iteration # i="hello world" # for a in i: # print(a) i="hello world" for a in i: if a=="l": print(a) # i="malayalam" # print(i[3]) # for a in i: # if a=="l": # print(a) #### use of break statement inside the loop ### # for val in "string": # if val=="i": # break # print(val) # # print("the end") # for val in "string": # if val=="i": # continue # print(val) # # print("the end") #5 # 1*2*3*4*5
8984188ba1fb9a6b7e363d273ab75a3a3fc1e3de
Keerthanavikraman/Luminarpythonworks
/oop/ex6.py
860
3.921875
4
#create objects of the following file and print details of student with maximum mark? class Student: def __init__(self, name,rollno,course,mark): self.name = name self.rollno= rollno self.course=course self.mark=mark def printval(self): print("name:",self.name) print("age:",self.rollno) print("course:",self.course) print("mark:",self.mark) lst=[] f=open("ex6","r") for i in f: data=i.rstrip("\n").split(",") #print(data) name=data[0] rollno=data[1] course=data[2] mark=data[3] s1=Student(name,rollno,course,mark) #s1.printval() lst.append(s1) #print(lst) mark=[] for st in lst: mark.append(st.mark) print(mark) for st in lst: if(st.mark==max(mark)): print(st.rollno,st.name,st.course,st.mark) print(st.mark) #maximum mark
36201840b24e06c53d728e76cbf250e1695415ca
Keerthanavikraman/Luminarpythonworks
/lamda_function/ex10.py
88
4
4
#lambda function to check a number is even or not? a=lambda num:num%2==0 print(a(5))
9c520d7bd9a72e69d3ea0e21cd800eb4ab8849a4
maiphuong1809/nguyemaiphuong-fundamental-c4t4
/session02/matrix.py
246
3.625
4
# cach1 # print('''*** # *** # *** # *** # ***''') # cach 2 # for i in range(4): # print("***") #cach 3 # for i in range(4): # print("*" *7) for i in range(50): print() for j in range(30): print("* ", end="")
4e003ebe3fcb2e37bca6a838a0a170ba106d1e16
maiphuong1809/nguyemaiphuong-fundamental-c4t4
/session01/btvn_buoi01/btvn2.py
131
3.953125
4
celsius = float(input("Enter the temperature in celsius:")) fahrenheit = celsius*1.8 + 32 print(celsius,"(C) =", fahrenheit," (F)")
1bccbfc421bb7d3acc30b7b1e89f0942db7f1f0e
maiphuong1809/nguyemaiphuong-fundamental-c4t4
/session06/turtle02.py
222
3.75
4
from turtle import* for i in range(4,10): for k in range (i): if k%2 == 1: color("blue") else: color("red") forward(100) left(360/i) mainloop()