blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
54d13bef355f59710b0b6f7a314d86a6daf8af68
TroyJJeffery/troyjjeffery.github.io
/Computer Science/Data Structures/Week 4/CH5_EX3.py
2,347
4.5
4
""" Modify the recursive tree program using one or all of the following ideas: Modify the thickness of the branches so that as the branchLen gets smaller, the line gets thinner. Modify the color of the branches so that as the branchLen gets very short it is colored like a leaf. Modify the angle used in turning the turtle so that at each branch point the angle is selected at random in some range. For example choose the angle between 15 and 45 degrees. Play around to see what looks good. Modify the branchLen recursively so that instead of always subtracting the same amount you subtract a random amount in some range. If you implement all of the above ideas you will have a very realistic looking tree. """ """ Modify the recursive tree program using one or all of the following ideas: Modify the thickness of the branches so that as the branchLen gets smaller, the line gets thinner. Modify the color of the branches so that as the branchLen gets very short it is colored like a leaf. Modify the angle used in turning the turtle so that at each branch point the angle is selected at random in some range. For example choose the angle between 15 and 45 degrees. Play around to see what looks good. Modify the branchLen recursively so that instead of always subtracting the same amount you subtract a random amount in some range. If you implement all of the above ideas you will have a very realistic looking tree. """ """ I'll come back to this if I have time. I'm tired of dealing with it atm. """ import turtle def tree(branchLen,t): if branchLen > 5: drawRect(t,branchLen) t.right(20) tree(branchLen-15,t) t.left(40) tree(branchLen-15,t) t.right(20) t.backward(branchLen) def drawRect(t, len): width = ((len // 15)*2) x, y = t.xcor(), t.ycor() t.fillcolor("brown") t.fill(True) t.left(90) t.forward(width//2) for i in range(2): t.forward(len) t.left(90) t.forward(width) t.left(90) t.fill(False) t.setx(x) t.sety(y+40) def main(): t = turtle.Turtle() myWin = turtle.Screen() t.left(90) t.up() t.backward(100) t.down() t.color("green") myWin.exitonclick() tree(75,t) main()
952a66e0dcde2ef1da5214ba50f443b355df9d4e
PythonPostgreSQLDeveloperCourse/Section13
/2_queue/linkedlist.py
3,011
4.3125
4
from node import Node class LinkedList: """ You should implement the methods of this class which are currently raising a NotImplementedError! Don't change the name of the class or any of the methods. """ def __init__(self): self.__root = None def get_root(self): return self.__root def add_start_to_list(self, node): """ You can reuse the method written for the previous assignment here. :param node: the node to add at the start :return: None """ marker = self.get_root() node.set_next(marker) self.__root = node def remove_end_from_list(self): """ Implement this method! It should: - Iterate over each node - Find both the second-to-last node and the last node - Set the second-to-last node's next to be None - Return the last node :return: the removed Node. """ marker = self.get_root() while marker: next_node = marker.get_next() if next_node: if not next_node.get_next(): # print('Removing {}'.format(next_node)) marker.set_next(None) return next_node else: self.__root = None return marker marker = next_node def print_list(self): marker = self.get_root() while marker: marker.print_details() marker = marker.get_next() else: print(None) def find(self, name): """ You can reuse the method written for the previous assignment here. :param name: the name of the Node to find. :return: the found Node, or raises a LookupError if not found. """ marker = self.get_root() while marker: if marker.name == name: return marker marker = marker.get_next() else: raise LookupError("Didn't find anyone by the name '{}'".format(name)) def size(self): """ You should implement this method! It should return the amount of Nodes in the list. :return: the amount of nodes in this list. """ count = 0 marker = self.get_root() while marker: count += 1 marker = marker.get_next() return count ''' nodes = [Node(*x) for x in [['George', 9995554444], ['Sarah', 8884442222], ['John', 6662227777]]] ll = LinkedList() for node in nodes: ll.add_start_to_list(node) ll.print_list() print('Root Node: {}'.format(ll.get_root())) print('Found {}'.format(ll.find('Sarah'))) try: print(ll.find('Foo')) except LookupError as e: print(str(e)) print('Length of LL before: {}'.format(ll.size())) ll.remove_end_from_list() print('Length of LL after: {}'.format(ll.size())) print('Contents of LL after') ll.print_list() '''
21f0ba5e725f4dcde7406db8a215105e4402e383
gitcardoso/Pyquest
/Pyquest 1/ex_3.py
698
4.0625
4
"""Faça um programa para solicitar o nome e as duas notas de um aluno. Calcular sua média e informá-la. Se ela for inferior a 7, escrever "Reprovado”; caso contrário escrever "Aprovado".""" aluno = str(input('Digite o nome do aluno:')) nota1 = float(input('Digite a primeira nota do aluno {}:'.format(aluno))) nota2 = float(input('Digite a segunda nota do aluno {}:'.format(aluno))) media = (nota1 + nota2)/2 if media >= 7: print('A média do aluno {} é:{}'.format(aluno, media)) print('O aluno {} foi aprovado, parabéns!'.format(aluno)) else: print('A média do aluno {} é: {}'.format(aluno, media)) print('O aluno {} foi reprovado, precisa estudar mais!'.format(aluno))
d787c39a40fb55aff1e6eb34259254def303f9c4
walkoncross/mxnet-test-zyf
/lr_scheduler/advanced_lr_schedulers.py
15,438
3.828125
4
#!/usr/bin/env python # coding: utf-8 # # Advanced Learning Rate Schedules # # Given the importance of learning rate and the learning rate schedule for training neural networks, there have been a number of research papers published recently on the subject. Although many practitioners are using simple learning rate schedules such as stepwise decay, research has shown that there are other strategies that work better in most situations. We implement a number of different schedule shapes in this tutorial and introduce cyclical schedules. # # See the "Learning Rate Schedules" tutorial for a more basic overview of learning rates, and an example of how to use them while training your own models. # In[ ]: # get_ipython().magic(u'matplotlib inline') import copy import math import mxnet as mx import numpy as np # import matplotlib.pyplot as plt # In[ ]: # def plot_schedule(schedule_fn, iterations=1500): # # Iteration count starting at 1 # iterations = [i+1 for i in range(iterations)] # lrs = [schedule_fn(i) for i in iterations] # plt.scatter(iterations, lrs) # plt.xlabel("Iteration") # plt.ylabel("Learning Rate") # plt.show() # ## Custom Schedule Shapes # # ### (Slanted) Triangular # # While trying to push the boundaries of batch size for faster training, [Priya Goyal et al. (2017)](https://arxiv.org/abs/1706.02677) found that having a smooth linear warm up in the learning rate at the start of training improved the stability of the optimizer and lead to better solutions. It was found that a smooth increases gave improved performance over stepwise increases. # # We look at "warm-up" in more detail later in the tutorial, but this could be viewed as a specific case of the **"triangular"** schedule that was proposed by [Leslie N. Smith (2015)](https://arxiv.org/abs/1506.01186). Quite simply, the schedule linearly increases then decreases between a lower and upper bound. Originally it was suggested this schedule be used as part of a cyclical schedule but more recently researchers have been using a single cycle. # # One adjustment proposed by [Jeremy Howard, Sebastian Ruder (2018)](https://arxiv.org/abs/1801.06146) was to change the ratio between the increasing and decreasing stages, instead of the 50:50 split. Changing the increasing fraction (`inc_fraction!=0.5`) leads to a **"slanted triangular"** schedule. Using `inc_fraction<0.5` tends to give better results. # In[ ]: class TriangularSchedule(): def __init__(self, min_lr, max_lr, cycle_length, inc_fraction=0.5): """ min_lr: lower bound for learning rate (float) max_lr: upper bound for learning rate (float) cycle_length: iterations between start and finish (int) inc_fraction: fraction of iterations spent in increasing stage (float) """ self.min_lr = min_lr self.max_lr = max_lr self.cycle_length = cycle_length self.inc_fraction = inc_fraction def __call__(self, iteration): if iteration <= self.cycle_length*self.inc_fraction: unit_cycle = iteration * 1 / \ (self.cycle_length * self.inc_fraction) elif iteration <= self.cycle_length: unit_cycle = (self.cycle_length - iteration) * 1 / \ (self.cycle_length * (1 - self.inc_fraction)) else: unit_cycle = 0 adjusted_cycle = ( unit_cycle * (self.max_lr - self.min_lr)) + self.min_lr return adjusted_cycle # We look an example of a slanted triangular schedule that increases from a learning rate of 1 to 2, and back to 1 over 1000 iterations. Since we set `inc_fraction=0.2`, 200 iterations are used for the increasing stage, and 800 for the decreasing stage. After this, the schedule stays at the lower bound indefinitely. # In[ ]: # schedule = TriangularSchedule(min_lr=1, max_lr=2, cycle_length=1000, inc_fraction=0.2) # plot_schedule(schedule) # ### Cosine # # Continuing with the idea that smooth decay profiles give improved performance over stepwise decay, [Ilya Loshchilov, Frank Hutter (2016)](https://arxiv.org/abs/1608.03983) used **"cosine annealing"** schedules to good effect. As with triangular schedules, the original idea was that this should be used as part of a cyclical schedule, but we begin by implementing the cosine annealing component before the full Stochastic Gradient Descent with Warm Restarts (SGDR) method later in the tutorial. # In[ ]: class CosineAnnealingSchedule(): def __init__(self, min_lr, max_lr, cycle_length): """ min_lr: lower bound for learning rate (float) max_lr: upper bound for learning rate (float) cycle_length: iterations between start and finish (int) """ self.min_lr = min_lr self.max_lr = max_lr self.cycle_length = cycle_length def __call__(self, iteration): if iteration <= self.cycle_length: unit_cycle = ( 1 + math.cos(iteration * math.pi / self.cycle_length)) / 2 adjusted_cycle = ( unit_cycle * (self.max_lr - self.min_lr)) + self.min_lr return adjusted_cycle else: return self.min_lr # We look at an example of a cosine annealing schedule that smoothing decreases from a learning rate of 2 to 1 across 1000 iterations. After this, the schedule stays at the lower bound indefinietly. # In[ ]: # schedule = CosineAnnealingSchedule(min_lr=1, max_lr=2, cycle_length=1000) # plot_schedule(schedule) # ## Custom Schedule Modifiers # # We now take a look some adjustments that can be made to existing schedules. We see how to add linear warm-up and its compliment linear cool-down, before using this to implement the "1-Cycle" schedule used by [Leslie N. Smith, Nicholay Topin (2017)](https://arxiv.org/abs/1708.07120) for "super-convergence". We then look at cyclical schedules and implement the original cyclical schedule from [Leslie N. Smith (2015)](https://arxiv.org/abs/1506.01186) before finishing with a look at ["SGDR: Stochastic Gradient Descent with Warm Restarts" by Ilya Loshchilov, Frank Hutter (2016)](https://arxiv.org/abs/1608.03983). # # Unlike the schedules above and those implemented in `mx.lr_scheduler`, these classes are designed to modify existing schedules so they take the argument `schedule` (for initialized schedules) or `schedule_class` when being initialized. # # ### Warm-Up # # Using the idea of linear warm-up of the learning rate proposed in ["Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour" by Priya Goyal et al. (2017)](https://arxiv.org/abs/1706.02677), we implement a wrapper class that adds warm-up to an existing schedule. Going from `start_lr` to the initial learning rate of the `schedule` over `length` iterations, this adjustment is useful when training with large batch sizes. # In[ ]: class LinearWarmUp(): def __init__(self, schedule, start_lr, length): """ schedule: a pre-initialized schedule (e.g. TriangularSchedule(min_lr=0.5, max_lr=2, cycle_length=500)) start_lr: learning rate used at start of the warm-up (float) length: number of iterations used for the warm-up (int) """ self.schedule = schedule self.start_lr = start_lr # calling mx.lr_scheduler.LRScheduler effects state, so calling a copy self.finish_lr = copy.copy(schedule)(0) self.length = length def __call__(self, iteration): if iteration <= self.length: return iteration * (self.finish_lr - self.start_lr)/(self.length) + self.start_lr else: return self.schedule(iteration - self.length) # As an example, we add a linear warm-up of the learning rate (from 0 to 1 over 250 iterations) to a stepwise decay schedule. We first create the `MultiFactorScheduler` (and set the `base_lr`) and then pass it to `LinearWarmUp` to add the warm-up at the start. We can use `LinearWarmUp` with any other schedule including `CosineAnnealingSchedule`. # In[ ]: # schedule = mx.lr_scheduler.MultiFactorScheduler(step=[250, 750, 900], factor=0.5) # schedule.base_lr = 1 # schedule = LinearWarmUp(schedule, start_lr=0, length=250) # plot_schedule(schedule) # ### Cool-Down # # Similarly, we could add a linear cool-down period to our schedule and this is used in the "1-Cycle" schedule proposed by [Leslie N. Smith, Nicholay Topin (2017)](https://arxiv.org/abs/1708.07120) to train neural networks very quickly in certain circumstances (coined "super-convergence"). We reduce the learning rate from its value at `start_idx` of `schedule` to `finish_lr` over a period of `length`, and then maintain `finish_lr` thereafter. # In[ ]: class LinearCoolDown(): def __init__(self, schedule, finish_lr, start_idx, length): """ schedule: a pre-initialized schedule (e.g. TriangularSchedule(min_lr=0.5, max_lr=2, cycle_length=500)) finish_lr: learning rate used at end of the cool-down (float) start_idx: iteration to start the cool-down (int) length: number of iterations used for the cool-down (int) """ self.schedule = schedule # calling mx.lr_scheduler.LRScheduler effects state, so calling a copy self.start_lr = copy.copy(self.schedule)(start_idx) self.finish_lr = finish_lr self.start_idx = start_idx self.finish_idx = start_idx + length self.length = length def __call__(self, iteration): if iteration <= self.start_idx: return self.schedule(iteration) elif iteration <= self.finish_idx: return (iteration - self.start_idx) * (self.finish_lr - self.start_lr) / (self.length) + self.start_lr else: return self.finish_lr # As an example, we apply learning rate cool-down to a `MultiFactorScheduler`. Starting the cool-down at iteration 1000, we reduce the learning rate linearly from 0.125 to 0.001 over 500 iterations, and hold the learning rate at 0.001 after this. # In[ ]: # schedule = mx.lr_scheduler.MultiFactorScheduler(step=[250, 750, 900], factor=0.5) # schedule.base_lr = 1 # schedule = LinearCoolDown(schedule, finish_lr=0.001, start_idx=1000, length=500) # plot_schedule(schedule) # #### 1-Cycle: for "Super-Convergence" # # So we can implement the "1-Cycle" schedule proposed by [Leslie N. Smith, Nicholay Topin (2017)](https://arxiv.org/abs/1708.07120) we use a single and symmetric cycle of the triangular schedule above (i.e. `inc_fraction=0.5`), followed by a cool-down period of `cooldown_length` iterations. # In[ ]: class OneCycleSchedule(): def __init__(self, start_lr, max_lr, cycle_length, cooldown_length=0, finish_lr=None): """ start_lr: lower bound for learning rate in triangular cycle (float) max_lr: upper bound for learning rate in triangular cycle (float) cycle_length: iterations between start and finish of triangular cycle: 2x 'stepsize' (int) cooldown_length: number of iterations used for the cool-down (int) finish_lr: learning rate used at end of the cool-down (float) """ if (cooldown_length > 0) and (finish_lr is None): raise ValueError( "Must specify finish_lr when using cooldown_length > 0.") if (cooldown_length == 0) and (finish_lr is not None): raise ValueError( "Must specify cooldown_length > 0 when using finish_lr.") finish_lr = finish_lr if (cooldown_length > 0) else start_lr schedule = TriangularSchedule( min_lr=start_lr, max_lr=max_lr, cycle_length=cycle_length) self.schedule = LinearCoolDown( schedule, finish_lr=finish_lr, start_idx=cycle_length, length=cooldown_length) def __call__(self, iteration): return self.schedule(iteration) # As an example, we linearly increase and then decrease the learning rate from 0.1 to 0.5 and back over 500 iterations (i.e. single triangular cycle), before reducing the learning rate further to 0.001 over the next 750 iterations (i.e. cool-down). # In[ ]: # schedule = OneCycleSchedule(start_lr=0.1, max_lr=0.5, cycle_length=500, cooldown_length=750, finish_lr=0.001) # plot_schedule(schedule) # ### Cyclical # # Originally proposed by [Leslie N. Smith (2015)](https://arxiv.org/abs/1506.01186), the idea of cyclically increasing and decreasing the learning rate has been shown to give faster convergence and more optimal solutions. We implement a wrapper class that loops existing cycle-based schedules such as `TriangularSchedule` and `CosineAnnealingSchedule` to provide infinitely repeating schedules. We pass the schedule class (rather than an instance) because one feature of the `CyclicalSchedule` is to vary the `cycle_length` over time as seen in [Ilya Loshchilov, Frank Hutter (2016)](https://arxiv.org/abs/1608.03983) using `cycle_length_decay`. Another feature is the ability to decay the cycle magnitude over time with `cycle_magnitude_decay`. # In[ ]: class CyclicalSchedule(): def __init__(self, schedule_class, cycle_length, cycle_length_decay=1, cycle_magnitude_decay=1, **kwargs): """ schedule_class: class of schedule, expected to take `cycle_length` argument cycle_length: iterations used for initial cycle (int) cycle_length_decay: factor multiplied to cycle_length each cycle (float) cycle_magnitude_decay: factor multiplied learning rate magnitudes each cycle (float) kwargs: passed to the schedule_class """ self.schedule_class = schedule_class self.length = cycle_length self.length_decay = cycle_length_decay self.magnitude_decay = cycle_magnitude_decay self.kwargs = kwargs def __call__(self, iteration): cycle_idx = 0 cycle_length = self.length idx = self.length while idx <= iteration: cycle_length = math.ceil(cycle_length * self.length_decay) cycle_idx += 1 idx += cycle_length cycle_offset = iteration - idx + cycle_length schedule = self.schedule_class( cycle_length=cycle_length, **self.kwargs) return schedule(cycle_offset) * self.magnitude_decay**cycle_idx # As an example, we implement the triangular cyclical schedule presented in ["Cyclical Learning Rates for Training Neural Networks" by Leslie N. Smith (2015)](https://arxiv.org/abs/1506.01186). We use slightly different terminology to the paper here because we use `cycle_length` that is twice the 'stepsize' used in the paper. We repeat cycles, each with a length of 500 iterations and lower and upper learning rate bounds of 0.5 and 2 respectively. # In[ ]: # schedule = CyclicalSchedule(TriangularSchedule, min_lr=0.5, max_lr=2, cycle_length=500) # plot_schedule(schedule) # And lastly, we implement the scheduled used in ["SGDR: Stochastic Gradient Descent with Warm Restarts" by Ilya Loshchilov, Frank Hutter (2016)](https://arxiv.org/abs/1608.03983). We repeat cosine annealing schedules, but each time we halve the magnitude and double the cycle length. # In[ ]: # schedule = CyclicalSchedule(CosineAnnealingSchedule, min_lr=0.01, max_lr=2, # cycle_length=250, cycle_length_decay=2, cycle_magnitude_decay=0.5) # plot_schedule(schedule) # # # # # **_Want to learn more?_** Checkout the "Learning Rate Schedules" tutorial for a more basic overview of learning rates found in `mx.lr_scheduler`, and an example of how to use them while training your own models. # # <!-- INSERT SOURCE DOWNLOAD BUTTONS -->
ea6bae24ae2729aaf178c6be03102f6d6ab8b5d1
ovravindra/SentimentAnalysis
/word_embeddings.py
10,339
3.75
4
# word embeddings are the vector representations of a word in the context. # similar words have similar embeddings, in the sence that they have similar cosine score # # %% import pandas as pd import numpy as np import nltk import matplotlib.pyplot as plt import re twitter_df = pd.read_csv('twitter_train.csv') twitter_df = twitter_df.fillna('0') twitter_df_test = pd.read_csv('twitter_test.csv') twitter_df_test = twitter_df_test.fillna('0') twitter_df = twitter_df.drop('location', axis=1) target = twitter_df.target # twitter_df = twitter_df.drop('target', axis=1) twitter_df_test = twitter_df_test.drop('location', axis=1) # target = twitter_df_test.target # CBOW is a word embedding technique to predict middle word in the context. # hence capturing some semantic information. #%% from nltk import TweetTokenizer wt = TweetTokenizer() stop_words = nltk.corpus.stopwords.words('english') def normalize_corpus(df_1 = twitter_df, text_col = 'text'): # refining the text by removing the special characters, # lower casing all the words, removing white spaces # size less than 3 # RNN, LSTM # remove all non words. # can remove names as they each form a different vocabulary, and 2 common names dosent mean anything. # stemming, lemmatization df = df_1.copy() df.dropna(inplace=True) url_re = r'(https?://\S+|www\.\S+)' #r'(https?:\/\/\S+)$?' english_re = r'([a-zA-Z]\w+)' extended_stop_words_re = stop_words + ['&amp;','rt','th','co', 're','ve','kim','daca','p.m.'] single_letters_re = r'.' df['preprocessed_'+ text_col] = df[text_col].str.lower() # lower casing the text. df['preprocessed_'+ text_col] = df['preprocessed_'+ text_col].apply(lambda row: ' '.join([word for word in row.split() if (re.match(english_re, word)) and (not word in extended_stop_words_re) and (not word in single_letters_re)])) # df['preprocessed_'+text] = re.sub(english, '', df['preprocessed_'+text]) df['preprocessed_'+ text_col] = df['preprocessed_'+ text_col].apply(lambda row: re.sub(url_re, '', row)) # removing urls. # tokenize document df['tokenised_' + text_col] = df['preprocessed_'+ text_col].apply(lambda row: wt.tokenize(row)) # df['tokenised_' + text_col].apply(re.sub(single_letters_re, '', row)) return df norm_df = normalize_corpus(twitter_df) norm_df_test = normalize_corpus(twitter_df_test) # %% # importing the requires libraries to generate word embeddings. from gensim.models.doc2vec import Doc2Vec, TaggedDocument tokenised_doc = norm_df.tokenised_text target = norm_df.target # convert tokenized document into gensim formatted tagged data tagged_data = [TaggedDocument(d , [i]) for i, d in zip(target, tokenised_doc)] # tagged_data = [TaggedDocument(d , [i]) for (i, d) in norm_df[["keyword", "tokenised_text"]]] tokenised_doc_test = norm_df_test.tokenised_text keywords = norm_df_test.keyword tagged_data_test = [TaggedDocument(d, [i]) for i, d in zip(keywords, tokenised_doc_test)] # tagged_dada_1 = norm_df.apply(lambda r: TaggedDocument(words=r['tokenised_text'], tags = r['keyword'])) # initialising doc2vec model weights ''' model = Doc2Vec(dm = 1, documents = tagged_data, vector_size = 200, min_count = 5, epochs = 50) # model.wv.vocab # model.corpus_total_words # the model weights are already initialised. # Paragraph Vector Distributed memory acts as a memory that remembers what is missing from the # current context. for epoch in range(30): model.train(tagged_data, total_examples = len(tagged_data), epochs=5) model.alpha -=0.002 model.min_alpha = model.alpha # save trained model model.save('train_doc2vec.model') ''' # load saved model model = Doc2Vec.load("train_doc2vec.model") # tagged_data[1000].tags[0] vector = model.infer_vector(['leagues', 'ball', 'olympic', 'level', 'body', 'bagging', 'like', 'career', 'nothing']) vector.shape # %% def vectors_Doc2vec(model, tagged_docs): sents = tagged_docs tags, vectors = zip(*[(doc.tags[0], model.infer_vector(doc.words)) for doc in sents]) return tags, vectors targets, vectors = vectors_Doc2vec(model, tagged_data) targets_test, vectors_test = vectors_Doc2vec(model, tagged_data_test) # %% from sklearn.linear_model import LogisticRegression from sklearn.model_selection import GridSearchCV import pickle import csv def use_Logistic_reg(params, use_GridSearchCV = False, C = 0.01, n_jobs = -1, cv = 5, save_model = False): # this function returns the optimum Logistic Regression Model according to the preferences. clf = LogisticRegression(C=C, n_jobs=n_jobs) if use_GridSearchCV: model = GridSearchCV(clf, param_grid=params, cv = cv) model.fit(vectors, target) else: model = clf.fit(vectors, target) filename = "Logistic_Reg_clf.pickle" if save_model: pickle.dump(model, open(filename, 'wb')) # load the model from the disk model = pickle.load(open(filename, 'rb')) return model id_1 = twitter_df_test.id def save_pred(model, id_ = id_1, name_ = "name_1.csv", vectors_ = vectors_test): predict = model.predict(vectors_) # checking if the predictions are correct format vector assert len(predict) == 3263 # the file is saved in the current folder with open(name_, 'w', newline='\n') as f: writer = csv.writer(f) writer.writerow(['id', 'target']) for id_, target in zip(id_, predict): writer.writerow([id_, target]) # Fitting the vectors over Logistic Regression Model # calling the function over s # params = {'C':[0.001, 0.01, 0.1]} # model_lr = use_Logistic_reg(params = params, use_GridSearchCV=True) # y_pred = model_lr.predict(vectors) from sklearn.metrics import accuracy_score # print('Logistic Regression Accuracy Score is : ',accuracy_score(y_pred, target)) # save_pred(model=model_lr, id_= id_1, name_="LR_twitter.csv") from sklearn.ensemble import RandomForestClassifier # %% def use_Rand_forest(params, use_GridSearchCV = False, n_jobs = -1, cv = 5, save_model = False): # this function fits a RandomForest Model on the word vectors. clf = RandomForestClassifier(n_jobs=n_jobs) if use_GridSearchCV: model = GridSearchCV(clf, param_grid=parameters, cv = cv, scoring='accuracy') model.fit(vectors, target) else: model = clf.fit(vectors, target) filename = "RandomForestClf.pickle" if save_model: pickle.dump(model, open(filename, 'wb')) # load the model from the disk model = pickle.load(open(filename, 'rb')) return model parameters = {'max_depth': [100, 150], # max depth of the tree 'max_features': [7, 9, 11], # number of features to consider when looking for best split 'n_estimators': [900], # Number of trees in the forest 'min_samples_leaf': [3, 4, 5], 'min_samples_split': [2, 5, 10], 'criterion': ['gini', 'entropy']} # Quality of the split model_rf = use_Rand_forest(params=parameters, use_GridSearchCV=False) print('the Random Forest Accuracy score is : ',accuracy_score(model_rf.predict(vectors), target)) # the test set does not containt the labels. # save the predictions in as csv format required by the kaggle competitions. # saving the Random Forest Model using the function save_pred save_pred(model=model_rf, id_= id_1, name_="Rf_twitter.csv") # the testing accuracy was 68.188%, which clearly means that the Random Forest algorithm overfits. # %% import catboost as cb cat_1 = cb.CatBoostClassifier(iterations=1000, eval_metric='F1') from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(vectors, targets, stratify = targets) model_2= cat_1.fit(X_train, y_train, eval_set=(X_test,y_test), plot=True) from sklearn.model_selection import StratifiedKFold from sklearn.metrics import mean_squared_error k = 5 # number of Kfolds list_train_index = [] list_valid_index = [] skf = StratifiedKFold(n_splits=k, shuffle = True) for train_index, valid_index in skf.split(X = vectors, y=targets): list_train_index.append(train_index) list_valid_index.append(valid_index) list_train_index cat = cb.CatBoostClassifier(iterations=300, eval_metric='F1') for i in range(k): X_t = np.asarray(vectors)[list_train_index[i],:] X_v = np.asarray(vectors)[list_valid_index[i],:] y_t = np.asarray(targets)[list_train_index[i]] y_v = np.asarray(targets)[list_valid_index[i]] cat.fit(X = X_t, y = y_t, eval_set=(X_v, y_v)); print(accuracy_score(y_t, cat.predict(X_t))) pred_cat = cat.predict(np.asarray(vectors_test)) # %% # running the XGBoost classifier on data from xgboost import XGBClassifier def use_XGBoost(params, use_GridSearchCV = False, C = 0.01, n_jobs = -1, cv = 5, save_model = False): # this function fits a RandomForest Model on the word vectors. clf = XGBClassifier(nthread = -1) if use_GridSearchCV: model = GridSearchCV(clf, param_grid=params, cv = cv, scoring='accuracy') model.fit(np.array(vectors), np.array(target)) else: model = clf.fit(np.array(vectors), np.array(target)) filename = "XGB.pickle" if save_model: pickle.dump(model, open(filename, 'wb')) # load the model from the disk model = pickle.load(open(filename, 'rb')) return model params_xgb = {'n_estimators' : [4, 10, 20, 50, 100, 200], 'gamma':np.linspace(.01, 1, 10, endpoint=True), 'learning_rate' : np.linspace(.01, 1, 10, endpoint=True), 'reg_lambda': np.linspace(0.01, 10, 20, endpoint=True), 'max_depth' : np.linspace(1, 32, 32, endpoint=True, dtype=int) } model_xg = use_XGBoost(params_xgb, use_GridSearchCV=True, save_model=True) print('the Accuracy score using XGBoost is : ',accuracy_score(model_xg.predict(np.array(vectors)), np.array(target))) save_pred(model=model_xg, id_= id_1, name_="xgb_twitter.csv", vectors_=np.array(vectors_test)) # %%
a11978bb1c6f16924822da8859b245108fe65de0
Wattanajit/Python
/week3/work3.py
4,026
3.578125
4
#แบบฝึกหัดที่ 3.1 """print("\tเลือกเมนูเพื่อทำรายการ") print("#"*50) print("\tกด 1 เลือกจ่ายเพิ่ม") print("\tกด 2 เลือกเหมาจ่าย") choose = int(input(" ")) #เลือกจ่ายเพิ่มหรือเหมาจ่าย km = int(input("กรุณากรอกระยะทาง กิโลเมตร\n")) #กรอกระยะทาง if choose == 1 : #เลือกแบบจ่ายเพิ่ม if km <= 25: #ถ้าไม่ถึง 25 km จ่าย 25 บาท print("ค่าใช้จ่ายรวมทั้งหมด 25 บาท") elif km > 25: #ถ้าเกิน 25 km จ่าย 25+55 บาท print("ค่าใช้จ่ายรวมทั้งหมด 80 บาท") if choose == 2 : #เลือกแบบเหมาจ่าย if km <= 25: #ถ้าไม่เกิน 25 km จ่าย 25 บาท print("ค่าใช้จ่ายรวมทั้งหมด 25 บาท") elif km > 25: #ถ้าเกิน 25 km จ่าย 55 บาท print("ค่าใช้จ่ายรวมทั้งหมด 55 บาท")""" #แบบฝึกหัดที่ 3.2 '''a1=int(input("กรุณากรอกจำนวนครั้งการรับค่า\n")) a2 = 0 a3 = 1 while(a3 <= a1) : num = int(input("กรอกตัวเลข : ")) a2 += num a3+=1 print("ผลรวมค่าที่รับมาทั้งหมด = %d"%a2)''' #แบบฝึกหัด 3.3 """print("ป้อนชื่ออาหารสุดโปรดของคุณ หรือ exitเพื่อออกจากโปรแกรม") a1 = [] i = 0 while(True) : i += 1 food = input("อาหารโปรดอันดับที่ {} คือ \t".format(i)) a1.append(food) if food == "exit" : break print("อาหารสุดโปรดของคุณมีดังนี้ ",end= "") for x in range(1,i): print(x,".",a1[x-1],end=" ")""" #แบบฝึกหัด 3.4 a = [] while True : b = input('----ร้านคุณหลินบิวตี้----\n เพิ่ม [a]\n แสดง [s]\n ออกจากระบบ [x]\n') b = b.lower() if b == 'a' : c = input('ป้อนรายชื่อลูกค้า(รหัส : ชื่อ : จังหวัด)') a.append(c) print('\n*******ข้อมูลได้เข้าสู่ระบบแล้ว*******\n') elif b == 's' : print('{0:-<30}'.format("")) print('{0:-<8}{1:-<10}{2:10}'.format('รหัส','ชื่อ','จังหวัด')) print('{0:-<6}{0:-<10}{0:-<10}'.format("")) for d in a : e = d.split(":") print('{0[0]:<6} {0[1]:<10}({0[2]:<10})'.format(e)) continue elif b == 'x' : c=input("ต้องการปิดโปรแกรมใช่หรือไม่ : ") if c =="ใช่": print("จบการทำงาน") break else : continue #แบบฝึกหัด3.5 '''student = int(input('please enter student :')) print('-'*30) total = [0 , 0 , 0 , 0 , 0 , 0] score = ['90-100 :','80-89 :','70-79 :','60-69 :','50-59 : ','0-49 :'] x = 1 while x <= student : point = int(input('please enter score :')) if point <= 100 and point >= 90 : total[0] += 1 elif point < 90 and point >= 80 : total[1] += 1 elif point < 80 and point >= 70 : total[2] += 1 elif point < 70 and point >= 60 : total[3] += 1 elif point < 60 and point >= 50 : total[4] += 1 elif point < 50 and point >= 0 : total[5] +=1 x = x+1 for x in range(0,6) : print(score[x],'*'*total[x])'''
4a2ebd50aeeb20316d67ac7e3262c492d97dceb4
pddpp/alogrithm-practice
/Kth-Largest-Element/solution.py
1,671
3.859375
4
class Solution: # @param k & A a integer and an array # @return ans a integer def kthLargestElement(self, k, A): # Bubble sort is time consuming, use two pointer and quick sort # This question needs review, it is a two pointer question and use the module of quick sort from "partition array" def kthLargestHelper(start, end): pos = quicksort(start, end) # put A[start] to correct position and return the position if pos == len(A)-k: # kth integer is A[k-1] return A[pos] elif pos < len(A)-k: return kthLargestHelper(pos+1, end) #!!!!!!!!!!!!!!!!!!don't forget return!!!!!!!!!!!!! else: return kthLargestHelper(start, pos-1) #!!!!!!!!!!!!don't forget return!!!!!!!!!!!!!! def quicksort(left, right): start = left+1 #!!!!!!start from left+1 end = right target = A[left] while start <= end: while start <= end and A[start] <= target: #<= start += 1 while start <= end and A[end] >= target: #<= end -= 1 if start <= end: tmp = A[start] A[start] = A[end] A[end] = tmp temp = A[left] #!!!!!!!!!! without this swap, the target element won't be in the correct position, even if the return index 'end' is correct A[left] = A[end] A[end] = temp return end if not A or len(A) < k: return None result = kthLargestHelper(0, len(A)-1) return result
b7a7a03ef0b5849bf80ebc548ae178e371a1f79b
leonardolginfo/Exercicios_python_org
/Coursera/semana_3/desafio_raiz.py
756
3.828125
4
import math a = int(input("Digite o valor de a:")) b = int(input("Digite o valor de b:")) c = int(input("Digite o valor de c:")) delta = (b**2)-4*a*c if(delta >= 0): delta_teste = math.sqrt(delta) #print("Delta =", delta_teste) if (delta < 0): print("Não existe raiz, pois o delta é menor que 0.") elif (delta_teste == 0): print("Como o Delta é igual a 0, teremos duas raizes reais e iguais.") raiz1 = (-b + delta_teste)/2*a print("As raizes soluções serão:", raiz1, "e,", raiz1) else: print("Como o Delta é maior que 0, teremos duas raízes reais diferentes") raiz1 = (-b + delta_teste)/2*a raiz2 = (-b - delta_teste)/2*a print("As raizes soluções serão:", raiz1, "e", raiz2)
bcaadd4ef1abe91fdbd9bb9a2c0bf906b58dd825
leonardolginfo/Exercicios_python_org
/EstruturaSequencial/calcula_salario_base_horas.py
423
3.875
4
# Faça um Programa que pergunte quanto você ganha por hora e o # número de horas trabalhadas no mês. Calcule e mostre o total do seu salário no referido mês. print() valorhora = float(input('Qual o valor da hora trabalhada? ')) qtd_horas_trabalhadas = float(input('Quantas horas trabalhou esse mês? ')) salario = valorhora * qtd_horas_trabalhadas print() print(f'O valor que você receberá será de R${salario}')
20e673cfe85c66080f258e1aca0ddc0fff6b5380
leonardolginfo/Exercicios_python_org
/EstruturaSequencial/exerc_16_latas_tintas.py
640
3.9375
4
# Faça um programa para uma loja de tintas. O programa deverá pedir o # tamanho em metros quadrados da área a ser pintada. Considere que a cobertura da tinta # é de 1 litro para cada 3 metros quadrados e que a tinta é vendida em latas de 18 litros, que custam R$ 80,00. # Informe ao usuário a quantidades de latas de tinta a serem compradas e o preço total. print() metros_pintura = float(input('Quantos metros serão pintados? ')) valor_lt = int(80) cob_lata = int(54) qtd_lts = metros_pintura/cob_lata valor_compra = qtd_lts * valor_lt print(f'Você precisará de {qtd_lts:.2f}') print(f'Sua compra será de R${valor_compra:.2f}')
d51b87217e551bafae041a03411606f6c89d5f9b
leonardolginfo/Exercicios_python_org
/EstruturaDeDecisao/exerc_3_veri_F_ou_M.py
357
4.09375
4
# Faça um Programa que verifique se uma letra digitada # é "F" ou "M". Conforme a letra escrever: F - Feminino, M - Masculino, Sexo Inválido. print() sexo = input('Digite uma letra em caixa alta para ientificar o sexo: ') if sexo == 'F': print(f'{sexo} - Feminino') elif sexo == 'M': print(f'{sexo} - Masculino') else: print('Sexo Inválido')
08639865633197e713d1d89bb5ffa8a721898a4f
leonardolginfo/Exercicios_python_org
/EstruturaSequencial/exer_12_calc_peso_ideal.py
287
3.8125
4
#Tendo como dados de entrada a altura de uma pessoa, construa um algoritmo que #calcule seu peso ideal, usando a seguinte fórmula: (72.7*altura) - 58 print() altura = float(input('Qual sua altura? ')) peso_ideal = (72.7 * altura) - 58 print() print(f'O seu peso ideal é {peso_ideal}')
829fb6b015d406292e9bebfc73817be1e3c8f7ce
vpelletier/python-prepy
/prepy.py
5,281
3.671875
4
r""" Simple python preprocessor. All keywords are on a new line beginning with "##", followed by any number of whitespace chars and the keyword, optionally followed by arguments. Names Definitions can be anything the regular expression "\w+" can match. Expressions Expressions are evaluated in python with current definitions plus python builtins. In-place operations with definition are not currently possible. Supported keywords (signification should be straightforward): IF expr IFDEF name IFNDEF name ELIF expr ELSE ENDIF DEFINE name[=expr] UNDEF[INE] name NOTE: There is NO SUBSTITUTION support, and none is planned. You can just execute any substitution you wish in the code calling preprocess(). Hence definition names will not cause any conflict with code. Test case >>> from cStringIO import StringIO >>> code = '''\ ... ##IFNDEF baz # This is a comment ... ## DEFINE baz = 1 + 1 # Another comment ... ##ELSE ... ## DEFINE baz = baz + 1 ... ##ENDIF ... ##IFDEF foo ... print 'foo' ... ##UNDEF foo ... ##ELSE ... print 'bar' ... ##ENDIF ... ##IF baz > 2 # Yet another comment ... print 'baz' ... ##ENDIF ... ''' First run, with empty variable definition. >>> out = StringIO() >>> defines = {} >>> preprocess(StringIO(code), out, defines=defines) >>> out.getvalue() "print 'bar'\n" >>> defines['baz'] 2 Second run, reusing the same set of variable definition and defining "foo". >>> defines['foo'] = None >>> out = StringIO() >>> preprocess(StringIO(code), out, defines=defines) >>> out.getvalue() "print 'foo'\nprint 'baz'\n" >>> defines['baz'] 3 >>> 'foo' in defines False """ import re # Note: should ideally be written as a tokeniser and a grammar, but I intend # to use it to preprocess a parser... _PREFIX = re.compile(r'^##\s*(.+)').match _IF = re.compile(r'IF\s+(.+)').match _ELIF = re.compile(r'ELIF\s+.+').match _ELSE = re.compile(r'ELSE\b').match _ENDIF = re.compile(r'ENDIF\b').match _DEFINE = re.compile(r'DEFINE\s+(\w+)\s*(?:=\s*(.+))?').match _UNDEF = re.compile(r'UNDEF(?:INE)?\s+(\w+)').match _IFDEF = re.compile(r'IFDEF\s+(\w+)').match _IFNDEF = re.compile(r'IFNDEF\s+(\w+)').match class PreprocessorError(Exception): """ Raised when there are preprocessor syntax errors in input. """ pass def preprocess(infile, outfile, defines=None): """ infile File-like object, opened for reading. outfile File-like object, opened for writing. defines Mapping of values to start preprocessing with. Note: This mapping will be modified during file preprocessing. """ def _eval(expression): my_globals = defines.copy() my_globals['__builtins__'] = __builtins__ return eval(expression, my_globals) def enter(): stack.append((emit, lineno)) stack = [] emit = True if defines is None: defines = {} for lineno, line in enumerate(infile.readlines(), 1): directive = _PREFIX(line) if directive is not None: line = directive.group(1) if _IF(line) is not None: enter() emit = stack[-1][0] and _eval(_IF(line).group(1)) elif _ELIF(line) is not None: if not stack: raise PreprocessorError('%i: Unexpected conditional block ' 'continuation' % (lineno, )) if not emit: emit = stack[-1][0] and _eval(_ELIF(line).group(1)) elif _ELSE(line) is not None: if not stack: raise PreprocessorError('%i: Unexpected conditional block ' 'continuation' % (lineno, )) emit = stack[-1][0] and not emit elif _ENDIF(line) is not None: if not stack: raise PreprocessorError('%i: Unexpected conditional block ' 'continuation' % (lineno, )) try: emit, _ = stack.pop() except IndexError: raise PreprocessorError('%i: Unexpected conditional block ' 'end' % (lineno, )) elif _IFDEF(line) is not None: enter() emit = stack[-1][0] and _IFDEF(line).group(1) in defines elif _IFNDEF(line) is not None: enter() emit = stack[-1][0] and _IFNDEF(line).group(1) not in defines elif _DEFINE(line) is not None: if emit: groups = _DEFINE(line).groups() if len(groups) == 1: value = None else: value = _eval(groups[1]) defines[groups[0]] = value elif _UNDEF(line) is not None: if emit: del defines[_UNDEF(line).group(1)] else: raise PreprocessorError('%i: Unknown directive %r' % (lineno, directive)) continue if emit: outfile.write(line) if stack: raise PreprocessorError('Blocks still open at end of input (block ' 'starting line): %r' % (stack, )) if __name__ == "__main__": import doctest doctest.testmod()
c8e6fd0ff21b2b52effc3948ff6472ee2c0c9db0
koteswaracse/Pycharm-Prac
/Practice1.py
772
4.03125
4
#!/usr/bin/python var = 100 if ( var == 100 ) : print ("Value of expression is 100") print ("Good bye!") var1 = 'Hello World!' var2 = "Python Programming" print ("var1[0]: ", var1[0]) print ("var2[1:5]: ", var2[1:5]) var1 = 'Hello World!' print ("Updated String :- ", var1[:6] + 'Python') print ("My name is %s and weight is %d kg!" % ('Zara', 21)) para_str = """this is a long string that is made up of several lines and non-printable characters such as TAB ( \t ) and they will show up that way when displayed. NEWLINEs within the string, whether explicitly given like this within the brackets [ \n ], or just a NEWLINE within the variable assignment will also show up. """ print (para_str) print ('C:\\nowhere') print (r'C:\\nowhere') print (u'Hello, world!')
85c26afa478691ad15a99435f734a79453178c54
damianmc88/python-challenge
/PyBank/main.py
1,199
3.5625
4
import os import csv data = [] with open('C:/Users/damia/Desktop/UDEN201811DATA3/Week3/HW/Instructions/PyBank/Resources/budget_data.csv') as f: reader = csv.reader(f) next(reader) months=0 total=0 for row in reader: months+=1 data.append(row) total+=int(row[1]) pairs = [] for index, val in enumerate(data): try: pairs.append((val[1], data[index + 1][1],val[0])) except IndexError: pass diffs = [] combo=[] for pair in pairs: first, second, third = pair diff = int(second) - int(first) diffs.append(diff) combo.append([third,diff]) for i in range(len(combo)): if combo[i][1]==max(diffs): max_month=combo[i+1][0] if combo[i][1]==min(diffs): min_month=combo[i+1][0] print("Financial Analysis") print("-------------------------") print(f"Total Months: {months}") print(f"Total: ${total}") print(f"Average Change: ${round(sum(diffs) / len(diffs), 2)}") print(f"Greatest Increase in Profits: {max_month} (${max(diffs)})") print(f"Greatest Decrease in Profits: {min_month} (${min(diffs)})")
9d9bb277ecea40850906449755bc6de5f39826a1
tanureuyo/uyovbievbo_story
/m/python_functions/mathfunctions.py
289
4.09375
4
""" Math Functions """ a = 27 b = 4 c = 3 # Addition / Subtraction print (a+b) print (a-b) # Multiplication / Division print (a*b) print (a/b) # Exponents print (a**b) print (b**a) # Roots print (b**(1/2)) print (a**(1/3)) # Modulus -- Only returns the remainder after division print (a%c)
9929886a03e43fa46190c72e5f13766c4e0d39f6
wise-bit/g3po
/Fractals and NCBI api (Stray functions)/cantor1.py
476
3.828125
4
import turtle t = turtle.Turtle() def cantor_loop(length, current_loop_number): t.penup() t.setposition(0, current_loop_number) t.pendown() for i in range(int(current_loop_number*3/10)): t.forward(length) if t.isdown(): t.penup() else: t.pendown() if current_loop_number == 1: current_loop_number += 9 else: current_loop_number += 10 length *= 0.3 if length > 2: cantor_loop(length, current_loop_number) cantor_loop(100, 1) turtle.exitonclick()
c27137e5ecbc98f3eb1ce9461b964f4b4664b455
RohithKalvakota/Cybersecurity-Algorithms
/Vernam Cipher.py
2,103
3.90625
4
print("Kalvakota Rohith") choice = input("Encryption(E/e) or Deceyption(D/d)?") if ord(choice.upper()) == 69: plaintext = input("Enter Plain Text:") key = input("Enter key:") if(len(key) == len(plaintext)): def split(pt): return list(pt) ptlist = [] for j in plaintext: ptlist.append(ord(j)-65) klist = [] for k in key: klist.append(ord(k)-65) sum = [] for i in range(0,len(ptlist)): add = ptlist[i]+klist[i]+65 if add>90: add = add-26 sum.append(add) else: sum.append(add) result=[] for value in sum: result.append("".join(chr(value))) final="" for ch in result: final += ch print("Cipher Text:",final) else: print("Length of key not equal to length of plaintext!!!") elif ord(choice.upper()) == 68: plaintext = input("Enter Cipher Text:") key = input("Enter key:") if(len(key) == len(plaintext)): encrypt = "" def split(pt): return list(pt) ptlist = [] for j in plaintext: ptlist.append(ord(j)-65) klist = [] for k in key: klist.append(ord(k)-65) sum = [] for i in range(0,len(ptlist)): add = ptlist[i]-klist[i]+65 if add<65: add = add+26 sum.append(add) else: sum.append(add) result=[] for value in sum: result.append("".join(chr(value))) final="" for ch in result: final += ch print("Plain Text:",final) else: print("Length of key not equal to length of plaintext!!!") elif ord(choice.upper()) != 68 or 69: print("enter correct options")
a0bef2e102937c13953f0aee0e0838c536572646
joshey-bit/Short_Codes
/number_series.py
505
3.609375
4
def meth_1(n): diff = 1 a0 = 1 li = [] while n > 0: a_num = a0 + (n - 1)*diff n = n - 1 li.insert(0, str(a_num)) k = "".join(li) print(k) def meth_2(n): diff = 1 a0 = 1 li = [] num = 1 while num <= n: a_num = a0 + (num - 1)*diff num = num + 1 li.append(str(a_num)) k = ",".join(li) print(k) n = input('enter the number: ') meth_2(int(n)) #althogh method 1 is easy and memory efficient but it takes 0.4 sec to execute, method 2 takes 0.2sec
8a00f9a865c069cf0946932a8ee0859ffc4a7d15
vinicius-hora/python_udemy
/intermeriario/aula71.py
143
3.59375
4
from itertools import count contador = count(start = 5, step = 2) for valor in contador: print(valor) if valor >=100: break
1d2f84f2f3a4a22172a30392f5ac8a146555cd0d
lopezjronald/Python-Crash-Course
/part-1-basics/Ch_2/name_cases.py
1,968
4.625
5
""" 2-3. Personal Message: Use a variable to represent a person’s name, and print a message to that person. Your message should be simple, such as, “Hello Eric, would you like to learn some Python today?” 2-4. Name Cases: Use a variable to represent a person’s name, and then print that person’s name in lowercase, uppercase, and title case. 2-5. Famous Quote: Find a quote from a famous person you admire. Print the quote and the name of its author. Your output should look something like the following, including the quotation marks: Albert Einstein once said, “A person who never made a mistake never tried anything new.” 2-6. Famous Quote 2: Repeat Exercise 2-5, but this time, represent the famous person’s name using a variable called famous_person. Then compose your message and represent it with a new variable called message. Print your message. 2-7. Stripping Names: Use a variable to represent a person’s name, and include some whitespace characters at the beginning and end of the name. Make sure you use each character combination, "\t" and "\n", at least once. Print the name once, so the whitespace around the name is displayed. Then print the name using each of the three stripping functions, lstrip(), rstrip(), and strip(). """ name = "Eric" print(f"Hello, {name}! Would you like to learn some python today?") first_name = "jEfF" last_name = "LoPEz" print(f"Lowercase: {first_name.lower()} {last_name.lower()}") print(f"Uppercase: {first_name.upper()} {last_name.upper()}") print(f"Title: {first_name.title()} {last_name.title()}") author = "tony robbins" print(f"Repetition is the mother of skill ~ {author.title()}") famous_person = "kevin hart" message = "is one hilarious dude!" print(f"{famous_person.title()} {message}") name = "\t\nRonald Lopez\t\t\n" print(f"Left Strip function: {name.lstrip()}") print(f"Strip function: {name.strip()}") print(f"Right Strip function: {name.rstrip()}") fav_num = 17 print(f'Favorite number is {fav_num}')
e5a1bced0363cbd95e114b1de2d2ffafee0514fe
lopezjronald/Python-Crash-Course
/part-1-basics/ch_6/exercises.py
5,758
4.53125
5
# exercise 6-1 person = { 'first_name': 'ronald', 'last_name': 'lopez', 'age': 34, 'city': 'honolulu', } for key, value in person.items(): print(f'{key.title()}: {value}') # exercise 6-2 print() favorite_numbers = { 'joyce': 9, 'ronald': 3, 'Boo': 33, 'Stew': 22, 'Clue': 100, } favorite_numbers['jason'] = 13 favorite_numbers['violet'] = 2 for key, value in favorite_numbers.items(): print(key, ": ", value) # exercise 6-3 glossary = { 'algorithm': 'An algorithm is a set of instructions or rules designed to solve a definite problem. The problem ' 'can be simple like adding two numbers or a complex one, such as converting a video file from one ' 'format to another.', 'program': 'A computer program is termed as an organized collection of instructions, which when executed perform ' 'a specific task or function. A program is processed by the central processing unit (CPU) of the ' 'computer before it is executed. An example of a program is Microsoft Word, which is a word processing ' 'application that enables user to create and edit documents. The browsers that we use are also ' 'programs created to help us browse the internet.', 'api': 'Application Programming Interface (API) is a set of rules, routines, and protocols to build software ' 'applications. APIs help in communication with third party programs or services, which can be used to ' 'build different software. Companies such as Facebook and Twitter actively use APIs to help developers ' 'gain easier access to their services.', 'argument': 'Argument or arg is a value that is passed into a command or a function. For example, if SQR is a ' 'routine or function that returns the square of a number, then SQR(4) will return 16. Here, ' 'the value 4 is the argument. Similarly, if the edit is a function that edits a file, then in edit ' 'myfile.txt, ‘myfile.txt’ is the argument.', 'ascii': 'American Standard Code for Information Interexchange (ASCII) is a standard that assigns letters, ' 'numbers and other characters different slots, available in the 8-bit code. The total number of slots ' 'available is 256. The ASCII decimal number is derived from binary, which is assigned to each letter, ' 'number, and character. For example, the ‘$’ sign is assigned ASCII decimal number 036, ' 'while the lowercase ‘a’ character is assigned 097.', } for key, value in glossary.items(): print(f"{key.title()}:\n{value}\n") # exercise 6-5 major_rivers = { 'mississippi': 'mississippi river', 'egypt': 'niles', 'israel': 'jordan', } for place, river in major_rivers.items(): print(f'{place.title()}: {river.title()}') print() for place in major_rivers.keys(): print(place.title()) print() for river in major_rivers.values(): print(river.title()) # exercise 6-6 print() voters = ['jen', 'sarah'] non_voters = ['ronald', 'violet'] favorite_languages = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', } for name in favorite_languages.keys(): if name not in voters: print(f'{name.title()}, you need to vote!') else: print(f'{name.title()}, thank you for voting :)') print() for name in favorite_languages.keys(): if name in non_voters: print(f'{name.title()}, you need to vote!') else: print(f'{name.title()}, thank you for voting :)') # exercise 6-7 print() person_0 = { 'first_name': 'ronald', 'last_name': 'lopez', 'age': 34, 'city': 'honolulu', } person_1 = { 'first_name': 'donald', 'last_name': 'trump', 'age': 70, 'city': 'new york', } person_2 = { 'first_name': 'bears', 'last_name': 'grills', 'age': 45, 'city': 'alaska', } people = [person_0, person_1, person_2] for person in people: print() print(person['first_name']) print(person['last_name']) print(person['age']) print(person['city']) # exercise 6-8 print() pet_0 = { 'type': 'cat', 'breed': 'house cat', 'name': 'whiskers', 'owner': 'steve austin', } pet_1 = { 'type': 'dog', 'breed': 'husky', 'name': 'pudding', 'owner': 'hanky', } pet_2 = { 'type': 'fish', 'breed': 'blue', 'name': 'dora', 'owner': 'nemo', } pets = [pet_0, pet_1, pet_2] for pet in pets: print() for key, value in pet.items(): print(key.title(), ": ", value.title()) # exercise 6-9 # exercise 6-10 print() favorite_numbers = { 'joyce': [22, 33, 35], 'ronald': [232, 22, 139], 'mcfee': [33, 233, 3566223345], } for name, numbers in favorite_numbers.items(): print() print(f"{name.title()}'s favorite number(s):") for number in numbers: print(f"- {number}") # exercise 6-11 print() states = { 'california': { "nickname": "the golden state", "capital": "sacramento", "population": 39_144_818, "abbreviation": "ca", }, 'alabama': { "nickname": "the heart of dixie", "capital": "montgomery", "population": 4_858_979, "abbreviation": "al", }, 'florida': { "nickname": "the sunshine state", "capital": "tallahassee", "population": 20_271_272, "abbreviation": "fl", }, } for state, state_info in states.items(): print() print(state.title()) for key, value in state_info.items(): if (type(value) == int): print(key.title(), ":", value) else: print(key.title(), ":", value.title()) # exercise 6-12
c352da9c2cc16ce099d93750c680d18d4c138011
lopezjronald/Python-Crash-Course
/part-1-basics/ch_9/practice.py
1,383
3.859375
4
class Dog: def __init__(self, name, age): self.name = name self.age = age def sit(self): print(f'{self.name} is now sitting') def roll(self): print(f'{self.name} rolled over!!!') my_dog = Dog("Willie", 6) print(f"Dog's Name: {my_dog.name}") print(f"Dog's Age: {my_dog.age}") my_dog.roll() my_dog.sit() class Car: def __init__(self, make, model, year): self.make = make self.model = model self.year = year self.odometer_reading = 0 def get_descriptive_name(self): long_name = f"{self.year} {self.make} {self.model}" return long_name.title() def read_odometer(self): print(f"This car has {self.odometer_reading} miles on it.") def update_odometer(self, mileage): if mileage >= self.odometer_reading: self.odometer_reading = mileage else: print("You can't roll back an odometer!") def increment_odometer(self, miles): self.odometer_reading += miles class ElectricCar(Car): def __init__(self, make, model, year): super().__init__(make, model, year) self.battery_size = 75 def describe_battery(self): print(f'This car has a {self.battery_size}-kWh battery') my_tesla = ElectricCar('tesla', 'model s', 2019) print(my_tesla.get_descriptive_name()) my_tesla.describe_battery()
fb2aff5e37a9e9d061c9e0e5fc3e7119c7248b4b
namannimmo10/AdventOfCode
/Day1-2.py
153
3.734375
4
tot = 0 with open("Day1-input", "r") as f: for line in f: num = int(line) while (int(num/3)-2)>0: num = int(num/3)-2 tot += num print(tot)
d90474d7db36960d29059509886edf769a8e4a19
galizar/6001x
/Week2/polysum.py
369
3.8125
4
from math import tan, pi def polysum(n, s): """ Calculates the sum of the area and the square of the perimeter of the polygon. n: int, number of sides of the polygon s: int, length of each side of the polygon """ boundary_length = n*s area = (1/4 * n * pow(s, 2) / (tan( pi/n )) return round(area + boundary_length**2, 4)
15a166cbb0763ae5131d0e568b0d9535056df434
AbhishekGit-hash/Customer-Churn-Prediction-Model-with-XGBoost
/Customer Churn Prediction Model with XGBoost.py
46,577
3.671875
4
#!/usr/bin/env python # coding: utf-8 # <br> # <br> # In this project based the dataset used is of an electricity power company that supplies electricity utility to coorporates, SME and residential customers. <br>A significant amount of churn in customers is happening in the SME customer segments which is decreasing the revenue of the company. At a high level research the customer churn among SME segment is driven by price sensitivity.<br> # <br> # The motive of this project is to develop a predictive model that will predict the customers likely to churn and from a strategic perspective to decrease the churn rate of customers, some monetary benefits may be provided to the predicted customers. # <br> # <br> # <b>Datasets used:<br></b> # 1. Customer data - which should include characteristics of each client, for example, industry, historical # electricity consumption, date joined as customer etc<br> # 2. Churn data - which should indicate if customer has churned<br> # 3. Historical price data – which should indicate the prices the client charges to each customer for both # electricity and gas at granular time intervals<br> # <br> # From the XGBoost model it was observed that other factors apart from price sensitivity like Yearly consumption, Forecasted Consumption and net margin were drivers of customer churn.<br><br> # <b>Recommendations :</b> The strategy of monetary benefits is effective. However it should be appropiately targeted to high-valued customers with high churn probability. If not administered properly then the company may face a hard impact on their revenue<br> # <br> # <b>Table of Contents</b><br><br> # <b> # 1. Loading Dataset<br> # 2. Data Quality Assessment<br> # &ensp; 2.1. Data Types<br> # &ensp; 2.2. Descriptive Statistics<br> # &ensp; 2.3. Descriptive Statistics<br> # 3. Exploratory Data Analysis<br> # 4. Data Cleaning<br> # &ensp;4.1. Missing Data<br> # &ensp;4.2. Duplicates<br> # &ensp;4.3. Formatting Data<br> # &emsp;4.3.1. Missing Dates<br> # &emsp;4.3.2. Formatting dates - customer churn data and price history data<br> # &emsp;4.3.3. Negative data points<br> # 5. Feature Engineering # &ensp;5.1. New Feature Creation<br> # &ensp;5.2. Boolean Data Transformation<br> # &ensp;5.3. Categorical data and dummy variables<br> # &ensp;5.4. Log Transformation<br> # &ensp;5.5. High Correlation Features<br> # &ensp;5.6. Outliers Removal<br> # 6. Churn Prediction Model with XGBoost<br> # &ensp;6.1. Splitting Dataset<br> # &ensp;6.2. Modelling<br> # &ensp;6.3. Model Evaluation<br> # &ensp;6.4. Stratified K-fold validation<br> # &ensp;6.5. Model Finetuning<br> # &emsp;6.5.1. Grid search with cross validation<br> # 7. Model Understanding<br> # &ensp;7.1. Feature Importance<br> # In[1]: import pandas as pd import numpy as np import matplotlib.pyplot as plt get_ipython().run_line_magic('matplotlib', 'inline') plt.style.use('fivethirtyeight') import seaborn as sns import shap import datetime import warnings warnings.filterwarnings("ignore") from sklearn import metrics from sklearn.model_selection import train_test_split from sklearn.model_selection import StratifiedKFold import xgboost as xgb # In[2]: pd.set_option('display.max_columns',500) # ## 1. Loading Datasets # In[3]: cust_data = pd.read_csv('customer_data.csv') hist_price = pd.read_csv('historical_price_data.csv') churned_data = pd.read_csv('churn_data.csv') # <b>Customer Data</b> # In[4]: cust_data.head() # From the above data set we see that there are null values. We will replace with appropiate values or remove columns # <b>Churn Indicator Data</b> # In[5]: churned_data.head() # The churn data is in correct format. 0 stands for not churn and 1 stands for churn. # <b> Historical Price Data</b> # In[6]: hist_price.head() # A lot of values are 0 in the historical price dataset. # <b>Merging the customer data and churn data</b> # In[7]: print('Total records in customer dataset :{}'.format(cust_data.shape[0])) print('Total records in churn dataset :{}'.format(churned_data.shape[0])) # In[8]: cust_churn = pd.merge(cust_data, churned_data, left_on='id', right_on='id', how='inner') # In[9]: cust_churn.head() # ## 2. Data Quality Assessment and Data Cleaning # ### 2.1. Data Types # The dates in cust_churn dataframe are not datetime types yet, which means we might need to convert them. In addition, we can see that the churn is full of integers so we can keep it in that form. # In[10]: cust_churn.info() # In[11]: hist_price.info() # ### 2.2. Descriptive Statistics # In[12]: cust_churn.describe() # Based on the above statistics the following points can be outlined : # # 1. The min consumption and forecasted values for elictricity and gas are negative. This could mean that the client companies are producing energy and likely to be returned. # It is unlikely to consider this data to be corrupted. # # 2. The campaign_disc_ele column contains onlu null values # 3. The metric columns in are highly skewed, looking at the percentiles. # In[13]: round(cust_data['campaign_disc_ele'].isnull().mean()*100) # In[14]: hist_price.describe() # The historical price dataset is looking fine. <br>Even though the prices are negative. The prices will be made positive in the data cleaning step. # ### 2.3. Missing Values # There are a lot of missing data so we can check the percentage of missing values. # In[15]: missing_data = (cust_churn.isnull().mean()*100).reset_index() missing_data.rename(columns={0 : 'Percentage of Missing Values'}) # <b>Columns having missing values greater than 75% will be dropped.</b> # In[16]: (hist_price.isnull().mean()*100).reset_index() # Here the missing values are less so appropiate values may be imputed. # ## 3. Exploratory Data Analysis # ### Churn # In[17]: churn_data = cust_churn[['id', 'churn']] churn_data.rename(columns={'id':'Companies'}, inplace=True) churn_count = churn_data.groupby(['churn']).count().reset_index() churn_count.rename(columns={'Companies' : 'Num'},inplace=True) churn_count['Num'] = round((churn_count['Num']/churn_count['Num'].sum())*100,1) # In[18]: churn_count # In[19]: plt.figure(figsize=(5,5)) churn_count.transpose().drop('churn', axis=0).plot(y=[0,1], kind='bar', stacked=True) plt.ylabel('Companies Base (%)') plt.legend(['Retention', 'churn'], loc='upper right') plt.title('Churning Status') # 10% of the customers have churned from service. # ### SME Activity # Lets see the category of the company's activity in relation to companies clients and churn # In[20]: sme_activity = cust_churn[['id', 'activity_new', 'churn']] # In[21]: sme_activity.head() # In[22]: # Number of companies under SME Activity num_comp_per_sme_activity = sme_activity.groupby(['activity_new', 'churn'])['id'].count().unstack(level=1) # In[23]: num_comp_per_sme_activity.head(10) # In[24]: num_comp_per_sme_activity.plot(kind='bar', figsize=(20,10), width=2, stacked=True, title='Number of Companies under SME Activity') plt.ylabel('Number of Companies') plt.xlabel('SME Activity') plt.legend(['Retention', 'Churn']) plt.xticks([]) plt.show() # In[25]: sme_activity_total = num_comp_per_sme_activity.fillna(0)[0]+num_comp_per_sme_activity.fillna(0)[1] sme_activity_total_percentage = num_comp_per_sme_activity.fillna(0)[1]/(sme_activity_total)*100 pd.DataFrame({'Churn Percentage': sme_activity_total_percentage, 'Number of Companies':sme_activity_total}).sort_values( by='Churn Percentage', ascending=False).head(20) # Our predictive model is likely to struggle accurately predicting the the SME activity due to the large number of categories and lownumber of companies belonging to each category. # In[26]: # Function to plot stacked bars with annotations def plot_stack_bars(df, title_, y_label, size_=(20,10), rot_=0, legend_='upper_right'): ax = df.plot(kind='bar', stacked=True, figsize=size_, rot=rot_, title=title_) annotate_plot(ax, textsize=15) plt.legend(['Retention', 'Churn'], loc=legend_) plt.ylabel(y_label) plt.show() def annotate_plot(ax, pad=1, colour='white', textsize=14): for i in ax.patches: val = str(round(i.get_height(),1)) if val=='0.0': continue ax.annotate(val , ((i.get_x()+i.get_width()/2)*pad-0.05, (i.get_y()+i.get_height()/2)*pad), color=colour, size=textsize) # ### Sales channel # The sales channel seems to be an important feature when predecting the churning of a user. It is not the same if the sales were through email ortelephone. # In[27]: sales_channel = cust_churn[['id','channel_sales','churn']] # In[28]: sales_channel = sales_channel.groupby(['channel_sales', 'churn'])['id'].count().unstack(level=1).fillna(0) # In[29]: sales_channel_churn = (sales_channel.div(sales_channel.sum(axis=1), axis=0)*100).sort_values(by=[1], ascending=False) # In[30]: plot_stack_bars(sales_channel_churn, 'Sales Channel Chart', 'Company %', rot_=30) # In[31]: # Percentage Wise sales_channel_total = sales_channel.fillna(0)[0]+sales_channel.fillna(0)[1] sales_channel_total_percentage = sales_channel.fillna(0)[1]/(sales_channel_total)*100 pd.DataFrame({'Churn Percenatge': sales_channel_total_percentage, 'Number of Companies':sales_channel_total}).sort_values(by='Churn Percenatge', ascending=False).head(10) # ### Consumption # In[32]: cust_churn.columns # In[33]: consumption = cust_churn[['id', 'cons_12m', 'cons_gas_12m','cons_last_month','imp_cons', 'has_gas', 'churn']] # In[34]: # Functions to plot Histograms def plot_histogram(df, col, ax): data_hist = pd.DataFrame({'Retention':df[df['churn']==0][col], 'Churn' : df[df['churn']==1][col]}) data_hist[['Retention', 'Churn']].plot(kind='hist', bins=50, ax=ax, stacked=True) ax.set_xlabel(col) # In[35]: fig, axs = plt.subplots(nrows=4, figsize=(20,25)) plot_histogram(consumption, 'cons_12m', axs[0]) plot_histogram(consumption[consumption['has_gas']=='t'], 'cons_12m', axs[1]) plot_histogram(consumption, 'cons_last_month', axs[2]) plot_histogram(consumption, 'imp_cons', axs[3]) # <b>Consumption</b> data is highly skewed to the right, presenting a very long right-tail towards the higher values of thedistribution. # The values on the higher end and lower ends of the distribution are likely to be outliers. We can use a standard plot to visualise the outliers in moredetail. A boxplot is a standardized way of displaying the distribution of data based on a five number summary (“minimum”, first quartile (Q1), median,third quartile (Q3), and “maximum”). It can tell us about our outliers and what their values are. It can also tell us if our data is symmetrical, how tightlyour data is grouped, and if and how our data is skewed. # In[36]: fig, axs = plt.subplots(nrows=4, figsize=(18,25)) sns.boxplot(consumption['cons_12m'], ax=axs[0]) sns.boxplot(consumption[consumption['has_gas']=='t']['cons_12m'], ax=axs[1]) sns.boxplot(consumption['cons_last_month'], ax=axs[2]) sns.boxplot(consumption['imp_cons'], ax=axs[3]) for ax in axs : ax.ticklabel_format(style='plain', axis='x') axs[0].set_xlim(-200000,2000000) axs[1].set_xlim(-200000,2000000) axs[2].set_xlim(-200000,1000000) plt.show() # We have a highly skewed distribution, and several outliers. # ### Dates # In[37]: dates = cust_churn[['id', 'date_activ', 'date_end', 'date_modif_prod', 'date_renewal', 'churn']].copy() # In[38]: dates['date_activ'] = pd.to_datetime(dates['date_activ'] , format='%Y-%m-%d') dates['date_end'] = pd.to_datetime(dates['date_end'] , format='%Y-%m-%d') dates['date_modif_prod'] = pd.to_datetime(dates['date_modif_prod'] , format='%Y-%m-%d') dates['date_renewal'] = pd.to_datetime(dates['date_renewal'] , format='%Y-%m-%d') # In[39]: # Function to plot monthly churn and retention distribution def plot_dates(df, col , fontsize_=12) : date_df = df[[col, 'churn', 'id']].set_index(col).groupby([pd.Grouper(freq='M'), 'churn']).count().unstack(level=1) ax = date_df.plot(kind='bar', stacked=True, figsize=(18,10), rot=0) ax.set_xticklabels(map(lambda x: line_format(x), date_df.index)) plt.xticks(fontsize = fontsize_) plt.ylabel('Num of Companies') plt.legend(['Retention', 'Churn'], loc='upper_right') plt.show() # In[40]: # Function to convert time label to the format of pandas line plot def line_format(label): month = label.month_name()[:1] if label.month_name()=='January': month+=f'\n{label.year}' return month # In[41]: plot_dates(dates, 'date_activ', fontsize_=8) # In[42]: plot_dates(dates, 'date_end', fontsize_=8) # In[43]: plot_dates(dates, 'date_modif_prod', fontsize_=8) # In[44]: plot_dates(dates, 'date_renewal', fontsize_=8) # We can visualize the distribution of churned companies according to the date. However, this does not provide us with any usefulinsight. We will create a new feature using the raw dates provided in the next exercise. # ### Forecast # In[45]: forecast_churn = cust_churn[['id' , 'forecast_base_bill_ele', 'forecast_base_bill_year', 'forecast_bill_12m', 'forecast_cons', 'forecast_cons_12m', 'forecast_cons_year', 'forecast_discount_energy','forecast_meter_rent_12m', 'forecast_price_energy_p1', 'forecast_price_energy_p2', 'forecast_price_pow_p1', 'churn']] # In[46]: fig , axs = plt.subplots(nrows=11, figsize=(20,55)) plot_histogram(forecast_churn, 'forecast_base_bill_ele', axs[0]) plot_histogram(forecast_churn, 'forecast_base_bill_year', axs[1]) plot_histogram(forecast_churn, 'forecast_bill_12m', axs[2]) plot_histogram(forecast_churn, 'forecast_cons', axs[3]) plot_histogram(forecast_churn, 'forecast_cons_12m', axs[4]) plot_histogram(forecast_churn, 'forecast_cons_year', axs[5]) plot_histogram(forecast_churn, 'forecast_discount_energy', axs[6]) plot_histogram(forecast_churn, 'forecast_meter_rent_12m', axs[7]) plot_histogram(forecast_churn, 'forecast_price_energy_p1', axs[8]) plot_histogram(forecast_churn, 'forecast_price_energy_p2', axs[9]) plot_histogram(forecast_churn, 'forecast_price_pow_p1', axs[10]) # Similarly to the consumption plots, we can observe that a lot of the variables are highly skewed to the right, creating a very long tail on the highervalues. # We will make some transformations to correct for this skewness # ### Contract type (electricity, gas) # In[47]: contract_type = cust_churn[['id', 'has_gas', 'churn']] # In[48]: contract_type_count = contract_type.groupby(['has_gas', 'churn'])['id'].count().unstack(level=1) # In[49]: contract_type_percent = (contract_type_count.div(contract_type_count.sum(axis=1), axis=0)*100).sort_values(by=[1], ascending=False) # In[50]: contract_type_percent # In[51]: plot_stack_bars(contract_type_percent, 'Contract Type (gas)', 'Company %') # ### Margin # In[52]: margin_churn = cust_churn[['id', 'margin_gross_pow_ele', 'margin_net_pow_ele', 'net_margin']] # In[53]: fig, axs = plt.subplots(nrows=3, figsize=(18,20)) sns.boxplot(margin_churn['margin_gross_pow_ele'] , ax=axs[0]) sns.boxplot(margin_churn['margin_net_pow_ele'] , ax=axs[1]) sns.boxplot(margin_churn['net_margin'] , ax=axs[2]) plt.show() # We can observe a few outliers in here as well. # ### Subscribed power # In[54]: subs_power_churn = cust_churn[['id', 'pow_max' , 'churn']].fillna(0) # In[55]: fig, axs = plt.subplots(nrows=1, figsize=(20,10)) plot_histogram(subs_power_churn, 'pow_max' , axs) # ### Other Features # In[56]: other_feat = cust_churn[['id', 'nb_prod_act', 'num_years_antig', 'origin_up', 'churn']] # In[57]: num_products = other_feat.groupby(['nb_prod_act' , 'churn'])['id'].count().unstack(level=1) # In[58]: num_products_percent = (num_products.div(num_products.sum(axis=1) , axis=0)*100).sort_values(by=[1] , ascending=False) # In[59]: plot_stack_bars(num_products_percent, 'Number of products', 'Company %') # In[60]: years_antiquity = other_feat.groupby(['num_years_antig' , 'churn'])['id'].count().unstack(level=1) years_antiquity_percent = (years_antiquity.div(years_antiquity.sum(axis=1) , axis=0)*100) plot_stack_bars(years_antiquity_percent, 'Number of Years of Antiquity', 'Company %') # In[61]: origin = other_feat.groupby(['origin_up' , 'churn'])['id'].count().unstack(level=1) origin_percent = (origin.div(origin.sum(axis=1) , axis=0)*100) plot_stack_bars(origin_percent, 'Origin', 'Company %') # ## 4. Data cleaning # ### 4.1. Missing data # In[62]: cust_churn.isnull().mean()*100 # In[63]: (cust_churn.isnull().mean()*100).plot(kind='bar' , figsize=(20,10)) plt.xlabel('Variables') plt.ylabel('% of Missing Values') plt.show() # The columns with more than 60% of the values missing, will be dropped. # In[64]: cust_churn.drop(columns=['campaign_disc_ele', 'date_first_activ', 'forecast_base_bill_ele', 'forecast_base_bill_year', 'forecast_bill_12m', 'forecast_cons'], inplace=True) # ### 4.2. Duplicates # There are no duplicate rows in dataset. # In[65]: cust_churn[cust_churn.duplicated()] # ### 4.3. Formatting Data # ### 4.3.1. Missing dates # There could be several ways in which we could deal with the missing dates.<br> # One way, we could "engineer" the dates from known values. For example, the # date_renewal # is usually the same date as the # date_modif_prod # but one year ahead. # The simplest way, we will replace the missing values with the median (the most frequent date). For numerical values, the built-in function # .median() # can be used, but this will not work for dates or strings, so we will use a workaround using # .valuecounts() # In[66]: cust_churn.loc[cust_churn['date_modif_prod'].isnull(), 'date_modif_prod'] = cust_churn['date_modif_prod'].value_counts().index[0] cust_churn.loc[cust_churn['date_end'].isnull(), 'date_end'] = cust_churn['date_end'].value_counts().index[0] cust_churn.loc[cust_churn['date_renewal'].isnull(), 'date_renewal'] = cust_churn['date_renewal'].value_counts().index[0] # We might have some prices missing for some companies and months # In[67]: (hist_price.isnull().mean()*100).plot(kind='bar', figsize=(20,10)) plt.xlabel('Variables') plt.ylabel('Percentage of Missing Values %') plt.show() # There is not much data missing. Instead of removing the entries that are empty we will simply substitute them with the # median # In[68]: hist_price.columns # In[69]: hist_price.loc[hist_price['price_p1_var'].isnull(), 'price_p1_var']=hist_price['price_p1_var'].median() hist_price.loc[hist_price['price_p2_var'].isnull(), 'price_p2_var']=hist_price['price_p2_var'].median() hist_price.loc[hist_price['price_p3_var'].isnull(), 'price_p3_var']=hist_price['price_p3_var'].median() hist_price.loc[hist_price['price_p1_fix'].isnull(), 'price_p1_fix']=hist_price['price_p1_fix'].median() hist_price.loc[hist_price['price_p2_fix'].isnull(), 'price_p2_fix']=hist_price['price_p2_fix'].median() hist_price.loc[hist_price['price_p3_fix'].isnull(), 'price_p3_fix']=hist_price['price_p3_fix'].median() # In order to use the dates in our churn prediction model we are going to change the representation of these dates. Instead of using the date itself, wewill be transforming it in number of months. In order to make this transformation we need to change the dates to # datetime # and create a # reference date # which will be January 2016 # ### 4.3.2. Formatting dates - customer churn data and price history data # In[70]: cust_churn['date_activ'] = pd.to_datetime(cust_churn['date_activ'] , format='%Y-%m-%d') cust_churn['date_end'] = pd.to_datetime(cust_churn['date_end'] , format='%Y-%m-%d') cust_churn['date_modif_prod'] = pd.to_datetime(cust_churn['date_modif_prod'] , format='%Y-%m-%d') cust_churn['date_renewal'] = pd.to_datetime(cust_churn['date_renewal'] , format='%Y-%m-%d') # In[71]: hist_price['price_date'] = pd.to_datetime(hist_price['price_date'], format='%Y-%m-%d') # ### 4.3.3. Negative data points # In[72]: hist_price.describe() # We can see that there are negative values for # price_p1_fix # , # price_p2_fix # and # price_p3_fix # . # Further exploring on those we can see there are only about # 10 # entries which are negative. This is more likely to be due to corrupted data rather thana "price discount". # We will replace the negative values with the # median # (most frequent value) # In[73]: hist_price[(hist_price['price_p1_fix'] < 0) | (hist_price['price_p2_fix'] < 0) | (hist_price['price_p3_fix'] < 0)] # In[74]: hist_price.loc[hist_price['price_p1_fix'] < 0 , 'price_p1_fix'] = hist_price['price_p1_fix'].median() hist_price.loc[hist_price['price_p2_fix'] < 0 , 'price_p2_fix'] = hist_price['price_p2_fix'].median() hist_price.loc[hist_price['price_p3_fix'] < 0 , 'price_p3_fix'] = hist_price['price_p3_fix'].median() # ## 5. Feature engineering # ### 5.1. New Feature Creation # We will create new features using the average of the year, the last six months, and the last three months to our model beacuse we have the consumption data for each of the companies for the year 2015. # In[75]: mean_year = hist_price.groupby(['id']).mean().reset_index() # In[76]: mean_6m = hist_price[hist_price['price_date'] > '2015-06-01'].groupby(['id']).mean().reset_index() mean_3m = hist_price[hist_price['price_date'] > '2015-10-01'].groupby(['id']).mean().reset_index() # In[77]: mean_year = mean_year.rename(index = str, columns={'price_p1_var' : 'mean_year_price_p1_var', 'price_p2_var' : 'mean_year_price_p2_var', 'price_p3_var' : 'mean_year_price_p3_var', 'price_p1_fix' : 'mean_year_price_p1_fix', 'price_p2_fix' : 'mean_year_price_p2_fix', 'price_p3_fix' : 'mean_year_price_p3_fix'}) # In[78]: mean_year['mean_year_price_p1'] = mean_year['mean_year_price_p1_var'] + mean_year['mean_year_price_p1_fix'] mean_year['mean_year_price_p2'] = mean_year['mean_year_price_p2_var'] + mean_year['mean_year_price_p2_fix'] mean_year['mean_year_price_p3'] = mean_year['mean_year_price_p3_var'] + mean_year['mean_year_price_p3_fix'] # In[79]: mean_6m = mean_6m.rename(index = str, columns={'price_p1_var' : 'mean_6m_price_p1_var', 'price_p2_var' : 'mean_6m_price_p2_var', 'price_p3_var' : 'mean_6m_price_p3_var', 'price_p1_fix' : 'mean_6m_price_p1_fix', 'price_p2_fix' : 'mean_6m_price_p2_fix', 'price_p3_fix' : 'mean_6m_price_p3_fix'}) # In[80]: mean_6m['mean_6m_price_p1'] = mean_6m['mean_6m_price_p1_var'] + mean_6m['mean_6m_price_p1_fix'] mean_6m['mean_6m_price_p2'] = mean_6m['mean_6m_price_p2_var'] + mean_6m['mean_6m_price_p2_fix'] mean_6m['mean_6m_price_p3'] = mean_6m['mean_6m_price_p3_var'] + mean_6m['mean_6m_price_p3_fix'] # In[81]: mean_3m = mean_3m.rename(index = str, columns={'price_p1_var' : 'mean_3m_price_p1_var', 'price_p2_var' : 'mean_3m_price_p2_var', 'price_p3_var' : 'mean_3m_price_p3_var', 'price_p1_fix' : 'mean_3m_price_p1_fix', 'price_p2_fix' : 'mean_3m_price_p2_fix', 'price_p3_fix' : 'mean_3m_price_p3_fix'}) # In[82]: mean_3m['mean_3m_price_p1'] = mean_3m['mean_3m_price_p1_var'] + mean_3m['mean_3m_price_p1_fix'] mean_3m['mean_3m_price_p2'] = mean_3m['mean_3m_price_p2_var'] + mean_3m['mean_3m_price_p2_fix'] mean_3m['mean_3m_price_p3'] = mean_3m['mean_3m_price_p3_var'] + mean_3m['mean_3m_price_p3_fix'] # We create a new feature, <b> tenure = date_end - date_activ</b> # In[83]: cust_churn['tenure'] = ((cust_churn['date_end'] - cust_churn['date_activ'])/np.timedelta64(1, "Y")).astype(int) # In[84]: tenure = cust_churn[['tenure', 'churn' , 'id']].groupby(['tenure', 'churn'])['id'].count().unstack(level=1) tenure_percentage = (tenure.div(tenure.sum(axis=1) , axis=0)*100) # In[85]: tenure.plot(kind = 'bar' , figsize=(20,10) , stacked=True, rot=0, title='Tenure') plt.legend(['Retention', 'Churn'], loc='upper_right') plt.ylabel('Number of Companies') plt.xlabel('Number of years') plt.show() # The churn is very low for companies which joined recently or that have made the contract a long time ago. With the higher number of churners within the 3-7 years of tenure. # Need to transform the date columns to gain more insights.<br> # months_activ : Number of months active until reference date (Jan 2016)<br> # months_to_end : Number of months of the contract left at reference date (Jan 2016)<br> # months_modif_prod : Number of months since last modification at reference date (Jan 2016)<br> # months_renewal : Number of months since last renewal at reference date (Jan 2016) # In[86]: def get_months(ref_date, df , col): time_diff = ref_date-df[col] months = (time_diff / np.timedelta64(1, "M")).astype(int) return months # In[87]: ref_date = datetime.datetime(2016,1,1) # In[88]: cust_churn['months_activ'] = get_months(ref_date, cust_churn , 'date_activ') cust_churn['months_end'] = -get_months(ref_date, cust_churn , 'date_end') cust_churn['months_modif_prod'] = get_months(ref_date, cust_churn , 'date_modif_prod') cust_churn['months_renewal'] = get_months(ref_date, cust_churn , 'date_renewal') # In[89]: def plot_monthly_churn(df, col): churn_per_month = df[[col, 'churn', 'id']].groupby([col, 'churn'])['id'].count().unstack(level=1) churn_per_month.plot(kind = 'bar', figsize=(20,10) , stacked=True, rot=0, title=col) plt.legend(['Retention', 'Churn'], loc='upper_right') plt.ylabel('Number of companies') plt.ylabel('Number of Months') plt.show() # In[90]: plot_monthly_churn(cust_churn, 'months_activ') # In[91]: plot_monthly_churn(cust_churn, 'months_end') # In[92]: plot_monthly_churn(cust_churn, 'months_modif_prod') # In[93]: plot_monthly_churn(cust_churn, 'months_renewal') # Removing date columns # In[94]: cust_churn.drop(columns=['date_activ', 'date_end', 'date_modif_prod', 'date_renewal'], inplace=True) # ### 5.2. Boolean Data Transformation # For the column has_gas, we will replace t for True or 1 and f for False or 0 (onehot encoding) # In[95]: cust_churn['has_gas'] = cust_churn['has_gas'].replace(['t', 'f'], [1,0]) # ### 5.3. Categorical data and dummy variables # ### Categorical data channel_sales # Categorical data channel_sales # What we are doing here relatively simple, we want to convert each category into a new dummy variable which will have 0 s and 1 s depending # whether than entry belongs to that particular category or not # First of all let's replace the Nan values with a string called null_values_channel # In[96]: cust_churn['channel_sales'] = cust_churn['channel_sales'].fillna('null_channels') # Now transform the channel_sales column into categorical data type # In[97]: cust_churn['channel_sales'] = cust_churn['channel_sales'].astype('category') # In[98]: cust_churn['channel_sales'].value_counts().reset_index() # So that means we will create 8 different dummy variables . Each variable will become a different column. # In[99]: # Dummy Variables channels_category = pd.get_dummies(cust_churn['channel_sales'] , prefix='channel') # In[100]: channels_category.columns = [col[:11] for col in channels_category.columns] # In[101]: channels_category.head(10) # Multicollinearity can affect our models so we will remove one of the columns. # In[102]: channels_category.drop(columns=['channel_nul'] , inplace=True) # ### Categorical data origin_up # In[103]: cust_churn['origin_up'] = cust_churn['origin_up'].fillna('null_origin') # In[104]: cust_churn['origin_up'] = cust_churn['origin_up'].astype('category') # In[105]: cust_churn['origin_up'].value_counts().reset_index() # In[106]: origin_categories = pd.get_dummies(cust_churn['origin_up'] , prefix='origin') origin_categories.columns = [col[:11] for col in origin_categories.columns] # In[107]: origin_categories.head(10) # In[108]: origin_categories.drop(columns=['origin_null'] , inplace=True) # ### Categorical data activity_new # In[109]: cust_churn['activity_new'] = cust_churn['activity_new'].fillna('null_activity') # In[110]: cat_activity = cust_churn['activity_new'].value_counts().reset_index().rename(columns={'activity_new' : 'Activity_Counts', 'index' : 'Activity'}) cat_activity # As we can see below there are too many categories with very few number of samples. So we will replace any category with less than 75 samples as # null_values_category # In[111]: cat_activity[cat_activity['Activity']=='null_activity'] # In[112]: #to_replace = list(cat_activity[cat_activity['Activity_Counts'] <= 75].index) to_replace = list(cat_activity[cat_activity['Activity_Counts'] <= 75]['Activity']) # In[113]: cust_churn['activity_new'] = cust_churn['activity_new'].replace(to_replace, 'null_activity') # In[114]: cat_activity = pd.get_dummies(cust_churn['activity_new'], prefix='activity') cat_activity.columns = [col[:12] for col in cat_activity.columns] # In[115]: cat_activity.head(10) # In[116]: cat_activity.drop(columns = ['activity_nul'], inplace=True) # We will merge all the new categories into our main dataframe and remove the old categorical columns # In[117]: cust_churn = pd.merge(cust_churn, channels_category , left_index=True, right_index=True) cust_churn = pd.merge(cust_churn, origin_categories , left_index=True, right_index=True) cust_churn = pd.merge(cust_churn, cat_activity , left_index=True, right_index=True) # In[118]: cust_churn.drop(columns=['channel_sales', 'origin_up', 'activity_new'], inplace=True) # ### 5.4. Log transformation # There are several methods in which we can reduce skewness such as square root , cube root , and log . In this case, we will use a log # transformation which is usually recommended for right skewed data. # In[119]: cust_churn.describe() # Columns having large standard deviation std need log trnsformation for skewness. Log transformation doesnot work with negative data, in such case we will convert the values to Nan. Also for 0 data we will add 1 then apply Log transformation. # In[120]: # Removing negative data cust_churn.loc[cust_churn['cons_12m'] < 0 , 'cons_12m'] = np.nan cust_churn.loc[cust_churn['cons_gas_12m'] < 0 , 'cons_gas_12m'] = np.nan cust_churn.loc[cust_churn['cons_last_month'] < 0 , 'cons_last_month'] = np.nan cust_churn.loc[cust_churn['forecast_cons_12m'] < 0 , 'forecast_cons_12m'] = np.nan cust_churn.loc[cust_churn['forecast_cons_year'] < 0 , 'forecast_cons_year'] = np.nan cust_churn.loc[cust_churn['forecast_meter_rent_12m'] < 0 , 'forecast_meter_rent_12m'] = np.nan cust_churn.loc[cust_churn['imp_cons'] < 0 , 'imp_cons'] = np.nan # In[121]: # Applying Log Transformation cust_churn['cons_12m'] = np.log10(cust_churn['cons_12m']+1) cust_churn['cons_gas_12m'] = np.log10(cust_churn['cons_gas_12m']+1) cust_churn['cons_last_month'] = np.log10(cust_churn['cons_last_month']+1) cust_churn['forecast_cons_12m'] = np.log10(cust_churn['forecast_cons_12m']+1) cust_churn['forecast_cons_year'] = np.log10(cust_churn['forecast_cons_year']+1) cust_churn['forecast_meter_rent_12m'] = np.log10(cust_churn['forecast_meter_rent_12m']+1) cust_churn['imp_cons'] = np.log10(cust_churn['imp_cons']+1) # In[122]: fig, axs = plt.subplots(nrows=7, figsize=(20,60)) sns.distplot((cust_churn['cons_12m'].dropna()), ax=axs[0]) sns.distplot((cust_churn[cust_churn['has_gas']==1]['cons_gas_12m'].dropna()), ax=axs[1]) sns.distplot((cust_churn['cons_last_month'].dropna()), ax=axs[2]) sns.distplot((cust_churn['forecast_cons_12m'].dropna()), ax=axs[3]) sns.distplot((cust_churn['forecast_cons_year'].dropna()), ax=axs[4]) sns.distplot((cust_churn['forecast_meter_rent_12m'].dropna()), ax=axs[5]) sns.distplot((cust_churn['imp_cons'].dropna()), ax=axs[6]) plt.show() # In[123]: fig, axs = plt.subplots(nrows=7, figsize=(20,60)) sns.boxplot((cust_churn['cons_12m'].dropna()), ax=axs[0]) sns.boxplot((cust_churn[cust_churn['has_gas']==1]['cons_gas_12m'].dropna()), ax=axs[1]) sns.boxplot((cust_churn['cons_last_month'].dropna()), ax=axs[2]) sns.boxplot((cust_churn['forecast_cons_12m'].dropna()), ax=axs[3]) sns.boxplot((cust_churn['forecast_cons_year'].dropna()), ax=axs[4]) sns.boxplot((cust_churn['forecast_meter_rent_12m'].dropna()), ax=axs[5]) sns.boxplot((cust_churn['imp_cons'].dropna()), ax=axs[6]) plt.show() # In[124]: cust_churn.describe() # From the boxplots we can still see some values are quite far from the range ( outliers ). # ### 5.5. High Correlation Features # In[125]: features = mean_year correlation = features.corr() # In[126]: plt.figure(figsize=(20,15)) sns.heatmap(correlation, xticklabels=correlation.columns.values, yticklabels=correlation.columns.values, annot=True, annot_kws={'size' : 10}) plt.xticks(fontsize=10) plt.yticks(fontsize=10) plt.show() # We can remove highly correlated variables. # In[127]: correlation = cust_churn.corr() correlation # As expected, num_years_antig has a high correlation with months_activ (it provides us the same information).<br> # We can remove variables with very high correlation. # In[128]: cust_churn.drop(columns=['num_years_antig', 'forecast_cons_year'], inplace=True) # ### 5.6. Outliers Removal # The consumption data has several outliers. Need to remove those outliers # The most common way to identify an outlier are either:<br> # 1. Data point that falls outside of 1.5 times of an interquartile range above the 3rd quartile and below the 1st quartile OR, <br> # 2. Data point that falls outside of 3 standard deviations. # We will replace the outliers with the mean (average of the values excluding outliers). # In[129]: # Replace outliers with the mean values using the Z score. # Nan values are also replaced with the mean values. def replace_z_score(df, col, z=3): from scipy.stats import zscore temp_df = df.copy(deep=True) temp_df.dropna(inplace=True, subset=[col]) temp_df["zscore"] = zscore(df[col]) mean_=temp_df[(temp_df['zscore'] > -z) & (temp_df['zscore'] < z)][col].mean() df[col] = df[col].fillna(mean_) df['zscore']=zscore(df[col]) no_outlier=df[(df['zscore'] < -z) | (df['zscore'] > z)].shape[0] df.loc[(df['zscore'] < -z) | (df['zscore'] > z) , col] = mean_ print('Replaced : {} outliers in {}'.format(no_outlier, col)) return df.drop(columns='zscore') # In[130]: for feat in features.columns: if feat!='id': features = replace_z_score(features, feat) # In[131]: features.reset_index(drop=True, inplace=True) # When carrying out the log transformation , the dataset has several outliers. # What are the criteria to identify an outlier? # The most common way to identify an outlier are: # 1. Data point that falls outside of 1.5 times of an interquartile range above the 3rd quartile and below the 1st quartile # OR # 2. Data point that falls outside of 3 standard deviations. # Once, we have identified the outlier, What do we do with the outliers? # There are several ways to handle with those outliers such as removing them (this works well for massive datasets) or replacing them with sensible data # (works better when the dataset is not that big). # We will replace the outliers with the mean (average of the values excluding outliers). # In[132]: def find_outliers_iqr(df, column): col = sorted(df[column]) q1, q3 = np.percentile(col, [25,75]) iqr = q3-q1 lower_bound = q1 - (1.5*iqr) upper_bound = q3 + (1.5*iqr) results_ouliers = {'iqr' : iqr , 'lower_bound' : lower_bound , 'upper_bound' : upper_bound} return results_ouliers # In[133]: def remove_ouliers_iqr(df, column): outliers = find_outliers_iqr(df,column) removed_outliers = df[(df[col] < outliers['lower_bound']) | (df[col] > outliers['upper_bound'])].shape df = df[(df[col] > outliers['lower_bound']) | (df[col] < outliers['upper_bound'])] print('Removed {} outliers'.format(removed_outliers[0])) return df # In[134]: def remove_outliers_zscore(df, col, z=3): from scipy.stats import zscore df["zsscore"]=zscore(df[col]) removed_outliers = df[(df["zscore"] < -z) | (df["zscore"] > z)].shape df = df[(df["zscore"] > -z) | (df["zscore"] < z)] print('Removed: {} otliers of {}'.format(removed_outliers[0], col)) return df.drop(columns="zscore") # In[135]: def replace_outliers_z_score(df, col, z=3): from scipy.stats import zscore temp_df = df.copy(deep=True) #temp_df.dropna(inplace=True, subset=[col]) temp_df["zscore"] = zscore(df[col]) mean_=temp_df[(temp_df["zscore"] > -z) & (temp_df["zscore"] < z)][col].mean() num_outliers = df[col].isnull().sum() df[col] = df[col].fillna(mean_) df["zscore"]=zscore(df[col]) df.loc[(df["zscore"] < -z) | (df["zscore"] > z) , col] = mean_ print('Replaced : {} outliers in {}'.format(num_outliers, col)) return df.drop(columns="zscore") # In[136]: cust_churn = replace_outliers_z_score(cust_churn , 'cons_12m') cust_churn = replace_outliers_z_score(cust_churn , 'cons_gas_12m') cust_churn = replace_outliers_z_score(cust_churn , 'cons_last_month') cust_churn = replace_outliers_z_score(cust_churn , 'forecast_cons_12m') cust_churn = replace_outliers_z_score(cust_churn , 'forecast_discount_energy') cust_churn = replace_outliers_z_score(cust_churn , 'forecast_meter_rent_12m') cust_churn = replace_outliers_z_score(cust_churn , 'forecast_price_energy_p1') cust_churn = replace_outliers_z_score(cust_churn , 'forecast_price_energy_p2') cust_churn = replace_outliers_z_score(cust_churn , 'forecast_price_pow_p1') cust_churn = replace_outliers_z_score(cust_churn , 'imp_cons') cust_churn = replace_outliers_z_score(cust_churn , 'margin_gross_pow_ele') cust_churn = replace_outliers_z_score(cust_churn , 'margin_net_pow_ele') cust_churn = replace_outliers_z_score(cust_churn , 'net_margin') cust_churn = replace_outliers_z_score(cust_churn , 'pow_max') cust_churn = replace_outliers_z_score(cust_churn , 'months_activ') cust_churn = replace_outliers_z_score(cust_churn , 'months_end') cust_churn = replace_outliers_z_score(cust_churn , 'months_modif_prod') cust_churn = replace_outliers_z_score(cust_churn , 'months_renewal') # In[137]: cust_churn.reset_index(drop=True, inplace=True) # Let's see how the boxplots changed! # In[138]: fig, axs = plt.subplots(nrows=6, figsize=(20,60)) sns.boxplot((cust_churn['cons_12m'].dropna()), ax=axs[0]) sns.boxplot((cust_churn[cust_churn['has_gas']==1]['cons_gas_12m'].dropna()), ax=axs[1]) sns.boxplot((cust_churn['cons_last_month'].dropna()), ax=axs[2]) sns.boxplot((cust_churn['forecast_cons_12m'].dropna()), ax=axs[3]) sns.boxplot((cust_churn['forecast_meter_rent_12m'].dropna()), ax=axs[4]) sns.boxplot((cust_churn['imp_cons'].dropna()), ax=axs[5]) plt.show() # In[139]: # Loading JS visualization shap.initjs() # In[140]: train = pd.merge(cust_churn, hist_price, on='id') # In[141]: pd.DataFrame({'Columns' : train.columns}) # ## 6. Churn Prediction Model with XGBoost # ### 6.1. Splitting Dataset # In[142]: y = train['churn'] X = train.drop(labels=['id', 'churn', 'price_date'], axis=1) # In[143]: X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42) # ### 6.2. Modelling # In[144]: model = xgb.XGBClassifier(learning_rate=0.1, max_depth=6, n_estimators=500, n_jobs=-1) result = model.fit(X_train, y_train) # ### 6.3. Model Evaluation # We are going to evaluate our Logistic Regression model on our test data (which we did not use for training) using the evalution metrics <b>Accuracy, Precision, Recall</b> # In[145]: def evaluation(model_, X_test_, y_test_): predict_test = model_.predict(X_test_) results = pd.DataFrame({'Accuracy' : [metrics.accuracy_score(y_test_, predict_test)], 'Precision' : [metrics.precision_score(y_test_, predict_test)], 'Recall' : [metrics.recall_score(y_test_, predict_test)]}) print(metrics.classification_report(y_test_, predict_test)) return results # In[146]: evaluation(model, X_test, y_test) # <b>ROC-AUC :</b> Receiver Operating Characteristic(ROC) curve is a plot of the true positive rate against the false positive rate. It shows the tradeoff between sensitivityand specificity. # In[147]: def calculation_roc_auc(model_, X_test_, y_test_): # Get the model predictions, class 1 -> churn prediction_test_ = model_.predict_proba(X_test_)[:,1] # Computing roc-auc fpr, tpr, thresholds = metrics.roc_curve(y_test_, prediction_test_) score = pd.DataFrame({"ROC-AUC" : [metrics.auc(fpr, tpr)]}) return fpr, tpr, score def plot_roc_auc(fpr,tpr): f, ax = plt.subplots(figsize=(14,8)) # Plot ROC roc_auc = metrics.auc(fpr, tpr) ax.plot(fpr, tpr, lw=2, alpha=0.3, label="AUC = %0.2f" % (roc_auc)) plt.plot([0, 1], [0, 1], linestyle='--', lw=3, color='r', label="Random", alpha=.8) ax.set_xlim([-0.05, 1.05]) ax.set_ylim([-0.05, 1.05]) ax.set_xlabel("False Positive Rate (FPR)") ax.set_ylabel("True Positive Rate (TPR)") ax.set_title("ROC-AUC") ax.legend(loc="lower right") plt.show() # In[148]: fpr, tpr, auc_score = calculation_roc_auc(model, X_test, y_test) # In[149]: auc_score # In[150]: plot_roc_auc(fpr, tpr) plt.show() # ### 6.4. Stratified K-fold validation # In[151]: def plot_roc_curve(fprs, tprs): tprs_interp = [] aucs = [] mean_fpr = np.linspace(0, 1, 100) f, ax = plt.subplots(figsize=(18,10)) # Plot ROC for each K-Fold and compute AUC scores. for i, (fpr, tpr) in enumerate(zip(fprs, tprs)): tprs_interp.append(np.interp(mean_fpr, fpr, tpr)) tprs_interp[-1][0] = 0.0 roc_auc = metrics.auc(fpr, tpr) aucs.append(roc_auc) ax.plot(fpr, tpr, lw=2, alpha=0.3, label="ROC fold %d (AUC = %0.2f)" % (i, roc_auc)) plt.plot([0, 1], [0, 1], linestyle='--', lw=3, color='r', label="Random", alpha=.8) # Plot the mean ROC. mean_tpr = np.mean(tprs_interp, axis=0) mean_tpr[-1] = 1.0 mean_auc = metrics.auc(mean_fpr, mean_tpr) std_auc = np.std(aucs) ax.plot(mean_fpr, mean_tpr, color='b', label=r"Mean ROC (AUC = %0.2f $\pm$ %0.2f)" % (mean_auc, std_auc), lw=4, alpha=.8) # Plot the standard deviation around the mean ROC. std_tpr = np.std(tprs_interp, axis=0) tprs_upper = np.minimum(mean_tpr + std_tpr, 1) tprs_lower = np.maximum(mean_tpr - std_tpr, 0) ax.fill_between(mean_fpr, tprs_lower, tprs_upper, color="grey", alpha=.2, label=r"$\pm$ 1 std. dev.") # Fine tune and show the plot. ax.set_xlim([-0.05, 1.05]) ax.set_ylim([-0.05, 1.05]) ax.set_xlabel("False Positive Rate (FPR)") ax.set_ylabel("True Positive Rate (TPR)") ax.set_title("ROC-AUC") ax.legend(loc="lower right") plt.show() return (f, ax) # In[152]: def compute_roc_auc(model_, index): y_predict = model_.predict_proba(X.iloc[index])[:,1] fpr, tpr, thresholds = metrics.roc_curve(y.iloc[index], y_predict) auc_score = metrics.auc(fpr, tpr) return fpr, tpr, auc_score # In[153]: cv = StratifiedKFold(n_splits=3, random_state=42, shuffle=True) fprs, tprs, scores = [], [], [] # In[154]: for (train, test), i in zip(cv.split(X, y), range(3)): model.fit(X.iloc[train], y.iloc[train]) _, _, auc_score_train = compute_roc_auc(model, train) fpr, tpr, auc_score = compute_roc_auc(model, test) scores.append((auc_score_train, auc_score)) fprs.append(fpr) tprs.append(tpr) # In[155]: plot_roc_curve(fprs, tprs) plt.show() # ### 6.5. Model Finetuning # ### 6.5.1. Grid search with cross validation # In[156]: from sklearn.model_selection import GridSearchCV # Parameter grid based on the results of random search param_grid ={'subsample': [0.7], 'scale_pos_weight': [1], 'n_estimators': [1100], 'min_child_weight': [1], 'max_depth': [12, 13, 14], 'learning_rate': [0.005, 0.01], 'gamma': [4.0], 'colsample_bytree': [0.6]} # In[157]: # Create model xg = xgb.XGBClassifier(objective='binary:logistic',silent=True, nthread=1) # In[158]: # Grid search model grid_search = GridSearchCV(estimator = xg, param_grid = param_grid, cv = 3, n_jobs = -1, verbose = 2, scoring = "roc_auc") # In[159]: # Fit the grid search to the data grid_search.fit(X_train,y_train) # In[160]: best_grid = grid_search.best_params_ best_grid # In[165]: # Model with the parameters found model_grid = xgb.XGBClassifier(objective='binary:logistic',silent=True, nthread=1, **best_grid) # In[166]: fprs, tprs, scores = [], [], [] for (train, test), i in zip(cv.split(X, y), range(3)): model_grid.fit(X.iloc[train], y.iloc[train]) _, _, auc_score_train = compute_roc_auc(model_grid, train) fpr, tpr, auc_score = compute_roc_auc(model_grid, test) scores.append((auc_score_train, auc_score)) fprs.append(fpr) tprs.append(tpr) # In[167]: plot_roc_curve(fprs, tprs) plt.show() # ## 7. Model Understanding # ### 7.1. Feature Importance # Feature importance is done by counting the number of times each feature is split on across all boosting rounds (trees) in the model, and then visualizing the result as a bar graph, with the features ordered according to how many times they appear. # In[168]: fig, ax = plt.subplots(figsize=(15,20)) xgb.plot_importance(model_grid, ax=ax) # In the feature importance graph above we can see that cons_12m, forecast_meter_rent_12m, forecast_cons_12m, margin_gross_pow_ele and net_margin are the features that appear the most in our model and we could infere that these two features have a significant importnace in our model
5e9432e2699b1cb36af225e17ecddc93106aee41
lackhoa/kara
/server.py
538
3.59375
4
from math import factorial def mm1_avg(lam, mu): rho = lam/mu return rho/(1-rho) def C(rho, s): tmp0 = sum([(((s*rho)**k)/factorial(k)) for k in range(s)]) tmp1 = tmp0*(factorial(s)/((s*rho)**s)) tmp2 = tmp1*(1-rho) tmp3 = tmp2+1 return 1/tmp3 def mms_avg(lam, mu, s): rho = lam/(mu*s) c = C(rho, s) return (rho/(1-rho))*c + s*rho print("m/m/1: {}".format(mm1_avg(5,7))) print print("m/m/1 (but with many server formula): {}".format(mms_avg(5,7,1))) print("m/m/50: {}".format(mms_avg(5,2,50)))
483ea8da418c872b647da5d004054f590052f568
srohit619/Assignments_LetsUpgrade
/Day_2/Assignment_1.py
1,667
4.53125
5
# Assignment of Python for LetsUpgrade Python Course ##### Question 1 # Experiment with Five list's Built in Function students = ["Rohit Shetty","Ram Mishra", "Pari Yadav","Shubam Mishra", "Kanta Bhai", "Urvi Kanade"] print(students) students.append("Raakhi Singh") #1 Adds a value to the end of the List print(students) students.pop() students.pop() students.pop() #2 Removes a value from the last from a list print(students) students.remove("Pari Yadav") #3 Removes a specific given value from a list print(students) students.sort() #4 Sorts the list in Alphabatic order print(students) students.clear() #5 Clears the list items without deleting the List print(students) ##### Question 2 # Experiment with Five Dictionary's Built in Function st_aloysius_school = { "Student_1": "Raju Shashtri", "Age": 14, "Std": "7th", "Result": "Pass", "Attendance": "91%", "Loc": "Mumbai" } # this is a Dict which has a Key value Pair print(st_aloysius_school) a = st_aloysius_school.get("Result") #1 To get a specific Value we use get() Function print(a) b = st_aloysius_school.keys() #2 key() helps us to get all the keys from a dictionary print(b) c = st_aloysius_school.pop("Loc") #3 Like List, Dict also have a pop function but in Dict's Pop we have to give a value to get it removed print(c) d = st_aloysius_school.values() #4 values() helps us to get all the Values from a dictionary print(d) del st_aloysius_school["Age"] #5 del helps us delete a key:value from a dictionary it can also delete whole dict too
b370f355c82e724ab3c66691aa6099d89f5a5a97
Sammie86/My-Homework-3
/1127.py
2,017
3.8125
4
print('Iyai Bassey 1937369') # This is my name ans PSID dictionary = {} for i in range(5): jersey = int(input("Enter player %s's jersey number:\n" % str(i + 1))) rating = int(input("Enter player %s's rating:\n" % str(i + 1))) if jersey not in dictionary: dictionary[jersey] = rating print() print("ROSTER") for k, v in sorted(dictionary.items()): print("Jersey number:%d,Rating:%d" % (k, v)) print() while True: print('\na - Add player') print('d - Remove player') print('u - Update player rating') print('r - Output players above a rating') print('o - Output roster') print('q - Quit') choice = input('\nChoose an option:\n') choice = choice.lower() if choice == 'o': print("\nROSTER") for k, v in sorted(dictionary.items()): print("Jersey number:%d,Rating:%d" % (k, v)) elif choice == 'a': jersey = int(input("Enter a new player jersey number:\n")) rating = int(input("Enter player's rating:\n")) if jersey not in dictionary: dictionary[jersey] = rating else: print("\nThe Player already in the list") elif choice == 'd': jersey = int(input("\nEnter a jersey number:\n")) if jersey in dictionary: del dictionary[jersey] else: print("\nThe Player is not in the list") elif choice == 'u': jersey = int(input("\nEnter a jersey number:\n")) if jersey in dictionary: rating = int(input("\nEnter a new rating for the player:\n")) dictionary[jersey] = rating else: print("\nThe Player is not in the list") elif choice == 'r': rating = int(input("\nEnter a rating:\n")) for k, v in sorted(dictionary.items()): if v > rating: print("Jersey number:%d,Rating:%d" % (k, v)) elif choice == 'q': break else: print("\nEnter a valid choice")
634e82400d7a132b599a4d3b8172b6de32dc4b7b
rebeccawmx/python3_test
/day4.py
534
3.515625
4
#!/usr/bin/env python # encoding: utf-8 # date:2018/9/13 # comment:输入某年某月某日,判断这一天是这一年的第几天? # 第一步:输入年月日 # 第二步:调用time函数的的tm_yday显示天数 # 第三步:输出天数 import time # 第一步:输入年月日 Date = input("请输入年月日,格式为YYYYMMDD:") # 第二步:调用time函数的的tm_yday显示天数 days = time.strptime(Date, '%Y%m%d').tm_yday # 第三步:输出天数 print("这一天在这一年的 {}".format(days))
5810545da76d2c4ca5ba2af08833cd5353f0bb3e
rhys-simpson/assignment2
/test_place.py
1,188
3.921875
4
""" Assignment 2 - Place Class test Rhys Simpson """ from place import Place def run_tests(): """Test Place class""" # Test empty place (defaults) print("Test empty place:") default_place = Place("", "", 0, False) print(default_place) assert default_place.name == "" assert default_place.country == "" assert default_place.priority == 0 assert not default_place.is_visited # Test initial-value place print("Test initial-value place:") new_place = Place("Malagar", "Spain", 1, False) # Test __str__ method print(new_place) # Test mark visited method new_place.mark_visited() print(new_place) # Test mark unvisited method new_place.mark_unvisited() print(new_place) # Test marking multiple places visited/ unvisited and testing is_important method print() print("Test multiple places and is_important:") second_place = Place("Lima", "Peru", 3, False) places = [new_place, second_place] for place in places: place.mark_visited() print(place) place.mark_unvisited() print(place) if place.is_important(): print(place.name) run_tests()
97858f535d9217878a0b36a2ad612d443027a750
NitinSingh1071/DS
/Practical3d.py
793
4.21875
4
def factorial(num): fact = 1 while (num>0): fact = fact * num num = num - 1 return fact def factorial_recursion(num): if num == 1: return num else : return num*factorial_recursion(num-1) def factors_num(num): for i in range(1,num+1): if (num%i)==0: print(i, end =" ") def factors_recursion(num,x): if x <= num: if (num % x == 0): print(x, end =" ") factors_recursion(num, x + 1) num = 11 print(f"Factorial of {num} is {factorial(num)}") print(f"Factorial of {num} using recursion is {factorial_recursion(num)}") print(f"Factors of {num} : ") factors_num(num) print(f"\nFactors of {num} using recursion :") print(factors_recursion(num,1))
203ac1b04734ccd27fc1edd2fd2a7d7700fad4a1
dasankit1411/IQpython
/IQ3.py
255
3.828125
4
#Write a Python program to convert the Python dictionary object (sort by key) to JSON data. Print the object members with indent level 4. import json p_str={'4': 5, '6': 7, '1': 3, '2': 4} j_dict=json.dumps(p_str,sort_keys=True,indent=4) print(j_dict)
93906d4f1277f013a5847b30eb94dc0d15a1f8bd
rambo3300/Olympic--Data-Analysis-web-app
/preprocessor.py
436
3.5625
4
import pandas as pd def preprocess(df, region_df): # filtering the summer olympics df = df[df['Season'] == 'Summer'] # left joining the two dataframes based on NOC df = df.merge(region_df, on = 'NOC', how = 'left') # dropping the duplicates df.drop_duplicates(inplace = True) # concatinate the medal columns in original df df = pd.concat([df, pd.get_dummies(df['Medal'])], axis = 1) return df
0303554bdee7176fd7fea1654a8d37e266972247
hermes-jr/adventofcode2017-in-python
/level_23/level_23b.py
1,113
3.90625
4
#!/usr/bin/env python """ run as `python -O level_23b.py` to disable debug garbage """ b = 108400 # 100000 + 84 * 100 c = 125400 # 100000 + 84 * 100 + 17000 step = 17 # line 31 result2 = 0 for rng in range(b, c + 1, step): for i in range(2, rng): if rng % i == 0: result2 += 1 break print("Result2: {}".format(result2)) u""" --- Part Two --- Now, it's time to fix the problem. The debug mode switch is wired directly to register a. You flip the switch, which makes register a now start at 1 when the program is executed. Immediately, the coprocessor begins to overheat. Whoever wrote this program obviously didn't choose a very efficient implementation. You'll need to optimize the program if it has any hope of completing before Santa needs that printer working. The coprocessor's ultimate goal is to determine the final value left in register h once the program completes. Technically, if it had that... it wouldn't even need to run the program. After setting register a to 1, if the program were to run to completion, what value would be left in register h? """
e7f092bc6f80c4d3818552ad27ec6c75343edf27
Alegarse/Python-Exercises
/Ejercicio1_1.py
513
3.75
4
#! /usr/bin/python3 # Ejercicio 1. Escriba un programa que pida una cantidad de segundos menor a 1 millón y que retorne cuántos días, horas, minutos y segundos son. segundos=int(input("Cantidad de segundos menor a 1 millon: ")) if segundos>1000000: print("El numero debe ser menor a 1 millon") segundos=int(input("Cantidad de segundos menor a 1 millon: ")) else: print ("Dias:%d - Horas:%d - Minutos:%d - Segundos:%d" % (segundos/86400,segundos%86400/3600,segundos%86400%3600/60,segundos%86400%3600%60))
ad352e5ef77e961e39356333fc2e6808b27481ad
Alegarse/Python-Exercises
/Ejercicio4_1.py
917
4.3125
4
#! /usr/bin/python3 # Ejercicio 4_1. Pig Latin es un lenguaje creado en el que se toma la primera letra de una palabra # y se pone al final de la misma y se le agrega también el sonido vocálico “ei”. Por ejemplo, la # palabra perro sería "erropei". ¿Cuáles pasos debemos seguir? # Pedir al usuario que ingrese una palabra en español. # Verificar que el usuario introdujo una palabra válida. # Convertir la palabra de español a Pig Latin. # Mostrar el resultado de la traducción. palabra = input("Introduzca una palabra en español: ") while (palabra == ""): print("No has introducido ninguna palabra") palabra = input("Por favor, introduzca una palabra en español: ") primeraletra = palabra[0] longitud = len(palabra) sinprimera = palabra[1:longitud] palabra_pig = sinprimera + primeraletra + "ei" print("La palabra introducida '%s' en idioma pig sería: %s" % (palabra,palabra_pig))
8c384ed7883af590b02e00adcec98390d4462458
Alegarse/Python-Exercises
/Ejercicio7_1.py
542
4.15625
4
#! /usr/bin/python3 # Ejercicio 7_1. Escribir un programa que guarde en una variable el diccionario # {'Euro':'€', 'Dollar':'$', 'Yen':'¥'}, pregunte al usuario por una divisa y # muestre su símbolo o un mensaje de aviso si la divisa no está en el diccionario. divisas = {'Euro':'€', 'Dollar':'$', 'Yen':'¥'} divP = input("Escriba una divisa para saber su símbolo: ") if (divP in divisas): print("El símbolo de la divisa %s es: %s" % (divP,divisas[divP])) else: print("La divisa %s no existe en el diccionario." % divP)
bc60019b0405e20006ce7e73a4e44910818d3bab
Alegarse/Python-Exercises
/EjemploRecusividad-Factorial.py
401
4.21875
4
#! /usr/bin/python3 # Ejercicio Recursividad. Resulver el factorial de un número. print("Resolucion del factorial de un número.") print("======================================") n = int(input("Introduzca el número al que calcular el factorial: ")) resultado = 0 def factN(n): if (n == 0 or n == 1): return 1 else: return n * factN(n - 1) resultado = factN(n) print(resultado)
70c3d0a8e954924ebdd5818b3e4a03dc44c0fb89
arnaudperalta/hex-engine
/hex_engine/common.py
4,163
3.78125
4
from hex_game import hex from math import inf def board_evaluation(board: hex.Board): """" Return the substraction between blue and red score. If the heuristic evaluation return a positive value, blue player has an advantage on the board, else red has an advantage. """ return get_score(board, board.RED) - get_score(board, board.BLUE) def get_score(board: hex.Board, color: bool) -> int: """ The score of a side on the board is calculated by the minimum amount of hex needed to finish the game with the dijkstra algorithm. The less is the score, the best it is. First and last rows/lines are linked with a cost of 0, the path is calculated with the opposites corner of the board. """ # Initialisation visited = [] values = [] open_list = [] for _ in range(hex.Board.BOARD_LEN): values.append(inf) if color == hex.Board.RED: for i in range(hex.Board.LINE_LEN): values[i] = 0 open_list.append(i) else: for i in range(0, hex.Board.BOARD_LEN, hex.Board.LINE_LEN): values[i] = 0 open_list.append(i) # Tant qu'il existe un sommet non visité while len(open_list) != 0: # On choisit un sommet pas encore visité minimal curr = open_list.pop(0) visited.append(curr) # Pour chaque voisin de current hors de visited # et différent de la couleur opposée for h in hex.neighbors(curr): # print (curr, hex.neighbors(curr)) if h not in visited and board.board_state[h] != (not color): weight = transition_value( curr, board.hex_color(curr), h, board.hex_color(h), color ) if values[h] > (values[curr] + weight) and weight != inf: values[h] = values[curr] + weight index = 0 while (index < len(open_list) and values[open_list[index]] < values[h]): index = index + 1 open_list.insert(index, h) if color == hex.Board.RED: res_values = [] for i in range(110, hex.Board.BOARD_LEN): res_values.append(values[i]) res = min(res_values) else: res_values = [] for i in range(10, hex.Board.BOARD_LEN, hex.Board.LINE_LEN): res_values.append(values[i]) res = min(res_values) return res def find_lowest(visited, values): """ Secondary function for get_score, returns the minimal element in values who's not in visited. """ mini = inf sommet = -1 for i in range(len(values)): if i not in visited and values[i] <= mini: mini = values[i] sommet = i return sommet def transition_value(hex1: int, color1: bool, hex2: int, color2: bool, side: bool) -> int: """ Return the value of a transition between two neighbours hex and their colors. Return inf if the transition is not possible. """ if color1 == color2 and color1 is not None: return 0 # Si hex1 et hex2 sont dans la premiere colonne. if (hex1 % hex.Board.LINE_LEN == 0 and hex2 % hex.Board.LINE_LEN == 0 and side == hex.Board.BLUE): return 0 # Si hex1 et hex2 sont dans la derniere colonne. if (hex1 % hex.Board.LINE_LEN == hex.Board.LINE_LEN - 1 and hex2 % hex.Board.LINE_LEN == hex.Board.LINE_LEN - 1 and side == hex.Board.BLUE): return 0 # Si hex1 et hex2 sont dans la premiere ligne. if (hex1 <= hex.Board.K1 and hex2 <= hex.Board.K1 and side == hex.Board.RED): return 0 # Si hex1 et hex2 sont dans la derniere ligne. if (hex1 >= hex.Board.A11 and hex2 >= hex.Board.A11 and side == hex.Board.RED): return 0 if color1 == (not side) or color2 == (not side): return 1000 return 1
72b730b83db79e0bef6ccd97734d1c16b4fb07cd
baharaysel/python-study-from-giraffeAcademy
/dictionaries.py
832
3.59375
4
monthConversions = { "Jan" : "January", "Feb" : "Febuary", "Mar" : "March", "Apr" : "April", "May" : "May", "Jun" : "June", "Jul" : "July", "Aug" : "August", "Sep" : "September", "Oct" : "October", "Nov" : "November", "Dec" : "December", } print(monthConversions["Nov"]) #November print(monthConversions.get("Dec")) #December print(monthConversions.get("X")) #none print(monthConversions.get("X","Not a valid key")) #Not a valid key # We can use numbers instead of strings as well monthConversions2 = { 1 : "January", 2 : "February", 3 : "March", 4 : "April", 5 : "May", 6 : "June", 7 : "July", 8 : "August", 9 : "September", 10 : "October", 11 : "November", 12 : "December", } print(monthConversions2[2]) #February print(monthConversions2.get(1)) #January
26d4c7b0708fab0a34f64a0446a488ca6aafc6b4
baharaysel/python-study-from-giraffeAcademy
/tryexcept.py
719
4.1875
4
try: number = int(input("Enter a number: ")) print(number) except: print("Invalid Input") # trying to catch different type of errors try: value = 10 / 0 number = int(input("Enter a number: ")) print(number) except ZeroDivisionError: print("Divide by zero") except ValueError: print("Invalid Input") # it didnt work it gives error # saving Error as variable try: answer = 10/0 number = int(input("Enter a number: ")) print(number) except ZeroDivisionError as err: print(err) except ValueError: print("Invalid Input") #division by zero #try: #except: # dont leave except empty it is not good practice . We want to know catch the specific type of error.
2929641de43ee29ccaa86d1f5864203c6ec8e5c9
baharaysel/python-study-from-giraffeAcademy
/for_Loops.py
693
4.1875
4
for letter in "Giraffe Academy": print(letter) friends = ["Figen", "Birgul", "Esra"] for friend in friends: print(friend) # Figen # Birgul # Esra friends = ["Figen", "Birgul", "Esra"] for index in range(10): # 10 is not included print(index) #0 #1 #2 #3 #4 #5 #6 #7 #8 #9 friends = ["Figen", "Birgul", "Esra"] for index in range(3, 6): # 6 is not included print(index) #3 #4 #5 friends = ["Figen", "Birgul", "Esra"] for index in range(len(friends)): print(friends[index]) #Figen #Birgul #Esra friends = ["Figen", "Birgul", "Esra"] for index in range(len(friends)): if index == 0: print("first Iteration") else: print("Not first")
d3ca722ba429ba67ab48a281f8a20b7c3ddaeaf1
awosikaola/guess-the-number
/module.py
548
3.8125
4
import random secretno = random.randint(1, 20) print('There is a number in my mind now between 1-20') for guesstaken in range(1, 7): guess = int(input('Take a quick guess: ')) if guess<secretno: print('your guess is a bit low, keep trying') elif guess>secretno: print('your guess is high, keep trying') else: break if guess==secretno: print('You have done well champ, you guessed right in ' + str(guesstaken)) else: print('Nope, you missed all chances, the number i thought of was ' + str(secretno))
44e718b875751abd5c58ad19a9fec3532a72533d
TimurKukharskiy/tictactoe
/viewtictac.py
464
3.59375
4
import sys def view(list): for yy in range(0,3): if yy==0: sys.stdout.write(" 0 1 2\n") sys.stdout.write(str(yy)+" ") for xx in range (0,3): if list[yy][xx]==0: sys.stdout.write(" ") if list[yy][xx]==1: sys.stdout.write("X") if list[yy][xx]==2: sys.stdout.write("O") if xx<2: sys.stdout.write("|") if yy<2:sys.stdout.write("\n -----\n") sys.stdout.write("\n")
f6dc235df0027aeb109e3a36be65cb9ab170a5a7
BenjaminLange/work_log
/work_log.py
12,987
3.5
4
import csv import re import os import sys from datetime import datetime from datetime import timedelta WORK_LOG_FILENAME = 'work_log.csv' TEMP_WORK_LOG_FILENAME = 'temp_work_log.csv' FMT_MONTH_DAY_YEAR = '%m/%d/%y' FMT_HOUR_MINUTE = '%H:%M' FIELDNAMES = ['id', 'name', 'date', 'time_spent', 'notes'] def initialize(): """Creates a work log csv file with headers if the file does not exist""" if not os.path.isfile(WORK_LOG_FILENAME): with open(WORK_LOG_FILENAME, 'a', newline='') as work_log: work_log_writer = csv.DictWriter(work_log, fieldnames=FIELDNAMES) work_log_writer.writeheader() def start(): """Displays a menu that allows navigation to create a new entry, search, or quit""" while True: clear_screen() print("Select an option:") print(" e: Enter new entry (Default)") print(" s: Search") print(" q: Quit") user_input = input("> ").lower() if user_input == 'q': sys.exit() if user_input == 's': search_menu() else: new_entry() def new_entry(): """Adds a new entry to the work log csv file""" clear_screen() entry = {} entry['id'] = get_next_id() entry['name'] = input_name() print("How many minutes did you spend on {}?".format(entry['name'])) print("Or you may specify a format after the time, seperated by a comma") entry['time_spent'] = input_time_spent() add_notes = input("Add notes? Y/n ").lower() if add_notes != 'n': entry['notes'] = input_notes() entry['date'] = datetime.now().strftime(FMT_MONTH_DAY_YEAR) with open(WORK_LOG_FILENAME, 'a', newline='') as work_log: work_log_writer = csv.DictWriter(work_log, fieldnames=FIELDNAMES) work_log_writer.writerow(entry) def input_name(): name = input("Task Name: ") return name def input_time_spent(update=False): time_spent = input("Time Spent: ") if update: if time_spent == '': return '' if ',' in time_spent: entry_list = time_spent.split(',') entry_time = entry_list[0] entry_time_format = entry_list[1] return convert_string_to_timedelta(entry_time, entry_time_format) else: try: return convert_minutes_to_timedelta(time_spent) except ValueError: print("I don't recognize that format. Please try again.") return input_time_spent() def input_notes(): note_list = [] notes = "A" print("Notes (Enter a blank line to save):") while notes != '': notes = input("> ") note_list.append(notes.replace('\\n', '\n')) notes = '\n'.join(note_list) return notes def input_date(update=False): date = input("Date (MM/DD/YY): ") if update: if date == '': return '' try: date = datetime.strptime(date, FMT_MONTH_DAY_YEAR) except ValueError: print("I don't recognize that format, please try again.") return input_date() date = date.strftime(FMT_MONTH_DAY_YEAR) return date def search_menu(): """Displays a menu to pick search method""" clear_screen() print("What would you like to search by?") print(" d: Date (Default)") print(" t: Time spent") print(" e: Exact") print(" p: Pattern (Regex)") user_input = input("> ").lower() if user_input == 't': search_by_time_spent() elif user_input == 'e': search_by_string() elif user_input == 'p': search_by_pattern() else: search_by_date() def search_by_time_spent(error=None): clear_screen() if error: print(error) print("Enter the minute amount to search for or search using %H:%M.") print("You may specify a time range using %H:%M - %H:%M") user_input = input("> ").strip() time_range = re.compile(r'\d{1,2}:\d{1,2} - \d{1,2}:\d{1,2}') time_format = re.compile(r'\d{1,2}:\d\d') minute_format = re.compile(r'^\d+$') if time_range.search(user_input): time_list = user_input.split('-') minimum = convert_string_to_timedelta(time_list[0].strip()) maximum = convert_string_to_timedelta(time_list[1].strip()) entries = [] with open(WORK_LOG_FILENAME, 'r') as work_log: work_log_reader = csv.DictReader(work_log) for entry in work_log_reader: entry_time = convert_string_to_timedelta( entry['time_spent'], '%H:%M:%S') if minimum <= entry_time <= maximum: entries.append(entry) print_entries(entries) elif time_format.search(user_input): user_input = convert_string_to_timedelta(user_input) elif minute_format.search(user_input): user_input = convert_minutes_to_timedelta(user_input) else: error = "I don't recognize that format. Please try again.\n" return search_by_time_spent(error) with open(WORK_LOG_FILENAME, 'r') as work_log: entries = [] work_log_reader = csv.DictReader(work_log) for entry in work_log_reader: if entry['time_spent'] == str(user_input): entries.append(entry) print_entries(entries) def search_by_date(error=None): clear_screen() if error: print(error) print("Please enter a date to search for (MM/DD/YY).") print("You may also search a date range using MM/DD/YY - MM/DD/YY") user_input = input("> ") date_range = re.compile(r'\d\d/\d\d/\d\d - \d\d/\d\d/\d\d') date = re.compile(r'\d\d/\d\d/\d\d') if date_range.search(user_input): date_list = user_input.split('-') start_date = datetime.strptime( date_list[0].strip(), FMT_MONTH_DAY_YEAR) end_date = datetime.strptime( date_list[1].strip(), FMT_MONTH_DAY_YEAR) entries = [] with open(WORK_LOG_FILENAME, 'r') as work_log: work_log_reader = csv.DictReader(work_log) for entry in work_log_reader: entry_date = datetime.strptime( entry['date'], FMT_MONTH_DAY_YEAR) if start_date <= entry_date <= end_date: entries.append(entry) print_entries(entries) elif date.search(user_input): entries = [] with open(WORK_LOG_FILENAME, 'r') as work_log: work_log_reader = csv.DictReader(work_log) for entry in work_log_reader: if user_input == entry['date']: entries.append(entry) print_entries(entries) else: error = "I don't recognize that format. Please try again.\n" return search_by_date(error) input("\nPress enter to return to the main menu...") def search_by_string(): clear_screen() user_input = input("What would you like to search for? ").lower() entries = [] with open(WORK_LOG_FILENAME, 'r') as work_log: work_log_reader = csv.DictReader(work_log) for entry in work_log_reader: if(user_input in entry['name'].lower() or user_input in entry['notes'].lower()): entries.append(entry) print_entries(entries) def search_by_pattern(): clear_screen() user_input = input("What pattern would you like to search for? ") search_pattern = re.compile(user_input) entries = [] with open(WORK_LOG_FILENAME, 'r') as work_log: work_log_reader = csv.DictReader(work_log) for entry in work_log_reader: try: if (search_pattern.search(entry['name']) or search_pattern.search(entry['notes'])): entries.append(entry) except IndexError: pass print_entries(entries) def print_entry(entry): """Print a single entry to the screen""" border = '-' * 50 print(border) print(entry['name']) print("Date: {}".format(entry['date'])) print("Time Spent: {}".format(entry['time_spent'])) if entry['notes'] != '': print("Notes:\n{}\n{}".format('----------', entry['notes'])) print(border) def print_entries(entries): """Prints a list of log entries and allows paging through each entry individually. Also allows picking an entry for editing or deletion.""" if len(entries) == 0: print("\nNo results were found.\n") input("Press enter to return to the main menu...") start() counter = 0 error = None while True: clear_screen() if len(entries) == 0: print("There are no more entries!") input("Press enter to return to the main menu...") start() if error: print(error) input("Press enter to continue...") clear_screen() error = None print_entry(entries[counter]) print("\nWhat would you like to do?") print(" n: Next entry (Default)") print(" p: Previous entry") print(" e: Edit entry") print(" d: Delete entry") print(" q: Quit to main menu") user_input = input("> ").lower() if user_input == 'q': start() elif user_input == 'p': if counter <= 0: error = "End of list. Can't go back." continue counter -= 1 elif user_input == 'd': delete_entry(entries[counter]['id']) del entries[counter] if counter > len(entries) - 1: counter -= 1 elif user_input == 'e': edit_entry(entries[counter]) else: counter += 1 if counter > len(entries) - 1: counter -= 1 error = "End of list. Can't move forward." def delete_entry(entry_id): with open(WORK_LOG_FILENAME, 'r') as work_log: copy = open(TEMP_WORK_LOG_FILENAME, 'a', newline='') copy_writer = csv.DictWriter(copy, fieldnames=FIELDNAMES) copy_writer.writeheader() work_log_reader = csv.DictReader(work_log) for entry in work_log_reader: if entry['id'] == entry_id: continue else: copy_writer.writerow(entry) copy.close() os.remove(WORK_LOG_FILENAME) os.rename(TEMP_WORK_LOG_FILENAME, WORK_LOG_FILENAME) def edit_entry(entry): print("\nUpdate each value or press enter to leave it unchanged.\n") prev_name = entry['name'] prev_date = entry['date'] prev_time_spent = entry['time_spent'] prev_notes = entry['notes'] new_name = input_name() entry['name'] = new_name or prev_name new_date = input_date(update=True) entry['date'] = new_date or prev_date new_time_spent = input_time_spent(update=True) entry['time_spent'] = new_time_spent or prev_time_spent new_notes = input_notes() entry['notes'] = new_notes or prev_notes with open(WORK_LOG_FILENAME, 'r') as work_log: copy = open(TEMP_WORK_LOG_FILENAME, 'a', newline='') copy_writer = csv.DictWriter(copy, fieldnames=FIELDNAMES) copy_writer.writeheader() work_log_reader = csv.DictReader(work_log) for prev_entry in work_log_reader: if prev_entry['id'] == entry['id']: copy_writer.writerow(entry) else: copy_writer.writerow(prev_entry) copy.close() os.remove(WORK_LOG_FILENAME) os.rename(TEMP_WORK_LOG_FILENAME, WORK_LOG_FILENAME) def convert_string_to_timedelta(time, fmt=FMT_HOUR_MINUTE): time_range = datetime.strptime(time, fmt) time_range_delta = timedelta(hours=time_range.hour, minutes=time_range.minute, seconds=time_range.second) return time_range_delta def convert_minutes_to_timedelta(minutes_string): minutes = int(minutes_string) if minutes >= 60: hours = int(minutes / 60) minutes = minutes % 60 minutes_string = "{}:{}".format(hours, minutes) minutes_date_time = datetime.strptime(minutes_string, FMT_HOUR_MINUTE) else: minutes_date_time = datetime.strptime(minutes_string, '%M') minutes_delta = timedelta(hours=minutes_date_time.hour, minutes=minutes_date_time.minute, seconds=minutes_date_time.second) return minutes_delta def get_next_id(): """Gets the next unique id for creating a new entry""" with open(WORK_LOG_FILENAME, 'r') as work_log: work_log_reader = csv.DictReader(work_log) entry_id = 0 for entry in work_log_reader: if int(entry['id']) > entry_id: entry_id = int(entry['id']) entry_id += 1 return entry_id def clear_screen(): if os.name == 'nt': os.system('cls') else: os.system('clear') if __name__ == '__main__': initialize() start()
fc831d3a4869ab1084622ec1cdee10b43d11203d
Diamoon18/grafika
/burning_flower.py
1,106
4.1875
4
import turtle from turtle import Turtle, Screen ANGLE = 2 color = 'blue' color1 = 'black' color2 = 'red' color3 = 'yellow' def circles(t, size, small): for i in range(10): t.circle(size) size=size-small def circle_direction(t, size, repeat, small): for i in range (repeat): circles(t, size, small) t.right(360/repeat) def circle_spiral(turtle, radius, color_name): for i in range(360 // ANGLE): turtle.color(color_name) turtle.circle(radius) turtle.left(ANGLE) def main(): screen = Screen() screen.bgcolor('black') eye = Turtle(visible=False) eye.speed('fastest') spiral(eye, 100, color) spiral(eye, 50, color2) spiral(eye, 25, color1) s = Turtle(visible=False) s.speed('fastest') s.color('red') circle_small(s, 200, 10, 4) t1 = Turtle(visible=False) t1.speed('fastest') t1.color('yellow') circle_small(t1, 160, 10, 10) spiral(eye, 10, color3) screen.exitonclick() if __name__ == "__main__": main()
2016cae12f56a04bff23c155448a76a09c595005
xiangling1991/xiangling
/Python/自定义模块.py
299
3.875
4
''' 为了使参数的合法化,需要将参数初始化,或者定义参数的类型 ''' #例如: #i=0 #j=0 int i int j def mul(i,j): k = i*j return k z = mul(i,j) print z #dir函数,显示该模块的功能函数,还能查看任意指定的函数列表
5d0371c886729ffd8070088321fe21381c2d3487
xiaowuc2/Code-in-Place-2021-Assignment-Solution
/Assignment-2/4. Random Numbers.py
864
4.59375
5
""" Write a program in the file random_numbers.py that prints 10 random integers (each random integer should have a value between 0 and 100, inclusive). Your program should use a constant named NUM_RANDOM, which determines the number of random numbers to print (with a value of 10). It should also use constants named MIN_RANDOM and MAX_RANDOM to determine the minimal and maximal values of the random numbers generated (with respective values 0 and 100). To generate random numbers, you should use the function random.randint() from Python’s random library. Here's a sample run of the program: $ python random_numbers.py 35 10 45 59 45 100 8 31 48 6 """ import random NUM_RANDOM=10 MIN_RANDOM=0 MAX_RANDOM=100 def main(): NUM_RANDOM=0 for i in range(10): print(random.randint(MIN_RANDOM,MAX_RANDOM)) if __name__ == '__main__': main()
cf695905d4d217da034247bf4bd9d5b4ab3b0c76
xiaowuc2/Code-in-Place-2021-Assignment-Solution
/Assignment-3/2. Finding Forest Flames.py
1,630
4.1875
4
""" This program highlights fires in an image by identifying pixels whose red intensity is more than INTENSITY_THRESHOLD times the average of the red, green, and blue values at a pixel. Those "sufficiently red" pixels are then highlighted in the image and other pixels are turned grey, by setting the pixel red, green, and blue values to be all the same average value. """ from simpleimage import SimpleImage INTENSITY_THRESHOLD = 1.0 DEFAULT_FILE = 'images/greenland-fire.png' def find_flames(filename): """ This function should highlight the "sufficiently red" pixels in the image and grayscale all other pixels in the image in order to highlight areas of wildfires. """ image = SimpleImage(filename) # TODO: your code here for pixel in image: average=(pixel.red+pixel.green+pixel.blue)//3 if pixel.red>=average*INTENSITY_THRESHOLD: pixel.red=255 pixel.green=0 pixel.blue=0 else: pixel.red=average pixel.blue=average pixel.green=average return image def main(): # Get file name from user input filename = get_file() # Show the original fire original_fire = SimpleImage(filename) original_fire.show() # Show the highlighted fire highlighted_fire = find_flames(filename) highlighted_fire.show() def get_file(): # Read image file path from user, or use the default file filename = input('Enter image file (or press enter for default): ') if filename == '': filename = DEFAULT_FILE return filename if __name__ == '__main__': main()
4cb2c3538140b1b4f49d29ae713d5129da8f8e20
CordThomas/census_2020
/src/insert_census_data.py
4,233
3.796875
4
""" Inserts the geo heading and p1 data from the legacy file format into the census sqlite database created by create_database. """ import os import sqlite3 from sqlite3 import Error census_file = '../data/census_2020.db' geo_heading_table = 'geo_heading' p1_table = 'p1' geo_heading_file = '../data/ca2020.pl/cageo2020.pl' p1_file = '../data/ca2020.pl/ca000012020.pl' def create_connection(db_file): """ create a database connection to a SQLite database """ conn = None try: conn = sqlite3.connect(db_file) except Error as e: print(e) return conn def execute_many_sql(census_db, sql_statement, sql_field_values): """ create a table from the create_table_sql statement :param census_db: Connection object :param sql_statement: the insert statement string :param sql_field_values: the array of insert values :return: """ try: c = census_db.cursor() # print (sql_statement) # print(sql_field_values) c.executemany(sql_statement, sql_field_values) except Error as e: print(e) def execute_sql(census_db, sql_statement): """ create a table from the create_table_sql statement :param census_db: Connection object :param sql_statement: the insert statement string :param sql_field_values: the array of insert values :return: """ try: c = census_db.cursor() # print (sql_statement) # print(sql_field_values) c.execute(sql_statement) except Error as e: print(e) def get_fields_holder(src_file): first_line = src_file.readline() fields = first_line.split('|') fields_holder = ',?' * (len(fields)) return fields_holder[1:] def populate_table_geo_headings(census_db, table_name, source_file): """Populate the named table from the source file""" src_file = open(source_file, 'r', encoding='cp1252') field_holders = get_fields_holder(src_file) src_file.seek(0, os.SEEK_SET) log_rec_nos = [] sql_statement = 'INSERT INTO ' + table_name + ' VALUES (' + field_holders + ');' sql_values = [] record_count = 0 for record in src_file: record_count += 1 values = record.replace('\r\n', '').split('|') # Only inserting records from LA County if values[14] == '037': sql_values.append(values) log_rec_nos.append(values[7]) if record_count % 1000 == 0: print("Populating {} with {} records".format(str(record_count), str(len(sql_values)))) execute_many_sql(census_db, sql_statement, sql_values) if record_count % 10000 == 0: census_db.commit() # One last execute to catch the remaining records execute_many_sql(census_db, sql_statement, sql_values) census_db.commit() return log_rec_nos def populate_table_p1(census_db, table_name, source_file, log_rec_nos): """Populate the named table from the source file""" src_file = open(source_file, 'r', encoding='cp1252') field_holders = get_fields_holder(src_file) src_file.seek(0, os.SEEK_SET) sql_statement = 'INSERT INTO ' + table_name + ' VALUES (' + field_holders + ');' sql_values = [] record_count = 0 for record in src_file: record_count += 1 values = record.replace('\r\n', '').split('|') # Only inserting records from LA County - based on the geo_headings data if values[4] in log_rec_nos: sql_values.append(values) if record_count % 1000 == 0: print("Populating {} with {} records".format(str(record_count), str(len(sql_values)))) execute_many_sql(census_db, sql_statement, sql_values) if record_count % 10000 == 0: census_db.commit() # One last execute to catch the remaining records execute_many_sql (census_db, sql_statement, sql_values) census_db.commit() if __name__ == '__main__': census_db = create_connection(census_file) log_rec_nos = populate_table_geo_headings(census_db, geo_heading_table, geo_heading_file) populate_table_p1(census_db, p1_table, p1_file, log_rec_nos) if census_db: census_db.close()
1a482e608f7624ff133116bfe2646b6f0f437e4c
RmanKarimi/CodeWarsFundamental
/longest.py
173
3.671875
4
""" . Return a new sorted string, the longest possible, containing distinct letters, """ @staticmethod def longest(self, s1, s2): return "".join(sorted(set(s1 + s2)))
93a8fada3a2bac48d3ac31333b48fdfac7b36e26
RmanKarimi/CodeWarsFundamental
/make_readable.py
311
3.921875
4
""" returns the time in a human-readable format (HH:MM:SS) from none-negative integer value """ def make_readable(sec): hours, rem = divmod(sec, 3600) minutes, seconds = divmod(rem, 60) return '{:02d}:{:02d}:{:02d}'.format(hours, minutes, seconds) # return strftime("%I:%M:%S", gmtime(sec))
cab0b90aac273c28cf2626d72ee2d2c19f16d69a
RmanKarimi/CodeWarsFundamental
/even_or_odd.py
73
3.640625
4
def even_or_odd(number): return "Odd" if number % 2 == 0 else "Even"
36753ba049d88aae9ea04173bf2de03a86bc8c7b
willerhehehe/audio_mixer
/audio_mixer/common_tools/fft_data_divide.py
412
3.65625
4
# -*- coding:utf-8 -*- def fft_data_divide(fft_data): n = len(fft_data) if n % 2 == 0: part1 = fft_data[0:int(n / 2)] part2 = fft_data[int(n / 2):] elif n % 2 == 1: part1 = fft_data[0:int((n + 1) / 2)] part2 = fft_data[int((n + 1) / 2):] else: raise RuntimeError("n % 2 must 1 or 0, but n is {} and type(n)={}".format(n, type(n))) return part1, part2
cef37285f99e97d1d3e7a371e32c451478c768c6
nickmachnik/AoC-solutions
/2020/python/day11/solution.py
3,273
3.765625
4
#!/usr/bin/env python DIRECTIONS = [ (0, 1), # right (0, -1), # left (1, 0), # down (-1, 0), # up (1, 1), # down right (1, -1), # down left (-1, -1), # up left (-1, 1) # up left ] def main(): print("Answer part one:", part_one("puzzleinput.txt")) print("Answer part two:", part_two("puzzleinput.txt")) def part_one(path): room = WaitingRoom(path) room.fill_and_free_seats(room._get_num_occupied_neighboring_seats, 4) return room.num_occupied_seats def part_two(path): room = WaitingRoom(path) room.fill_and_free_seats(room._get_num_occupied_in_sight, 5) return room.num_occupied_seats class WaitingRoom: def __init__(self, path): self._load_layout(path) self.num_occupied_seats = 0 def _load_layout(self, path): self.room = [] with open(path, 'r') as fin: for line in fin: self.room.append(list(line.strip())) self.nrows = len(self.room) self.ncols = len(self.room[0]) def fill_and_free_seats( self, neighbor_count_function, seat_free_thr ): while True: fill = [] free = [] for i in range(self.nrows): for j in range(self.ncols): curr_state = self.room[i][j] if curr_state == ".": continue full_neighbors = \ neighbor_count_function(i, j) if curr_state == "#" and full_neighbors >= seat_free_thr: free.append((i, j)) elif curr_state == 'L' and full_neighbors == 0: fill.append((i, j)) if len(fill) == len(free) == 0: return for i, j in fill: self.room[i][j] = '#' self.num_occupied_seats += 1 for i, j in free: self.room[i][j] = 'L' self.num_occupied_seats -= 1 def _get_num_occupied_neighboring_seats(self, row, col): occupied_count = 0 for i in range(row - 1, row + 2): if i < 0 or i >= self.nrows: continue for j in range(col - 1, col + 2): if (j < 0 or j >= self.ncols) or (i == row and j == col): continue if self.room[i][j] == '#': occupied_count += 1 return occupied_count def _get_num_occupied_in_sight(self, row, col): occupied_count = 0 for di, dj in DIRECTIONS: curr_row, curr_col = row + di, col + dj while self.is_in_room(curr_row, curr_col): if self.room[curr_row][curr_col] == 'L': break elif self.room[curr_row][curr_col] == '#': occupied_count += 1 break else: curr_row += di curr_col += dj return occupied_count def is_in_room(self, row, col): if row < 0 or row >= self.nrows: return False if col < 0 or col >= self.ncols: return False return True if __name__ == '__main__': main()
3e8ff20769491123d24fc8fe8212878172baaebd
nickmachnik/AoC-solutions
/2020/python/day21/solution.py
2,232
3.671875
4
#!/usr/bin/env python def main(): data = load_data('puzzleinput.txt') print("Answer part one: ", part_one(data)) print("Answer part two: ", part_two(data)) def part_one(data): alg_to_ingr = {} ingr_counts = {} for ingredients, allergens in data: for allergen in allergens: if allergen not in alg_to_ingr: alg_to_ingr[allergen] = ingredients else: alg_to_ingr[allergen] = alg_to_ingr[allergen] & ingredients for ingredient in ingredients: if ingredient not in ingr_counts: ingr_counts[ingredient] = 0 ingr_counts[ingredient] += 1 ingredients_to_avoid = set().union(*alg_to_ingr.values()) res = 0 for ingredient, count in ingr_counts.items(): if ingredient not in ingredients_to_avoid: res += count return res def part_two(data): alg_to_ingr = {} ingr_counts = {} for ingredients, allergens in data: for allergen in allergens: if allergen not in alg_to_ingr: alg_to_ingr[allergen] = ingredients else: alg_to_ingr[allergen] = alg_to_ingr[allergen] & ingredients for ingredient in ingredients: if ingredient not in ingr_counts: ingr_counts[ingredient] = 0 ingr_counts[ingredient] += 1 # sieve ingr_to_alg = {} algs = list(alg_to_ingr.keys()) curr_ix = -1 while len(algs) != 0: curr_ix = (curr_ix + 1) % len(algs) curr_alg = algs[curr_ix] curr_ingr = alg_to_ingr[curr_alg] - ingr_to_alg.keys() if len(curr_ingr) == 1: ingr_to_alg[curr_ingr.pop()] = curr_alg algs.remove(curr_alg) return ",".join(sorted(ingr_to_alg, key=lambda x: ingr_to_alg[x])) def load_data(path): data = [] with open(path, 'r') as fin: for line in fin: line = line.strip() ingredients, allergens = line.split(' (contains ') ingredients = ingredients.split() allergens = allergens[:-1].split(', ') data.append([set(ingredients), set(allergens)]) return data if __name__ == '__main__': main()
18668038ffcb6355fd642ba6fb3151648ef0ff85
nickmachnik/AoC-solutions
/2020/python/day17/solution.py
2,191
3.53125
4
#!/usr/bin/env python from itertools import product class PocketDimension: def __init__(self, path, dimensionality): self.ndim = dimensionality self.load_initial_state(path) def load_initial_state(self, path): self.active_cubes = set() with open(path, 'r') as fin: for y, line in enumerate(fin): line = line.strip() for x, symbol in enumerate(line): if symbol == '#': self.active_cubes.add( tuple([x, y] + [0] * (self.ndim - 2))) def cycle(self): inactive_candidates = set() active_in_next_cycle = set() for cube in self.active_cubes: active_neighbors = 0 for neighbor in self.neighbors(cube): if neighbor == cube: continue elif neighbor in self.active_cubes: active_neighbors += 1 else: inactive_candidates.add(neighbor) if active_neighbors == 2 or active_neighbors == 3: active_in_next_cycle.add(cube) for cube in inactive_candidates: active_neighbors = 0 for neighbor in self.neighbors(cube): if neighbor in self.active_cubes: active_neighbors += 1 if active_neighbors == 3: active_in_next_cycle.add(cube) self.active_cubes = active_in_next_cycle def neighbors(self, cube): return product( *[ [cube[i] - 1, cube[i], cube[i] + 1] for i in range(self.ndim)] ) def num_active_cubes(self): return len(self.active_cubes) def main(): print("Answer part one:", part_one("puzzleinput.txt")) print("Answer part two:", part_two("puzzleinput.txt")) def part_one(path): pd = PocketDimension(path, 3) for i in range(6): pd.cycle() return pd.num_active_cubes() def part_two(path): pd = PocketDimension(path, 4) for i in range(6): pd.cycle() return pd.num_active_cubes() if __name__ == '__main__': main()
0016b75282b5d0355ac2ab3fc9b7b755a1aee667
p506/PyThon-ProGrammIng
/python_prob_5.py
972
3.875
4
''' Author: Aditya Mangal Date: 12 september,2020 Purpose: python practise problem ''' def next_palindrome(number): number += 1 while not is_palindrome(number): number += 1 return number def is_palindrome(number): return str(number) == str(number)[::-1] if __name__ == '__main__': print('\t\tHello!') user = int(input('How many numbers are there in your list?\n')) user_list = [] for i in range(user): user_list_input = int( input(f'Enter your {i+1} number in your list.\n')) user_list.append(user_list_input) for i in range(user): if user_list[i] > 10: print( f'Your next palindrome of number {user_list[i]} is {next_palindrome(user_list[i])}.\n') elif user_list[i] < 10: # exit() print(f'Your number {user_list[i]} is lesser than 10 so palindrome cant be find.\n') else: print('Something gone Wrong!')
8161f21c556e806ff076ad44a4639abe971418d5
p506/PyThon-ProGrammIng
/adding_matrixes.py
994
3.921875
4
''' Author: Aditya Mangal Date: 20 september,2020 Purpose: python practise problem ''' def input_matrixes(m, n): output = [] for i in range(m): row = [] for j in range(n): user_matrixes = int(input(f'Enter number on [{i}][{j}]\n')) row.append(user_matrixes) output.append(row) return output def sum(A, B): output2 = [] for i in range(len(A)): row2 = [] for j in range(len(A[0])): row2.append(A[i][j] + B[i][j]) output2.append(row2) return output2 if __name__ == "__main__": rows = int(input('Enter the m rows of matrixes.\n')) columns = int(input('Enter the n columns of matrixes.\n')) print('Enter your first matrix.\n') A = input_matrixes(rows, columns) print('Enter your secound matrix.\n') B = input_matrixes(rows, columns) result = sum(A, B) print('Your sum of matrixes are :-\n') for i in range(len(result)): print(result[i])
eac81f4aa11e96b8479a9ae071be9b3631dbdb19
p506/PyThon-ProGrammIng
/Itertools.permutations.py
373
3.921875
4
''' Author: Aditya Mangal Date: 5 october,2020 Purpose: python practise problem ''' from itertools import permutations x = word, num = input().split() a = list(permutations(word, int(num))) b = list(map(list, a)) final_list = [] for i in range(len(b)): final_list.append(''.join(b[i])) a = sorted(final_list) # sorted function for i in range(len(a)): print(a[i])
a904abefad2dd40aed7e41d1e06b71c7cbcd3043
MeryemsCode/PyhtonBasicProjects
/05_Projects/FactorialCalculation_Function_For.py
144
3.65625
4
def factorial(sayi): factorial = 1 for i in range(1,sayi+1): factorial *= i return factorial print(factorial(5))
17247024e0cf48881a077727816ff7aa7eb94bf3
MeryemsCode/PyhtonBasicProjects
/20_Project/ManavFiyatListesi_Dict.py
2,036
4
4
meyveler={} #meyveler isminde bir sözlük giris=-1 #kullanıcıdan aldıgım secenek while giris!="0": #kullanıcının seçenekleri print("Yapacağınız işlemin numarasını seçiniz: ") giris=input("1- Kayıt Ekle \n 2- Kayıt Düzelt \n 3- Kayıt Ara\n 4- Tümünü Listele\n 5- KAyıt Sil\n 6-Tümünü Sil\n 0-Çıkış\n") if giris=="0": #eğer 0 basarsa, sistmden cıkar quit() if giris=="1": #eğer 1 basarsa kayıt ekler meyveadi=input("Meyve adı giriniz: ") #meyve adi gir fiyat=input("Fiyat giriniz: ") #fiyat gir meyveler[meyveadi]=fiyat #meyveler sözlüğüne ekle print("Meyve Eklendi") #kullanıcıya bilgi ver if giris=="2": #kayıt düzelt meyveadi=input("Meyve adı giriniz: ") #meyve adi iste if meyveadi in meyveler.keys(): #eğer KEYler arasında varsa fiyat=input("Fiyat giriniz: ") #fiyat iste meyveler[meyveadi]=fiyat #fiyatı güncelle print("Meyve Düzeltildi") #kullanıcıya bilgi ver else: #eğer yoksa print("Böyle bir meyve yok") #meyve olmadığını söyle if giris=="3": #kayıt ara meyveadi=input("Meyve adı giriniz: ") #meyveadi nı iste durum=meyveler.get(meyveadi,"Böyle bir meyve yok") #var print(f"{durum}") if giris=="4": #tümünü listele for meyveadi in meyveler.keys(): #meyveler sözlüğündeki print(meyveadi,meyveler[meyveadi]) #meyve adi ve fiyatlarını bas if giris=="5": #kaydı sil meyveadi=input("Meyve adı giriniz: ") #meyve adini al durum=meyveler.pop(meyveadi,"Böyle bir meyve yok") #varsa sil, yoksa mesaj print(f"{durum}") if giris=="6": #tümünü sil meyveler={} #meyveler sözlüğünü boşalt meyveler.clear() print("Tümü Silindi")
2201f654d9bb424efbb07d46f015dc38971f72f0
hesajs/Timer
/timer-console.py
681
3.78125
4
import time import os os.system("clear") minutes = int(input("Enter the minutes: ")) sec = minutes*60 min = minutes elapsed_min=0 for i in range(1, minutes*60+1): time.sleep(1) sec-=1 os.system("clear") if(i%60==0): elapsed_min+=1 min-=1 print(f"Number of miutes: {minutes}\n") print("--------------------------------------------") print(f"\t| Time Elapsed: {elapsed_min}: {i%60} |") print("--------------------------------------------\n\n\n") print("--------------------------------------------") print(f"\t| Time Remaining: {min}: {sec%60} |") print("--------------------------------------------")
41e98e7c943f2f6b36eb00ae60338ea6170ac588
tomatolike/MyLittleGame
/main.py
8,090
3.703125
4
from GameClass import * from Game import * import socket import _thread from multiprocessing import Lock import time # Initialize the world! Game = Game() Game.initialization() f = open('log.txt','w') print("世界建立完成!") f.writelines("世界建立完成!\n") # This is the server class # The logic of communication with client is here class MainConnect: def __init__(self,c,addr): print("连接点建立中……") f.writelines("连接点建立中……\n") self.c = c self.addr = addr self.mutex = Lock() self.actor = None print("连接点建立结束!") f.writelines("连接点建立结束!\n") # I have to explain the relationship of these print and input functions # I rewrite the print/input functions as printss/inputss # However, we need mutex lock or the messages will crush togethor. # So I used prints/inputs to use mutex locks. def prints(self, s): #s = s+"\n" self.mutex.acquire() self.c.send(str.encode(s)) self.mutex.release() def printss(self, s): self.actor.busy.acquire() self.prints(s) self.actor.busy.release() def inputss(self,s=""): self.actor.busy.acquire() x = self.inputs(s) self.actor.busy.release() time.sleep(0.5) return x def inputs(self, s=""): self.mutex.acquire() if s != "": #s = s+"\n" self.c.send(str.encode(s)) x = bytes.decode(self.c.recv(1024)) self.mutex.release() time.sleep(0.5) return x def login(self): answer = self.inputs("请输入角色名(账号):") for a in Actor.actorlist: if a.name == answer and a.status == True: answer = self.inputs("请输入密码:") if a.sec == answer: self.actor = a a.status = False a.net = self print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())+a.name+"登录成功!") f.writelines(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())+a.name+"登陆成功!\n") return True print("登录失败") f.writelines("登录失败\n") return False def mainprocess(self): while True: self.printss("\n\n#####################\n") self.printss("欢迎来到 神秘大陆 !") self.printss("你要做什么?\n你可以选择:\n回复1:查看自己的信息\n回复2:前往一个地方\n回复3:找这里的人做事\n回复4:使用物品\n回复5:创造\n回复6:离开") answer = self.inputss("请回复1~6:"); if answer == "1": self.printss("你想查看:\n1:自己所在的位置;2:自己的基本信息;3:自己拥有的物品\n") answer = self.inputss("请回复1~3:"); if answer == "1": self.printss(self.actor.printwhere()) continue elif answer == "2": self.printss(self.actor.printbasic()) continue elif answer == "3": self.printss("你想查看:\n1:背包;2:身上穿的;\n") answer = self.inputss("请回复1~2:"); if answer == "1": self.printss(self.actor.printrepertory()) continue elif answer == "2": self.printss(self.actor.printequipment()) self.printss("\n卸下装备?1、是;2、否:") answer = self.inputss() if answer == "1": answer = self.inputss("卸下:1、头盔;2、盔甲;3、武器;4、鞋子:") no = int(answer) self.printss(self.actor.equipment.unequip(self.actor,no-1)) continue else: self.printss("好好说话行吗。") else: self.printss("好好说话行吗。") elif answer == "2": self.printss("你想去:\n1:这里的地点;2:外面;3:其他城镇\n") answer = self.inputss("请回复1~3:"); if answer == "1": if self.actor.where == None: self.printss("你在天堂呢。") continue self.printss("这里有如下一些地点:") self.printss(self.actor.where.printplaces()) answer = self.inputss("请回复编号:"); to = int(answer) if to < 0 or to >= self.actor.where.placeaccount: self.printss("好好说话行吗。") else: self.printss(self.actor.goto(1,to)) elif answer == "2": self.printss(self.actor.goto(2,0)) elif answer == "3": self.printss("这个世界有如下一些城镇:") world = Objects.world self.printss(world.printplaces()) answer = self.inputss("请回复编号:"); to = int(answer) if to < 0 or to >= world.placeaccount: self.printss("好好说话行吗?") else: self.printss(self.actor.goto(3,to)) elif answer == "3": self.printss("这里有这些人:\n") self.printss(self.actor.where.printactors()) answer = self.inputss("请回复编号:"); to = int(answer) if self.actor.where.actorcontain[to] == self.actor: self.printss("自己找自己干嘛!") continue else: whom = self.actor.where.actorcontain[to] self.printss("你找到了"+whom.name+"\n") self.printss("你想要:\n回复1:交谈\n回复2:战斗\n回复3:交易\n") answer = self.inputss("请回复1~3:"); if answer == "1": if type(whom) is NPC: self.printss("你开始了交谈:\n") Game.GetInLogic(self.actor,whom) continue elif type(whom) is Player and whom.status == False: Game.GetInChat(self.actor,whom) continue else: self.printss("这个人不存在或不在线!") elif answer == "2": if type(whom) is NPC: self.printss("你开始了战斗!\n") Game.GetInFight(self.actor,whom) elif type(whom) is Player and whom.status == False: self.printss("你开始了战斗!\n") Game.GetInFight(self.actor,whom) else: self.printss("这个人不存在或不在线!") elif answer == "3": if type(whom) is NPC: self.printss("你开始了交易!\n") Game.GetInTrade(self.actor,whom) elif type(whom) is Player and whom.status == False: self.printss("你开始了交易!\n") Game.GetInTrade(self.actor,whom) else: self.printss("这个人不存在或不在线!") else: self.printss("好好说话!") elif answer == "4": Game.usething(self.actor) elif answer == "5": self.printss("你可以创造:\n回复1:在当前位置的新人物\n回复2:在当前地点下的新地点\n回复3:物品\n") answer = self.inputss("请回复1~3:") if answer == "1": Game.createActor(self.actor) elif answer == "2": Game.createPlace(self.actor) elif answer == "3": Game.createThing(self.actor) else: self.printss("好好说话。") elif answer == "6": self.printss("你暂时离开了大陆!") self.actor.status = True break else: self.printss("好好说话。") self.end() def end(self): print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())+self.actor.name+"退出游戏") f.writelines(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())+self.actor.name+"退出游戏\n") cc = self.c self.c = None cc.close() def connectgame(c, addr): print("尝试建立连接点") f.writelines("尝试建立连接点"+"\n") newplay = MainConnect(c,addr) print("建立连接点完毕") f.writelines("建立连接点完毕\n") if newplay.login(): newplay.mainprocess() else: c.send(str.encode("登录失败")) c.close() s = socket.socket() def startupserver(): #host = socket.gethostname() host = '10.186.46.50' port = 12344 s.bind((host,port)) s.listen(5) print("开始监听") f.writelines("开始监听\n") while True: c, addr = s.accept() print(addr,end=" connected!\n") try: _thread.start_new_thread(connectgame, (c,addr,)) except: c.send(str.encode("进入游戏失败。")) c.close() try: print("尝试建立服务器") f.writelines("尝试建立服务器\n") _thread.start_new_thread(startupserver, ()) except: print("服务器建立失败") f.writelines("服务器建立失败\n") while True: x = input() if x == "stop": s.close() Game.save() f.close() exit() if x == "save": Game.save()
2e2999ea776e5f8d449f697e4555d9415e5a2d99
arkssss/alien_invasion
/bullet.py
1,139
3.65625
4
import pygame from pygame.sprite import Sprite class Bullet(Sprite): def __init__(self, ai_setting, screen, ship): super().__init__() self.screen_rect = screen.get_rect() self.screen = screen # 创建一个新矩形 在0,0处 self.rect = pygame.Rect(0, 0, ai_setting.bullet_width, ai_setting.bullet_high) # 重新定位 self.rect.top = ship.rect.top self.rect.centerx = ship.rect.centerx # 设置背景颜色 self.color = ai_setting.bullet_color self.y = float(self.rect.y) self.bullet_speed = ai_setting.bullet_speed # 子弹数量 self.bullet_allow_number = ai_setting.bullet_allow_number def draw_bullet(self, bullets): """绘制子弹""" self.update(bullets) pygame.draw.rect(self.screen, self.color, self.rect) def update(self, bullets): """控制子弹向上移动,碰到顶端则移除""" self.y -= self.bullet_speed self.rect.top = self.y # 此时到达顶端,则移除子弹 if self.rect.top < 0: bullets.remove(self)
3683a953acb651128dd00cf7a90df96486c2a986
jakezachariahnixon/rosalind-py3
/REVC/main.py
270
3.5
4
# title: Complementing a Strand of DNA # id: REVC dataset = ['A','A','A','A','C','C','C','G','G','T'] comp = {'A':'T', 'T':'A', 'C':'G', 'G':'C'} def main(): for char in dataset: print(comp[char], end='') print() if __name__ == '__main__': main()
c5bd3fd0107db4a2c013626ad75718af8ae2ab34
tourloukisg/Streamlit_Prophet_TSeriesWebApp
/tseriesforecast_streamlit_webapp.py
5,923
3.640625
4
# STREAMLIT --- PYTHON --- MACHINE LEARNING --- Time Series Forecasting # In this example, the use of the FB Prophet model for time series forecasting # with respect to four stocks(Netflix, Amazon, Google & Microsoft ) is # demonstrated. In addition, there is use of the Streamlit open-source Python # library to create a web app where a)stock selection option is provided, # b)prediction horizon selection option is also provided, c)the stock open,high, # low, close, adj close & volume prices are included, d) basic descriptive # statistics are presented, e) a time series plot of the selected stock is # displayed, together with its histogram and KDE distribution plot, # f)the last 5 forecasted Adj Close values are displayed and g)the Adj Close # Time Series Forecast plot & plots of the forecast components are provided # To download the historical market data with python, there is use of the # Yahoo! finance market data downloader. # NOTE: # I) # Streamlit requires a filename with the suffix .py appended. If there is # use of a notebook(ipynb file), then it should be saved as 'filename.py' # II) # To run the Web App, a command similar to the one presented below can # be used (Command Prompt, Anaconda Prompt..) # streamlit run "C:\Users\username\Desktop\web_app\stock_forecast.py" # Importing the libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt import streamlit as st from datetime import date from fbprophet import Prophet from fbprophet.plot import plot_plotly import yfinance as yfin import warnings warnings.filterwarnings('ignore') # Creating the Web App Title st.title('Stock Time Series Forecasting - Web App') # User option to select the name of the stock for time series forecasting available_stocks=('NFLX','AMZN','GOOGL','MSFT') select_stock=st.selectbox('Select Stock for Time Series Forecasting', available_stocks) # Selection of the prediction horizon in years (1 to 5 years ahead) pred_hor=st.slider("Prediction Horizon Selection (Years Ahead):",1,5) # Selecting the dataset start and end date start_date='2011-01-01' end_date=date.today().strftime("%Y-%m-%d") # Function to download the selected stock dataset and save it to cache #(avoiding stock re-download) @st.cache def get_stock_data(stock): dataset=yfin.download(stock,start_date,end_date) dataset.reset_index(inplace=True) return dataset # Display message while downloading the selected stock dataset stock_dload=st.text('Downloading the selected Stock Dataset. . . . . .') stock_data=get_stock_data(select_stock) stock_dload.text('The Dataset has been downloaded !!!') # Observing the last 5 trading days st.subheader('{} Dataset - Last 5 Trading Days'.format(select_stock)) st.write(stock_data.tail()) # Observing basic statistical details of the stock st.subheader('{} Dataset - Descriptive Statistics'.format(select_stock)) st.write(stock_data.describe().transpose()) # Plotting the Ajd.Close time series of the selected stock st.subheader('{} Dataset - Time Series Plot'.format(select_stock)) def timeseriesplot(): fig=plt.figure(figsize=(10,6)) plt.plot(stock_data['Date'],stock_data['Adj Close'],c='magenta', linestyle='dashed',label='Trading Days') plt.xlabel('Date',fontweight='bold',fontsize=12) plt.ylabel('Adj Close',fontweight='bold',fontsize=12) st.pyplot(fig) timeseriesplot() # Selected stock: Ajd.Close Histogram and KDE plot st.subheader('{} Dataset - Stock Adj Close Histogram & KDE Plot'. format(select_stock)) def stockplots(): fig,axs=plt.subplots(1,2,figsize=(14,6)) stock_data['Adj Close'].plot(label='Adj Close Hist.', kind='hist',bins=10,ax=axs[0]) axs[0].set_ylabel('Frequency',fontweight='bold') stock_data['Adj Close'].plot(label='Adj Close Dist.',c='darkorange', kind='kde',ax=axs[1]) axs[1].set_ylabel('Density',fontweight='bold') for ax in axs.flat: plt.rcParams['font.size']=14 ax.set_xlabel('Adj Close',fontweight='bold') ax.legend() ax.figure.tight_layout(pad=2) st.pyplot(fig) stockplots() # New dataframe that contains only the Date and Adj Close columns # of the selected stock as this is the required 'Prophet' model format # with respect to model training df_prophet_train=stock_data[['Date','Adj Close']] df_prophet_train=df_prophet_train.rename(columns={"Date":"ds","Adj Close":"y"}) # Creating and fiting the 'Prophet' model to the training set # Interval Width -> Uncertainty interval width (95%) # changepoint_prior_scale -> The higher its value, the higher the value of # forecast uncertainty. model=Prophet(interval_width=0.95,changepoint_prior_scale=1) model.fit(df_prophet_train) # Adding the future Dates (1 year ~ 252 trading days) # Setting the frequency to Business day ('B') to avoid predictions on weekends future_dates=model.make_future_dataframe(periods=252*pred_hor,freq='B') # Forecasting the Adj Close price for the selected time period prophet_forecast=model.predict(future_dates) # Observing the last 5 forecasted Adj Close values st.subheader("{} Dataset - Last 5 'Prophet' model Predictions".format( select_stock)) st.write(prophet_forecast.tail()) # Adj Close Time Series Forecast plot & plots of the forecast components st.subheader("{} Dataset - Forecast plot (Years Ahead: {})".format(select_stock, pred_hor)) fig_forecast = plot_plotly(model, prophet_forecast) st.plotly_chart(fig_forecast) st.subheader("{} Dataset - Time Series Forecast Components".format( select_stock)) fig_comp = model.plot_components(prophet_forecast) st.write(fig_comp)
25fc000fae0441b45308ed3d314033beced52e88
Graey/pythoncharmers
/Genetic Algorithm/Population.py
4,620
3.59375
4
from Individual import Individual import random class Population: def __init__(self, id, size, lower_inps, upper_inps): # id : (int) population's id # size : (int) how many individual objects in this population # lower_inps : (list) list of lower-boundary inputs # upper_inps : (list) list of upper-boundary inputs self.id = id self.size = size self.lower_inps = lower_inps self.upper_inps = upper_inps self.generation = 0 self.Individuals = [] for i in range(self.size): inps = [] for lower_inp, upper_inp in zip(lower_inps, upper_inps): inps.append(round(random.uniform(lower_inp, upper_inp),5)) self.Individuals.append(Individual(inps)) return None def __str__(self): # Pretty print of Population object return 'Id: '+str(self.id)+'\nSize: '+str(self.size)+'\nGeneration: '+str(self.generation)+'\nFrom '+str(self.lower_inps)+' to '+str(self.upper_inps) def show_individuals(self): if self.size == 0: print('The population is totally annihilated', sep = '\n') else: print(*self.Individuals, sep = '\n') return None def show_top_one(self): if self.size == 0: print('The population is totally annihilated', sep = '\n') else: print('Top 1 '+str(self.Individuals[0])) return None def show_top(self, percentage = 10): if self.size == 0: print('The population is totally annihilated', sep = '\n') else: percentage = percentage/100 if int(len(self.Individuals)*percentage) >= 1: print(*self.Individuals[:int(len(self.Individuals)*percentage)], sep = '\n') else: self.show_individuals() return None def apply_func(self, func, paras): for indiv_obj in self.Individuals: if indiv_obj.val == None: indiv_obj.apply_func(func, paras) return None def apply_test(self, expected_val): for indiv_obj in self.Individuals: indiv_obj.test_score(expected_val) return None def sort_by_score(self): self.Individuals = sorted(self.Individuals, key = lambda Indiv: Indiv.score, reverse = True) return None def flatten_individual(self, indiv_obj): for i in range(len(indiv_obj.inps)): if indiv_obj.inps[i] < self.lower_inps[i]: indiv_obj.inps[i] = self.lower_inps[i] if indiv_obj.inps[i] > self.upper_inps[i]: indiv_obj.inps[i] = self.upper_inps[i] return indiv_obj def flatten(self): for indiv_obj in self.Individuals: indiv_obj = self.flatten_individual(indiv_obj) return None def event_kill_bot(self, percentage): # Annihilate Individuals objects that are in bottom self.sort_by_score() self.Individuals = self.Individuals[:int(len(self.Individuals)/100*(100-percentage))] self.size = len(self.Individuals) return None def event_balance(self): self.Individuals = random.sample(self.Individuals, int(len(self.Individuals)/2)) self.size = len(self.Individuals) return None def event(self, mode = 'natural_death'): if mode == 'natural_death': self.event_kill_bot(10) # Should kill 10% bot if mode == 'poverty': self.event_kill_bot(25) # Should kill 25% bot if mode == 'plague': self.event_kill_bot(50) # Should kill 50% bot if mode == 'war': self.event_kill_bot(75) # Should kill 75% bot if mode == 'nuclear_war': self.event_kill_bot(90) # Should kill 90% bot if mode == 'Thanos': self.event_balance() # Should kill 50% randomly return None def live_on(self, type = 'tiny'): if type == 'massive': for i in range(len(self.Individuals)-1): for ii in range(i+1, len(self.Individuals)): self.Individuals.append(Individual.breed(self.Individuals[i],self.Individuals[ii])) if type == 'tiny': for i in range(len(self.Individuals)-1): self.Individuals.append(Individual.breed(self.Individuals[i],self.Individuals[i+1])) for indiv_obj in self.Individuals: indiv_obj.evolve() self.flatten() self.generation = self.generation+1 self.size = len(self.Individuals) return None
9948289046b823a7888eea9afb42f43f2b2724ed
Graey/pythoncharmers
/hcfof2num.py
333
3.890625
4
#using loops # define a function def compute_hcf(x, y): # choose the smaller number if x > y: smaller = y else: smaller = x for i in range(1, smaller+1): if((x % i == 0) and (y % i == 0)): hcf = i return hcf num1 = 54 num2 = 24 print("The H.C.F. is", compute_hcf(num1, num2))
1a5aac856bd8a19833ccc0f21fb78c7646050d29
Graey/pythoncharmers
/koch curve.py
553
3.5
4
import turtle def snowflake(lengthSide, levels): if levels == 0: t.forward(lengthSide) return lengthSide /= 3.0 snowflake(lengthSide, levels - 1) t.left(60) snowflake(lengthSide, levels - 1) t.right(120) snowflake(lengthSide, levels - 1) t.left(60) snowflake(lengthSide, levels - 1) if __name__ == "__main__": t = turtle.Pen() t.speed(0) length = 300.0 t.penup() t.backward(length / 2.0) t.pendown() for i in range(3): snowflake(length, 4) t.right(120)
5df0cbe40e62d5efec6fb39ad48c2f90d5fd280b
Graey/pythoncharmers
/dijaktra.py
1,257
3.9375
4
import heapq def calculate_distances(graph, starting_vertex): distances = {vertex: float('infinity') for vertex in graph} distances[starting_vertex] = 0 pq = [(0, starting_vertex)] while len(pq) > 0: current_distance, current_vertex = heapq.heappop(pq) # Nodes can get added to the priority queue multiple times. We only # process a vertex the first time we remove it from the priority queue. if current_distance > distances[current_vertex]: continue for neighbor, weight in graph[current_vertex].items(): distance = current_distance + weight # Only consider this new path if it's better than any path we've # already found. if distance < distances[neighbor]: distances[neighbor] = distance heapq.heappush(pq, (distance, neighbor)) return distances example_graph = { 'U': {'V': 2, 'W': 5, 'X': 1}, 'V': {'U': 2, 'X': 2, 'W': 3}, 'W': {'V': 3, 'U': 5, 'X': 3, 'Y': 1, 'Z': 5}, 'X': {'U': 1, 'V': 2, 'W': 3, 'Y': 1}, 'Y': {'X': 1, 'W': 1, 'Z': 1}, 'Z': {'W': 5, 'Y': 1}, } print(calculate_distances(example_graph, 'X')) # => {'U': 1, 'W': 2, 'V': 2, 'Y': 1, 'X': 0, 'Z': 2}
a883747d2028159815103ad67d11f73a8a1fcda3
Graey/pythoncharmers
/calccompoundinterest.py
301
3.671875
4
# interest for given values. def compound_interest(principle, rate, time): # Calculates compound interest Amount = principle * (pow((1 + rate / 100), time)) CI = Amount - principle print("Compound interest is", CI) # Driver Code compound_interest(10000, 10.25, 5)
0e60cf785fa491656c8b87b5a42777db14048a4e
Graey/pythoncharmers
/palindromes.py
224
3.71875
4
def palindrome(s): s = s.replace(' ','') # This replaces all spaces ' ' with no space ''. (Fixes issues with strings that have spaces) return s == s[::-1] # Check through slicing palindrome('nurses run')
13b15323e2cca29ee326a58a7b7a74bf997f3ecd
Graey/pythoncharmers
/Die_Roller.py
322
4.1875
4
#Using Random Number Generator import random min_value = 1 max_value = 6 again = True while again: print(random.randint(min_value, max_value)) another_roll = input('Want to roll the dice again? ') if another_roll == 'yes' or another_roll == 'y': again = True else: again = False
0d885c684061825f0c657a9d4a98e416cfa41200
Graey/pythoncharmers
/complexconversion.py
761
4.03125
4
import math print("Enter your input format:") print("1. a+ib") print("2. r*e^(i*theta)") print("3. rCis(theta)") choice=int(input()) print("Enter number:") if choice==1: print("Enter a:") a=float(input()) print("Enter b:") b=float(input()) r=math.sqrt(a*a+b*b) theta=math.atan(b/a) elif choice==2: print("Enter r:") r=float(input()) print("Enter theta:") theta=float(input()) a=r*math.cos(theta) b=r*math.sin(theta) elif choice==3: print("Enter r:") r=float(input()) print("Enter theta:") theta=float(input()) a=r*math.cos(theta) b=r*math.sin(theta) else: print("wrong format!") print(a,"+i",b) print(r,"e^(i",theta,")") print(r,"Cis",theta)
ebd0bee6b3e9189c04add38a2d4290123d838f6c
Graey/pythoncharmers
/binarytree.py
440
4.09375
4
from binarytree import Node root = Node(3) root.left = Node(6) root.right = Node(8) # Getting binary tree print('Binary tree:', root) #Getting list of nodes print('List of nodes:', list(root)) #Getting inorder of nodes print('Inorder of nodes:', root.inorder) #checking tree properties print('Size of tree:', root.size) print('Height of tree:', root.height) #Get all properties at once print('Properties of tree: \n', root.properties)
fab253da275ab591be5002f7e17ea826a4c4cd43
Graey/pythoncharmers
/electricalf.py
323
4.03125
4
# calculate gravitational force import math print("enter the charge of the first body in C") q1=float(input()) print("enter the charge of the second body in C") q2=float(input()) print("enter the distance between them in m") d=float(input()) force=(9*math.pow(10,9)*q1*q2/(d*d)) print("Force=",force,"N")
cf94c48b12db2f1bc4ee69a8a82b85de13dc2149
Graey/pythoncharmers
/stack.py
698
3.875
4
s=[] ch='y' while (ch=='y'): print("1.Push") print("2.Pop") print("3.Display") choice=int(input("Enter your choice:")) if (choice==1): a=input("Enter any number:") b=input("name") c=(a,b) s.append(c) elif (choice==2): if (s==[]): print("Empty stack") else : print("Deleted item is:",s.pop()) elif choice==3: if s==[]: print("Nothing to display.") else: l=len(s) for i in range(l-1,-1,-1): print(s[i]) else: print("wrong entry.") ch=input("Do you want to continue or not(y or n):")
6fc58e11d2549dc50f66e4b2107424a40071a32e
Graey/pythoncharmers
/arrayrotation.py
532
4.125
4
#Function to left rotate arr[] of size n by d*/ def leftRotate(arr, d, n): for i in range(d): leftRotatebyOne(arr, n) #Function to left Rotate arr[] of size n by 1*/ def leftRotatebyOne(arr, n): temp = arr[0] for i in range(n-1): arr[i] = arr[i+1] arr[n-1] = temp # utility function to print an array */ def printArray(arr,size): for i in range(size): print ("%d"% arr[i],end=" ") # Driver program to test above functions */ arr = [1, 2, 3, 4, 5, 6, 7] leftRotate(arr, 2, 7) printArray(arr, 7)
54fe3a05f78b6724e0167776103d1d58bcc46d4c
lizalexandrita/kyd-scraper
/test_scrap.py
6,316
3.5
4
import unittest import scraps class TestScrap(unittest.TestCase): def test_Scrap(self): """it should create and instanciate a Scrap class""" class MyScrap(scraps.Scrap): a1 = scraps.Attribute() myScrap = MyScrap() self.assertEquals(myScrap.a1, None) myScrap.a1 = 1 self.assertEquals(myScrap.a1, 1) del(myScrap.a1) self.assertEquals(myScrap.a1, None) def test_Scrap_instanciation(self): """it should instanciate a Scrap passing parameter.""" import inspect class MyScrap(scraps.Scrap): title = scraps.Attribute() myScrap = MyScrap(title='Normstron') self.assertEquals(myScrap.title, 'Normstron') def test_Scrap_instanciation2(self): """it should instanciate a Scrap passing an invalid parameter.""" import inspect class MyScrap(scraps.Scrap): title = scraps.Attribute() with self.assertRaises(Exception): myScrap = MyScrap(title1='Normstron') def test_Scrap_errorisnone(self): """it should instanciate a Scrap passing an invalid parameter.""" import inspect class MyScrap(scraps.Scrap): float_attr = scraps.FloatAttr() error_is_none = True myScrap = MyScrap(float_attr='--') class MyScrap(scraps.Scrap): float_attr = scraps.FloatAttr() with self.assertRaises(Exception): myScrap = MyScrap(float_attr='--') class TestAttribute(unittest.TestCase): def test_Attribute(self): """ it should instanciate an Attribute class and its descriptor methods """ a = scraps.Attribute() self.assertEquals(a.__get__(None, None), None) a.__set__(None, 1) self.assertEquals(a.__get__(None, None), 1) a.__delete__(None) self.assertEquals(a.__get__(None, None), None) def test_Attribute_repeat(self): """it should instanciate a repeated Attribute""" a = scraps.Attribute(repeat=True) a.__set__(None, 1) a.__set__(None, 2) self.assertEquals(a.__get__(None, None), [1,2]) def test_Attribute_transform(self): """ it should instanciate an Attribute that should be transformed by some function while is set """ a = scraps.Attribute(transform=lambda x: x*100) a.__set__(None, 1) self.assertEquals(a.__get__(None, None), 100) class TestFloatAttr(unittest.TestCase): def test_FloatAttr(self): """it should instanciate the FloatAttr class and set it with a valid string.""" a = scraps.FloatAttr() a.__set__(None, '2.2') self.assertAlmostEqual(a.__get__(None, None), 2.2) def test_FloatAttr_int(self): """it should instanciate the FloatAttr class and set it with an int.""" a = scraps.FloatAttr() a.__set__(None, 2) self.assertAlmostEqual(a.__get__(None, None), 2.0) def test_FloatAttr_float(self): """it should instanciate the FloatAttr class and set it with a float.""" a = scraps.FloatAttr() a.__set__(None, 2.2) self.assertAlmostEqual(a.__get__(None, None), 2.2) def test_FloatAttr_decimal(self): """it should instanciate the FloatAttr class and set it with a decimal.""" from decimal import Decimal a = scraps.FloatAttr() a.__set__(None, Decimal(2.2)) self.assertAlmostEqual(a.__get__(None, None), 2.2) def test_FloatAttr_comma(self): """ it should instanciate the FloatAttr class and set it with a string which represents a float but uses comma as decimal separator.""" a = scraps.FloatAttr(decimalsep=',') a.__set__(None, '2,2') self.assertAlmostEqual(a.__get__(None, None), 2.2) def test_FloatAttr_percentage(self): """ it should instanciate the FloatAttr class and set it with a string which represents a percentage, ie, a float followed by the symbol '%'.""" a = scraps.FloatAttr(percentage=True) a.__set__(None, '22 %') self.assertAlmostEqual(a.__get__(None, None), 22./100) def test_FloatAttr_percentage_comma(self): """ it should instanciate the FloatAttr class and set it with a string which represents a percentage and uses comma as decimal separator.""" a = scraps.FloatAttr(decimalsep=',', percentage=True) a.__set__(None, '22,5 %') self.assertAlmostEqual(a.__get__(None, None), 22.5/100) def test_FloatAttr_thousand(self): """ it should instanciate the FloatAttr class and set it with a string which represents a float with thousand separators.""" a = scraps.FloatAttr(thousandsep=',') a.__set__(None, '2,222.22') self.assertAlmostEqual(a.__get__(None, None), 2222.22) a = scraps.FloatAttr(thousandsep='.', decimalsep=',') a.__set__(None, '2.222,22') self.assertAlmostEqual(a.__get__(None, None), 2222.22) def test_FloatAttr_repeat(self): """ it should instanciate the FloatAttr class and set the repeat parameter from Attribute.""" a = scraps.FloatAttr(repeat=True) a.__set__(None, '22.5') a.__set__(None, '22.5') self.assertEquals(a.__get__(None, None), [22.5, 22.5]) def test_FloatAttr_error(self): """ it should instanciate the FloatAttr class with an invalid string.""" a = scraps.FloatAttr() with self.assertRaises(Exception): a.__set__(None, '--') class TestDatetimeAttr(unittest.TestCase): def test_DatetimeAttr(self): """ it should instanciate the DatetimeAttr class and set it with a valid string.""" from datetime import datetime a = scraps.DatetimeAttr(formatstr='%Y-%m-%d') a.__set__(None, '2013-01-01') self.assertEquals(a.__get__(None, None), datetime(2013,1,1)) def test_DatetimeAttr_locale(self): """ it should instanciate the DatetimeAttr class and set it with a valid string and locale.""" from datetime import datetime a = scraps.DatetimeAttr(formatstr='%d/%b/%Y', locale='pt_BR') a.__set__(None, '11/Dez/2013') self.assertEquals(a.__get__(None, None), datetime(2013,12,11)) # Check if locale have been restored a = scraps.DatetimeAttr(formatstr='%d/%b/%Y') a.__set__(None, '11/Dec/2013') self.assertEquals(a.__get__(None, None), datetime(2013,12,11)) class TestFetcher(unittest.TestCase): def test_Fetcher(self): """ it should create a Fetcher.""" class MyFetcher(scraps.Fetcher): name = 'test' url = 'http://httpbin.org/html' def parse(self, content): from bs4 import BeautifulSoup soup = BeautifulSoup(content) class MockScrap(object): title = soup.html.body.h1.string return MockScrap() fetcher = MyFetcher() ret = fetcher.fetch() self.assertEquals(ret.title, 'Herman Melville - Moby-Dick') if __name__ == '__main__': unittest.main(verbosity=1)
e80a517f6eda1a019bf898bfa0d1721187563e6c
chrislucas/hackerrank-10-days-of-statistics
/python/BinomialDistribuitionII/solution/BinomialDistribution.py
1,224
3.625
4
''' https://www.hackerrank.com/challenges/s10-binomial-distribution-2/problem DONE ''' def fast_exp(b, e): if e == 0: return 1 elif e == 1: return b elif e < 0: b, e = 1 / b, -e acc = 1 while e > 0: if e & 1 == 1: acc *= b b *= b e >>= 1 return acc def fast_ncr(n, r): if r > n - r: r = n - r acc = 1 for i in range(0, r): acc *= (n - i) acc //= (i + 1) return acc def run(): prob_fail, q_production = tuple(map(int, input().split(" "))) p = prob_fail / 100 ''' b(x, n, p) x = numero de sucessos esperados apos N tentativas n = numero de tentativas p = probabilidade de sucesso em cada tentativa individual ''' # probabilidade de nao mais do que 2 pecas falharem prob_1 = 0 for i in range(0, 3): prob_1 += fast_ncr(q_production, i) * fast_exp(p, i) * fast_exp(1 - p, q_production - i) prob_2 = 0 for i in range(2, q_production+1): prob_2 += fast_ncr(q_production, i) * fast_exp(p, i) * fast_exp(1 - p, q_production - i) print("%.3f\n%.3f" % (prob_1, prob_2)) run() if __name__ == '__main__': pass
f69dafe7e3cd2bba8f46924f56fc36ccaeb49bb1
chrislucas/hackerrank-10-days-of-statistics
/python/PoissonDistribuition/solution/PoissonDistribII.py
536
4
4
''' https://www.hackerrank.com/challenges/s10-poisson-distribution-2/problem ''' from math import e as E def factorial(n): acc = 1 for i in range(n, 1, -1): acc *= i return acc def poisson_distribution(success, avg): return ((avg ** success) * (E ** (-avg))) / factorial(success) ''' a = 0.88 b = 1.55 ''' def run(): a, b = map(float, input().split(" ")) ca = 160 + 40 * (a + a * a) cb = 128 + 40 * (b + b * b) print("%.3f\n%.3f" % (ca, cb)) run() if __name__ == '__main__': pass
da9fb9e3090ffcffb8c94215776fad7a2749b80f
chrislucas/hackerrank-10-days-of-statistics
/python/BinomialDistribuitionI/solution/OKNCR.py
579
3.640625
4
''' https://www.geeksforgeeks.org/space-and-time-efficient-binomial-coefficient/ ''' ''' C(n, k) = n! / (n-k)! * k! ou C(M, k) = n * ... (n-k+1) / (k * k-1 * k-2 ... * 1) ou C(n, k) = C(n, n-k) = (n * n-1 ... * n-k+1) / (k * k-1 * ... * 1) ''' def ok_ncr(n, k): if k > n - k: k = n - k res = 1 for i in range(0, k): res *= (n - i) # (n * n-1 ... * n-k+1) res //= (i + 1) # dividir de (1 ... k) return res def run(): n, k = tuple(map(int, input().split())) print(ok_ncr(n, k)) run() if __name__ == '__main__': pass
19152fb52ea0155fa395061589dfb6cdb03c1f00
chrislucas/hackerrank-10-days-of-statistics
/python/Quartiles/sol/Quartiles.py
1,505
3.796875
4
''' https://www.hackerrank.com/challenges/s10-quartiles/problem https://en.wikipedia.org/wiki/Quartile https://en.wikipedia.org/wiki/Quantile DONE ''' def calc_q1(n, nums): half = (n // 2) if n > 4: # se ao cortar o array na metade temos 2 metades impares if (half & 1) == 1: # dividimos novamente ao meio t = nums[half//2] q1 = t # senao, pegamos o elemento na posicao de 1/4 do array e o elemento a sua direita else: t = nums[half//2-1] + nums[half//2] q1 = t // 2 else: # se o array tiver 2 elementos pegamos os 2 elementos mesmo q1 = (nums[0] + nums[1]) // 2 return q1 def calc_q3(n, nums): half = (n // 2) if n > 4: m = (n-half)//2+half if (half & 1) == 1: t = nums[m] q3 = t else: if (n & 1) == 0: m -= 1 t = nums[m] + nums[m+1] q3 = t // 2 else: q3 = (nums[0] + nums[1]) // 2 return q3 def run(): n = int(input()) nums = sorted(list(map(int, input().split()))) q1 = calc_q1(n, nums) q2 = nums[n // 2] if (n & 1) == 1 else (nums[n//2] + nums[n//2-1]) // 2 q3 = calc_q3(n, nums) return "%d\n%d\n%d" % (q1, q2, q3) ''' 9 3 7 8 5 12 14 21 13 18 11 6 7 15 36 39 40 41 42 43 47 49 6 7 15 36 39 40 41 10 3 7 8 5 12 14 21 15 18 14 12 4 17 7 14 18 12 3 16 10 4 4 12 ''' print(run()) if __name__ == '__main__': pass
85e741e34dcd26f4bffea551cbf9d6cc74fba3ce
alok-chandra/Python
/Proj013_Except.py
329
3.84375
4
while True: try: iData = int(input("Enter the number Buddy:\n")) print(100/iData) break except ValueError: print("Enter proper data \n") except ZeroDivisionError: print("Don't enter 0\n") except : print("Ufff") break finally: print("Bye Bye\n")
fbc7c914d0a9dc983e82f2bb3f604cbc5c794b0f
DanielJWagener/automate-the-boring-stuff-with-python
/regex/phoneNumbers.py
258
3.796875
4
import re message = "Call me 123-123-1234 because that's totes a real phone number. Otherwise, 432-432-4321" phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') mo = phoneNumRegex.search(message) print(mo.group()) print(phoneNumRegex.findall(message))
6b8ecdfb0306cf32d25814cbdba7d06de21a1af9
PalRob/rdp
/int/dp_348_int.py
2,536
3.9375
4
def pins_knocked_in_frame(frame): """Get number of knocked pins in given frame Args: frame(str): string containing information about throws in the frame formatted by "bowling rules" Returns: pins_knocked(int): number of knocked pins in given frame """ pins_knocked = 0 for i, throw in enumerate(frame): if throw.isnumeric(): pins_knocked += int(throw) elif throw == "X": pins_knocked += 10 elif throw == "-": pins_knocked += 0 elif throw == r"/": pins_knocked += 10 - pins_knocked_in_frame(frame[i-1]) return pins_knocked def get_score_table(throws): """Creates a string formatted by "bowling rules" from given string. Args: throws(str): string conteining number of knocked pins in every throw Retuns: formatted_table(str): string formatted by "bowling rules". Every frame is 3 characters long (including spaces). """ table = [] frame = "" frame_num = 1 throws = [int(x) for x in throws.split()] for throw in throws: if throw == 10: if frame_num != 10: frame = "X" table.append(frame) frame = "" frame_num += 1 else: frame += "X" else: if throw == 0: frame += "-" elif pins_knocked_in_frame(frame) + throw == 10: frame += r'/' else: frame += str(throw) if frame_num != 10 and len(frame) == 2: table.append(frame) frame = "" frame_num += 1 else: # here throws from the last frame added to the table # this will always be executed since "for" loop # has no "break" statement table.append(frame) # with str.ljust(3) all scores will be nicely aligned formatted_table = "".join([x.ljust(3) for x in table]) return formatted_table if __name__ == "__main__": bowling_games = """6 4 5 3 10 10 8 1 8 0 10 6 3 7 3 5 3 9 0 9 0 9 0 9 0 9 0 9 0 9 0 9 0 9 0 9 0 10 10 10 10 10 10 10 10 10 10 10 10 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 10 3 7 6 1 10 10 10 2 8 9 0 7 3 10 10 10 9 0 3 7 6 1 3 7 8 1 5 5 0 10 8 0 7 3 8 2 8""" bowling_games = bowling_games.split("\n") for game in bowling_games: print(get_score_table(game))
480d5d5cc49249179f48f1f81faa59a2cc36fffb
PalRob/rdp
/easy/dp_344_easy.py
1,011
4.0625
4
def have_odd_zeros(num): """ Returns True if binary representation of a num contains block of consecutive 0s of odd length. False otherwise.""" # [2:] to slice out starting 0b from a binary number bin_num = bin(num)[2:] odd_zeros = False num_of_zeros = 0 for i in bin_num: if i == '0': num_of_zeros += 1 elif i == '1': if num_of_zeros % 2 != 0: odd_zeros = True break else: num_of_zeros = 0 else: if num_of_zeros % 2 != 0: odd_zeros = True return odd_zeros def get_baum_sweet_sequence(num): """Generates Baum-Sweet sequence from 0 to num. Returns list of integer 0s and 1s with len(num).""" baum_sweet_sequence = [] for i in range(num): if have_odd_zeros(i): baum_sweet_sequence.append(1) else: baum_sweet_sequence.append(0) return baum_sweet_sequence print(get_baum_sweet_sequence(20))
7f4e9bac7c1223c0baa8d90cf603dec2d6b11446
IsraMejia/CodeInterview
/1_TwoSum_Microsoft/Python/two_sum.py
821
3.875
4
"""Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order. Input: nums = [2,7,11,15], target = 9 Output: [0,1] Output: Because nums[0] + nums[1] == 9, we return [0, 1].""" class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: indices = [] #(nums[i] + nums[j] == target) and for i in range(len(nums)): for j in range(len(nums)): if( (nums[i] + nums[j] == target) and (i!=j) ): indices.append(i) indices.append(j) return indices
6ffcbf8b2dfd97191c106928be8b77a75655fbd2
Asmitadhikari/python_project
/Remove_user_input.py
180
3.921875
4
a = [1, 2, 4, 5, 6, 1, 3, 1, 8, 10, 1] num = int(input("Enter a number you want to remove from list:")) print(a) for i in a: if num == i: a.remove(num) print(a)
4c4aadd140193a4507ba1c4f5f6dc0635ce4b546
ektogamut/battleship
/battleship_scratch.py
3,566
4.21875
4
from random import randint from random import choice # This function adds individual dictionaries to a specified square board (edge by edge). Cannot use the * function # as with the original example because calling to one member of a list alters everything in that lists row. def place_board(edge): board = [] for i in range(0, edge): board.append([{'hit': False}]) for j in range(0, edge - 1): board[i].append({'hit': False}) return board board = place_board(6) # # print 'Let's play Battleship!' # print_board(board) patrol = {'name': 'Patrol', 'origin': [], 'length': 2, 'vertical': False, } destroyer = {'name': 'Destroyer', 'origin': [], 'length': 3, 'vertical': False, } battleship = {'name': 'Battleship', 'origin': [], 'length': 4, 'vertical': False, } ships = [patrol, destroyer, battleship] def random_row(board, ship): length = ship['length'] board_row_length = len(board) if ship['vertical']: return randint(0, board_row_length - length) else: return randint(0, board_row_length - 1) def random_col(board, ship): length = ship['length'] board_col_length = len(board[0]) if ship['vertical']: return randint(0, board_col_length - 1) else: return randint(0, board_col_length - length) def seed_ship(ship): ship['vertical'] = choice([True, False]) ship['origin'] = [random_row(board, ship), random_col(board, ship)] def ship_collide(ship): origin_row = ship['origin'][0] origin_col = ship['origin'][1] length = ship['length'] if ship['vertical']: for position in range(0, length): inc_row = origin_row + position if 'ship' in board[inc_row][origin_col] and board[inc_row][origin_col]['ship'] != ship['name']: return True else: return False else: for position in range(0, length): inc_col = origin_col + position if 'ship' in board[origin_row][inc_col] and board[origin_row][inc_col]['ship'] != ship['name']: return True else: return False def generate_ship(ship): origin_row = ship['origin'][0] origin_col = ship['origin'][1] length = ship['length'] if ship['vertical']: for position in range(0, length): inc_row = origin_row + position board[inc_row][origin_col]['ship'] = ship['name'] else: for position in range(0, length): inc_col = origin_col + position board[origin_row][inc_col]['ship'] = ship['name'] def place_ship(ship): seed_ship(ship) while ship_collide(ship) is True: seed_ship(ship) else: generate_ship(ship) place_ship(battleship) place_ship(destroyer) place_ship(patrol) print "battleship info: ", battleship print "destroyer info: ", destroyer print ship_collide(destroyer) def print_board(board): board_output = [] for i in range(0, len(board)): board_output.append([" "]) for j in range(0, len(board[0])): board_output[i].append(" ") if 'ship' in board[i][j]: # print i, j, board[i][j]['ship'] board_output[i][j] = board[i][j]['ship'][0] elif board[i][j]['hit'] == False: board_output[i][j] = "X" for row in board_output: print " ".join(row) print_board(board) #
7b7327d61d90ab6266a8db9d4a45c82e81c1b432
qiushenjie/myLeetcode
/29_两数相除.py
1,304
3.78125
4
# 给定两个整数,被除数 dividend 和除数 divisor。将两数相除,要求不使用乘法、除法和 mod 运算符。 # 返回被除数 dividend 除以除数 divisor 得到的商。 # 示例 1: # 输入: dividend = 10, divisor = 3 # 输出: 3 # 示例 2: # 输入: dividend = 7, divisor = -3 # 输出: -2 # 说明: # 被除数和除数均为 32 位有符号整数。 # 除数不为 0。 # 假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−2^31, 2^31 − 1]。本题中,如果除法结果溢出,则返回 231 − 1。 class Solution: #二倍累加的方法 def divide(self, dividend, divisor): if (dividend >= 0 and divisor >= 0) or (dividend < 0 and divisor < 0): sig = 1 else : sig = -1 dividend = left = abs(dividend) divisor = div = abs(divisor) Q = 1 res = 0 while left >= divisor: left -= div #此时总有left >= div res += Q Q += Q div += div if left < div: div = divisor # 重置 Q = 1 # 累加值Q重置 if sig == 1: return min(res, 2147483647) else: return max(-res, -2147483648) a = Solution() print(a.divide(7, -3))
52a6f941a820f1050f183831550010d6734d51d5
qiushenjie/myLeetcode
/62_不同路径.py
1,696
3.515625
4
# 一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为“Start” )。 # 机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。 # 问总共有多少条不同的路径? # 输入: m = 3, n = 2 # 输出: 3 # 解释: # 从左上角开始,总共有 3 条路径可以到达右下角。 # 1. 向右 -> 向右 -> 向下 # 2. 向右 -> 向下 -> 向右 # 3. 向下 -> 向右 -> 向右 class Solution: def uniquePaths(self, m, n): grid = [[0] * n for i in range(m)] for row in range(m): #第一列上每个位置的路径走法只有一种 grid[row][0] = 1 for col in range(n): #第一行上每个位置的路径走法只有一种 grid[0][col] = 1 for i in range(1, m): for j in range(1, n): grid[i][j] = grid[i - 1][j] + grid[i][j - 1] #之后每一个的走法为当前位置上边一个和左边一个的走法的总和 return grid[-1][-1] #超出时间限制 def uniquePaths1(self, m, n): count = [] def lu(currm, currn, stack): if currm == m - 1 and currn == n - 1: count.append(stack) return elif currm == m - 1 and currn != n - 1: lu(currm, currn + 1, stack + 'd') elif currm != m - 1 and currn == n - 1: lu(currm + 1, currn, stack + 'r') else: lu(currm, currn + 1, stack + 'd') lu(currm + 1, currn, stack + 'r') lu(0, 0, '') return len(count) a = Solution().uniquePaths(23, 12) print(a)
e555401276ae7e25dd052dc6a686a4d4555648d0
qiushenjie/myLeetcode
/26_删除排序数组中的重复项.py
1,776
3.75
4
# 给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。 # 不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。 # 示例 1: # 给定数组 nums = [1,1,2], # 函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。 # 你不需要考虑数组中超出新长度后面的元素。 # 示例 2: # 给定 nums = [0,0,1,1,1,2,2,3,3,4], # 函数应该返回新的长度 5, 并且原数组 nums 的前五个元素被修改为 0, 1, 2, 3, 4。 # 你不需要考虑数组中超出新长度后面的元素。 # 说明: # 为什么返回数值是整数,但输出的答案是数组呢? # 请注意,输入数组是以“引用”方式传递的,这意味着在函数里修改输入数组对于调用者是可见的。 # 你可以想象内部操作如下: # // nums 是以“引用”方式传递的。也就是说,不对实参做任何拷贝 # int len = removeDuplicates(nums); # // 在函数里修改输入数组对于调用者是可见的。 # // 根据你的函数返回的长度, 它会打印出数组中该长度范围内的所有元素。 # for (int i = 0; i < len; i++) { # print(nums[i]); # } class Solution: def removeDuplicates(self, nums): if not nums: return 0 #nums = sorted(nums) stop = 0 for i in range(1, len(nums)): #没重复的替掉重复的 if nums[i] != nums[stop] and i > stop: # if nums[i] not in nums[0: stop + 1] and i >stop: stop += 1 nums[stop] = nums[i] else:continue return stop + 1
2e01179c5f5d1a7c1f80fbd9030bcbf430b2728c
qiushenjie/myLeetcode
/55_跳跃游戏.py
1,283
3.703125
4
# 给定一个非负整数数组,你最初位于数组的第一个位置。 # 数组中的每个元素代表你在该位置可以跳跃的最大长度。 # 判断你是否能够到达最后一个位置。 # 示例 1: # 输入: [2,3,1,1,4] # 输出: true # 解释: 从位置 0 到 1 跳 1 步, 然后跳 3 步到达最后一个位置。 # 示例 2: # 输入: [3,2,1,0,4] # 输出: false # 解释: 无论怎样,你总会到达索引为 3 的位置。但该位置的最大跳跃长度是 0 , 所以你永远不可能到达最后一个位置 #贪心算法 class Solution: def canJump(self, nums): n = len(nums) if n <= 1: return True farthest = 0 #当前位置能跳的最远的位置 i = 0 for i in range(n): if i > farthest: return False #说明上一个能跳最远的距离跳不到i这个位置 ''' 这时候已经满足i<=farthest,即上一次的最大跳跃距离已经能到达或者 超过i这个位置,此时比较当前i位置基础上能跳到的最远距离即i+nums[i] 和原始的能跳的最远距离,作为当前能跳跃的最远距离 ''' farthest = max(farthest, i + nums[i]) return True
225f71f198f337eb1468c9525a579ee6e8364888
qiushenjie/myLeetcode
/96_不同的二叉搜索树.py
2,069
3.578125
4
# 给定一个整数 n,求以 1 ... n 为节点组成的二叉搜索树有多少种? # 示例: # 输入: 3 # 输出: 5 # 解释: # 给定 n = 3, 一共有 5 种不同结构的二叉搜索树: # 1 3 3 2 1 # \ / / / \ \ # 3 2 1 1 3 2 # / / \ \ # 2 1 2 3 ''' 解题思路: 这道题实际上是 Catalan Number卡塔兰数的一个例子,如果对卡塔兰数不熟悉的童鞋可能真不太好做。先来看当 n = 1的情况,只能形成唯一的一棵二叉搜索树,n分别为1,2,3的情况如下所示: 1 n = 1 2 1 n = 2 / \ 1 2 1 3 3 2 1 n = 3 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3 就跟斐波那契数列一样,我们把n = 0 时赋为1,因为空树也算一种二叉搜索树,那么n = 1时的情况可以看做是其左子树个数乘以右子树的个数,左右字数都是空树,所以1乘1还是1。那么n = 2时,由于1和2都可以为跟,分别算出来,再把它们加起来即可。n = 2的情况可由下面式子算出: dp[2] = dp[0] * dp[1]   (1为根的情况)     + dp[1] * dp[0]   (2为根的情况) 同理可写出 n = 3 的计算方法: dp[3] = dp[0] * dp[2]   (1为根的情况)     + dp[1] * dp[1]   (2为根的情况)     + dp[2] * dp[0]   (3为根的情况) ''' class Solution: def numTrees(self, n): if n == 1: return 1 dp = [0] * (n + 1) dp[0], dp[1] = 1, 1 for i in range(2, n + 1): nTrees = 0 for j in range(i): nTrees += dp[j] * dp[i - 1 - j] dp[i] = nTrees return dp[n] aa = Solution().numTrees(3) print(aa)
f99d1cf51c8505b82e17d11709a82f40fb1ab6a4
qiushenjie/myLeetcode
/2_两数相加.py
1,690
3.953125
4
# 给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。 # 你可以假设除了数字 0 之外,这两个数字都不会以零开头。 # 示例: # 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) # 输出:7 -> 0 -> 8 # 原因:342 + 465 = 807 # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None #链表具有递归性,所以每个链表节点是一个类,类里包含.val和.next,其中.next指向下一个节点,下一个节点作为类同样包含.val和.next,以此类推。。。 class Solution: def addTwoNumbers(self, l1, l2): #定义一个链表,表头值为零 l3 = ListNode(0) #将l3赋值给dummy,并将dummy.next作为返回值 dummy = l3 #进位数,每10进一,初始为0 add = 0 #满足其中一个条件即运行,l1的当前节点存在;l2的当前节点存在;存在进位 while (l1 !=None or l2 !=None or add != 0): if (l1 == None): l1 = ListNode(0) if (l2 == None): l2 = ListNode(0) current = l1.val + l2.val + add l1 = l1.next l2 = l2.next add = 0 #判断是否进位 if current >= 10: add = 1 current = current % 10 #为下个节点添加新节点 l3.next = ListNode(current) l3 = l3.next #最后返回虚拟节点的下一个节点开始的链表 return dummy.next
62ed5fcef461fc03b01b99815c7e5787ab271fc2
qiushenjie/myLeetcode
/1_两数之和.py
649
3.6875
4
''' 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。 示例: 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1] ''' class Solution: def twoSum(self, nums, target): dic = {} for i in range(len(nums)): el1 = nums[i] if (el1 in dic): return [dic[el1], i] else: dic[target - el1] = i a = Solution() aaa = a.twoSum([-2, -2, -2, 0, 1, 2, 2, 2, 3, 3, 4, 4, 6, 6],0) print(aaa)
ea1dfb54388799367e88108cb50c74f800ff5589
qiushenjie/myLeetcode
/38_报数.py
950
3.625
4
# 报数序列是指一个整照其中的整数的顺序进数序列,按行报数,得到下一个数。其前五项如下: # 1. 1 # 2. 11 # 3. 21 # 4. 1211 # 5. 111221 # 1 被读作 "one 1" ("一个一") , 即 11。 # 11 被读作 "two 1s" ("两个一"), 即 21。 # 21 被读作 "one 2", "one 1" ("一个二" , "一个一") , 即 1211。 # 给定一个正整数 n(1 ≤ n ≤ 30),输出报数序列的第 n 项。 # 注意:整数顺序将表示为一个字符串。 class Solution: def countAndSay(self, n): res = '1' for i in range(n - 1): temp = '' curr = res[0] count = 0 for ele in res: if ele == curr: count += 1 else: temp += str(count) + curr curr = ele count = 1 temp += str(count) + curr #针对上面两行代码的对应结果 res = temp return res