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
e498ed4283c63dc47c0772e06389a9e189b5b2d7
betoxedon/CursoPython
/Funções/callable_packing.py
732
3.71875
4
#!/usr/bin/python3 """calcular o preço do produto com o imposto""" def calc_preco_final(preco_bruto, calc_imposto, *params): """calcula o preço final do produtos a partir de parâmetros posicionais. que são indicados através do '*' antes do argumento""" return preco_bruto * (1 + calc_imposto(*params)) def imposto_x(importado): return 0.22 if importado else 0.13 def imposto_y(explosivo, fator_mult=1): return 0.11 * fator_mult if explosivo else 0 if __name__ == '__main__': preco_bruto = 134.98 preco_final = calc_preco_final(preco_bruto, imposto_x, True) preco_final = calc_preco_final(preco_final, imposto_y, True, 1.5) print(f'O preço final do produto será R$: {preco_final}')
069f7da88df8724e108c799d46a57686c2e3e703
betoxedon/CursoPython
/Programação_Funcional/funcoes_imutabilidade_v2.py
471
3.765625
4
#!/usr/bin/python3 from functools import reduce from operator import add # utilizando tuplas onde os valores não podem ser mudados # pode ser uma solução para a imutabilidade valores = (30, 10, 25, 70, 100, 94) # por ser uma tupla, ela não será mutável print(sorted(valores)) print(valores) print(min(valores)) print(max(valores)) print(sum(valores)) print(reduce(add, valores)) print(tuple(reversed(valores))) print(valores) print(valores) # valores.reverse()
d91b9125f37b549b39a412173d4d4e096ce89875
WinstonR96/Fraccionario
/Metodos/metodos.py
2,104
3.890625
4
#Declaro la clase y sus Atributos class Fraccionario: numerador=0 denominador=0 #Constructor def __init__(self, num, den): self.numerador = num self.denominador = den #Metodo ToString def __str__(self): cadena = self.numerador," / ",self.denominador return cadena #MetodoS GET def getNumerador(self): return self.numerador def getDenominador(self): return self.denominador #Metodos SET def setNumerador(self, num): self.numerador=num def setDenominador(self, den): self.denominador=den #Metodo Para Imprimir def imprimir(self): return "Numerador: ",self.numerador," Denominador: ",self.denominador #Metodos propios de fracciones def esHomogenea(self, f): if(self.denominador == f.denominador): return True else: return False def invertir(self): print (self.denominador," / ", self.numerador) def esPositiva(self): if ((self.numerador>0 and self.denominador>0) or (self.numerador<0 and self.denominador<0)): return "Es positiva" else: return "Es negativa" def valorFraccion(self): return self.numerador/self.denominador def suma(self, f): if(self.esHomogenea(f)): return Fraccionario(self.numerador+f.numerador, self.denominador) else: return Fraccionario(self.numerador*f.denominador + self.denominador*f.numerador, self.denominador*f.denominador) def resta(self, f): if (self.esHomogenea(f)): return Fraccionario(self.numerador - f.numerador, self.denominador) else: return Fraccionario(self.numerador * f.denominador - self.denominador * f.numerador, self.denominador * f.denominador) def multiplicacion(self, f): return Fraccionario(self.numerador*f.numerador, self.denominador*f.denominador) def division(self, f): return Fraccionario(self.numerador*f.denominador, self.denominador*f.numerador)
1d04d4da9740f90573981a7815b36ee143e8806d
itapogna/s21_class_library
/smallest_number.py
123
3.640625
4
def smallest_number(*, the_list, the_item): new_list = [item for item in the_list if item < the_item] return new_list
3e3091032f2b7054215ea279c504e3f8994681bf
binarybin/exp-machines
/src/objectives/logistic.py
2,008
3.625
4
""" Utils related to the logistic regression. """ import numpy as np from sklearn.linear_model import LogisticRegression def log1pexp(x): """log(1 + exp(x))""" return np.logaddexp(0, x) def sigmoid(x): return 1.0 / log1pexp(-x) def binary_logistic_loss(linear_o, y): """Returns a vector of logistic losses of each object. Given a vector of linear ouputs a vector of ground truth target values y returns logistic losses with respect to the linear outputs. Linear outputs can be e.g. <w, x_i> + b. """ return log1pexp(-y.flatten() * linear_o.flatten()) / linear_o.size def binary_logistic_loss_grad(linear_o, y): """Derivative of the binary_logistic_loss w.r.t. the linear output""" # Sometimes denom overflows, but it's OK, since if it's very large, it would # be set to INF and the output correctly takes the value of 0. # TODO: Fix overflow warnings. denom = 1 + np.exp(y.flatten() * linear_o.flatten()) return -y / (denom * linear_o.size) def _multinomial_loss(linear_o, y): raise NotImplementedError() def preprocess(X, y, info=None): """Prepare the data for the learning""" if info is None: info = {} info['classes'] = np.unique(y) n_classes = info['classes'].size if n_classes < 2: raise ValueError("This solver needs samples of 2 classes" " in the data, but the data contains only one" " class: %r." % info['classes'][0]) if n_classes > 2: raise NotImplementedError("multiclass is not implemented yet.") idx_min_1 = (y == info['classes'][0]) y = np.ones(y.shape) y[idx_min_1] = -1 return X, y, info def linear_init(X, y, fit_intercept=True): logreg = LogisticRegression(fit_intercept=fit_intercept) logreg.fit(X, y) if fit_intercept: intercept = logreg.intercept_[0] else: intercept = logreg.intercept_ return logreg.coef_[0, :], intercept
c4f82abb7cdff252ae48297cadb217ff9fab3209
ByrMucahit/Machine-Learning-Algorithms
/Algorithms/MeanRemoval.py
3,076
3.5
4
# -*- coding: utf-8 -*- """ Created on Thu Jan 9 17:25:54 2020 @author: mücahit """ import numpy as np from sklearn import preprocessing # STANDARDİZED #We need to convert values into data to between one and zero to get more succesfully result # We prepared data to operate. input_data=np.array([[3,-1.5,3,-6.4],[0,3,-1.3,4.1],[1,2.3,-2.9 ,-4.3]]) #We scale out to data data_Standardized=preprocessing.scale(input_data) print("\n Mean=",data_Standardized.mean(axis=0)) print ("Std deviation =",data_Standardized.std(axis=0)) # SCALİNG # We decided to which range change to this value in data ... Data_Scaler=preprocessing.MinMaxScaler(feature_range=(0,1)) # we applied data_scaled=Data_Scaler.fit_transform(input_data) # scaling's formul # ( ANY NUMBER - MEAN VALUES ) / STANDARD DEVİATİON print("\nMin max scaled =",data_scaled) # NORMALİZATİON Data_Normalized=preprocessing.normalize(input_data,norm='l1') # Normalization's formule = (ANY NUMBER - MİN(ANY NUMBER))/[MAX(X) - MİN(X)] print("\nNormalied Data=",Data_Normalized) # BİNARİZATİON # here used to convert value of array to binary value accoringto threshold value Data_Binarized=preprocessing.Binarizer(threshold=1.4).transform(input_data) print("\nBinarized Data:",Data_Binarized) # ONE-HOT-ENCODER Encoder=preprocessing.OneHotEncoder() Encoder.fit([[0,2,1,12],[1,3,5,3],[2,3,2,12],[1,2,4,3]]) encoded_vector = Encoder.transform([[2,3,5,3]]).toarray() print("\nEncoderd Vector--->",encoded_vector) # LABEL ENCODİNG Etiket_Kodlayıcı = preprocessing.LabelEncoder() Araba_Markaları = ['suzuki' , 'ford' , 'suzuki' , 'suzuki' , 'toyota' , 'ford' , 'bmw' ] Etiket_Kodlayıcı.fit(Araba_Markaları) print("\n Class mapping:") for i , item in enumerate(Etiket_Kodlayıcı.classes_): print(item,"-->",i) labels=['toyota' , 'ford','suzuki'] encoded_labels =Etiket_Kodlayıcı.transform(labels) print("\nLabels:",labels) print("Encoded Labels:",list(encoded_labels)) # DATA ANALYSIS import pandas data = 'pima-indians-diabetes.csv' names = ['Pregnancies', 'Glucose', 'BloodPressure', 'SkinThickness', 'Insulin', 'Outcome'] dataset=pandas.read_csv(data,names=names) # DIMENSIONS OF DATASET print(dataset.shape) #LIST THE ENTIRE DATA print(dataset.head(20)) #View the Statistical Summary print(dataset.describe()) # UNİVARİATE PLOTS # which has a variable import matplotlib.pyplot as plt data2 = 'iris_df.csv' names= ['sepal.length', 'sepal.width', 'petal.length', 'petal.width', 'class'] dataset2=pandas.read_csv(data2 , names = names) dataset2.plot(kind='box' , subplots=True , layout=(2,2) , sharex = False , sharey = False) plt.show() #BOX AND WHİSKER PLOTS #Histograms dataset.hist() #plt().show() #MULTİVARİATE PLOTS(whic has varaiblen more then 1) from pandas.plotting import scatter_matrix scatter_matrix(dataset2) plt.show()
63f58cab84527dd6512a584757d47da90e6185f8
DMvers/Physarum-VRP-Solver
/Branch and Bound Solver/code/greedyfirst.py
2,247
3.828125
4
from code import baseobjects class GreedyFirst(object): """ A very simple greedy algorithm, used for initializing more complex algo's. Nodes are sorted by their demand, and then selected i that order to be attended by first vehicle that has availible capacity. After that every route is sorted (if sort=True) by distance - first nearest node from the previous node in the route. So starting from the depot it goes to nearest, and then nearest from that one, and so on. """ def __init__(self, instance): self.instance = instance def run(self, sort=False): self.instance.network.sort_network_by_demand() network = self.instance.network fleet = self.instance.fleet # assigning nodes so that they fit the capacity restriction for node in network: if not node.visited: for vehicle in fleet: try: vehicle.add_node(node) break except ValueError: continue # sorting (if sort=True), and inserting start and end point of the route - the depot. depot = network.get_node(1) for vehicle in fleet: vehicle.route.insert_node(0, depot) if sort: vehicle.route = self.sort_by_distance(vehicle.route) vehicle.route.append_node(depot) return self.instance def sort_by_distance(self, route): sorted_route = baseobjects.Route() sorted_route.append_node(route.pop_node_id(1)) while(route): source_id = sorted_route[-1].id destination_id = self.get_nearest_node(source_id, route) sorted_route.append_node(route.pop_node_id(destination_id)) return sorted_route def get_nearest_node(self, source_id, present_nodes): minimum = 99999999999 destination_id = None for destination in present_nodes: distance = self.instance.distance_matrix[source_id - 1][destination.id - 1] if 0 < distance < minimum: minimum = distance destination_id = destination.id return destination_id
23db66c9a3c05e471c4a36c652eb8522ab65c5a6
OnerBerk/b-f-Python-flask
/3_user-input/code.py
263
3.75
4
name=input("enter your name : ") gretting=f"Salut {name} " print(gretting) size_input=input("combien de pied de long fait votre maison :") pied=int(size_input) metre=pied/10.8 print(f"{pied} Pied font {metre:.2f} metre") # :.2f permet de n'affher que 2 decimal
1528f381b6b211aed9fe9a48dbb380e03dbafe7d
OnerBerk/b-f-Python-flask
/17_lambdaFonction/code.py
545
4.0625
4
add=lambda x,y:x+y print(add(5,7)) #comme les fonctions lambda n'ont pas de nom on les lie a une variable print((lambda x,y: x+y)(6,8)) #ou ont definis l'action et les les argument sur la meme ligne def double(x): return x * 2 sequence =[1,3,5,7] doubler = [double(x) for x in sequence] #code classic doubled= list(map(double, sequence)) # map permet d'utiliser une function au element d'un tableau ...boucle doubled2 = list(map(lambda x: x *2, sequence)) # meme fonction en version lambda print(doubler) print(doubled) print(doubled2)
d35a45f9e59186c3a45a4519b6fe71ab2fcf199b
OnerBerk/b-f-Python-flask
/15_defaultParametreFunction/code.py
208
3.828125
4
def add(x, y=8): print(x+y) add(5) add(4, y=5) defaultY=5 def add2(x, defaultY): print(x+y) add(5) defaultY=8 #en une variable avec une valeur dans la fonction on ne peut plus la modifier add(5)
1605bc14384fc7d8f74a0af5f3eb1b03f23b1cd5
Oussema3/Python-Programming
/encryp1.py
343
4.28125
4
line=input("enter the string to be encrypted : ") num=int(input("how many letters you want to shift : ")) while num > 26: num = num -26 empty="" for char in line: if char.isalpha() is True: empty=chr(ord(char)+num) print(empty, end = "") else: empty=char print(empty,end="")
cd4f74089c51889a00492c3918c3134dde50c83c
Oussema3/Python-Programming
/looping.py
101
3.578125
4
print("the odds number are above") for i in range(21): if i%2 != 0: print("i = ",i)
aa3efd739891956cf40b7d50c8e4b8211039eccd
Oussema3/Python-Programming
/conditions2.py
417
4.1875
4
#if elif age = input("please enter your age :") age = int(age) if age > 100: print("no such age haha") exit else: if age <= 13: print("you are a kid") elif age >13 and age < 18: print("You are a teenager") elif age >= 18 and age < 27: print("You are young enough") elif age >= 27 and age < 50: print("you are adult") else: print("you are old ")
7c9f4808e2bf8155c4de96ce16e07f7a869ac4a5
Oussema3/Python-Programming
/lists1.py
151
3.578125
4
import math import random numList = [] for i in range(5): numList.append(random.randrange(0,9)) for i in numList: print(i) print(numList)
0302c283eeb9b921ba8c95120e62f49aac51a095
margonjo/Records
/1.1.py
451
3.890625
4
#Marc Gonzalez #29/01/15 #1.1 class StudentMarks: def __init__(self): self.studentName = "" self.testMark = int() new_student = StudentMarks() new_student.studentName = input("please enetr student name: ") new_student.testMark = int(input("please eneter the test score for this student: ")) print("The student {0} has achieved a score of {1} well done".format(new_student.studentName, new_student.testMark))
162acf35104d849e124d88a07e13fbdbc58e261b
stevewyl/chunk_segmentor
/chunk_segmentor/trie.py
2,508
4.15625
4
"""Trie树结构""" class TrieNode(object): def __init__(self): """ Initialize your data structure here. """ self.data = {} self.is_word = False class Trie(object): def __init__(self): self.root = TrieNode() def insert(self, word): """ Inserts a word into the trie. :type word: str :rtype: void """ node = self.root for letter in word: child = node.data.get(letter) if not child: node.data[letter] = TrieNode() node = node.data[letter] node.is_word = True def search(self, word): """ Returns if the word is in the trie. :type word: str :rtype: bool """ node = self.root for letter in word: node = node.data.get(letter) if not node: return False return node.is_word # 判断单词是否是完整的存在在trie树中 def starts_with(self, prefix): """ Returns if there is any word in the trie that starts with the given prefix. :type prefix: str :rtype: bool """ node = self.root for letter in prefix: node = node.data.get(letter) if not node: return False return True def get_start(self, prefix): """ Returns words started with prefix :param prefix: :return: words (list) """ def _get_key(pre, pre_node): words_list = [] if pre_node.is_word: words_list.append(pre) for x in pre_node.data.keys(): words_list.extend(_get_key(pre + str(x), pre_node.data.get(x))) return words_list words = [] if not self.starts_with(prefix): return words if self.search(prefix): words.append(prefix) return words node = self.root for letter in prefix: node = node.data.get(letter) return _get_key(prefix, node) if __name__ == '__main__': tree = Trie() tree.insert('深度学习') tree.insert('深度神经网络') tree.insert('深度网络') tree.insert('机器学习') tree.insert('机器学习模型') print(tree.search('深度学习')) print(tree.search('机器学习模型')) print(tree.get_start('深度')) print(tree.get_start('深度网'))
ea5a406e74744a3861301187014ade89a9f4fcbd
hozzjss/veneer
/listing.py
312
3.53125
4
from art import Art class Listing: def __init__(self, art: Art, price, seller): self.art = art self.price = price self.seller = seller def __repr__(self): return "{art_name}, {price}.".format( art_name=self.art.title, price=self.price )
ee044d2d9b52f6e834aef6f1e7bcca7231e49018
LeilaBagaco/DataCamp_Courses
/Unsupervised Learning in Python/Chapter3-Decorrelating your data and dimension reduction/Exercises_chapter_3.py
11,955
4.15625
4
# ********** Correlated data in nature ********* #You are given an array grains giving the width and length of samples of grain. You suspect that width and length will be correlated. # To confirm this, make a scatter plot of width vs length and measure their Pearson correlation. # ********** Exercise Instructions ********** # 1 - Import: # 1.1 - matplotlib.pyplot as plt. # 1.2 - pearsonr from scipy.stats. # 2 - Assign column 0 of grains to width and column 1 of grains to length. # 3 - Make a scatter plot with width on the x-axis and length on the y-axis. # 4 - Use the pearsonr() function to calculate the Pearson correlation of width and length. # ********** Script ********** # Perform the necessary imports import matplotlib.pyplot as plt from scipy.stats import pearsonr # Assign the 0th column of grains: width width = grains[:,0] # Assign the 1st column of grains: length length = grains[:,1] # Scatter plot width vs length plt.scatter(width, length) plt.axis('equal') plt.show() # Calculate the Pearson correlation correlation, pvalue = pearsonr(width, length) # Display the correlation print(correlation) # ------------------------------------------------------------------------------- # ********** Decorrelating the grain measurements with PCA ********** # You observed in the previous exercise that the width and length measurements of the grain are correlated. # Now, you'll use PCA to decorrelate these measurements, then plot the decorrelated points and measure their Pearson correlation. # ********** Exercise Instructions ********** # 1 - Import PCA from sklearn.decomposition. # 2 - Create an instance of PCA called model. # 3 - Use the .fit_transform() method of model to apply the PCA transformation to grains. Assign the result to pca_features. # 4 - The subsequent code to extract, plot, and compute the Pearson correlation of the first two columns pca_features has been written for you, so hit 'Submit Answer' to see the result! # ********** Script ********** # Import PCA from sklearn.decomposition import PCA # Create PCA instance: model model = PCA() # Apply the fit_transform method of model to grains: pca_features pca_features = model.fit_transform(grains) # Assign 0th column of pca_features: xs xs = pca_features[:,0] # Assign 1st column of pca_features: ys ys = pca_features[:,1] # Scatter plot xs vs ys plt.scatter(xs, ys) plt.axis('equal') plt.show() # Calculate the Pearson correlation of xs and ys correlation, pvalue = pearsonr(xs, ys) # Display the correlation print(correlation) # ------------------------------------------------------------------------------ # ********** The first principal component ********** # The first principal component of the data is the direction in which the data varies the most. # In this exercise, your job is to use PCA to find the first principal component of the length and width measurements of the grain samples, and represent it as an arrow on the scatter plot. # The array grains gives the length and width of the grain samples. PyPlot (plt) and PCA have already been imported for you. # ********** Exercise Instructions ********** # 1 - Make a scatter plot of the grain measurements. This has been done for you. # 2 - Create a PCA instance called model. # 3 - Fit the model to the grains data. # 4 - Extract the coordinates of the mean of the data using the .mean_ attribute of model. # 5 - Get the first principal component of model using the .components_[0,:] attribute. # 6 - Plot the first principal component as an arrow on the scatter plot, using the plt.arrow() function. You have to specify the first two arguments - mean[0] and mean[1]. # ********** Script ********** # Make a scatter plot of the untransformed points plt.scatter(grains[:,0], grains[:,1]) # Create a PCA instance: model model = PCA() # Fit model to points model.fit(grains) # Get the mean of the grain samples: mean mean = model.mean_ # Get the first principal component: first_pc first_pc = model.components_[0,:] # Plot first_pc as an arrow, starting at mean plt.arrow(mean[0], mean[1], first_pc[0], first_pc[1], color='red', width=0.01) # Keep axes on same scale plt.axis('equal') plt.show() # ------------------------------------------------------------------------------ # ********** Variance of the PCA features ********** # The fish dataset is 6-dimensional. But what is its intrinsic dimension? Make a plot of the variances of the PCA features to find out. # As before, samples is a 2D array, where each row represents a fish. You'll need to standardize the features first. # ********** Exercise Instructions ********** # 1 - Create an instance of StandardScaler called scaler. # 2 - Create a PCA instance called pca. # 3 - Use the make_pipeline() function to create a pipeline chaining scaler and pca. # 4 - Use the .fit() method of pipeline to fit it to the fish samples samples. # 5 - Extract the number of components used using the .n_components_ attribute of pca. Place this inside a range() function and store the result as features. # 6 - Use the plt.bar() function to plot the explained variances, with features on the x-axis and pca.explained_variance_ on the y-axis. # ********** Script ********** # Perform the necessary imports from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler from sklearn.pipeline import make_pipeline import matplotlib.pyplot as plt # Create scaler: scaler scaler = StandardScaler() # Create a PCA instance: pca pca = PCA() # Create pipeline: pipeline pipeline = make_pipeline(scaler, pca) # Fit the pipeline to 'samples' pipeline.fit(samples) # Plot the explained variances features = range(pca.n_components_) plt.bar(features, pca.explained_variance_) plt.xlabel('PCA feature') plt.ylabel('variance') plt.xticks(features) plt.show() # ------------------------------------------------------------------------------ # ********** Dimension reduction of the fish measurements ********** # In a previous exercise, you saw that 2 was a reasonable choice for the "intrinsic dimension" of the fish measurements. # Now use PCA for dimensionality reduction of the fish measurements, retaining only the 2 most important components. # The fish measurements have already been scaled for you, and are available as scaled_samples. # ********** Exercise Instructions ********** # 1 - Import PCA from sklearn.decomposition. # 2 - Create a PCA instance called pca with n_components=2. # 3 - Use the .fit() method of pca to fit it to the scaled fish measurements scaled_samples. # 4 - Use the .transform() method of pca to transform the scaled_samples. Assign the result to pca_features. # ********** Script ********** # Import PCA from sklearn.decomposition import PCA # Create a PCA model with 2 components: pca pca = PCA(n_components=2) # Fit the PCA instance to the scaled samples pca.fit(scaled_samples) # Transform the scaled samples: pca_features pca_features = pca.transform(scaled_samples) # Print the shape of pca_features print(pca_features.shape) # ------------------------------------------------------------------------------ # ********** A tf-idf word-frequency array ********** # In this exercise, you'll create a tf-idf word frequency array for a toy collection of documents. # For this, use the TfidfVectorizer from sklearn. It transforms a list of documents into a word frequency array, which it outputs as a csr_matrix. # It has fit() and transform() methods like other sklearn objects. # You are given a list documents of toy documents about pets. Its contents have been printed in the IPython Shell. # ********** Exercise Instructions ********** # 1 - Import TfidfVectorizer from sklearn.feature_extraction.text. # 2 - Create a TfidfVectorizer instance called tfidf. # 3 - Apply .fit_transform() method of tfidf to documents and assign the result to csr_mat. This is a word-frequency array in csr_matrix format. # 4 - Inspect csr_mat by calling its .toarray() method and printing the result. This has been done for you. # 5 - The columns of the array correspond to words. Get the list of words by calling the .get_feature_names() method of tfidf, and assign the result to words. # ********** Script ********** # Import TfidfVectorizer from sklearn.feature_extraction.text import TfidfVectorizer # Create a TfidfVectorizer: tfidf tfidf = TfidfVectorizer() # Apply fit_transform to document: csr_mat csr_mat = tfidf.fit_transform(documents) # Print result of toarray() method print(csr_mat.toarray()) # Get the words: words words = tfidf.get_feature_names() # Print words print(words) # ------------------------------------------------------------------------------ # ********** Clustering Wikipedia part I ********** # You saw in the video that TruncatedSVD is able to perform PCA on sparse arrays in csr_matrix format, such as word-frequency arrays. # Combine your knowledge of TruncatedSVD and k-means to cluster some popular pages from Wikipedia. # In this exercise, build the pipeline. In the next exercise, you'll apply it to the word-frequency array of some Wikipedia articles. # Create a Pipeline object consisting of a TruncatedSVD followed by KMeans. # (This time, we've precomputed the word-frequency matrix for you, so there's no need for a TfidfVectorizer). # The Wikipedia dataset you will be working with was obtained from here. # ********** Exercise Instructions ********** # 1 - Import: # 1.1 - TruncatedSVD from sklearn.decomposition. # 1.2 - KMeans from sklearn.cluster. # 1.3 - make_pipeline from sklearn.pipeline. # 2 - Create a TruncatedSVD instance called svd with n_components=50. # 3 - Create a KMeans instance called kmeans with n_clusters=6. # 4 - Create a pipeline called pipeline consisting of svd and kmeans. # ********** Script ********** # Perform the necessary imports from sklearn.decomposition import TruncatedSVD from sklearn.cluster import KMeans from sklearn.pipeline import make_pipeline # Create a TruncatedSVD instance: svd svd = TruncatedSVD(n_components=50) # Create a KMeans instance: kmeans kmeans = KMeans(n_clusters=6) # Create a pipeline: pipeline pipeline = make_pipeline(svd, kmeans) # ------------------------------------------------------------------------------ # ********** Clustering Wikipedia part II ********** # It is now time to put your pipeline from the previous exercise to work! # You are given an array articles of tf-idf word-frequencies of some popular Wikipedia articles, and a list titles of their titles. # Use your pipeline to cluster the Wikipedia articles. # A solution to the previous exercise has been pre-loaded for you, so a Pipeline pipeline chaining TruncatedSVD with KMeans is available. # ********** Exercise Instructions ********** # 1 - Import pandas as pd. # 2 - Fit the pipeline to the word-frequency array articles. # 3 - Predict the cluster labels. # 4 - Align the cluster labels with the list titles of article titles by creating a DataFrame df with labels and titles as columns. This has been done for you. # 5 - Use the .sort_values() method of df to sort the DataFrame by the 'label' column, and print the result. # 6 - Hit 'Submit Answer' and take a moment to investigate your amazing clustering of Wikipedia pages! # ********** Script ********** # Import pandas import pandas as pd # Fit the pipeline to articles pipeline.fit(articles) # Calculate the cluster labels: labels labels = pipeline.predict(articles) # Create a DataFrame aligning labels and titles: df df = pd.DataFrame({'label': labels, 'article': titles}) # Display df sorted by cluster label print(df.sort_values('label'))
eb1ba8ee65ab19dad296f9793e0a0f6ba6230100
LeilaBagaco/DataCamp_Courses
/Supervised Machine Learning with scikit-learn/Chapter_1/1-k-nearest-neighbors-fit.py
2,163
4.28125
4
# ********** k-Nearest Neighbors: Fit ********** # Having explored the Congressional voting records dataset, it is time now to build your first classifier. # In this exercise, you will fit a k-Nearest Neighbors classifier to the voting dataset, which has once again been pre-loaded for you into a DataFrame df. # In the video, Hugo discussed the importance of ensuring your data adheres to the format required by the scikit-learn API. # The features need to be in an array where each column is a feature and each row a different observation or data point - in this case, a Congressman's voting record. # The target needs to be a single column with the same number of observations as the feature data. We have done this for you in this exercise. # Notice we named the feature array X and response variable y: This is in accordance with the common scikit-learn practice. # Your job is to create an instance of a k-NN classifier with 6 neighbors (by specifying the n_neighbors parameter) and then fit it to the data. # The data has been pre-loaded into a DataFrame called df. # ********** Exercise Instructions ********** # 1 - Import KNeighborsClassifier from sklearn.neighbors. # 2 - Create arrays X and y for the features and the target variable. Here this has been done for you. # Note the use of .drop() to drop the target variable 'party' from the feature array X as well as the use of the .values attribute to ensure X and y are NumPy arrays. # Without using .values, X and y are a DataFrame and Series respectively; the scikit-learn API will accept them in this form also as long as they are of the right shape. # 3 - Instantiate a KNeighborsClassifier called knn with 6 neighbors by specifying the n_neighbors parameter. # ********** Script ********** # Import KNeighborsClassifier from sklearn.neighbors from sklearn.neighbors import KNeighborsClassifier # Create arrays for the features and the response variable y = df['party'].values X = df.drop('party', axis=1).values # Create a k-NN classifier with 6 neighbors knn = KNeighborsClassifier(n_neighbors=6) # Fit the classifier to the data knn.fit(X, y)
05be799f79b19ca74ce7c50b425da9ac5f0a3ca3
oszikr/PyHEX
/processing1.py
1,685
3.78125
4
from board import board from datetime import datetime """ The program read games and write game outcome to the output file. The output file name is generated based on input file name. The input raw_games.dat contains a list of moves corresponding to a 13x13 hex game on each line. A game represented by space separated coordinates. """ boardsize = 13 def generatescoring(filename): print("Reading input file:", filename) infile = open(filename, "r") print("Creating output file.") filenames = filename.split(".") outfilename = filenames[0] + "_scored." + filenames[1] outfile = open(outfilename, "w") outfilename2 = filenames[0] + "_steps." + filenames[1] outfile2 = open(outfilename2, "w") print("Playing games:") s = 0 i = 0 for line in infile: i += 1 print("Game", i) game = board(boardsize) moves = line.split() j = 0; for move in moves: #print(move) #game.put(move) print(game.__str__()) j += 1 s += 1; print(game) print(game.firstPlayerWins()) print() outfile.write(str(game.firstPlayerWins("positive", "negative")) + '\n') outfile2.write(str(j) + '\n') print("Total", s, "states") outfile.close() outfile2.close() print("End.") if __name__ == "__main__": start_time = datetime.now().strftime("%H:%M:%S") print("Start Time =", start_time) generatescoring("raw_games_small.dat") generatescoring("raw_games.dat") stop_time = datetime.now().strftime("%H:%M:%S") print("Start Time =", start_time) print("Stop Time =", stop_time)
160fdeed8bd2c5b06b68270bad80a238962bcb67
Arthyom/PythonX-s
/metodos.py
867
4.25
4
#### revizando los metodos de las structuras principales # diccionarios D = {1:"alfredo", 2:"aldo", 3:"alberto",4:"angel"} print D.has_key(9) print D.items() print D.keys() ##print D.pop(1) #lista = [1,2] #print D.pop(1[0,1]) print D.values() print D # cadenas cadena = "esta es una cadena de prueba esta cadena es una prueba" print cadena.count('esta') print cadena.find('una') print cadena.partition(',') print cadena.replace('e', 'E') print cadena print cadena.split(' ') # listas lst = [1,2,3,4,5,6,7,8] print lst.append(1) print lst print lst.count(1) print lst.index(4) print lst.insert(3,12) print lst print lst.pop(3) print lst.pop() print lst.pop() print lst.pop() print lst it = [1,'3',1,"cadena"] print lst.extend(it) #lst.append(1,'3',1,"cadena") lst.remove("cadena") print lst lst.reverse() print lst lst.sort(reverse=True) print lst
29e640f6d86c598486c8b74a57c4e088e2e75dd9
Omar-zoubi/data-structures-and-algorithms
/python/Data_Structures/linked_list/linked_list.py
3,304
4.125
4
class Node: def __init__(self, data): self.data = data self.next = None class Linked_list: def __init__(self): self.head = None def insert(self,data): new_node = Node(data) if self.head is None: self.head = new_node return last_node =self.head while last_node.next: last_node = last_node.next last_node.next=new_node def __str__(self): cur_node= self.head result ="" while cur_node: # print (f"{"cur_node.data"}" ,"->" ) result += f"{ {str(cur_node.data)} } -> " cur_node=cur_node.next # print("=>NULL") result += "NULL" return result def include(self, index): cur_node= self.head inc=False while cur_node: if cur_node.data== index: inc = True cur_node=cur_node.next return inc def append(self, data): new_node = Node(data) if self.head is None: self.head = new_node else : last_node =self.head while last_node.next: last_node = last_node.next last_node.next=new_node def insert_after(self, aftervalue, addval): new_node = Node(addval) current = self.head if not self.head: return "EMPETY LIST" else: current = self.head while current: if current.next: if current.data == aftervalue: nv = current.next current.next = new_node new_node.next = nv return else: current = current.next else: current.next = new_node return return "No mathch" def insert_before(self, nxvalue, addval): new_node = Node(addval) current = self.head if not self.head: return "this list is emptey" else: if self.head.data == nxvalue: previous = self.head self.head = new_node new_node.next = previous return current = self.head while current.next : if current.next.data == nxvalue: previous = current.next current.next = new_node new_node.next = previous return current = current.next return "No match" def kthFromEnd(self, k): length = 0 current = self.head while(current): length += 1 current = current.next print(length) if k >= length or k < 0: return 'Invalid Index' current = self.head for i in range(0,length-k): if i== length-k-1: return current.data current = current.next llist = Linked_list() llist.insert("Omar") llist.insert("Mohammad") llist.insert("Al-zoubi") llist.insert_after("Mohammad", "5") llist.insert_before("Mohammad", "5") print(llist) print(llist.kthFromEnd(0))
5b516c9ac4e3e023cbdd121e938aa6d1eacecf4e
FMNN025KDC/Project-2
/differentiation.py
3,079
3.515625
4
# -*- coding: utf-8 -*- """ Created on Sat Sep 24 13:24:45 2016 @author: David Olsson, Kristoffer Svendsen, Claes Svensson """ from scipy import * from pylab import * def getGradient(function): """Returns the gradient of a funciton as a function object. Uses finite differences approximation. Args: function: function object to find the gradient of. Returns: function object of the gradient. """ def grad(x): return evaluateGradient(function,x) return grad def evaluateGradient(function,x,epsilon = 1e-5): """Evaluates the gradient of function in point x using finite difference approximation. Args: function: function object to find the gradient of. x: nparray object contining point to evaluate in. epsilon: {Optional} {Default = 1e-5} Finite difference step size. Returns: nparray object containing the value of the gradient in point x. """ h = zeros(shape(x)) res = zeros(shape(x)) for i in range(0,len(x)): # Set the step on the correct variable. h[i] = epsilon # Approximate derivative using central difference approximation. res[i] = (function(x + h) - function(x - h)) / (2 * epsilon) # Reset step for next iteration. h[i] = 0.0 return res def getHessian(fgradient): """Returns the hessian of a funciton as a function object. Uses finite differences approximation. Args: fgradient: function object of gradient to find the hessian of. Returns: function object of the hessian. """ def hess(x): return evaluateHessian(fgradient,x) return hess def evaluateHessian(fgradient,x,epsilon = 1e-5): """Evaluates the hessian of function in point x using finite difference approximation. Args: fgradient: function object of gradient to find the hessian of. x: nparray object contining point to evaluate in. epsilon: {Optional} {Default = 1e-5} Finite difference step size. Returns: nparray object containing the value of the hessian in point x. """ h = zeros(shape(x)) res = zeros((len(x),len(x))) for i in range(0,len(x)): # Define new gradient function which returns only the i:th element of # the gradient in a point x. def fgradienti(x): return fgradient(x)[i] # Evaluate new funciton object and store the result as a row in the # hessian. row = evaluateGradient(fgradienti,x) res[i,:] = row return res # for i in range(0,len(point)): ## print(array(point)) # xf = array(point) # xf[i] = xf[i] +epsilon # xb = array(point) # xb[i] = xb[i] -epsilon # res[i] = (function(xf) - function(xb)) / (2 * epsilon)
1ee6ca7236d718e25bf2e974632c538fb061a175
Slidem/coding-problems
/string-multiply/string-multiply.py
3,500
3.515625
4
from collections import deque import copy def multiply(num1: str, num2: str) -> str: if num1 == "0" or num2 == "0": return "0" multiplication_rows_container = MultiplicationRowsContainer() for d in reversed(num1): row = DigitAndStringMultiplicationHolder(int(d), num2) multiplication_rows_container.add_and_compute_for_existing_rows(row) multiplication_rows_container.compute_remaining() return str(multiplication_rows_container) class MultiplicationRowsContainer(): def __init__(self): self.rows_iterators = [] self.result = deque() self.result_str = "" self.carry = 0 self.computation_finished = False def add_and_compute_for_existing_rows(self, row): if self.computation_finished: raise Exception( "Computation finished; nothing left to do with this class but only to use the result") self.rows_iterators.append(iter(row)) self.compute_column() def compute_remaining(self): if self.computation_finished: return while not self.computation_finished: self.compute_column() def compute_column(self): at_least_something_was_computed = False computed_value = 0 for row_iterator in self.rows_iterators: value = next(row_iterator) if value != None: at_least_something_was_computed = True computed_value += value if not at_least_something_was_computed: self.computation_finished = True if self.carry and self.carry > 0: self.result.appendleft(self.carry) self.carry = 0 self.result_str = "".join([str(d) for d in self.result]) return computed_value += self.carry self.carry = computed_value // 10 self.result.appendleft(computed_value % 10) def __str__(self): return self.result_str class DigitAndStringMultiplicationHolder: def __init__(self, digit: int, string: str): self.multiplication = self.__multiply(digit, string) def __iter__(self): self.multiplication_copy = copy.copy(self.multiplication) return self def __next__(self): if len(self.multiplication_copy) > 0: return self.multiplication_copy.popleft() else: return None def __multiply(self, digit, string): carry = 0 result = deque() for multiply_with in reversed(string): digit_multiplication = int(multiply_with) * digit + carry carry = digit_multiplication // 10 to_add = digit_multiplication % 10 result.append(to_add) if carry > 0: result.append(carry) return result def __str__(self): return "".join([str(d) for d in self.multiplication]) # Test methods ........................ # thest for the DigitAndStringMultiplicationHolder class def test_digit_string_multiplication_computation(): digit = 3 string = "224" print(DigitAndStringMultiplicationHolder(digit, string)) def test_digit_string_multiplication_iterator(): digit = 3 string = "224" result = DigitAndStringMultiplicationHolder(digit, string) for r in result: print(r) # test_digit_string_multiplication_computation() # test_digit_string_multiplication_iterator() # test multiply method print(multiply("100", "25"))
9aab1afcb9f59c2c65e1856933e1ce699c9796d1
Slidem/coding-problems
/swap-nodes-in-pairs/swap-nodes-in-pairs.py
1,153
3.875
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def swapPairs(self, head: ListNode) -> ListNode: if not head or not head.next: return head prev = None new_head = head.next node = head while node: swap_this = node swap_that = node.next next = swap_that.next if swap_that else None if prev and swap_that: prev.next = swap_that if swap_that: swap_that.next = swap_this swap_this.next = next prev = node node = next else: node = None return new_head # create list head = ListNode(1) head.next = ListNode(2) head.next.next = ListNode(3) head.next.next.next = ListNode(4) head.next.next.next.next = ListNode(5) head.next.next.next.next.next = ListNode(6) # print solution solution = Solution().swapPairs(head) n = solution solution_str = "" while n: solution_str += str(n.val) + " " n = n.next print(solution_str)
4f5024060129ad988a3b766cbd9221a20973a5b9
Slidem/coding-problems
/permutations-II/permutations-II.py
778
3.859375
4
def permuteUnique(nums): return permute(nums, set(), "") def permute(nums, permuted_keys, key): if not nums: return None if key in permuted_keys: return -1 permutations = [] initial_key = key for x in nums: remaining = nums.copy() remaining.remove(x) key = initial_key + str(x) remaining_permutations = permute(remaining, permuted_keys, key) if remaining_permutations is None: permutations.append([x]) continue if remaining_permutations == -1: continue for r in remaining_permutations: r.append(x) permutations.append(r) permuted_keys.add(key) return permutations print(permuteUnique([1, 1, 2]))
07a1a5e20f9f03a0e72f3bcc6c9e471170640c27
KushagraChauhan/HackerRank
/array/array2.py
322
3.65625
4
#this is the left rotation question n, k = map(int, input().strip().split(' ')) c = a = [int(i) for i in input().split()] def array_left_rotation(a, n, k): for i in range(k, n + k): if i < n: print(a[i], end=' ') else: print(a[i - n], end=' ') array_left_rotation(a, n, k)
18344819e0bfa8316b45878a197559e320d041f7
Bruck1701/CodingInterview
/stringManipulation/makingAnagrams.py
730
3.796875
4
#!/bin/python3 import math import os import random import re import sys from collections import Counter # Complete the makeAnagram function below. def makeAnagram(a, b): hash_a = dict(Counter(a)) hash_b = dict(Counter(b)) union_hash = {**hash_a,**hash_b} count = 0 for key, value in union_hash.items(): if key not in hash_b: count+=hash_a[key] elif key not in hash_a: count+=hash_b[key] else: count+= abs(hash_a[key]-hash_b[key]) return count if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') a = input() b = input() res = makeAnagram(a, b) fptr.write(str(res) + '\n') fptr.close()
412de080bbbae3728b6ecb6fe3750198b0379a48
Bruck1701/CodingInterview
/Arrays/LeetCode/TwoSum.py
1,293
3.703125
4
''' Two Sum problem: Given an array of integers, return indices of the two numbers such that they add up to a specific target. This problem is similar to the Ice cream problem from Hackerrank. What you store in the hashmap is the difference from a specific target but you check the current number of the array it is in the hashmap. ''' class Solution: def twoSum(self, nums, target): hashmap = {} for idx in range(len(nums)): el = nums[idx] comp = target-el if el not in hashmap: hashmap[comp] = idx else: return [hashmap[el], idx] print(Solution().twoSum([2, 7, 11, 15], 9)) ''' first solution: 552 ms hashmapV = {} hashmapK = {} for index in range(len(nums)): hashmapV[index] = nums[index] hashmapK[nums[index]] = index complement = target - nums[index] if complement in hashmapV.values() and hashmapK[complement] != index: return [index, hashmapK[complement]] for index in range(len(nums)): complement = target - nums[index] if complement in hashmapV.values() and hashmapK[complement] != index: return [index, hashmapK[complement]] '''
ea364a5baa704ff55a0366b04dceec86d2a0b9e8
Bruck1701/CodingInterview
/Arrays/LeetCode/defangIP.py
387
3.59375
4
""" Defang IP address """ class Solution: def defangIPaddr(self, address: str) -> str: hashmap = {} for el in address: if el not in hashmap: hashmap[el] = el hashmap["."] = "[.]" output = "" for el in address: output += hashmap[el] return output print(Solution().defangIPaddr("1.1.1.1"))
ebcb4f204e3f8b1572da47fde4a102180bfd926b
Bruck1701/CodingInterview
/Arrays/Codility/stacksAndQueues/manhattanSkyline.py
935
3.75
4
# you can write to stdout for debugging purposes, e.g. # print("this is a debug message") def solution(H): # write your code in Python 3.6 if len(H) == 1: return 1 stack = [] # stack.append(H[0]) counter = 0 for el in H: if not stack: stack.append(el) else: block = stack.pop() if el < block: while el < block: counter += 1 if len(stack) > 0: block = stack.pop() else: break if el > block: stack.append(block) stack.append(el) elif el > block: stack.append(block) stack.append(el) elif el == block: stack.append(block) return len(stack)+counter print(solution([8, 8, 5, 7, 9, 8, 7, 4, 8]))
932afb5064029e16f6343d1247f584e0de4a2a55
melissaehong/online-python-aug-2016
/GideonLee/Assignments/oop/mathDojo/mathDojo.py
2,076
3.78125
4
# Part 1 # Create a python class that allows for add and subtract that accepts at least 1 parameter class MathDojo1(object): def __init__(self): self.total = 0 def add(self, *x): for i in x: self.total += i return self def subtract(self, *x): for i in x: self.total -= i return self def result(self): print 'Total: ' + str(self.total) md = MathDojo1().add(2).add(2, 5).subtract(3, 2).result() # Part 2 # Refactor it to allow the user to input at least one integer(s) and/or list(s) as a parameter with any number # values passed into the list class MathDojo2(object): def __init__(self): self.total = 0 def add(self, *x): # Search through the length of the given numbers for i in range(len(x)): # If it's a list ... if type(x[i]) == list: for j in range(0, len(x[i])): self.total += x[i][j] # Else if it's just a float or an int else: self.total += x[i] return self def subtract(self, *x): for i in range(len(x)): if type(x[i]) == list: for j in range(len(x[i])): self.total -= x[i][j] else: self.total -= x[i] return self def result(self): print 'Total is: ' + str(self.total) cd = MathDojo2().add([1], 3, 4).add([3, 5, 7, 8], [2, 4.3, 1.25]).subtract(2, [2, 3], [1.1, 2.3]).result() # Part 3 # Make any needed changes in MathDojo in order to support tuples of values in addition to lists and singletons class MathDojo3(object): def __init__(self): self.total = 0 def add(self, *x): for i in range(len(x)): # Exactly like Part 2 except with this added tuple conditional if type(x[i]) == list or type(x[i]) == tuple: for j in range(0, len(x[i])): self.total += x[i][j] else: self.total += x[i] return self def subtract(self, *x): for i in range(len(x)): if type(x[i]) == list or type(x[i]) == tuple: for j in range(len(x[i])): self.total -= x[i][j] else: self.total -= x[i] return self def result(self): print 'Total is: ' + str(self.total) bd = MathDojo3().add([1], (2, 3)).subtract([1.25, 3.75]).add(2).subtract([1]).result()
9fe168224f546a49bf60aa6c4f75d2f9eb904edd
rozifa/mystuff2
/ex401.py
472
3.703125
4
class Song(object): def __init__(self, lyrics): self.lyrics = lyrics def make_song(self): for line in self.lyrics: print line puff = Song(['puff the magic dragon', 'lived by the sea', 'what a cool fucking dragon']) immigrant = Song(['come from the land of the ice and snow', 'midnight sun where the hot springs blow', 'AHHHHHHHHHHHHHH!']) puff.make_song() immigrant.make_song() # print puff # print immigrant
4ee49b9f3daca7e8504953005094db95487e6152
HouseJaay/LCPractice
/657_Judge_Route_Circle.py
573
3.625
4
class Solution(object): def judgeCircle(self,moves): def move(posi,dirc): if dirc == 'U': posi[0] += 1 elif dirc == 'D': posi[0] -= 1 elif dirc == 'L': posi[1] -= 1 elif dirc == 'R': posi[1] += 1 posi = [0,0] for dirc in moves: move(posi,dirc) if posi[0]==0 and posi[1]==0: return True else: return False ins = Solution() print(ins.judgeCircle('UD')) print(ins.judgeCircle('RR'))
46d2c55724c2751a0f4ddeb93c60027a87ac38af
quesadap/CursoPython
/autos.py
5,536
3.78125
4
# class Autos: # def __init__(self, marca, modelo, patente, color, velocidad_maxima): # self.marca = marca # self.modelo = modelo # self.patente = patente # self.color = color # self.velocidad_maxima = velocidad_maxima # self.velocidad_actual = 0 # self.encendido = False # # def mostrar_informacion(self): # return ('Este auto es un '+self.marca+' '+self.modelo+' y esta andando a '+str(self.velocidad_actual)) # # def acelarar(self, velocidad): # if self.encendido: # try: # velocidad_final = self.velocidad_actual + velocidad # if velocidad_final < self.velocidad_maxima: # self.velocidad_actual = self.velocidad_actual + velocidad # else: # self.velocidad_actual = self.velocidad_maxima # except TypeError: # print('no puedo acelarar eso') # except ValueError: # print('lo que nos paso no es un integer') # except: # print('excepcion atrapada') # finally: # print('se intento acelar con '+str(velocidad)) # else: # self.velocidad_actual = self.velocidad_maxima # # # def frenar(self): # if self.encendido: # try: # velocidad_final = self.velocidad_actual + velocidad # if velocidad_final > 0: # self.velocidad_actual = self.velocidad_actual + velocidad # else: # self.velocidad_actual = self.velocidad_maxima # except TypeError: # print('no puedo frenar eso') # except ValueError: # print('lo que nos paso no es un integer') # except: # print('excepcion atrapada') # finally: # print('se intento frenar con '+str(velocidad)) # else: # self.velocidad_actual = self.velocidad_maxima # # def encender(self): # if not self.encendido: # self.encendido = True # else: # print('el auto ya esta encendido') # # def apagar(self): # if self.encendido: # self.encendido = False # #self.velocidad_actual = 0 # self.frenar(self.velocidad_actual) # else: # print('el auto ya esta apagado') # # mi_auto = Autos('Ford', 'Falcon', 'AE5211XX', "rojo", 200) # print(mi_auto.marca) # print(mi_auto.mostrar_informacion()) # mi_auto.encender() # mi_auto.acelerar(50) # print(mi_auto.velocidad_actual) # mi_auto.acelerar(5000) # print(mi_auto.velocidad_actual) # print(mi_auto.velocidad_maxima) # mi_auto.acelerar(100) # mi_auto.acelerar(12.34) class Autos: def __init__(self, marca, modelo, patente, color, velocidad_maxima): self.marca = marca self.modelo = modelo self.patente = patente self.color = color self.velocidad_maxima = velocidad_maxima self.velocidad_actual = 0 self.encendido = False def mostrar_informacion(self): return ('Este auto es un '+self.marca+' '+self.modelo+' y esta andando a '+str(self.velocidad_actual)) def acelerar(self,velocidad): if self.encendido: if type(velocidad) is float: raise Exception('Only Integers') try: velocidad_final = self.velocidad_actual + velocidad if velocidad_final < self.velocidad_maxima: self.velocidad_actual = velocidad_final else: self.velocidad_actual = self.velocidad_maxima except TypeError: print('No puedo acelerar eso') except ValueError: print('Lo que nos pasó no es un integer') except: print('Excepción atrapada') finally: print('Se intentó acelerar con '+str(velocidad)) else: print('Debe encender el auto') def frenar(self): if self.encendido: try: velocidad_final = self.velocidad_actual - velocidad if velocidad_final> 0: self.velocidad_actual = velocidad_final else: self.velocidad_actual = self.velocidad_maxima except TypeError: print('No puedo frenar eso') except ValueError: print('Lo que nos pasó no es un integer') except: print('Excepción atrapada') finally: print('Se intentó frenar con '+str(velocidad)) else: print('Debe encender el auto') def encender(self): if not self.encendido: #if self.encendido == False self.encendido = True else: print('El auto ya está encendido') def apagar(self): if self.encendido: #if self.encendido == True self.encendido = False #self.velocidad_actual = 0 self.frenar(self.velocidad_actual) else: print('El auto ya está apagado') mi_auto = Autos('Ford', 'Fiesta', 'AE 167','Azul',180) print(mi_auto.marca) print(mi_auto.mostrar_informacion()) mi_auto.encender() mi_auto.acelerar(50) print(mi_auto.velocidad_actual) mi_auto.acelerar(5000) print(mi_auto.velocidad_actual) print(mi_auto.velocidad_maxima) mi_auto.acelerar('papa') mi_auto.acelerar(12.34)
fb2e9096ebf2ab6c48b1b44cca65376601acc7c0
utukJ/zuri
/budget_oop/oop_task.py
909
3.75
4
class Budget: def __init__(self, amount=0, category="any"): self.amount = amount self.category = category def deposit(self, amount): self.amount += amount def withdraw(self, amount): self.amount -= amount def transfer(self, other, amount): self.withdraw(amount) other.deposit(amount) def get_balance(self): return self.amount ## Use cases food = Budget(10000, category="food") clothing = Budget(10000, category="clothing") entertainment = Budget(10000) food.deposit(3500) print("Result after depositing in food: {}".format(food.get_balance())) clothing.withdraw(1700) print("Result after withdrawing clothing budget: {}".format(clothing.get_balance())) food.transfer(entertainment, 1000) print("Result after transferring from food: {} to entertainment budget: {}".format(food.get_balance(), entertainment.get_balance()))
3ff5a72bea73d61a9d8196c839219594b504597d
gilvpaola/Ciclos_Python
/Suma_1_hasta_n_for.py
614
3.734375
4
# -*- coding: utf-8 -*- """ Created on Sat Jun 12 09:41:18 2021 @author: USUARIO """ n = int(input("Ingrese un número entero: ")) suma = 0 # Forma correcta for i in range(1, n+1, 1): suma = suma + i print("La suma de los números enteros de 1 hasta n con parámetros 1, n+1, 1 es:", suma) # Forma incorrecta suma = 0 for i in range(1, n, 1): suma = suma + i print("La suma de los números enteros de 1 hasta n con parámetros 1, n, 1 es:", suma) # Forma correcta suma = 0 for i in range(n+1): suma = suma + i print("La suma de los números enteros de 1 hasta n con el paramétro n+1 es:", suma)
560d6ca00a4036c921050036f3d791c9c8ed2fd2
gilvpaola/Ciclos_Python
/For_Anidados.py
644
3.84375
4
# -*- coding: utf-8 -*- """ Created on Sat Jun 12 11:25:11 2021 @author: USUARIO """ # Programa para generar secuencias con ciclo anidados n = int(input("Ingrese un número entero: ")) for i in range(1, n+1): for j in range (1, i+1): print(i, end="") print("") print("") for i in range(1, n+1): for j in range (1, i+1): print(j, end="") print("") print("") # Genera que se impriman inversamente for i in range(n, 0, -1): for j in range (1, i+1): print(i, end="") print("") print("") for i in range(n, 0, -1): for j in range (i, 0, -1): print(j, end="") print("") print("")
b5ce09abe340df57a8a61a770f2b18916215308b
KKIverson/python_ds_alg
/parChecker.py
674
3.53125
4
# -*-coding: utf-8 -*- # 括号匹配算法(stack实现) from pythonds.basic.stack import Stack def parChecker(parstring): s = Stack() match = True pos = 0 while pos < len(parstring) and match: par = parstring[pos] if par in '([{<': s.push(par) else: if s.isEmpty(): match = False break top = s.pop() match = parMatch(top, par) pos += 1 if not s.isEmpty(): match = False return match def parMatch(top, par): right = ')]}>' left = '([{<' return left.index(top) == right.index(par) print(parChecker('([<>]>'))
8f219f0722a5b971dab8e1f3904038197cc7ab74
KKIverson/python_ds_alg
/anagramSolution3.py
698
3.5625
4
# using Counter: O(n) solution # space in exchange of time # from collections import Counter # 空间换时间,形成字典,比对字典中key对应的value是否相等 # 时间复杂度为O(n) def anagramSolution3(s1, s2): if len(s1) != len(s2): return False # c1 = Counter(s1) # c2 = Counter(s2) c1 = [0] * 26 c2 = [0] * 26 for i in range(len(s1)): c1[ord(s1[i]) - ord('a')] += 1 c2[ord(s2[i]) - ord('a')] += 1 stillOK = True j = 0 while j < 26 and stillOK: if c1[j] != c2[j]: stillOK = False break j += 1 # return c1 == c2 return stillOK print(anagramSolution3('apple', 'plfap'))
f3d8e79c234d1feebef8a9646bd850963482a298
nageshnemo/python-tkinter-media-player-practice
/messagebox.py
1,290
3.546875
4
from tkinter import * from tkinter import messagebox def finish(): root.destroy() def clear(): e1.delete(0,END) e2.delete(0, END) e3.delete(0, END) e1.focus() def divide(): try: e3.delete(0,END) a = int(e1.get()) b = int(e2.get()) c = a/b e3.insert(0,str(c)) e3.config(fg = "green") except ZeroDivisionError: messagebox.showerror("Error!","Denominator not allowed") except ValueError: messagebox.showerror("Error!", "only integers allowed") root = Tk() root.geometry("400x200+100+200") l1 = Label(root,text = "number division program") l2 = Label(root,text = "first no") l3 = Label(root,text = "second no") l4 = Label(root,text = "result") e1 = Entry(root) e2 = Entry(root) e3 = Entry(root) b1 = Button(root , text = "Divide",command = divide) b2 = Button(root , text = "Clear",command = clear) b3 = Button(root , text = "Quit",command = finish) l1.grid(row = 0,column = 0,columnspan = 4) e1.grid(row = 1,column = 1) l2.grid(row = 1,column = 0,sticky = E) e2.grid(row = 2,column = 1) l3.grid(row = 2,column = 0,sticky = E) l4.grid(row = 3,column = 0,sticky = E) e3.grid(row = 3,column = 1) b1.grid(row = 4,column = 0) b2.grid(row = 4,column = 1) b3.grid(row = 4,column = 2) root.mainloop()
4bd672db671a61754d0c7686669d1dca7ed95580
nageshnemo/python-tkinter-media-player-practice
/revision21(choice control).py
550
3.84375
4
# choice controls allow user to select an option from the available list of choices """ == Checkbutton """ from tkinter import * def changecolor(): if x.get() == 1: root.configure(bg = "red") else: root.configure(bg = old_color) root = Tk() root.geometry("200x200") old_color = root["bg"] x = IntVar() #x is object of Intvar we make a object of this because checkbutton doesnt have any method to get the value cb = Checkbutton(root,text = "Red",command = changecolor,variable = x) cb.pack() root.mainloop() root.mainloop()
fab350d499b8157596923bfaef8a639f83dec1a3
pashamur/euler-golf
/017/p17.py
1,036
3.890625
4
#!/usr/bin/python import sys small_num = { 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"} tens = {2 : "twenty", 3 : "thirty", 4 : "forty", 5 : "fifty", 6 : "sixty", 7 : "seventy", 8 : "eighty", 9 : "ninety" } def sm_getsize(n): if n < 20: return len(small_num.get(n)) elif n % 10 == 0: return len(tens.get(int(n/10))) else: return len(tens.get(int(n/10)))+len(small_num.get(n%10)) def getsize(n): if n<100: return sm_getsize(n) elif n%100 == 0: return len(small_num.get(n/100)) + len("hundred") else: return len(small_num.get(n/100)) + len("hundredand") + sm_getsize(n%100) def main(): total = 0 for i in range(1,1000): total += getsize(i) print total+len("onethousand") if __name__ == "__main__": main()
a8d673cf846640945cff93ea07ae11f416512f78
nirmalshah88/pygame-sudoku
/sudoku_section.py
2,534
4.09375
4
# -*- coding: utf-8 -*- import pygame from pygame.sprite import Sprite from sudoku_settings import Settings from sudoku_block import Block class Section(Sprite): def __init__(self, num, game): """Initialize Sudoku section (9 x 9 blocks)""" super().__init__() ## Initialize vars self.screen = game.screen self.settings = Settings() self.width = self.settings.section_width self.height = self.settings.section_height self.game = game self.num = num self.left = 0 self.top = 0 def draw_section(self): """Draw Sudoku section of blocks""" ## Set section postitions based on num if self.num <= 3: self.left = float(self.width * (self.num - 1)) self.top = 0 elif self.num > 3 and self.num <= 6: self.left = float(self.width * (self.num % 3)) self.top = float(self.height) elif self.num > 6 and self.num <= 9: self.left = float(self.width * (self.num % 3)) self.top = float(self.height * 2) ## Create rect # print(self.left, self.top, self.width, self.height) self.rect = pygame.Rect((self.left, self.top), (self.width, self.height)) ## Create 9 blocks for each section self.blocks = pygame.sprite.Group() for num in range(1,10): block = Block(num, self.game) self.blocks.add(block) ## Draw section with blocks for block in self.blocks.sprites(): pygame.draw.rect(rect=self.rect, color=(0,0,0), surface=self.screen, border_radius=0) block.draw_block(self.left, self.top) ## Draw section borders pygame.draw.lines(surface=self.screen, color=(0,255,0), closed=True, points = [(self.left, self.top), (self.left, self.top + self.height), (self.left + self.width, self.top + self.height), (self.left + self.width, self.top)]) # Draw blocks for section # for num in range(1,10): # for block in self.blocks.sprites(): # block.draw_block(self.num)
61e5de5e94d03dd6a54066d413214363a26d5958
SABAT-dev/PROJETOS-EM-PYTHON
/TP3/Simon_Assagra_DR1_TP3 (QUESTÃO3).py
459
3.90625
4
#QUESTÃO 3: for voto in range(5): nome = str(input(f"Informe o nome do {voto + 1}º participante: ")).strip() nota = float(input(f"Informe a nota do {voto + 1}º participante: ")) #CONDIÇÃO: if nota >= 0 and nota <= 10: print() if voto == 0 or nota > nota_vencedor: vencedor = nome nota_vencedor = nota else: quit() print(f"O(a) vencedor(a) foi {vencedor} com nota {nota_vencedor}")
25f91e5a79b7006e9e52ba87767661d8eec1a84a
kickccat/sample
/PandasStaudy/Study_folder/src/testInherit.py
1,111
3.546875
4
import math import numpy class Animal(object): def __init__(self, name): self.name = name def getInfo(self): print "This is animal's name: %s" %self.name def sound(self): print "The sound of this animal goes?" class Dog(Animal): def __init__(self, name, size): super(Dog, self).__init__(name) self.__size = size def getInfo(self): print "This dog's name: %s" %self.name print "This dog's size: %s" %self.__size class Cat(Animal): def sound(self): print "The sound of cat goes meow" cat = Cat('kaka'); dog = Dog('coco', 'small') indices = [0,1,2,3,4] values = [6,7,8,9,0] def sp(indices,values): vec = [indices,values] #ind = values.index(numpy.nonzero(values)) print max(vec[1]).index #=========================================================================== # print indices[ind],values[ind] # return ind,max(values) #=========================================================================== sp(indices,values)
2e98af33d4218cbf5c05240826e5916e19fb931e
Rainlv/LearnCodeRepo
/Pycode/Crawler_L/threadingLib/demo1.py
949
4.15625
4
# 多线程使用 import time import threading def coding(): for x in range(3): print('正在写代码{}'.format(threading.current_thread())) # 当前线程名字 time.sleep(1) def drawing(n): for x in range(n): print('正在画画{}'.format(threading.current_thread())) time.sleep(1) if __name__ == "__main__": t1 = threading.Thread(target=coding) # 传入的函数不含(),是coding不是coding() t2 = threading.Thread(target=drawing,name='drawingThread',args=(3,)) # name参数给线程命名,arg=()参数是在函数需要传参时用的 t1.start() t2.start() print(threading.enumerate()) # 查看当前所有的线程 t1.join() # 插队,在主线程前,先运行t1、t2线程,保证先运行完t1和t2再进行下面的print t2.join() # 这是主线程 print(threading.enumerate()) # 查看当前所有的线程
0a96a9e56fac1e05146792e1df951f043daed5bb
cs-fullstack-2019-spring/python-arraycollections-cw-rsalcido-1
/Grade WorkW3.py
2,415
4.0625
4
# Problem 1: # # # # # # Create a function with the variable below. After you create the variable do the instructions below that. # # # # # # arrayForProblem2 = ["Kenn", "Kevin", "Erin", "Meka"] # # # a) Print the 3rd element of the numberList. # # # # # # b) Print the size of the array # # # # # # c) Delete the second element. # # # # # d) Print the 3rd ele from typing import List def main(): problem4() # /////////////////////////////////////////////////////////////////////////////// # def problem1(): # # nam = ["Kenn", "Kevin","Erin", "Meka"] # # print(nam[2]) # print(len(nam)) # nam.remove("Erin") # print(nam[2]) # /////////////////////////////////////////////////////////////////////////////// # Problem 2: # # We will keep having this problem until EVERYONE gets it right without help # # Create a function that has a loop that quits with ‘q’. If the user doesn't enter 'q', ask them to input another string. # # def problem2(): # uI = "" # userInputPrint = "" # # while(uI != 'q'): # userInputPrint += uI + "\n" # uI = input("Input string here") # print(userInputPrint) # ////////////////////////////////////////////////////////////////////////////////// # Create a function that contains a collection of information for the following. After you create the collection do the instructions below that. # # Jonathan/John # Michael/Mike # William/Bill # Robert/Rob # def problem3(): # # phonebook = { # "Jonathan":'John', # "Michael":'Mike', # "William":'Bill', # "Robert":'Rob' # } # print(phonebook) # print(phonebook['William']) # /////////////////////////////////////////////////////////////////////////// # Problem 4: # # Create an array of 5 numbers. Using a loop, print the elements in the array reverse order. Do not use a function # def problem4(): # nam = [1,2,3,4,5] # for eachEl in range(len(nam)-1,-1,-1): # print(nam[eachEl]) # ////////////////////////////////////////////////////////////////////////////// # Problem 5: # # Create a function that will have a hard coded array then ask the user for a number. # Use the userInput to state how many numbers in an array are higher, lower, or equal to it. def problem5(): list = [1,2,3,4,5] input("Please pick a number from 1 thru 4") if __name__ == '__main__': main()
8d7f17c196cd73489492db794c2ea8db9858bfbd
Anas-Tomazieh/Python_Stack-
/inter2.py
1,591
4.09375
4
# x = [ [5,2,3], [10,8,9] ] # students = [ # {'first_name': 'Michael', 'last_name' : 'Jordan'}, # {'first_name' : 'John', 'last_name' : 'Rosales'} # ] # sports_directory = { # 'basketball' : ['Kobe', 'Jordan', 'James', 'Curry'], # 'soccer' : ['Messi', 'Ronaldo', 'Rooney'] # } # z = [ {'x': 10, 'y': 20} ] # # Change the value 10 in x to 15. Once you're done, x should now be [ [5,2,3], [15,8,9] ]. # x[1][0] = 15 # print (X) # # Change the last_name of the first student from 'Jordan' to 'Bryant' # students [0]['last_name'] = 'Bryant' # print(students) # # In the sports_directory, change 'Messi' to 'Andres' # sports_directory ['soccer'][0]='Andres' # print(sports_directory) # # Change the value 20 in z to 30 # z[0]['y'] = 30 # print(z) # students = [ # {'first_name': 'Michael', 'last_name' : 'Jordan'}, # {'first_name' : 'John', 'last_name' : 'Rosales'}, # {'first_name' : 'Mark', 'last_name' : 'Guillen'}, # {'first_name' : 'KB', 'last_name' : 'Tonel'} # ] # def iterateDictionary(students): # for student in students: # print(f"first_name - {student['first_name']},last name - {student['last_name']}") # iterateDictionary(students) students = [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'}, {'first_name' : 'Mark', 'last_name' : 'Guillen'}, {'first_name' : 'KB', 'last_name' : 'Tonel'} ] def iterateDictionary2(key_name,students): for student in students: print(student[key_name]) iterateDictionary2('first_name',students)
39d5510129b23fc19a86740a018f61f19638570c
duchamvi/lfsrPredictor
/utils.py
599
4.28125
4
def bitToInt(bits): """Converts a list of bits into an integer""" n = 0 for i in range (len(bits)): n+= bits[i]*(2**i) return n def intToBits(n, length): """Converts an integer into a list of bits""" bits = [] for i in range(length): bits.append(n%2) n = n//2 return bits def stringToInt(str_input): """Checks that the input string is an integer then converts it""" try: int_input = int(str_input) except: print("That's not a valid input, please enter an integer next time") exit(0) return int_input
5009218a95311bb93c7a31fcab001aa22bdc2626
mike42/pyTodo
/todolist/ListBackend.py
837
3.546875
4
class ListBackend(object): """ Class to help manage the todo-list data structure in an array """ def __init__(self): self.lst = [] self.fname = None def load(self, fname): self.fname = fname with open(fname, 'r') as f: for line in f: self.append(line) def save(self): if self.fname is None: return with open(self.fname, 'w') as f: for line in self.lst: f.write(line + "\n") def del_by_index(self, index): if index < 0: # Too small. Ignore return if index >= len(self.lst): # Too large. Ignore return del self.lst[index] def append(self, item): if item != "": self.lst.append(item.strip("\n"))
b0401052dab558b2f3a893008e4d9261eae108e3
bhagi162/python2017fall
/4Task1.py
264
3.90625
4
def nested_sum(nested_list): total=0 for x in nested_list: if isinstance(x, int): total=total+x else: for n in x: total=total+n return total s=[4,5,6,[1,2,3],5] print (nested_sum(s))
9f594e1b409daa6b188336f1860b42ab2ff2ecd7
deyuwang/pisio
/test/comprehension.py
111
3.765625
4
''' @author: wdy ''' #comprehension print {x: x * x for x in range(3, 6)} print [x * 2 for x in range(3, 6)]
caa267957d591edadf7b2336e4cab3a4e294c4c5
kulkarpo/sparkfiles
/basic/exercise3/my-min-temperatures.py
1,449
3.625
4
from pyspark import SparkContext, SparkConf import collections def parse_line(line): """ parse the line and return required fields for performing analytics every entry has ITE00100554,18000101,TMAX,-75,,,E, [0], [1], [2], [3],[4],[5], [6] To analyse the minimum temperature by location [0] : location [1] : date [2] : min/ max [3] : respective temperature . . We need, [0], [2], [3] fields """ split_record = line.split(",") location = split_record[0] min_max = split_record[2] temp = float(split_record[3]) return (location, min_max, temp) conf = SparkConf().setMaster("local").setAppName("minTempByLocation") sc = SparkContext(conf = conf) lines = sc.textFile("file:/Users/pk/Documents/Studies/selflearn/gitspark/exercise3/1800.csv") rdd = lines.map(parse_line) # Now that your rdd has required data # 1. retain/filter only min temperatures min_temperatures = rdd.filter(lambda x: "TMIN" in x[1]) # 2. Now that you have only min temps, keep only location and temperature reading pair (loc, #reading) min_temp_pair = min_temperatures.map(lambda x: (x[0], x[2])) # 3. Reduce by key(location), have the minimum temp for every loc minbyloc = min_temp_pair.reduceByKey(lambda x, y: min(x, y)) # 4. let the magic happen! spark action - collect() result = minbyloc.collect() # Print result for res in result: print(""+ res[0]+" : "+str(res[1]))
3891b107447bab9fb392ffe1604ef54e772e1f5c
KostadinKrushkov/DesignPatterns
/adapter_pattern/implementation.py
1,356
3.5
4
class MetricSystem: # Target def derive_distance(self, minutes, velocity): return minutes * velocity / 60 class ImperialSystem: # Adaptee def derive_time(self, distance, velocity): return distance / velocity def derive_veloctiy(self, distance, time): return distance / time class SystemAdapter(ImperialSystem): # Adapter adaptee = None distance = None def __init__(self, adaptee): self.adaptee = adaptee def get_distance(self, time, velocity): self.distance = self.adaptee.derive_distance(time, velocity) return self.translate_distance_to_imperial() def translate_distance_to_imperial(self): self.distance = self.distance * 0.62137119 return self.distance def translate_distance_to_metric(self): self.distance = self.distance / 0.62137119 return self.distance class DistanceCalculator: # Client target = None def __init__(self, target): self.target = target def travel(self, time, velocity): distance = self.target.get_distance(time, velocity) print('With {} minutes and {} km/h, you traveled {} miles'.format(time, velocity, distance)) if __name__ == "__main__": adapter = SystemAdapter(MetricSystem()) calculator = DistanceCalculator(adapter) calculator.travel(120, 100)
04320d7cad5a0aff770a50170feb284ac231117d
Lukasz-MI/Knowledge
/Basics/02 Operators/math operators.py
718
4.25
4
# math operators a = 12 b = 7 result = a + b; print(result) result = a - b; print(result) result = a * b; print(result) result = a / b; print(result) result = a % b; print(result) result = a % 6; print(result) result = a ** 3; print(result) # 12*12*12 result = a // b; print(result) #assignment operators a = 12 a += 1 # a = a +1 print(a) a-= 1 print(a) a*= 3 print(a) a/= 4 print(a) a%= 4 print(a) a**= 7 print(a) a+= 8 print(a) a = int(a) print(a) a//= 4 print(a) # comparison operators b = 10 == 9 ; print(b) # False print (10 != 8) # True - 10 does not equal 8 print (9 >= 9) # True print (2<2) # False print (17 < 10) # False if 10 >5: print("Yay!") c= 14 if c > a: print ("damn!")
77868cdb39ef46ad241e51ef21ad88e1ed1897cc
Lukasz-MI/Knowledge
/Basics/03 if and loops/nested loops.py
217
3.84375
4
from typing import List severalLists = [ ["Kate" , "John" , "Adam"], [23, 80, 122], ["banjo" , 1 , "guitar" , 2 , "vocals " , 3] ] print(severalLists) for list in severalLists: for v in list: print (v)
239372e51dabbe5107846b0926983a6e5012894b
Lukasz-MI/Knowledge
/Basics/01 Data types/13 immutable vs mutable.py
464
3.671875
4
# immutable: int, float, bool, str, tuple, frozenset a = 1 addr1 = id(a) a += 1 addr2 = id(a) print (addr1) #2243938707760 print (addr2) #2243938707792 print (addr1 == addr2) # False - diferent ids in immutable types # mutable types: list, set, dict data = [1, "Anne" , 30, "Henry"] addr1 = id(data) print(addr1) data += [33, "Monica" , 40] print (data) addr2 = id(data) print (addr2) print (addr1 == addr2) # True - the same ids in mutable types
8e0148c31c798685c627b54d2d3fe90df4553443
Lukasz-MI/Knowledge
/Basics/01 Data types/06 type - tuple.py
907
4.28125
4
data = tuple(("engine", "breaks", "clutch", "radiator" )) print (data) # data [1] = "steering wheel" # cannot be executed as tuple does not support item assignment story = ("a man in love", "truth revealed", "choice") scene = ("new apartment", "medium-sized city", "autumn") book = story + scene + ("length",) # Tuple combined print (book) print(len(book)) print(type(book)) # <class 'tuple'> emptyTuple = () print(emptyTuple) print(type(emptyTuple)) # <class 'tuple'> print (book [-1]) print (book [len(book) -1]) print (book [3:]) print(book[::2]) cars = (("KIA", "Hyundai", "Mazda") , ("bmw", "mercedes", "Audi")) print(cars) print(cars[0][0]) # first tuple, first value - KIA if "Mazda" in cars[0]: print ("Yupi!") # del cars [0] - single element deletion not allowed del cars # print(cars) - whole tuple deleted - NameError: name 'cars' is not defined tuplex3 = book * 3 print(tuplex3)
42b0da6daa9978f806a2d4541637307753a61909
johnrichardrinehart/CodingProblems
/random/all_permutations/main.py
2,259
3.59375
4
def main(): wobt_tests() worp_tests() def wobt_tests(): tests = [ ([1,2,], [[1,2],[2,1],]), ([1,1,],[[1,1,],[1,1],]), ([1,2,3,], [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,2,1],[3,1,2],]) ] for i in range(len(tests)): test = tests[i] results = [] result = without_backtracking(test[0], 0, results) if result != test[1]: print(f"Failed: without_backtracking test {i}! Got {result}, expected {test[1]}") else: print("Passed: wobt test {i}") def without_backtracking(arr, depth, results): if depth == len(arr): results.append(arr[:]) for i in range(depth, len(arr)): # swap the ith and depth-th values tmp = arr[i] arr[i] = arr[depth] arr[depth] = tmp without_backtracking(arr,depth+1, results) # backtrack arr[depth] = arr[i] arr[i] = tmp return results def worp_tests(): tests = [ # ([1,2,], [[1,2],[2,1],]), ([1,1,],[[1,1,],]), ([1,1,2], [[1,1,2],[1,2,1],[2,1,1],],), (["a","b","a"],[["a","a","b"],["a","b","a"],["b","a","a",],],), ] for i in range(len(tests)): test = tests[i] results = [] result = without_repeats(test[0], 0, results) if result != test[1]: print(f"Failed: without_repeats test {i}! Got {result}, expected {test[1]}") else: print(f"Passed: worp test {i}") def without_repeats(arr, depth, results): m = dict() vals, counts = [],[] for val in arr: cnt = m.get(val,0) m[val] = cnt + 1 for k in m: vals.append(k) counts.append(m[k]) def loop(values, counts, arr, j, n, results): if j == n: results.append(arr[:]) return for i in range(0, len(values)): if counts[i] > 0: if len(arr) > j: arr[j] = values[i] else: arr.append(values[i]) counts[i] -= 1 loop(values, counts, arr, j+1, n, results) counts[i] += 1 # restore it return results return loop(vals, counts, [], 0, sum(counts), results) main()
52239420343b5adf7889dfc971f6417223b13c38
hoangnguyen1312/code-practice
/DivideAndConquer.py
3,576
4.09375
4
# Binary Search # Compare it to the middle element of array # if it is equal return result # else if it is lower , recursion first haft array # else if it is greater, recursion second half array def binarySearch (arr, element): if arr == []: return False middle = arr.index(arr[(len(arr) - 1)//2]) if element < arr[middle]: binarySearch(arr[:middle], element) elif element > arr[middle]: binarySearch(arr[middle+1:], element) return arr.index(element) if element in arr else False a = binarySearch([1,2,3,4,11,6,7,8,9,10,11],111) #print("Exist at index {0}".format(a)) # if element does not exist in array, last statement is still executed #------------------------------------------------------------------------------------ #Quick Sort #choose pivot is last element in array def partition1(arr, low, high): pivot = arr[high] index = low - 1 for i in range(low, high): if (arr[i] < pivot): index = index + 1 arr[i], arr[index] = arr[index], arr[i] arr[index+1], arr[high] = arr[high], arr[index+1] return index + 1 def quickSort1(arr, low, high): if (low < high): pos = partition1(arr, low, high) print (arr) quickSort1(arr, low, pos - 1) quickSort1(arr, pos + 1, high) return arr print(quickSort1([8, 9, 2, 1, 0, 0, 7, 6, 11, 4, 9, 5],0,11)) #-------------------------------------------------------------------------------------------------- def partition2(arr, low, high): #Choose most-left pivot pivot = arr[low] for i in range(low + 1, high + 1): if arr[i] <= pivot: continue for j in range(high - 1, low - 1, -1): if arr[j] > pivot: continue if i < j: arr[i],arr[j] = arr[j], arr[i] tmp = -1 for i in range(low, high + 1): if (arr[i] <= pivot): tmp += 1 arr[i], arr[arr.index(pivot)] = arr[arr.index(pivot)], arr[i] return tmp + low def quickSort2(arr, low, high): if low < high: pos = partition2(arr, low, high) quickSort2(arr, low, pos - 1) quickSort2(arr, pos + 1, high) return arr #print(quickSort2([10,9,8,7,3,2,4,13],0,7)) #print(quickSort2([1,2,3,4,3,6,7,8],0,7)) #print(quickSort2([8,8,8,8,8,8,8,8],0,7)) #print(quickSort2([8,7,6,5,4,3,2,1],0,7)) #---------------------------------------------------------------------------------------------------- # mergeSort # determine middle element, seperate array into two halves, seperate util each halve has one element # merge two halves into bigger sorted array def mergeSort(arr): if len(arr) > 1: print("hihi") print(arr) middle = len(arr)//2 L = arr[:middle] print(L) R = arr[middle:] print(R) mergeSort(L) mergeSort(R) i = 0 j = 0 k = 0 print("start merge") print(arr) print(L) print(R) while (i < len(L) and j < len(R)): if L[i] <= R[j]: arr[k] = L[i] i += 1 else: arr[k] = R[j] j += 1 k += 1 while (i < len(L)): arr[k] = L[i] i += 1 k += 1 while (j < len(R)): arr[k] = R[j] j += 1 k += 1 print("After merge") print(arr) return arr #print(mergeSort([10,9,8,7,3,2,4,13])) def binarySearchTree(): pass
164fcb27549ae14c058c7eaf3b6c47b58d198e6d
Dan-krm/interesting-problems
/gamblersRuin.py
2,478
4.34375
4
# The Gambler's Ruin # A gambler, starting with a given stake (some amount of money), and a goal # (a greater amount of money), repeatedly bets on a game that has a win probability # The game pays 1 unit for a win, and costs 1 unit for a loss. # The gambler will either reach the goal, or run out of money. # What is the probability that the gambler will reach the goal? # How many bets does it take, on average, to reach the goal or fall to ruin? import random as random import time as time stake = 10 # Starting quantity of currency units goal = 100 # Goal to reach in currency units n_trials = 10000 # Number of trials to run win_prob = 0.5 # Probability of winning an individual game def gamble(cash, target_goal, win_probability): """ A single trial of a gambler playing games until they reach their goal or run out of money. cash: the gambler's initial amount of currency units goal: the number of currency units to reach to be considered a win win_prob: the likelihood of winning a single game return: a tuple (outcome, bets): - outcome: the outcome of the trial (1 for success, 0 for failure) - bets: number of bets placed """ # play games until the goal is reached or no more currency units remain bets = 0 # number of bets placed while 0 < cash < target_goal: bets += 1 if random.random() < win_probability: cash += 1 else: cash -= 1 # return tuple of trial outcome, number of bets placed if cash == target_goal: return 1, bets else: return 0, bets def display_gamble(): print("\nQuestion 2: Gamblers Ruin\n") # run a number of trials while tracking trial wins & bet counts bets = 0 # total bets made across all games from all trials wins = 0 # total trials won start = time.time() # time when we started the simulation for t in range(n_trials): w, b = gamble(stake, goal, win_prob) wins += w bets += b end = time.time() # time when we stopped the simulation duration = end - start # display statistics of the trials print('Stake:', stake) print('Goal:', goal) print(str(100 * wins / n_trials) + '% were wins') print('Average number of bets made:', str(bets / n_trials)) print('Number of trials:', n_trials) print('The simulation took:', duration, 'seconds (about', n_trials/duration, 'trials per second)')
8babc659615885331c025a366d21e21dd701ee2c
Ckk3/functional-programming
/imperative.py
1,583
4.46875
4
def get_names(peoples_list): ''' Function to get all names in a list with dictionaries :param peoples_list: list with peoples data :return: list with all names ''' for people in peoples_list: names_list.append(people['name']) return names_list def search_obese(peoples_list): ''' Function to get people with BMI higher than 30 in as list with dictionaries :param peoples_list: list with peoples data :return: list with obese people ''' for people in peoples_list: if people['bmi'] >= 30: people_with_obesity.append(people) return people_with_obesity peoples = [{'name': 'Joao', 'bmi': 27}, {'name': 'Cleiton', 'bmi': 21}, {'name': 'Julia', 'bmi': 16}, {'name': 'Carlos', 'bmi': 43}, {'name': 'Daniela', 'bmi': 31} ] #Geting names names_list = [] names_list = get_names(peoples_list=peoples) other_names_list = get_names(peoples_list=peoples) print(f'Names: {names_list}') print(f'Other names: {other_names_list}') #Geting people with obesity people_with_obesity = [] people_with_obesity = search_obese(peoples_list=peoples) other_people_with_obesity = search_obese(peoples_list=peoples) print(f'Peoples with obesity: {people_with_obesity}') print(f'Other peoples with obesity: {other_people_with_obesity}') #Geting higher BMI bmi_list = [] for people in peoples: if people['bmi'] >= 30: bmi_list.append(int(people['bmi'])) higher_bmi = 0 for bmi in bmi_list: if higher_bmi < bmi: higher_bmi = bmi print(f'Higher BMI: {higher_bmi}')
d1526a3746a7e3956170475451d81f2bc9d3c1e1
codingwithchad/journal
/topscore/topscore.py
2,196
3.984375
4
import unittest def sort_scores(unsorted_scores, highest_possible_score): # if the length is 0 or 1, we can return. There is nothing to sort. if len(unsorted_scores) <= 1: return unsorted_scores # Create a list to hold all possible scores in O(m) space where m is the size of highest_possible_score all_scores = [0] * highest_possible_score # For each score in unsorted scores, add it to the all_scores list. this is O(n) time # where n is the size of unsorted_scores for score in unsorted_scores: all_scores[score] += 1 # sortedscores is a list to hold the scores in sorted order sortedscores = [] try: x = 1 + 2 except Bo # Loop through all the scores in the high score list is O(m) time # If there is a score at that number, we add it to the sortedscores list for score in range(len(all_scores) - 1, -1, -1): if(all_scores[score] > 0): for i in range(all_scores[score]): sortedscores.append(score) return sortedscores # Tests class Test(unittest.TestCase): def test_no_scores(self): actual = sort_scores([], 100) expected = [] self.assertEqual(actual, expected) def test_one_score(self): actual = sort_scores([55], 100) expected = [55] self.assertEqual(actual, expected) def test_two_scores(self): actual = sort_scores([30, 60], 100) expected = [60, 30] self.assertEqual(actual, expected) def test_many_scores(self): actual = sort_scores([37, 89, 41, 65, 91, 53], 100) expected = [91, 89, 65, 53, 41, 37] self.assertEqual(actual, expected) def test_repeated_scores(self): actual = sort_scores([20, 10, 30, 30, 10, 20], 100) expected = [30, 30, 20, 20, 10, 10] self.assertEqual(actual, expected) def test_repeated_longer_scores(self): actual = sort_scores([20, 98, 10, 30, 30, 10, 20, 98, 12, 99, 32, 47, 95, 12, 1, 95, 95, 95, 13], 100) expected = [99, 98, 98, 95, 95, 95, 95, 47, 32, 30, 30, 20, 20, 13, 12, 12, 10, 10, 1] self.assertEqual(actual, expected) unittest.main(verbosity=2)
8edd94d0b1eaf9b1c62ae0cd63bc03385d8c5fc7
breurlucas/computer-theory
/TM-simulator/main.py
3,493
3.609375
4
# import libraries # ----------------------------------------------------------------------------- # # Lucas Breur # 29-09-2020 # Senac Computer Theory - Turing Machine Simulator # # ----------------------------------------------------------------------------- # FILE READING file = open("tm-example.txt", "r") # Open file in read-only mode file_list = file.readlines() # Store lines as strings in an array file_list = [line.strip('\n') for line in file_list] # Remove newline characters file_list = [line.replace(' ', '') for line in file_list] # Remove spaces # VARIABLE CONSTRUCTION qa = file_list[1] # Acceptance state q0 = 1 # Initial state q = q0 # Current state initialization head_position = 1 # Head position initialization # Reading variables start_transitions = 3 # First transition item nr_transitions = int(file_list[2]) # Number of transitions start_words = start_transitions + nr_transitions + 1 # First word item nr_words = int(file_list[start_transitions + nr_transitions]) # Number of words # Create Transition Matrix # Crop the file in order to consider only the transition rules ts_matrix = file_list[start_transitions:(nr_transitions + start_transitions)] # ts_matrix = [list(line) for line in ts_matrix] # Convert strings to arrays of characters # print(ts_matrix) # Create list of words for the simulation words = file_list[start_words:(nr_words + start_words)] words = [list(word) for word in words] # Convert strings to arrays of characters [word.insert(0, '-') for word in words] # Insert '-' at the start [word.insert(len(word), '-') for word in words] # Insert '-' at the end # print(words) # SIMULATOR FUNCTIONS def write(index, new, tp): # Function that writes on the tape tp[index] = new return tp def move_head(direction, pos): # Function that moves the head if direction == 'D': pos += 1 else: pos -= 1 return pos def update_status(new, curr): # Function that updates the status curr = new return curr def array_to_string(arr): # Convert array to string temp = "" for char in arr: temp += char return temp # EXECUTION # Loop the simulation through all the words itr = 1 # Iteration counter for word in words: tape = word[:] # Copy word onto tape (Prevents passing it by reference) # While not in the accepting state while q != qa: # Create substring of current state (q) + current symbol (head position on tape) input_state_symbol = str(q) + str(tape[head_position]) # print(input_state_symbol) # Match the input substring to the list of available instructions, if none is found, reject ts_match = [ts.find(input_state_symbol, 0, 2) for ts in ts_matrix] try: ts_index = ts_match.index(0) except ValueError: break # Save transition found transition = ts_matrix[ts_index] # print(transition) # Write on tape tape = write(head_position, transition[2], tape) # Move head head_position = move_head(transition[3], head_position) # Update status q = update_status(transition[4], q) # Check in the acceptance state was reached if q == qa: print(f"{itr}: {(array_to_string(word[1:len(word)-1]))} OK") else: print(f"{itr}: {(array_to_string(word[1:len(word)-1]))} not OK") # Reset variables q = 1 head_position = 1 # Increment counter itr += 1
b58bb5e5e2b3095373c43ef9a50bb8b3354dd96f
jccramos/My-first-repository
/threads_concurrent/05-loop.py
1,335
4.03125
4
#Muito bem, para termos uma ideia mais consolidada sobre o assunto #criaremos um loop, executanto a função 10 vezes import time import threading def any_foo(): ''' any_foo é uma função cuja tarefa leva 1 segundo para ser realizada ''' print('sleeping 1 second') time.sleep(1) print('Feito Sleeping') inicio = time.perf_counter() #Lista de cada thread criadas, para posteriormente aplicarmos o join() threads = list() #criando um lop com 10 threads for _ in range(10): # Por convenção, utilizar o "_" como variável do for, significa que # está variável não será utilizada dentro do loop. Ex. de uma variável # utilizada no loop: "for i in range(10): n = n+i" t = threading.Thread(target = any_foo) t.start() threads.append(t) #aplicando o join(). Neste ponto, deve-se entender que colocar o join #dentro do ultimo loop, faria com que nosso código levasse 10 segundo para #ser executado. Pois para cada thread, o código ficara parado esperando o retorno #da função. Em resumo o código estaria funcionando de maneira síncrona. for thread in threads: thread.join() fim = time.perf_counter() tempo = fim - inicio print('O tempo de execução foi: ', tempo, 'segundos') #Vamos tornar as coisas mais interessante, vamos passar um argumento #para any_foo
24fbaecc8188a65661c110fccd4437c830441f9a
deepakpesumalnai/Project
/Sample Programs/Function/Function.py
412
4.0625
4
def square(num): ''' This funtion is get square of passed number in parameter num :param num: int :return: int ''' out = num ** 2 print('in function') print(out) return out def main(): print('In main function') # square(number) if __name__ == '__main__': number = 8 main() result = square(number) print(f'result is {result}') print(type(result))
0b07b95409bc0997f454bc6d70cb4d358e0e8646
quentin-burthier/MT_UGC
/tools/lid_filter.py
908
3.53125
4
"""Script to filter sentences in the wrong languages.""" def main(src_path: str, tgt_path: str, src_lid_path: str, tgt_lid_path: str, src_filtered: str, tgt_filtered: str, src_lang: str, tgt_lang: str): with open(src_path, "r") as src_raw, open(src_lid_path) as src_lid, open(tgt_path, "r") as tgt_raw, open(tgt_lid_path) as tgt_lid, open(src_filtered, "w") as src_f, open(tgt_filtered, "w") as tgt_f: for src_line, src_line_lang, tgt_line, tgt_line_lang in zip(src_raw, src_lid, tgt_raw, tgt_lid): if src_line_lang[-3:-1] == src_lang and tgt_line_lang[-3:-1] == tgt_lang: src_f.write(src_line) tgt_f.write(tgt_line) if __name__ == "__main__": import sys if len(sys.argv) != 9: print("python $lid_filter.py {{$input_dir/,$filtered_dir/{labels.,}}train.,}{$src,$tgt}") else: main(*sys.argv[1:])
61d4723114beae66a55474d38fee9a5b90a9db56
imdeepmind/AgeGenderNetwork
/model/utils.py
892
3.703125
4
import datetime as date from dateutil.relativedelta import relativedelta # This method compares two dates and return the difference in years def compare_date(start, end): try: d1 = date.datetime.strptime(start[0:10], '%Y-%m-%d') d2 = date.datetime.strptime(str(end), '%Y') rdelta = relativedelta(d2, d1) diff = rdelta.years except Exception as ex: print(ex) diff = -1 return diff # Cleans the full date def clean_full_date(dt): temp = dt.split('-') year = temp[0] month = temp[1] day = temp[2] if (len(year) != 4): year = '0000' if (len(month) == 1): month = '0' + month if (month == '00'): month = '01' if (len(day) == 1): day = '0' + day if (day == '00'): day = '01' return year + '-' + month + '-' + day
9d0a8bf89bb87595953b5344bd78529ae8f8b9a6
LeedsCodeDojo/Refuctoring
/Gordon_Phil_Python/versions/fizzbuzz.py.11.animal_abuse
631
3.640625
4
#!/usr/bin/python3 # Stringify the number # Over-indentation # Semi-colons # Not abuse # Magic numbers # ASCIIfication # Snooze # Cats and horses # linebreaks # Animal abuse def fizzbuzz(number): horse = 'cat'; cat = 'horse'; number = '.' * number; zzzz = chr(122) * 2 if not len(number) % len('a {1} and {0}'.format(horse, cat)): return fizzbuzz(147) + fizzbuzz(39580); else: if not len(number) % len(horse): return chr(70) + chr(105) + zzzz; else: if not len(number) % len(cat): return chr(66) + chr(117) + zzzz; else: return len(number); if __name__ == '__main__': for i in range(30): print(fizzbuzz(i))
8d6dae8f899541ae5683d26b8a8e8a0c87f5046a
MatthewBieda/Tenure-Track-2030
/Tenure Track.py
7,327
3.9375
4
""" Python Tkinter Splash Screen This script holds the class SplashScreen, which is simply a window without the top bar/borders of a normal window. The window width/height can be a factor based on the total screen dimensions or it can be actual dimensions in pixels. (Just edit the useFactor property) Very simple to set up, just create an instance of SplashScreen, and use it as the parent to other widgets inside it. """ from tkinter import * class SplashScreen(Frame): def __init__(self, master=None, width=0.8, height=0.6, useFactor=True): Frame.__init__(self, master) self.pack(side=TOP, fill=BOTH, expand=YES) # get screen width and height ws = self.master.winfo_screenwidth() hs = self.master.winfo_screenheight() w = 800 h = 600 # calculate position x, y x = 800 y = 600 self.master.geometry('%dx%d+%d+%d' % (w, h, x, y)) self.master.overrideredirect(True) self.lift() if __name__ == '__main__': root = Tk() sp = SplashScreen(root) sp.config(bg="#3366ff") m = Label(sp, text="TENURE TRACK 2030\n\n\nStop Chris!\n\nArrow keys to move\nSpace to shoot Karel bullets!") m.pack(side=TOP, expand=YES) m.config(bg="#3366ff", justify=CENTER, font=("calibri", 29)) Button(sp, text="Press this button to start!", bg='yellow', command=root.destroy).pack(side=BOTTOM, fill=X) root.mainloop() import random import math import pygame from pygame import mixer # Initialize pygamep pygame.init() # Create the screen screen = pygame.display.set_mode((800, 600)) # Background background = pygame.image.load("dusk.jpg") # Background sound bgm = pygame.mixer.Sound("background.wav") pygame.mixer.Channel(1).play(bgm, -1) # Caption and Icon pygame.display.set_caption("Tenure Track 2030") icon = pygame.image.load("UFO.png") pygame.display.set_icon(icon) # Player playerImg = pygame.image.load("Mehran.png") playerX = 370 playerY = 480 playerX_change = 0 # Enemy enemyImg = [] enemyX = [] enemyY = [] enemyX_change = [] enemyY_change = [] num_of_enemies = 6 for i in range(num_of_enemies): enemyImg.append(pygame.image.load("Chris.png")) enemyX.append(random.randint(0, 736)) enemyY.append(random.randint(50, 150)) enemyX_change.append(4) enemyY_change.append(40) # Bullet # Ready - You can't see the bullet on the screen # Fire - The bullet is currently moving bulletImg = pygame.image.load("Karel.png") bulletX = 0 bulletY = 480 bulletX_change = 0 bulletY_change = 10 bullet_state = "ready" # Score score_value = 0 font = pygame.font.Font('freesansbold.ttf', 32) textX = 10 textY = 10 # Game Over text over_font = pygame.font.Font('freesansbold.ttf', 64) lose_font = pygame.font.Font('freesansbold.ttf', 50) def show_score(x, y): score = font.render("Score: " + str(score_value) + "/50", True, (0, 0, 255)) screen.blit(score, (x, y)) def game_over_text(): over_text = lose_font.render("CHRIS STOLE YOUR TENURE! ", True, (0, 255, 0)) screen.blit(over_text, (25, 250)) def player(x, y): screen.blit(playerImg, (x, y)) def enemy(x, y, i): screen.blit(enemyImg[i], (x, y)) def fire_bullet(x, y): global bullet_state bullet_state = "fire" screen.blit(bulletImg, (x + 16, y + 10)) def isCollision(enemyX, enemyY, bulletX, bulletY): distance = math.sqrt((math.pow(enemyX - bulletX, 2)) + (math.pow(enemyY - bulletY, 2))) if distance < 27: return True else: return False # Game Loop running = True while running: # RGB values screen.fill((0, 0, 0)) # Background image screen.blit(background, (0, 0)) for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # if keystroke is pressed check whether its right or left if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: playerX_change = -5 if event.key == pygame.K_RIGHT: playerX_change = 5 if event.key == pygame.K_SPACE: if bullet_state == "ready": bullet_sound = mixer.Sound("laser.wav") bullet_sound.play() # Get the current x coordinate of the spaceship bulletX = playerX fire_bullet(bulletX, bulletY) if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: playerX_change = 0 # Checking for boundaries of spaceship so it doesn't go out of bounds playerX += playerX_change if playerX <= 0: playerX = 0 elif playerX >= 736: playerX = 736 # Enemy movement for i in range(num_of_enemies): # Game Over if enemyY[i] > 440: for j in range(num_of_enemies): enemyY[j] = 2000 game_over_text() play_again = font.render("Play again?: y/n ", True, (0, 255, 0)) screen.blit(play_again, (275, 425)) if event.type == pygame.KEYDOWN: if event.key == pygame.K_n: pygame.quit() elif event.key == pygame.K_y: score_value = 0 for j in range(num_of_enemies): enemyY[j] = 100 enemyX[i] += enemyX_change[i] if enemyX[i] <= 0: enemyX_change[i] = 4 enemyY[i] += enemyY_change[i] elif enemyX[i] >= 736: enemyX_change[i] = -4 enemyY[i] += enemyY_change[i] # Collision collision = isCollision(enemyX[i], enemyY[i], bulletX, bulletY) if collision: explosion_sound = mixer.Sound("explosion.wav") explosion_sound.play() mehran_party = mixer.Sound("party time.wav") if random.randint(0, 5) == 3: mehran_party.play() bulletY = 480 bullet_state = "ready" score_value += 1 enemyX[i] = random.randint(0, 735) enemyY[i] = random.randint(50, 150) enemy(enemyX[i], enemyY[i], i) # Bullet movement if bulletY <= 0: bulletY = 480 bullet_state = "ready" if bullet_state == "fire": fire_bullet(bulletX, bulletY) bulletY -= bulletY_change if score_value >= 50: you_win = over_font.render("YOU STOPPED CHRIS! ", True, (0, 255, 0)) screen.blit(you_win, (50, 250)) for i in range(num_of_enemies): enemyY[i] = -2000 play_again = font.render("Play again?: y/n ", True, (0, 255, 0)) screen.blit(play_again, (275, 425)) if event.type == pygame.KEYDOWN: if event.key == pygame.K_n: pygame.quit() elif event.key == pygame.K_y: score_value = 0 for j in range(num_of_enemies): enemyY[j] = 100 player(playerX, playerY) show_score(textX, textY) pygame.display.update()
c1fb0eb8ce344825c695e5dfcc408ff2c9f93a7e
befreeman/advent-of-code-2016
/day2/test_puzzle_two.py
4,497
4.03125
4
""" Let's test the Keypad Class! """ import unittest from puzzle_two import Keypad class TestKeypad(unittest.TestCase): """ make sure keypad works as expected! """ def setUp(self): """ set up an instance of keypad for the test cases """ self.keypad = Keypad() def test_can_make_keypad(self): """ test the default keypad """ # make sure we start on the middle key, 5 self.assertTrue(self.keypad.row == 2) self.assertTrue(self.keypad.column == 0) def test_get_key(self): """ make sure that 'get_key' returns the expected value """ # check the midle left self.assertEqual(self.keypad.get_key(), 5) # check the top middle self.keypad.row = 0 self.keypad.column = 2 self.assertEqual(self.keypad.get_key(), 1) # check the middle right self.keypad.row = 2 self.keypad.column = 4 self.assertEqual(self.keypad.get_key(), 9) # check the bottom middle self.keypad.row = 4 self.keypad.column = 2 self.assertEqual(self.keypad.get_key(), 'D') def test_move_up(self): """ make sure we move up correctly""" # make sure we can't move up from 2,0 to 1,0 self.keypad.move_up() self.assertTrue(self.keypad.row == 2) # make sure that we can move up from 3,1 to 2,1 self.keypad.row = 3 self.keypad.column = 1 self.keypad.move_up() self.assertTrue(self.keypad.row == 2) # make sure we won't go out of bounds from 0,2 self.keypad.row = 0 self.keypad.correctly = 2 self.keypad.move_up() self.assertTrue(self.keypad.row == 0) def test_move_down(self): """ make sure we move down correctly """ # make sure we can move down a row self.keypad.move_down() self.assertTrue(self.keypad.row == 2) # make sure that we can move down from 2,1 to 3,1 self.keypad.row = 2 self.keypad.column = 1 self.keypad.move_down() self.assertTrue(self.keypad.row == 3) # make sure that we can't go out of bounds from 4,2 self.keypad.row = 4 self.keypad.column = 2 self.keypad.move_down() self.assertTrue(self.keypad.row == 4) def test_move_left(self): """ make sure we move left correctly """ # make sure that we can't go out of bounds from 2,0 self.keypad.move_left() self.assertTrue(self.keypad.column == 0) # make sure that we move left from 1,2 to 1,1 self.keypad.row = 1 self.keypad.column = 2 self.keypad.move_left() self.assertTrue(self.keypad.column == 1) # make sure that, when we can't move left, we stay at 0 self.keypad.move_left() self.assertTrue(self.keypad.column == 1) def test_move_right(self): """ make sure we move down correctly """ # make sure we can move right a column self.keypad.move_right() self.assertTrue(self.keypad.column == 1) # make sure that we can't go out of bounds from 2,4 self.keypad.column = 4 self.keypad.move_right() self.assertTrue(self.keypad.column == 4) # make sure that, when we can't move right, we stay at 2 self.keypad.column = 3 self.keypad.row = 1 self.keypad.move_right() self.assertTrue(self.keypad.column == 3) def test_AoC_instructions(self): """ run through the AoC puzzle 2 example """ # first row - ULL - ends at 1 self.keypad.move_up() self.keypad.move_left() self.keypad.move_left() self.assertTrue(self.keypad.get_key() == 5) # second row - RRDDD - ends at 9 self.keypad.move_right() self.keypad.move_right() self.keypad.move_down() self.keypad.move_down() self.keypad.move_down() self.assertTrue(self.keypad.get_key() == 'D') # third row - LURDL - ends at 8 self.keypad.move_left() self.keypad.move_up() self.keypad.move_right() self.keypad.move_down() self.keypad.move_left() self.assertTrue(self.keypad.get_key() == 'B') # fourth row - UUUUD - ends at 5 self.keypad.move_up() self.keypad.move_up() self.keypad.move_up() self.keypad.move_up() self.keypad.move_down() self.assertTrue(self.keypad.get_key() == 3)
4f9b344063339fec622fae3a4ac18ceff57d10be
AlexandreCassilhas/W3schoolsExamples
/Dictionaries.py
1,370
4.3125
4
thisdict = { "brand": "Ford", "model": "Mustang", "year": "1964" } print (thisdict) x = thisdict["model"] print(x) # Acessando o valor de um elemento do dicionário z = thisdict.get("brand") print(z) # Alterando o valor de um elemento do dicionário thisdict["year"] = 2018 print (thisdict) # Varrendo as chaves do dicionário for x in thisdict: print(x) # Varrendo os valores de cada elemento de um dicionário print (" ") for x in thisdict: print (thisdict[x]) print ("ou") for x in thisdict.values(): print (x) # Varrendo as chaves e os respectivos valores print(" ") for x, y in thisdict.items(): print (x, y) # Verificando a existência de um valor no dicionário if "Ford" in thisdict.values(): print ("Ok. Existe") # Verificando a existência de uma key no dicionário if "model" in thisdict: print ("Ok. Model Existe") # Adicionando novo item ao dicionário thisdict["color"] = "red" print (thisdict) # Removendo um item do dicionário thisdict.pop("color") print(thisdict) print("ou") del thisdict["model"] print(thisdict) # Copiando um dicionário print (" ") novodicionario = thisdict.copy() print(novodicionario) # Esvaziando o conteúdo do dicionário thisdict.clear() print(thisdict) # Construindo pelo método dict() thisdict = dict(brand="Ford", model="Mustang", year=2019, color="red") print (thisdict)
5d96e91292e6591de9b42b40c5a5224e34179152
jesusapb/ADA_6-AED
/division.py
2,193
3.515625
4
''' Cambiar nombre a Castear''' class division: def __init__(self,cadena): self.cadena = cadena.pop() self.lista_cadena = [] self.nueva_lista = [] def proceso(self): self.lista_cadena = self.cadena.split() def hacer_ajuste(self): i = 0 while i < 17: if i != 0 and i != 1 and i != 10 and i != 11 and i != 12 and i != 37: self.nueva_lista.append(float(self.lista_cadena[i])) else: self.nueva_lista.append(self.lista_cadena[i]) i = i + 1 self.lista_cadena = self.nueva_lista def hacer_ajuste_2(self): ## Estado self.nueva_lista.append(int(self.lista_cadena[4])) ##fecha de defuncion self.nueva_lista.append((self.lista_cadena[12])) ##edad self.nueva_lista.append(int(self.lista_cadena[15])) self.lista_cadena= self.nueva_lista def hacer_ajuste_3(self): ##Estado self.nueva_lista.append(int(self.lista_cadena[4])) # Diabetes self.nueva_lista.append(int(self.lista_cadena[20])) #EPOC self.nueva_lista.append(int(self.lista_cadena[21])) # self.nueva_lista.append(int(self.lista_cadena[22])) # self.nueva_lista.append(int(self.lista_cadena[23])) # self.nueva_lista.append(int(self.lista_cadena[24])) # self.nueva_lista.append(int(self.lista_cadena[25])) # self.nueva_lista.append(int(self.lista_cadena[26])) # self.nueva_lista.append(int(self.lista_cadena[27])) # self.nueva_lista.append(int(self.lista_cadena[28])) # self.nueva_lista.append(int(self.lista_cadena[29])) self.lista_cadena = self.nueva_lista # Metodo para pruebas locales, NO USAR en el programa global def imprimir_cadena(self): print(self.lista_cadena) print(len(self.lista_cadena)) #print(self.nueva_lista) #for i in self.lista_cadena: # print(i) #print(float(self.lista_cadena[2]))
38f1ff52dd1686fe177bd44ced6a722be2ad677a
rajeshsrinivasa1981/Demo
/Unit Testing/Unittestfile1.py
738
3.546875
4
import unittest from SampleProjects.Examples import Example class MyTestCase1(unittest.TestCase): @classmethod def setUpClass(cls) -> None: print("This will run once before all the methods") @classmethod def tearDownClass(cls) -> None: print("This will run once after all the methods") def setUp(self) -> None: print("This will run before every method") def tearDown(self) -> None: print("this will run after every method") def test_add(self): result = Example.add(self,10,20) self.assertEqual(result,30) def test_sum(self): result = Example.sub(self,40,10) self.assertEqual(result,30) if __name__ == '__main__': unittest.main()
2988f907df24214c55e01e78ef2245a77b333a73
Roger-Yao8126/cmpe273_20spring
/cmpe273-lab1/submit/async_ext_merge_sort.py
4,269
3.75
4
#CMPE 273 lab 1 #Use any kind of External Sorting algorithm to # sort all numbers from input/unsorted_*.txt files # and save the sorted result into output/sorted.txt # file amd async_sorted.txt file. import sys import asyncio def read_file(filename): fp=open(filename,'r') contents=fp.readlines() fp.close() return contents # organize data as elements in a list def parse_data(data): dstore =[] for x in range(len(data)): if (data[x][-1] == '\n'): split = data[x][:-1] else: split = data[x] split = int(split) dstore.append(split) return dstore def findMin(numArr, n): min = sys.maxsize pos = 0 for x in range (0,n): if numArr[x]!= None: if numArr[x] < min: min = numArr[x] pos = x return pos def lineToInt(line): if line[-1]== '\n': number = int(line[:-1]) else: number = int(line) return number def merge(arr,l, m , r): n1 = m - l + 1 n2 = r - m # create temp arrays, initialized as 0 L = [0]*n1 R = [0]*n2 # Copy data to temp arrays L[] and R[] for i in range(0, n1): L[i] = arr[l + i] for j in range(0, n2): R[j] = arr[m + 1 + j] # Merge the temp arrays back into arr[l..r] i = 0 # Initial index of first subarray j = 0 # Initial index of second subarray k = l # Initial index of merged subarray while i < n1 and j < n2: if L[i] <= R[j]: arr[k] =L[i] i += 1 else: arr[k] = R[j] j+= 1 k += 1 # Copy the remaining elements of L[], if there # are any while i < n1: arr[k] = L[i] i += 1 k += 1 # Copy the remaining elements of R[], if there # are any while j < n2: arr[k] = R[j] j += 1 k += 1 # l is for left index and r is right index of the # sub-array of arr to be sorted def mergeSort(arr, l, r): if l < r: # Same as (l+r)/2, but avoids overflow for # large l and h. m = (l + r-1) // 2 # Sort first and second halves mergeSort(arr, l, m) mergeSort(arr, m + 1, r) merge(arr, l, m, r) # list is use to put 10 element to compare async def putNumber(myQueue): fileClosed = 0 while True: # print ("putNumber is working!") index = findMin(numArray,10) await myQueue.put(numArray[index]) await asyncio.sleep(0) numToFill = fps[index].readline() if numToFill == '': numArray[index] = None fps[index].close() fileClosed = fileClosed +1 else: numArray[index] = lineToInt(numToFill) if fileClosed == 10: break async def writeFile(myQueue): numWrote =0 while True: await asyncio.sleep(0) item = await myQueue.get() outFilePointer.write(str(item) + '\n') numWrote= numWrote+1 if (numWrote >= 1000): break outFilePointer.close() # start the main program # Specifiy the path of folder , files folder ='/Users/yao/Documents/Study/SJSU_course/273_enterprise_tech_platform/cmpe273-spring20-labs-master/lab1/' inPath= 'input/unsorted_' prePath= 'output/presorted_' outPath = 'output/async_sorted' fileExt = '.txt' # sort each individual file for x in range(1, 11): inputFile = folder + inPath + str(x) + fileExt preFile = folder + prePath + str(x) + fileExt context = read_file(inputFile) numArray = parse_data(context) mergeSort(numArray, 0, 99) with open (preFile,'w+') as f: for line in numArray: f.write(str(line) + "\n") ### Big Sort filenames = [] # read in presorted files for x in range (0,10): filenames.append(folder + prePath + str(x+1) + fileExt) fps = [] for filename in filenames: fps.append(open(filename, 'r')) numArray = [] for fp in fps: line = fp.readline() number = lineToInt(line) numArray.append(number) outputFile = folder + outPath + fileExt outFilePointer = open(outputFile, 'w+') loop = asyncio.get_event_loop() myQueue = asyncio.Queue(maxsize =20) try: loop.run_until_complete(asyncio.gather(putNumber(myQueue), writeFile(myQueue))) except KeyboardInterrupt: pass finally: loop.close()
2e2821bc842d2b6c16a6e9a5f5252b64c4f2d097
ngenter/lnorth
/guessreverse.py
631
4.125
4
# Nate Genter # 1-9-16 # Guess my number reversed # In this program the computer will try and guess your number import random print("\nWelcome to Liberty North.") print("Lets play a game.") print("\nPlease select a number, from 1-100 and I will guess it.") number = int(input("Please enter your number: ")) if number <= 0 or number >= 101: print("That is not a valid number.") tries = 1 guess = () while number != guess: tries == 1 guess = random.randint(1,100) print(guess) if guess != number: tries += 1 print("\nIt took me", tries, "tries.") input("\nPress the enter key to exit.")
5c0ea9f314a48d35fb26c039191122714f908ba1
stillsw/playzone
/interesting algorithms/python/assignments from algorithms courses/heapUtils.py
15,886
3.53125
4
import math, utils """ Home grown heap implementation, supports extractMin/Max, delete, key/priority update and fast lookup of an item (also by added optional lookup key) When calling pop() pass a function if need to do tie breaking... see pop() Note on structure: internally each entry is an array[3] comprising the key in the heap, the object being stored and an optional lookup. To facilitate fast deletes and lookups, the item's index into the heap is stored in a dictionary using the lookup passed in push(), if no lookup is passed, the object itself is used. There is no dependence on the value of an object, it can be changed outside of the heap and the heap *should* not be affected, passing a lookup is optional, but recommended if the item itself might be changed in a way that affects its hashing contract for dictionary lookup. The key/priority is set by the caller and can be changed without problems. API: Heap() : optional param <extractMax=True> if want to reverse the order to track and extract the max instead of min push() : optional param <lookup> if want to be able to be able to reference the item by something other than itself. see lookup() lookup() : returns the item associated with the lookup when stored, see push() pop() : optional param <tieBreaker> if there can be duplicate key items, pass the name of a function to break ties, see end of file for example delete() : deletes the item associated with the lookup param, or if not associated with a lookup pass the item itself in the param, see push() updateKey() : changes the key/priority of the item associated with the lookup param, or if not associated with a lookup, the item itself peek() : peek the top entry, no tie breaking, so if pop() with tie breaking could return a different item than without tie breaking, don't use peek() as it will be unreliable len() : the number of entries in the heap isEmpty() : as it says updateBetter() : conditionally updates an item's key/priority only if the value passed in is better than what it has already returns True if the key was updated as a result Additional functions for testing/debugging: __main__() : runs tests when run script directly from command line printHeapTree() : prints out the heap as a tree runTests() : runs all the tests (lots of output, pipe to a file for easier browsing of results) testTieBreakDupes() : function used to test tie breaking when pop() dupes """ class Heap: KEY_IDX = 0 ITEM_IDX = 1 LOOKUP_IDX = 2 def __init__(self, extractMax=False): self.heap = [] self.indexLookup = dict() # independent of the heap, its purpose it to track the index to the array for any item, so it can be grabbed fast self.extractMax = extractMax def __str__(self): return str(self.heap) def push(self, item, key, lookup=None): if lookup != None and self.indexLookup.has_key(lookup): raise ValueError('Heap.push: duplicate lookup not supported') if lookup == None: if self.indexLookup.has_key(item): raise ValueError('Heap.push: duplicate entry, use a separate lookup') else: lookup = item if self.extractMax: # reverse sign if extract max key *= -1 # doing an insert, add to end and bubble up till heap property is restored entry = [key, item, lookup] self.heap.append(entry) self._bubbleUp(entry, len(self.heap) -1) # idx -1 = end def _bubbleUp(self, entry, i): if i != 0: # unless already at the root parent = ((i + 1) / 2) -1 # trunc the index of the parent, finally also -1 because index from 0 while self.heap[parent][Heap.KEY_IDX] > self.heap[i][Heap.KEY_IDX]: parentEntry = self.heap[parent] # grap the parent self.heap[parent] = self.heap[i] # put the entry in parent's place self.heap[i] = parentEntry # swap the parent down self._updateLookup(parentEntry, i) # update the parent's lookup index if there was one i = parent # update index to new position if i == 0: # break out of the loop if at the root break; parent = ((i + 1) / 2) -1 # find next parent self._updateLookup(entry, i) # add/update lookup entry def _bubbleDown(self, entry, idx): parent = idx + 1 # the multiply to get children only works if start at 1 minChild = None # find the child with the least value for i in range(parent * 2 -1, parent * 2 +1): if i >= len(self.heap): break; if minChild == None or minChild[Heap.KEY_IDX] > self.heap[i][Heap.KEY_IDX]: minChild = self.heap[i] # swap the entry with the least key child if that child's key is < the entry's if minChild != None and minChild[Heap.KEY_IDX] < self.heap[idx][Heap.KEY_IDX]: childIdx = self.indexLookup.get(minChild[Heap.LOOKUP_IDX]) self.heap[childIdx] = entry # swap the entry into the child's pos self._updateLookup(entry, childIdx) # update that lookup self.heap[idx] = minChild # put the child where this entry was self._updateLookup(minChild, idx) # and update that lookup too self._bubbleDown(entry, childIdx) # recurse till drops out def _updateLookup(self, entry, i): self.indexLookup[self.heap[i][Heap.LOOKUP_IDX]] = i def lookup(self, lookup): i = self.indexLookup.get(lookup) if i != None: try: return self.heap[i][Heap.ITEM_IDX] except IndexError: print 'heap.lookup: ERROR with lookup indexing, lookups and indices are inconsistent lookup=\'%s\', index=%d' % (lookup, i) return None else: return None def pop(self, tieBreaker=None): entry = self._delete(0) # break ties by popping them all off into a list and choosing the one to go, then push the remaining ones back onto the heap if tieBreaker != None and len(self.heap) != 0: key = entry[Heap.KEY_IDX] if self.heap[0][Heap.KEY_IDX] == key: dupes = [] while len(self.heap) != 0 and self.heap[0][Heap.KEY_IDX] == key: dupes.append(self._delete(0)) if utils.Debug.debug: print 'FOUND %d duplicate key entries, using tieBreaker to return the correct one' % len(dupes) while len(dupes) != 0: dupe = dupes.pop() winner = tieBreaker(entry, dupe) if winner == entry: self.push(dupe[Heap.ITEM_IDX], dupe[Heap.KEY_IDX], dupe[Heap.LOOKUP_IDX]) else: self.push(entry[Heap.ITEM_IDX], entry[Heap.KEY_IDX], entry[Heap.LOOKUP_IDX]) entry = winner return entry[Heap.ITEM_IDX] def delete(self, lookup): # delete works with lookup, or if none was supplied, then the item itself i = self.indexLookup.get(lookup) if i == None: raise ValueError('Heap.delete: no matching entry found, locates by lookup or if none, then the item is the lookup') return self._delete(i)[Heap.ITEM_IDX] def _delete(self, i): if len(self.heap) == 0: return None entry = self.heap[i] self.indexLookup.pop(entry[Heap.LOOKUP_IDX])# delete from lookups if i == len(self.heap) -1: # last entry, not much to do self.heap.remove(entry) else: lastEntry = self.heap[-1] # overwrite the first entry with the last self.heap.remove(lastEntry) # remove the last entry first self.heap[i] = lastEntry # swap it into the first position self._updateLookup(lastEntry, i) # update the lookup as there might not be any changes from bubbling down self._bubbleDown(lastEntry, i) # bubble it down to where the heap property is restored return entry def updateKey(self, lookup, key): i = self.indexLookup.get(lookup) if i == None: raise ValueError('Heap.updateKey: no matching entry found, locates by lookup or if none, then the item is the lookup') self._updateKey(i, key) def _updateKey(self, i, key): if self.extractMax: # extract max need to reverse sign of key key *= -1 entry = self.heap[i] oldP = entry[Heap.KEY_IDX] entry[Heap.KEY_IDX] = key if key > oldP: self._bubbleDown(entry, i) # bubble it down to where the heap property is restored elif key < oldP and i > 0: # might need to bubble up self._bubbleUp(entry, i) def updateBetter(self, lookup, key): # conditionally does an update of the key, only if the value is improved i = self.indexLookup.get(lookup) if i == None: raise ValueError('Heap.promoteBetter: no matching entry found, locates by lookup or if none, then the item is the lookup') testKey = key # the update method also reverses the sign, so use a temp var if self.extractMax: # extract max need to reverse sign of key testKey *= -1 if self.heap[i][Heap.KEY_IDX] > testKey: self._updateKey(i, key) return True else: return False def peek(self): if len(self.heap) == 0: return None _,item,_ = self.heap[0] return item def len(self): return len(self.heap) def isEmpty(self): return len(self.heap) == 0 def _printChildren(heap, parent, showDetails): parent = parent + 1 # the multiply to get children only works if start at 1 for i in range(parent * 2 -1, parent * 2 +1): if i >= len(heap): break; line = ' ' * int(math.log(i+1,2)) if showDetails: print '%s|--- %s [%s lookup=\'%s\']' % (line, str(heap[i][0]), str(heap[i][1]), str(heap[i][2])) else: print '%s|--- %s' % (line, str(heap[i][0])) _printChildren(heap, i, showDetails) def printHeapTree(heap, showDetails=False): if len(heap) == 0: print 'heap is empty' else: print 'heap tree:' if showDetails: print ' %s [%s lookup=\'%s\']' % (str(heap[0][0]), str(heap[0][1]), str(heap[0][2])) else: print ' %s' % str(heap[0][0]) _printChildren(heap, 0, showDetails) def runTests(heap): print 'add a bunch of strings with numbers and lookups' test1 = [[1, 'one', 'one'],[6, 'six', 'six'],[4, 'four', 'four'],[9, 'nine', 'nine'],[0, 'zero', 'zero'],[12, 'twelve', None],[2, 'two', None],[3, 'three', None],[8, 'eight', None],[7, 'seven', None],[-2, 'minus two', None],[-2, 'minus two 2', 'dupe2'],[-2, 'minus 22', 'tutu']] for p,s,k in test1: heap.push(s,p,k) print 'heap after adding %s (key=%s)' % (s,str(p)) #print ' %s' % (str(heap)) printHeapTree(heap.heap) #utils.waitForInput() print 'test popping the items' while not heap.isEmpty(): s = heap.pop() print 'heap after popping %s' % (s) printHeapTree(heap.heap) #utils.waitForInput() print 'test re-adding all the items again' for p,s,k in test1: heap.push(s,p,k) printHeapTree(heap.heap) print 'test deleting a few of them' print 'deleting first entry (same as pop)' heap.delete('minus two') printHeapTree(heap.heap) print 'delete three' heap.delete('three') printHeapTree(heap.heap) print 'attempt deleting three (same again)' try: heap.delete('three') print 'ERROR: didn\'t raise value error....!' except ValueError: print 'got expected value error' print 'heap now: %s' % (str(heap)) print 'delete 2nd to last entry (nine)' heap.delete('nine') printHeapTree(heap.heap) print 'heap now: %s' % (str(heap)) print 'delete last entry (eight)' heap.delete('eight') printHeapTree(heap.heap) print 'test updateBetter' for i in range(1, 5): if heap.extractMax: lookup = 'zero' newKey = i * 3 else: lookup = 'twelve' newKey = 12 - i * 4 print ' change key for \'%s\' to %d' % (lookup, newKey) heap.updateBetter(lookup, newKey) printHeapTree(heap.heap, True) #utils.waitForInput() print 'test updating just the lower value priorities to their minus values' for p,s,k in test1: if p > 3: newP = p * -1 lookup = None if k != None and heap.lookup(k) != None: lookup = k elif k == None and heap.lookup(s) != None: lookup = s if lookup != None: print 'updating key for \'%s\' to %d' % (s, newP) heap.updateKey(lookup, newP) printHeapTree(heap.heap, True) #utils.waitForInput() print 'test lookups return the items' for p,s,k in test1: if k != None: print ' heap get value for lookup %s = %s' % (k, heap.lookup(k)) else: print ' heap get value for itself %s = %s' % (s, heap.lookup(s)) if not heap.extractMax: while not heap.isEmpty(): heap.pop() print 'test pop duplicate entries w/o tiebreaking' for p,s,k in test1: if p == -2: heap.push(s,p,k) print ' heap before pop anything, pop dupes in arbitrary order' printHeapTree(heap.heap, True) while not heap.isEmpty(): print ' popped %s' % heap.pop() print 'test pop duplicate entries w tiebreaking' for p,s,k in test1: if p == -2: heap.push(s,p,k) print ' heap before pop anything, pop dupes in tie break order (alphabetical)' printHeapTree(heap.heap, True) while not heap.isEmpty(): print ' popped %s' % heap.pop(testTieBreakDupes) def testTieBreakDupes(entry1, entry2): if entry1[Heap.ITEM_IDX] > entry2[Heap.ITEM_IDX]: winner = entry2 else: winner = entry1 print 'test tie break dupe %s v %s, winner is %s' % (str(entry1), str(entry2), str(winner)) return winner if __name__ == '__main__': utils.Debug.debug = True print 'running heap tests using extract max' heap = Heap(True) runTests(heap) print 'running heap tests' heap = Heap() runTests(heap)
9ec968141f9eb927247483e0f50d3ae94db70e1a
rdeaton/spyral
/rect.py
7,680
4.3125
4
class Rect(object): """ Rect represents a rectangle and provides some useful features. Rects can be specified 3 ways in the constructor * Another rect, which is copied * Two tuples, `(x, y)` and `(width, height)` * Four numbers, `x`, `y`, `width`, `height` Rects support all the usual :ref:`anchor points <anchors>` as attributes, so you can both get `rect.center` and assign to it. Rects also support attributes of `right`, `left`, `top`, `bottom`, `x`, and `y`. """ def __init__(self, *args): if len(args) == 1: r = args[0] self._x, self._y = r.x, r.y self._w, self._h = r.w, r.h elif len(args) == 2: self._x, self._y = args[0] self._w, self._h = args[1] elif len(args) == 4: self.left, self.top, self.width, self.height = args else: raise ValueError("You done goofed.") def __getattr__(self, name): if name == "right": return self._x + self._w if name == "left" or name == "x": return self._x if name == "top" or name == "y": return self._y if name == "bottom": return self._y + self._h if name == "topright": return (self._x + self._w, self._y) if name == "bottomleft": return (self._x, self._y + self._h) if name == "topleft": return (self._x, self._y) if name == "bottomright": return (self._x + self._w, self._y + self._h) if name == "centerx": return (self._x + self._w / 2.) if name == "centery": return (self._y + self._h / 2.) if name == "center": return (self._x + self._w / 2., self._y + self._h / 2.) if name == "midleft": return (self._x, self._y + self._h / 2.) if name == "midright": return (self._x + self._w, self._y + self._h / 2.) if name == "midtop": return (self._x + self._w / 2., self._y) if name == "midbottom": return (self._x + self._w / 2., self._y + self._h) if name == "size": return (self._w, self._h) if name == "width" or name == "w": return self._w if name == "height" or name == "h": return self._h raise AttributeError("type object 'rect' has no attribute '" + name + "'") def __setattr__(self, name, val): # This could use _a lot_ more error checking if name[0] == "_": self.__dict__[name] = int(val) return if name == "right": self._x = val - self._w elif name == "left": self._x = val elif name == "top": self._y = val elif name == "bottom": self._y = val - self._h elif name == "topleft": self._x, self._y = val elif name == "topright": self._x = val[0] - self._w self._y = val[1] elif name == "bottomleft": self._x = val[0] self._y = val[1] - self._h elif name == "bottomright": self._x = val[0] - self._w self._y = val[0] - self._h elif name == "width" or name == "w": self._w = val elif name == "height" or name == "h": self._h = val elif name == "size": self._w, self._h = val elif name == "centerx": self._x = val - self._w / 2. elif name == "centery": self._y = val - self._h / 2. elif name == "center": self._x = val[0] - self._w / 2. self._y = val[1] - self._h / 2. elif name == "midtop": self._x = val[0] - self._w / 2. self._y = val[1] elif name == "midleft": self._x = val[0] self._y = val[1] - self._h / 2. elif name == "midbottom": self._x = val[0] - self._w / 2. self._y = val[1] - self._h elif name == "midright": self._x = val[0] - self._w self._y = val[1] - self._h / 2. else: raise AttributeError("You done goofed!") def copy(self): """ Returns a copy of this rect """ return Rect(self._x, self._y, self._w, self._h) def move(self, x, y): """ Returns a copy of this rect offset by *x* and *y*. """ return Rect(x, y, self._w, self._h) def move_ip(self, x, y): """ Moves this rect by *x* and *y*. """ self._x, self._y = self._x + x, self._y + y def inflate(self, width, height): """ Returns a copy of this rect inflated by *width* and *height*. """ c = self.center n = self.copy() n.size = (self._w + width, self._h + height) n.center = c return n def inflate_ip(self, width, height): """ Inflates this rect by *width*, *height*. """ c = self.center self.size = (self._w + width, self._h + height) self.center = c def clip(self, r): """ Returns a Rect which is cropped to be completely inside of r. If the r does not overlap with this rect, 0 is returned. """ B = r A = self try: B._x except TypeError: B = Rect(B) if A._x >= B._x and A._x < (B._x + B._w): x = A._x elif B._x >= A._x and B._x < (A._x + A._w): x = B._x else: return Rect(A._x, A._y, 0, 0) if ((A._x + A._w) > B._x) and ((A._x + A._w) <= (B._x + B._w)): w = A._x + A._w - x elif ((B._x + B._w) < A._x) and ((B._x + B._w) <= A._x + A._w): w = B._x + B._w - x else: return Rect(A._x, A._y, 0, 0) if A._y >= B._y and A._y < (B._y + B._h): y = A._y elif B._y >= A._y and B._y < (A._y + A._h): y = B._y else: return Rect(A._x, A._y, 0, 0) if ((A._y + A._h) > B._y) and ((A._y + A._h) <= (B._y + B._h)): h = A._y + A._h - y elif ((B._y + B._h) > A._y) and ((B._y + B._h) <= (A._y + A._h)): h = B._y + B._h - y else: return Rect(A._x, A._y, 0, 0) return Rect(x, y, w, h) def contains(self, r): """ Returns True if the rect r is contained inside this rect """ if self.clip(r).size == r.size: return True return False def collide_rect(self, r): """ Returns true if this rect collides with rect r. """ return self.clip(r).size != (0,0) or r.clip(self).size != (0,0) def collide_point(self, point): """ Returns true if this rect collides with point """ # This could probably be optimized as well return point[0] > self.left and point[0] < self.right and \ point[1] > self.top and point[1] < self.bottom def __str__(self): return ''.join(['<rect(', str(self._x), ',', str(self._y), ',', str(self._w), ',', str(self._h), ')>']) def __repr__(self): return self.__str__()
0a2d5097d521d659c7bae0dd6ae4e0e03dfbb497
rdeaton/spyral
/color.py
1,475
3.546875
4
_scheme = {} sample = """ color,r,g,b color1,r,g,b,a """ def install_color_scheme(filename): """ Loads a colorscheme from a file, and installs the colors there for use with any spyral function which accepts a color by passing a string as the color name. You can install more than one scheme, but each installation will overwrite any colors which were already installed. Color schemes are CSV files which follow the form *name,r,g,b* or *name,r,g,b,a* where r,g,b,a are integers from 0-255 for the red, green, blue, and alpha channels respectively. """ f = open(filename, 'r') for line in f.readlines(): values = line.split(',') if len(values) == 4: color, r, g, b = values a = 0 elif len(values) == 5: color, r, g, b, a = values else: continue r = int(r) b = int(b) g = int(g) a = int(a) _scheme[color] = (r,g,b,a) def get_color(name): """ Takes a color name as a string and returns the rgba version of the color. """ try: return _scheme[name] except KeyError: raise ValueError("%s is not a color from an installed scheme." % name) def _determine(color): """ Internal to figure out what color representation was passed in. """ if isinstance(color, str): return get_color(name) else: return color
49aa5ca2f32071f9973f46886266469daab4c134
Mushinako/Advent-of-Code-2020
/Day_21/utils/read_input.py
475
3.5
4
""" Module: Read and parse input file Public Functions: read_input: Read and parse input file """ from pathlib import Path from .sentence import Sentence def read_input(path: Path) -> list[Sentence]: """ Read and parse input file Args: path (Path): Input file path Returns: (list[Sentence]): Parsed input file """ with path.open("r") as fp: return [Sentence.from_input_line(line) for l in fp if (line := l.strip())]
f52f96dbdfd7ed61d164be91ae57dadf0f9e24c9
Mushinako/Advent-of-Code-2020
/Day_22/utils/read_input.py
604
3.671875
4
""" Module: Read and parse input file Public Functions: read_input: Read and parse input file """ from pathlib import Path from collections import deque def read_input(path: Path) -> tuple[deque[int], deque[int]]: """ Read and parse the input file Args: path (Path): Input file path Returns: (tuple[deque[int], deque[int]]): Puzzle input """ with path.open("r") as fp: player1, player2 = fp.read().split("\n\n") return ( deque(int(n) for n in player1.splitlines()[1:]), deque(int(n) for n in player2.splitlines()[1:]), )
20ee733c07c2f5403b3b52004a6ec64e039f3f4f
sevgibayansalduzz/NLP-WORKS
/Corrector/driver1.py
1,041
3.546875
4
import pickle from src.convert_turkish import highest_possible_sentence, convert_to_english_letter, convert_to_turkish_letter from src.ngram import Ngram from src.hecele import text_to_syllable with open("input/tr_wiki_30.txt",encoding="utf8",errors='replace') as myfile: train_data=myfile.read() train_data=text_to_syllable(train_data) print("model is reading") ngrams=[] for i in range(5): ngrams.append(Ngram(i+1,train_data)) print("model is readed") while True: sentence=input("Enter a sentece or exit with E.") sentence=convert_to_english_letter(sentence) possible_sentences=convert_to_turkish_letter(sentence) if sentence.lower()=='e': print("Program is finished.") break for i in range(5): highest_possible_sentence(ngrams[i],i+1,possible_sentences) print("model is saving") for i in range(5): file = open('model/'+str(i+1)+"gram.pickle", 'wb') pickle.dump(ngrams[i], file) file.close() print("model is saved")
ecab82333f58ead4bbcce3d45f8c22f93490f78a
AvTe/Python-Complex-Coding-Question
/Solution_01.py
254
3.859375
4
# Answer 1: #program which will find all such numbers which are divisible by 7 # # but are not a multiple of 5, between 2000 and 320 nl=[] for x in range(1500, 2701): if (x%7==0) and (x%5==0): nl.append(str(x)) print (','.join(nl))
b60beee10433a71d8222f45985014f0e8d206cff
AlexseySukhanov/HomeWork14
/rectangle.py
2,073
3.671875
4
class Rectangle: def __init__(self, width, heigth): self.w = width self.h = heigth def __str__(self): return str(self.w * self.h) def __gt__(self, other): if not isinstance(self, Rectangle): raise TypeError(f'{type(self).__name__} Object is not valid') if not isinstance(other, Rectangle): raise TypeError(f'{type(other).__name__} Object is not valid') return self.w * self.h > other.w * other.h def __lt__(self, other): if not isinstance(self, Rectangle): raise TypeError(f'{type(self).__name__} Object is not valid') if not isinstance(other, Rectangle): raise TypeError(f'{type(other).__name__} Object is not valid') return self.w * self.h < other.w * other.h def __eq__(self, other): if not isinstance(self, Rectangle): raise TypeError(f'{type(self).__name__} Object is not valid') if not isinstance(other, Rectangle): raise TypeError(f'{type(other).__name__} Object is not valid') return self.w * self.h == other.w * other.h def __ne__(self, other): if not isinstance(self, Rectangle): raise TypeError(f'{type(self).__name__} Object is not valid') if not isinstance(other, Rectangle): raise TypeError(f'{type(other).__name__} Object is not valid') return self.w * self.h != other.w * other.h def __add__(self, other): if not isinstance(self, Rectangle): raise TypeError(f'{type(self).__name__} Object is not valid') if not isinstance(other, Rectangle): raise TypeError(f'{type(other).__name__} Object is not valid') return self.w * self.h + other.w * other.h def __mul__(self, other): if not isinstance(self, Rectangle): raise TypeError(f'{type(self).__name__} Object is not valid') if not isinstance(other, (int,float)): raise TypeError(f'{type(other).__name__} Multipyer is not valid') return self.w * self.h * other
33291e16ed1a09f2fede35fa1471a4f07b7cd043
ruthubc/ruthubc
/PythonDispersal/src/TestsDrafts/PlayingWithFunctions.py
132
3.71875
4
''' Created on 2013-01-12 @author: Ruth ''' def add_number(number): number += 15 return number print(add_number(10))
8b47b8d751892f46f1ff397a3c1de0ca7ffde08e
olga2288/lpthw
/ex16_1.py
509
3.75
4
from sys import argv script, filename = argv print "\nWe're going to read %r" % filename print "If you don't want that, hit CTRL-C (^C)" print "If you do want that, hit RETURN" raw_input("?") print "Opening the file..." target = open(filename, 'r') print target.read() print "Now I'm going to ask you for three lines " line1 = raw_input("line 1: ") print "Now I'm going to write these to file" target.write(line1) target.write("\n") print target.read() print "and finally, we close it" target.close()
f14076dac6b148114cfec193d02b35a7c16608a2
olga2288/lpthw
/ex44_my.py
659
3.828125
4
class Parent(object): def hello(self): print "\nHello all!!!" # implicite def bzz(self): print "\nI'm sleeping now!!!" print "Bz-z-z-z-z" class Child(Parent): # override def hello(self, name): self.name = name.title() print "\n\tHello %s" % self.name class Child_2(Parent): # alteted def hello(self,name): super(Child_2, self).hello() self.name = name.title() print "\n\tHello %s" % self.name dad = Parent() son = Child() daughter = Child() daughter_2 = Child_2() dad.hello() son.hello('ivan') son.bzz() daughter.hello('olga') daughter_2.hello('dasha') daughter_2.bzz()
5385c94ba5e1b5fba240b6298d4858a7c4490e68
olga2288/lpthw
/ex48/ex48/lexicon.py
721
3.84375
4
words = {'verb' : ['go', 'kill','eat', 'eats'], 'direction' : ['north', 'south', 'east'], 'stop' : ['the', 'in', 'of'], 'noun' : ["bear", "princess"]} def scan(sentence): phrase_words = sentence.split() result = [] for phrase_word in phrase_words: try: number = int(phrase_word) result.append(("number", number)) except: phrase_word_type = None for word_type in words: if phrase_word in words[word_type]: phrase_word_type = word_type if phrase_word_type is None: phrase_word_type = "error" result.append((phrase_word_type, phrase_word)) return result
342d4b53dc20b586b697bc002c78c2539722fb70
LeandrorFaria/Phyton---Curso-em-Video-1
/Script-Python/Desafio/Desafio-035.py
486
4.21875
4
# Desenvolva um programa que leia o comprimento de três retas e diga ao usuário se elas podem ou não formar um triângulo. print('--=--' * 7) print('Analisador de triângulo') print('--=--' * 7) a = float(input('Primeiro segmento:')) b = float(input('Segundo segmento: ')) c = float(input('Terceiro segmento: ')) if a < b + c and b < a + c and c < a + b: print('Os segmentos informados pode FORMAR um triângulo!') else: print('Os segmentos não podem formar um triângulo!')
de09ab5c8218bcd1993a2c5ebe5ee3143f5044a3
LeandrorFaria/Phyton---Curso-em-Video-1
/Script-Python/Desafio/Desafio-019.py
441
4.0625
4
# Um professor quer sortear um dos seus quatro alunos para apagar o quadro. Faça um programa que ajude ele, lendo o nome deles e escrevendo o nome do escolhido. import random a1 = input('Nome do primeiro aluno: ') a2 = input('Nome do segundo aluno: ') a3 = input('Nome do terceiro aluno: ') a4 = input('Nome do quarto aluno: ') lista = [a1, a2, a3, a4] escolhido = random.choice(lista) print('O aluno escolhido foi {} .'.format(escolhido))
10fd00b55bc1d02b636e346dd5b4df069349b337
LeandrorFaria/Phyton---Curso-em-Video-1
/Script-Python/Desafio/Desafio-016.py
227
3.890625
4
# Crie um programa que leia um número Real qualquer pelo teclado e mostre na tela a sua porção inteira. import math n = float(input('Diga-me um número: ')) i = int(n) print('O número absoluto de {} é {} .'. format(n, i))
75ad294709b9191d882e38c6cb3036b545c3dbe6
LeandrorFaria/Phyton---Curso-em-Video-1
/Script-Python/Desafio/Desafio-031.py
411
3.953125
4
# Desenvolva um programa que pergunte a distância de uma viagem em Km. Calcule o preço da passagem cobrando R$ 0,50 por Km para viagens de até 200Km e R$ 0,45 para viagens mais longas. distancia = int(input('Qual a distância em KM da viagem? ')) if distancia <= 200: preco = distancia*0.50 else: preco = distancia*0.45 print('O valor da viagem de {} Km é de R$ {:.2f} .' .format(distancia, preco))
f5fdc3620c1497c1d6356752ec7129ccffe09da7
zacwentzell/BIA660D_Group_1_Project
/prediction/features.py
9,732
3.71875
4
""" More EDA and feature selection BIA660D - Group 1: Alec Kulakowski """ import pandas as pd import numpy as np data = pd.read_csv('../BIA660D_Group_1_Project/eda/hoboken_step1.csv') data.head(2) # Lets see what correlations we can draw and what new features we can create ### Feature Evaluation """ For missing restaurant ratings, we could substitute the median restaurant rating, as that is the most likely value for it to have. A possible other solution would be to replace missing restaurant ratings with a 0 or other number that's outside of the normal range (1-5) for the variable. In nonlinear models (SVMs with a nonlinear kernel, neural nets with nonlinear activation functions, tree-based algorithms) this difference could be accounted for, but if interpreted linearly it would be misleading (the missing restaurant ratings are due to the fact that when I corrected for what the restaurant's rating would have been *before* the review happened, if the restaurant in question has only received that one review, it would have no rating before it. I confirmed this by running: data.iloc[np.where(data['restaurant_rating'].isnull())] which showed that all the restaurants with null ratings were restaurants that had only gotten the one review (I also double checked these ratings on Yelp to confirm that these restaurants had only received one review). Thus, for now (for the EDA as well as when utilizing nonlinear solvers) we will replace these missing restaurant ratings with a rating of 0, but when testing linear solvers we shall replace them with the median score (hopefully I will remember). Dropping them would mean that we wouldn't be training the model to predict any ratings for restaurants that haven't been rated before, which shouldn't be the case """ new_data = data.copy(deep=True) data.iloc[[np.where(data['restaurant_rating'].isnull())], np.where(data.columns == 'restaurant_rating')[0][0]] = 0 #for EDA and nonlinear new_data = new_data.drop(np.where(new_data['restaurant_rating'].isnull())[0]) #^just for EDA exploring the relationship of existing rating to the current review's rating new_data['restaurant_rating'].isnull().sum() == 0 new_data['restaurant_rating'] = new_data['restaurant_rating'].apply(lambda x: round(x*2)/2) # rounding # Lets look at a bar chart showing the variance present at various ratings average_to_rating = new_data[['restaurant_rating', 'user_rating']] #obviously a correlation ofc # maybe just plot dispursion # Relationship of restaurant cuisine type to rating? type_to_ratings = pd.read_csv('../BIA660D_Group_1_Project/eda/type_data.csv') type_to_ratings.sort_values(by='Average_Score', inplace=True) # Relationship of review length to ratings? data['review_len'] = data['user_text'].apply(len) length_to_ratings = data[['review_len', 'user_rating']] # Relationship of price to ratings? price_to_ratings = data[['restaurant_price', 'user_rating']] # Relationship of mispellings to ratings? from autocorrect import spell #import re #? from nltk import word_tokenize import re, string apostrophes = re.compile("'") punctuation = re.compile('[%s]' % re.escape(string.punctuation))# all punctuation marks, but not escape characters i.e \n multiple_spaces = re.compile(' +') # Custom mispelling identifiers #nltk.download('brown'), etc. #pyenchant spell checker doesn't work for non 2.x python on systems other than Linux # from textblob import TextBlob #nope, errors like restauraunts -> restaurant and Grand Vin -> Grand In from nltk.corpus import brown, gutenberg, reuters, masc_tagged, movie_reviews, treebank, \ opinion_lexicon, product_reviews_2, pros_cons, subjectivity, sentence_polarity, words # do not use: stopwords, conll2002, jeita, knbc, alpino, sinica_treebank, udhr, udhr2, these include non-english words # had weird or foreign or slang terms, oomlouts, etc: wordnet, cmudict, genesis corpuses = [brown, gutenberg, reuters, masc_tagged, movie_reviews, treebank, opinion_lexicon, product_reviews_2, pros_cons, subjectivity, sentence_polarity, words] all_word_list = set() #best maybe: words, for counter, corp in enumerate(corpuses, 1): print("Appending corpus #"+str(counter)+" of "+str(len(corpuses))+" to set of all words. ") all_word_list = all_word_list.union(set(map(lambda x: x.lower(), corp.words()))) ### Check where the incorrect words are coming from, to remove that source from the corpuses backup = all_word_list.copy() # for counter, corp in enumerate(corpuses, 1): # if 'jafef' in map(lambda x: x.lower(), corp.words()): # print(counter, corp)# break len(all_word_list) # brown_set = set(map(lambda x: x.lower(), brown.words())) #these all take a few seconds # gutenberg_set = set(map(lambda x: x.lower(), gutenberg.words())) # reuters_set = set(map(lambda x: x.lower(), reuters.words())) # import hunspell #nope # help(hunspell) # hobj = hunspell.hunspell('/usr/share/hunspell/en_US.dic') # len(reuters_set) #31078 # len(reuters_set | brown_set | gutenberg_set) # len(brown_set) #49815 # len(gutenberg_set) #42339 # # def correctly_spelled(word): if all([letter.isdigit() for letter in word]): return( True ) # result = (word.lower() == spell(word).lower()) #autocorrect version # result = (word in word_set) #brown corpus result = (word.lower() in all_word_list) if not result: result = (word.lower() == spell(word).lower()) #I think this one takes longest, so I did it in the 'if' return( result ) def strip_punct(text): text = apostrophes.sub('', text) # To prevent seperating "wouldn't" into "wouldn t" text = punctuation.sub(' ', text) return( multiple_spaces.sub(' ', text).strip() ) def correct_mispellings(text): text = strip_punct(text) sent = "" for word in word_tokenize(text): if any(character.isdigit() for character in word): sent = sent + " " + word else: sent = sent + " " + spell(word) return sent.strip() def count_mispellings(text): #text = temp #for testing #takes ages for all words text = strip_punct(text) mispellings = 0 for word in word_tokenize(text): if not correctly_spelled(word): #not any(character.isdigit() for character in word) # print("word: "+str(word)+", correct: "+str(spell(word))) #for diagnostic purposes mispellings += 1 return mispellings # ^ lol a simple concept but these took quite a while to code to make them robust # data_copy = data.copy(deep=True) # count_mispellings(data['user_text'][2]) # i could do it by chunk? len(data['user_text']) #74611 # data['user_text'] #[:15000] #[15000:30000] # [30000:45000] # [45000:60000] # [60000:] # first_1500 = data['user_text'][:1500].apply(count_mispellings) #careful this takes ages #15 minutes this is taking #86.25s # second_1500 = data['user_text'][1500:3000].apply(count_mispellings) # third_1500 = data['user_text'][3000:4500].apply(count_mispellings) #141s (i dont believe it, it took much longer than that # fourth_1500 = data['user_text'][4500:6000].apply(count_mispellings)#pd.Series # fifth_1500 = data['user_text'][6000:].apply(count_mispellings) #wait its not 7400 in size its 74,000... will take much longer import time #estimated time based on previous averages is roughly: 82.9 minutes, lets see how long it actually takes start = time.time() data['mispelling_count'] = data['user_text'].apply(count_mispellings) #careful this takes ages #started at 11:14 end at end = time.time() print("Process took "+str(end-start)+"s to finish") # 6092.65s = 101.5m # count_series = pd.Series(name='mispelling_count') # [first_1500, second_1500, third_1500, fourth_1500, fifth_1500] # data['user_text'][1498:1502] # count_series[1498:1502] mispelling_to_ratings = data[['mispelling_count', 'user_rating']] data.head(2) # data['mispelling_count'] # text = data['user_text'][23] #for testing # Save data so we don't have to calculate mispellings, review_len, etc. again (can always remove easily, but takes # time and effort to create from scratch. Thus we save it below \/ data.to_csv('../BIA660D_Group_1_Project/eda/hoboken_step2.csv', index = False) #yay! # data.drop(columns=[data.columns[0]], inplace=True) # data.head(3) # """ Some thoughts: maybe I should have kept in the user names for each reviewer so I could count all reviews they left in Hoboken and use that as an independent variable, BUT: upon further inspection this wouldn't really work as it would be quite an arbitrary variable, "number of total reviews" for a reviewer *would* work, but to be robust and avoid possible bias (not to mention the problems associated with small/sparse/incomplete data) it would have to include number of reviews for that user ovearall, not just in Hoboken. Since our scraping didn't pick this up, I can't incorporate it, thus it's fine to keep leaving out the usernames. As an afterthought one may think that counting the number of reviews a given user leaves on the same restaurant would be helpful, and indeed it would (you probably wouldn't go back to the same place unless you thought it was decent), but I believe that Yelp replaces past reviews with the most recent one, so scraping shouldn't be able to find multiple reviews for each user on the restaurant or even a review count. A possible workaround would be number of Yelp "check-ins" the user had at that specific restaurant, but this data (while available on the Yelp page that was scraped) was not scraped in our scraping process (although it is in the Yelp Open Dataset, which ultimately couldn't be used for the predicting due to issues involving the size of the dataset). """ # correct_mispellings(data['user_text'][0]) # data['user_text'][0] data.head(2)
3ef9c9c658eddbd7c5eca93c0a75dc17b3c1df4d
zenghuihuang/exercise-in-c-and-python
/pset6/mario/more/mario.py
398
4.03125
4
from cs50 import get_int def main(): while True: # height is the height of the pyramid height = get_int("Height: ") if height > 0 and height < 9: break get_pyramid(height) def get_pyramid(n): for i in range(n): j = n - i - 1 print(" " * j + "#" * (i + 1) + " " + "#" * (i + 1), end="\n") main()
0ff7c83cc7e96dcce7ffea36fe68941a6098cfe0
SaumyaSingh034/Python---Learning
/While1.py
849
4
4
Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:14:34) [MSC v.1900 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> num = 1 >>> while(num<10): print("Hi! I am ",num) num = num+1 Hi! I am 1 Hi! I am 2 Hi! I am 3 Hi! I am 4 Hi! I am 5 Hi! I am 6 Hi! I am 7 Hi! I am 8 Hi! I am 9 >>> while(num<10): print("Hi! I am ",num) num = num+1 print("While is end") SyntaxError: invalid syntax >>> while(num<10): print("Hi! I am ",num) num = num+1 print("While is end") SyntaxError: invalid syntax >>> while(num<10): print("Hi! I am ",num) num = num+1 print("While is end") SyntaxError: unindent does not match any outer indentation level >>> while(num<10): print("Hi! I am ",num) num = num+1 print("ed") SyntaxError: unindent does not match any outer indentation level >>>
c424471d6428f0fd07164ebc0c92a4ba33447677
SaumyaSingh034/Python---Learning
/Break2.py
145
3.875
4
while True: print("Enter a digit") num = input() var = str(num) if(ord(var) in range(48,58)): break print("You are in")
c442febe8991e40811e2b59fc65e67cde2504e47
SaumyaSingh034/Python---Learning
/AdvancePython/Argparse1.py
653
3.984375
4
import argparse def fib(n): a, b = 0, 1 for i in range(n): a, b = b, a+b return a def Main(): parser = argparse.ArgumentParser() parser.add_argument("num", help = "The Fibonnaci number "+ \ "You wish to calculate", type = int) parser.add_argument("-o","--output", help = "Output the result to a file", action ="store_true") args = parser.parse_args() result = fib(args.num) print("The "+str(args.num)+"th has fib no = "+str(result)) if args.output: f = open("Fibonacci.txt", "a") f.write(str(result)+'\n') if __name__ =="__main__": Main()
dd37f5c73e67f7d545c3551881051a7850405211
SaumyaSingh034/Python---Learning
/FileInput/Copying.py
841
3.96875
4
Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:14:34) [MSC v.1900 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> ufn = input("Enter your filename: ") Enter your filename: TestFile.txt >>> file1 = open(ufn,"r") Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> file1 = open(ufn,"r") FileNotFoundError: [Errno 2] No such file or directory: 'TestFile.txt' >>> ufn = input("Enter your file Name: ") Enter your file Name: WriteFile >>> ufn = ufn+".txt" >>> file1 = open(ufn,"r") >>> file2 = open("CopyFile.txt","w") >>> file2.write(file1.read()) 119 >>> file1.close() >>> file2.close() >>> file2 = open("CopyFile.txt","r") >>> file2.read() 'A new file is created \n Lets see if it works or not\n This is my appending text, lets see if it works or notSaumya singh' >>>
7109531b80f9a2152074b258f67fd5432e909b27
SaumyaSingh034/Python---Learning
/Module/Time Module/Sleep.py
250
3.71875
4
Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:14:34) [MSC v.1900 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> import time >>> for i in range(0,10): print(i) time.sleep(1) 0 1 2 3 4 5 6 7 8 9 >>>