text
stringlengths
37
1.41M
word=input("Enter a world: ") word=word.lower() vowel_count=0 consonant_count=0 vowels="aeiou" for letter in range(len(word)): if (vowels.find(word[letter]) != -1): vowel_count+=1 else: consonant_count+=1 print(word, "has", vowel_count, "vowels and", consonant_count, "consonants.")
nums=[1,3,5,7,9,10] def multiply(nums): for a in nums: print(a*5) multiply(nums)
# class MyClass: # x=5 # y=10; # z=20; # a=30; # print(MyClass) # # myObj = MyClass() # # print(myObj.z) class Person : def __init__(self,fname,lname): self.fname = fname self.lname = lname def fullName(self): print(self.fname +" "+self.lname) person2 = Person("Murali","Krishna") # print(person2.fname) person2.fullName()
x = 1 y = 2.8 # z = x//y x =5 ; x **= 4 print(x) # a = 27 # b = a % 4 # print(b) # x = x+y # x+=y # x = x - y # x-=y # ** Exponentation # // Floor Division # print(z) # print(x) # print(type(y)) # print(type(x))
########################################################################################################################################################### #-PROGRAM 1 numbers = [386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345, 399, 162, 758, 219, 918, 237, 412, 566, 826, 248, 866, 950, 626, 949, 687, 217, 815, 67, 104, 58, 512, 24, 892, 894, 767, 553, 81, 379, 843, 831, 445, 742, 717, 958,743, 527] for i in numbers: if(i==237): break elif(i%2==0): print(i) ############################################################################################################################################################ #PROGRAM 2 color_list_1 = set(["White", "Black", "Red"]) color_list_2 = set(["Red", "Green"]) final_list = color_list_1 - color_list_2 print(final_list) ############################################################################################################################################################ #PROGRAM 3 alphabet = "abcdefghijklmnopqrstuvwxyz" sentence = input("Write your setence : " ) flag = 0 for char in alphabet: if char in sentence.lower(): flag = 0 else: flag = -1 if(flag==0): print("Given sentence is a Pangram ") elif(flag==-1): print("Given sentence is Not a Pangram ") ############################################################################################################################################################## #PROGRAM 4 n = int(input("Enter yor given number :")) answer = (n + ((n*10)+n) + (n*100)+((n*10)+n)) print(answer) ############################################################################################################################################################## #PROGRAM 5 input_list = input("Enter your input : " ) result = [] result = input_list.split("#") list1 = [] list2 = [] for i in list(result[0].split()): list1.append(int(i)) print(list1) for i in list(result[1].split()): list2.append(int(i)) print(list2) ################################################################################################################################################################# #PROGRAM 6 output = [] s = input("Enter your Sequence : ") output = s.split(",") print("," .join(sorted(output))) ################################################################################################################################################################## ###PROGRAM 7 d = {'Student': ['Rahul', 'Kishore', 'Vidhya', 'Raakhi'],'Marks': [57,87,67,79]} index = 0 for i in d['Marks']: if(i==max(d['Marks'])): break elif(i!=max(d['Marks'])): index+=1 print(d['Student'][index]) ################################################################################################################################################################### ##PROGRAM 8 s = input("Input a string : ") digit,letter = 0,0 for c in s: if c.isdigit(): digit=digit+1 elif c.isalpha(): letter=letter+1 else: pass print("Letters", letter) print("Digits", digit) ################################################################################################################################################################### #PROGRAM 9 d = {'Name': ['Akash', 'Soniya', 'Vishakha' , 'Akshay', 'Rahul', 'Vikas'],'Subject': ['Python', 'Java', 'Python', 'C', 'Python', 'Java'],'Ratings': [8.4, 7.8, 8, 9, 8.2, 5.6]} n = input("Enter your subject : ") d1 =[] newdata= {} for i in range(len(d['Subject'])): if(d['Subject'][i]==n): d1.append(i) newdata['Name'] = [] newdata['Subject'] = [] newdata['Ratings'] = [] for i in d1: newdata['Name'].append(d['Name'][i]) newdata['Subject'].append(d['Subject'][i]) newdata['Ratings'].append(d['Ratings'][i]) print(newdata) ###################################################################################################################################################################### #PROGRAM 10 n = int(input("Enter the range upto: ")) def divbyseven(n): for i in range(1,n+1): if i % 7 == 0: yield i else: continue for num in divbyseven(n): print(num) ########################################################################################################################################################################## #PROGRAM 11 input_list = [] x = None print('Enter direction and route(in this format DIRECTION<space>STEPS):') for _ in range(0,4): s = input('') x = s.split(' ') input_list.append(x) up_steps = 0 down_steps = 0 left_steps = 0 right_steps = 0 for i in input_list: if i[0].upper() == 'UP': up_steps = int(i[1]) elif i[0].upper() == 'DOWN': down_steps = int(i[1]) elif i[0].upper() == 'LEFT': left_steps = int(i[1]) elif i[0].upper() == 'RIGHT': right_steps = int(i[1]) v_distance = up_steps-down_steps h_distance = left_steps-right_steps print(v_distance) print(h_distance) total_diatance = round(abs(((v_distance**2)+(h_distance**2))**0.5)) print(total_diatance) #################################################################################
# The program to find the different part of the sentence between # # two files which are your targets. You should tell the program # # hint which is the first of the word of the sentence. # # # # You can edit and use the code freely only if you state the original author. # # Author : phil ([email protected]) # import re # @brief Temporary space to store the data. # class File(): def __init__(self): self.loc1 = 0 #!< The path of the first file location self.loc2 = 0 #!< The path of second file location self.line1 = 0 #!< The place to store raw data of the first file self.line2 = 0 #!< The place to store raw data of second file self.diff = False #!< The flag to check whether files are different print("{0:*^50s}".format('Compare documents')) print("{0}".format('You should type pull path of the file location!')) print("{0}".format('After that, Type the exact word which \ is included in the sentence that you want to compare.\n')) # @brief Function for receiving the location of the file. # NOTE: fileloc1, fileloc2 should be the full path of the file location. # def inputname(self): fileloc1 = input("Type the location of file1 : ") fileloc2 = input("Type the location of file2 : ") self.loc1 = fileloc1 self.loc2 = fileloc2 # @brief Function for opening the file. # @return The file pointer. # def openfile(self): f1 = open(self.loc1, 'r') f2 = open(self.loc2, 'r') return (f1, f2) # @brief Function for comparing the diefferent part of the sentence. # @param[in] arr1 The list which contains the sentence that you want to compare # @param[in] arr2 same with arr1 # def ismatch(self, arr1, arr2): if arr1[-1] != arr2[-1]: print('{0} \n {1} : {2} \n {3} : {4}'.format('\nmismatch found!', \ self.loc1[-50:], \ arr1, \ self.loc2[-50:], \ arr2)) self.diff = True # @brief Function for reading whole lines of the file. # @param[in] f1 The file pointer. # @param[in] f2 Same with f1. # def readfile(self, f1, f2): self.line1 = f1.read() self.line2 = f2.read() string = input('Type the first word of the sentence which you want \ to compare : ') string = string + '.*' temp1 = re.findall(string, self.line1) temp2 = re.findall(string, self.line2) for array1 in temp1: for array2 in temp2: if array1[:-2] == array2[:-2]: File.ismatch(self, array1, array2) print('{0}'.format('\nComparing work is done!\n')) if self.diff is False: print('There is no difference\n') # @brief Function for comparing the each sentence of the file sequentially. # @param[in] f1 The file pointer. # @param[in] f2 Same with f1. # def compare(self, f1, f2): lineno = 1 while True: self.line1 = f1.readline() self.line2 = f2.readline() if self.line1 != self.line2: print('{0} {1}\n {2} : {3} \n {4} : {5}'.format('mismatch \ found :', lineno, self.loc1[-30:], self.line1, self.loc2[-30:], \ self.line2)) lineno += 1 if __name__ == '__main__': try: while True: files = File() files.inputname() file1, file2 =files.openfile() files.readfile(file1, file2) file1.close() file2.close() except FileNotFoundError as exc: print(exc)
# Library for Use by FactorModelMOOC.ipynb. """ This file applies to Week2. Python and Machine Learning for Asset Management by EDHEC Business School. on Coursera ----------- Week 1 - Introducing the fundamentals of machine learning Week 2 - Machine learning techniques for robust estimation of factor models Comment - This is useful / good background to know, but generally too big picture for a small trader like myself who does not have access to massive amounts of market data and large portfolios to manage Week 3 - Machine learning techniques for efficient portfolio diversification Comment - Same as Week 2 comment - Using powerful ML / data techniques for diversification is appropriate for massive portfolios. Small dog like me will have to rely on feel and picking stocks /ETFs. Week 4 - Machine learning techniques for regime analysis Comment - This is where it gets interesting. My idea was that if I could analyze the same data everyone else does and see a recession coming, then maybe I would have time to make a conviction call on shorting the SP500 futures, which are easier to trade than individual equities. Week 5 - Identifying recessions, crash regimes and feature selection Comment - Same as week 4 comment. The idea is to use ML techniques to help inform my otherwise very seat of the pants approach. Since the market is so automated and dependent on ML now, then perhaps I need to be armed with the same tools. At least that was the idea. Unfortunately, last year's crash was so fast and sharp, that it corrected based on Fed action within 6 weeks. Thus, Monthly data is not quick enough to inform huge daily moves in the market. """ import numpy as np # for numerical array data import pandas as pd # for tabular data # from scipy.optimize import minimize import matplotlib.pyplot as plt # for plotting purposes import time import cvxpy as cp # "CVXPY is a Python-embedded modeling language for convex optimization # problems. It allows you to express your problem in a natural way that # follows the math, rather than in the restrictive standard form # required by solvers." from sklearn.linear_model import LinearRegression from sklearn.linear_model import Lasso from sklearn.linear_model import Ridge from sklearn.linear_model import ElasticNet # from sklearn.model_selection import KFold from sklearn.model_selection import GridSearchCV # ============================================================================= # # Plotting Functions # ============================================================================= def plot_returns(data, names, flag='Total Return', date='Date', printFinalVals=False): """plot_returns returns a plot of the returns. INPUTS: names: string, name of column to be plotted, or list, in which case it plots all of them data: pd dataframe, where the data is housed flag: string, Either Total Return or Monthly Return date: string, column name corresponding to the date variable printFinalVals: Boolean, if True, prints the final Total Return Outputs: a plot """ # Clean Inputs: if(date not in data.columns): print('date column not in the pandas df') return if(type(names) is str): names = [names] for name in names: if(name not in data.columns): print('column ' + name + ' not in pandas df') return # If the inputs are clean, create the plot data = data.sort_values(date).copy() data.reset_index(drop=True, inplace=True) data[date] = pd.to_datetime(data[date]) if (flag == 'Total Return'): n = data.shape[0] totalReturns = np.zeros((n, len(names))) totalReturns[0, :] = 1. for i in range(1, n): totalReturns[i, :] = np.multiply(totalReturns[i - 1, :], (1 + data[names].values[i, :])) for j in range(len(names)): plt.semilogy(data[date], totalReturns[:, j]) plt.title('Total Return Over Time') plt.ylabel('Total Return') plt.legend(names) plt.xlabel('Date') plt.show() if(printFinalVals): print(totalReturns[-1]) elif (flag == 'Relative Return'): for i in range(len(names)): plt.plot(data[date], data[names[i]]) plt.title('Returns Over Time') plt.ylabel('Returns') plt.legend(names) plt.xlabel('Date') plt.show() else: print('flag variable must be either Total Return or Monthly Return') # ============================================================================= # # Helper Functions # ============================================================================= def create_options(): """Create standard options dictionary. dictionary to be used as input to regression functions. """ options = dict() options['timeperiod'] = 'all' options['date'] = 'Date' options['returnModel'] = False options['printLoadings'] = True return options def create_options_lasso(): options = create_options() options['lambda'] = 1 return options def create_options_ridge(): options = create_options() options['lambda'] = 1 return options def create_options_cv_lasso(): options = create_options() options['maxLambda'] = .25 options['nLambdas'] = 100 options['randomState'] = 7777 options['nFolds'] = 10 return options def create_options_cv_ridge(): options = create_options() options['maxLambda'] = .25 options['nlambdas'] = 100 options['randomState'] = 7777 options['nFolds'] = 10 return options def create_options_cv_elastic_net(): options = create_options() options['maxLambda'] = .25 options['maxL1Ratio'] = .99 options['nLambdas'] = 50 options['nL1Ratios'] = 50 options['randomState'] = 7777 options['nFolds'] = 10 return options def create_options_best_subset(): """Create options dictionary for input to regression functions.""" options = create_options() options['returnModel'] = False options['printLoadings'] = True options['maxVars'] = 3 return options def create_options_relaxed_lasso(CV=True, lambda1=.25): options = create_options() options['CV'] = CV options['gamma'] = .5 if(CV): options['maxLambda'] = .25 options['nLambdas'] = 100 options['randomState'] = 7777 options['nFolds'] = 10 else: # Need to specify lambda1 options['lambda'] = .25 return options def create_dictionary_for_analysis(method, methodDict=None): """Create the options dictionary as an input to a factor model. INPUTS: method: string, defines the method OUTPUTS: methodDict: dictionary, keys are specific options the user wants to specify, values are the values of those options """ if(method == 'OLS'): options = create_options() elif(method == 'CVLasso'): options = create_options_cv_lasso() elif(method == 'CVRidge'): options = create_options_cv_ridge() elif(method == 'CVElasticNet'): options = create_options_cv_elastic_net() elif(method == 'BestSubset'): options = create_options_best_subset() elif(method == 'RelaxedLasso'): options = create_options_relaxed_lasso() else: print('Bad Method Specification for Train') return options['returnModel'] = True options['printLoadings'] = False options['date'] = 'DataDate' for key in methodDict: options[key] = methodDict[key] return options def print_timeperiod(data, dependentVar, options): """Print out the time period. INPUTS: data: pandas df, df with the data dependentVar: string, name of dependent variable options: dictionary, should constain at least two elements, timeperiod, and date timeperiod: string, if == all, means use entire dataframe, otherwise filter the df on this value date: name of datecol OUTPUTS: printed stuff """ print('Dependent Variable is ' + dependentVar) if(options['timeperiod'] == 'all'): sortedValues = data.sort_values(options['date'])[options['date']].reset_index(drop=True) n = sortedValues.shape[0] beginDate = sortedValues[0] endDate = sortedValues[n - 1] print('Time period is between ' + num_to_month(beginDate.month) + ' ' + str(beginDate.year) + ' to ' + num_to_month(endDate.month) + ' ' + str(endDate.year) + ' inclusive ') else: print('Time period is ' + options['timeperiod']) def display_factor_loadings(intercept, coefs, factorNames, options): """Print the factor loadings in a readable way. INPUTS: intercept: float, intercept value coefs: np array, coeficients from pandas df factorNames: list, names of the factors options: dict, should contain at least one key, nameOfReg nameOfReg: string, name for the regression Outputs: output is printed """ loadings = np.insert(coefs, 0, intercept) if('nameOfReg' not in options.keys()): name = 'No Name' else: name = options['nameOfReg'] out = pd.DataFrame(loadings, columns=[name]) out = out.transpose() fullNames = ['Intercept'] + factorNames out.columns = fullNames print(out) def best_subset(x, y, l_0): # Mixed Integer Programming in feature selection # cp.matmul is matrix multiplication; x*b where b is coeffs, x is # boolean feature vector, a is # intercept M = 1000 n_factor = x.shape[1] z = cp.Variable(n_factor, boolean=True) beta = cp.Variable(n_factor) alpha = cp.Variable(1) def MIP_obj(x, y, b, a): return cp.norm(y - cp.matmul(x, b) - a, 2) best_subset_prob = cp.Problem(cp.Minimize(MIP_obj(x, y, beta, alpha)), [cp.sum(z) <= l_0, beta + M * z >= 0, M * z >= beta]) best_subset_prob.solve() return alpha.value, beta.value def linear_regression(data, dependentVar, factorNames, options): """Return the factor loadings using least squares regression. INPUTS: data: pandas df, data matrix, should constain the date column and all of the factorNames columns dependentVar: string, name of dependent variable factorNames: list, elements should be strings, names of the independent variables options: dictionary, should constain at least two elements, timeperiod, and date timeperiod: string, if == all, means use entire dataframe, otherwise filter the df on this value date: name of datecol returnModel: boolean, if true, returns model Outputs: reg: regression object from sikitlearn also prints what was desired """ # first filter down to the time period if(options['timeperiod'] == 'all'): newData = data.copy() else: newData = data.copy() newData = newData.query(options['timeperiod']) linReg = LinearRegression(fit_intercept=True) linReg.fit(newData[factorNames], newData[dependentVar]) if (options['printLoadings']): print_timeperiod(newData, dependentVar, options) display_factor_loadings(linReg.intercept_, linReg.coef_, factorNames, options) if(options['returnModel']): return linReg def lasso_regression(data, dependentVar, factorNames, options): """Return the factor loadings using lasso regression. INPUTS: data: pandas df, data matrix, should constain the date column and all of the factorNames columns dependentVar: string, name of dependent variable factorNames: list, elements should be strings, names of the independent variables options: dictionary, should constain at least two elements, timeperiod, and date timeperiod: string, if == all, means use entire dataframe, otherwise filter the df on this value printLoadings: boolean, if true, prints the coeficients date: name of datecol returnModel: boolean, if true, returns model alpha: float, alpha value for LASSO regression NOTE: SKLearn calles Lambda Alpha. Also, it uses a scaled version of LASSO argument, so here I scale when converting lambda to alpha Outputs: reg: regression object from sikitlearn also prints what was desired """ if('lambda' not in options.keys()): print('lambda not specified in options') return if(options['timeperiod'] == 'all'): newData = data.copy() else: newData = data.copy() newData = newData.query(options['timeperiod']) lassoReg = Lasso(alpha=options['lambda'] / (2 * data.shape[0]), fit_intercept=True) lassoReg.fit(newData[factorNames], newData[dependentVar]) if (options['printLoadings']): print_timeperiod(newData, dependentVar, options) print('lambda = ' + str(options['lambda'])) display_factor_loadings(lassoReg.intercept_, lassoReg.coef_, factorNames, options) if(options['returnModel']): return lassoReg def ridge_regression(data, dependentVar, factorNames, options): """Return the factor loadings using ridge regression. INPUTS: data: pandas df, data matrix, should constain the date column and all of the factorNames columns dependentVar: string, name of dependent variable factorNames: list, elements should be strings, names of the independent variables options: dictionary, should constain at least two elements, timeperiod, and date timeperiod: string, if == all, means use entire dataframe, otherwise filter the df on this value date: name of datecol returnModel: boolean, if true, returns model lambda: float, alpha value for Ridge regression printLoadings: boolean, if true, prints the coeficients Outputs: reg: regression object from sikitlearn also prints what was desired """ if('lambda' not in options.keys()): print('lambda not specified in options') return if(options['timeperiod'] == 'all'): newData = data.copy() else: newData = data.copy() newData = newData.query(options['timeperiod']) ridgeReg = Ridge(alpha=options['lambda'], fit_intercept=True) ridgeReg.fit(newData[factorNames], newData[dependentVar]) if (options['printLoadings']): print_timeperiod(newData, dependentVar, options) print('lambda = ' + str(options['lambda'])) display_factor_loadings(ridgeReg.intercept_, ridgeReg.coef_, factorNames, options) if(options['returnModel']): return ridgeReg def best_subset_regression(data, dependentVar, factorNames, options): """Return the factor loadings using best subset regression. INPUTS: data: pandas df, data matrix, should constain the date column and all of the factorNames columns dependentVar: string, name of dependent variable factorNames: list, elements should be strings, names of the independent variables options: dictionary, should constain at least two elements, timeperiod, and date timeperiod: string, if == all, means use entire dataframe, otherwise filter the df on this value date: name of datecol returnModel: boolean, if true, returns model maxVars: int, maximum number of factors that can have a non zero loading in the resulting regression printLoadings: boolean, if true, prints the coeficients Outputs: reg: regression object from sikitlearn also prints what was desired """ # Check dictionary for maxVars option if('maxVars' not in options.keys()): print('maxVars not specified in options') return if(options['timeperiod'] == 'all'): newData = data.copy() else: newData = data.copy() newData = newData.query(options['timeperiod']) # this is error because we do not have cvxpy in Anaconda, so best_subset # is commented out alpha, beta = best_subset(data[factorNames].values, data[dependentVar].values, options['maxVars']) beta[np.abs(beta) <= 1e-7] = 0.0 if (options['printLoadings']): print_timeperiod(newData, dependentVar, options) print('Max Number of Non-Zero Variables is ' + str(options['maxVars'])) display_factor_loadings(alpha, beta, factorNames, options) if(options['returnModel']): out = LinearRegression() out.intercept_ = alpha[0] out.coef_ = beta return out def cross_validated_lasso_regression(data, dependentVar, factorNames, options): """Return the factor loadings using lasso regression. Cross validating the choice of lambda. INPUTS: data: pandas df, data matrix, should constain the date column and all of the factorNames columns dependentVar: string, name of dependent variable factorNames: list, elements should be strings, names of the independent variables options: dictionary, should constain at least two elements, timeperiod, and date timeperiod: string, if == all, means use entire dataframe, otherwise filter the df on this value date: name of datecol returnModel: boolean, if true, returns model printLoadings: boolean, if true, prints the coeficients maxLambda: float, max lambda value passed nLambdas: int, number of lambda values to try randomState: integer, sets random state seed nFolds: number of folds NOTE: SKLearn calles Lambda Alpha. Also, it uses a scaled version of LASSO argument, so here I scale when converting lambda to alpha Outputs: reg: regression object from sikitlearn also prints what was desired """ if(options['timeperiod'] == 'all'): newData = data.copy() else: newData = data.copy() newData = newData.query(options['timeperiod']) # Do CV Lasso alphaMax = options['maxLambda'] / (2 * newData.shape[0]) print('alphaMax = ' + str(alphaMax)) alphas = np.linspace(1e-6, alphaMax, options['nLambdas']) if(options['randomState'] == 'none'): lassoTest = Lasso(fit_intercept=True) else: lassoTest = Lasso(random_state=options['randomState'], fit_intercept=True) tuned_parameters = [{'alpha': alphas}] clf = GridSearchCV(lassoTest, tuned_parameters, cv=options['nFolds'], refit=True) clf.fit(newData[factorNames], newData[dependentVar]) lassoBest = clf.best_estimator_ alphaBest = clf.best_params_['alpha'] print('Best Alpha') print(clf.best_params_['alpha']) if (options['printLoadings']): print_timeperiod(newData, dependentVar, options) print('best lambda = ' + str(alphaBest * 2 * newData.shape[0])) display_factor_loadings(lassoBest.intercept_, lassoBest.coef_, factorNames, options) if(options['returnModel']): return lassoBest def cross_validated_ridge_regression(data, dependentVar, factorNames, options): """Return the factor loadings using ridge regression. ...choosing lambda via ridge regression INPUTS: data: pandas df, data matrix, should constain the date column and all of the factorNames columns dependentVar: string, name of dependent variable factorNames: list, elements should be strings, names of the independent variables options: dictionary, should constain at least two elements, timeperiod, and date timeperiod: string, if == all, means use entire dataframe, otherwise filter the df on this value date: name of datecol returnModel: boolean, if true, returns model printLoadings: boolean, if true, prints the coeficients maxLambda: float, max lambda value passed nLambdas: int, number of lambda values to try randomState: integer, sets random state seed nFolds: number of folds NOTE: SKLearn calles Lambda Alpha. So I change Lambda -> Alpha in the following code Outputs: reg: regression object from sikitlearn also prints what was desired """ if(options['timeperiod'] == 'all'): newData = data.copy() else: newData = data.copy() newData = newData.query(options['timeperiod']) # Do CV Lasso alphaMax = options['maxLambda'] alphas = np.linspace(1e-6, alphaMax, options['nLambdas']) if(options['randomState'] == 'none'): ridgeTest = Ridge(fit_intercept=True) else: ridgeTest = Ridge(random_state=options['randomState'], fit_intercept=True) tuned_parameters = [{'alpha': alphas}] clf = GridSearchCV(ridgeTest, tuned_parameters, cv=options['nFolds'], refit=True) clf.fit(newData[factorNames], newData[dependentVar]) ridgeBest = clf.best_estimator_ alphaBest = clf.best_params_['alpha'] if (options['printLoadings']): print_timeperiod(newData, dependentVar, options) print('best alpha = ' + str(alphaBest)) display_factor_loadings(ridgeBest.intercept_, ridgeBest.coef_, factorNames, options) if(options['returnModel']): return ridgeBest def cross_validated_elastic_net_regression(data, dependentVar, factorNames, options): """Return the factor loadings using elastic net, also chooses alpha. ...and l1 ratio via cross validation INPUTS: data: pandas df, data matrix, should constain the date column and all of the factorNames columns dependentVar: string, name of dependent variable factorNames: list, elements should be strings, names of the independent variables options: dictionary, should constain at least two elements, timeperiod, and date timeperiod: string, if == all, means use entire dataframe, otherwise filter the df on this value date: name of datecol returnModel: boolean, if true, returns model printLoadings: boolean, if true, prints the coeficients maxLambda: float, max lambda value passed nLambdas: int, number of lambda values to try maxL1Ratio: float randomState: integer, sets random state seed nFolds: number of folds NOTE: SKLearn calles Lambda Alpha. So I change Lambda -> Alpha in the following code Outputs: reg: regression object from sikitlearn also prints what was desired """ if(options['timeperiod'] == 'all'): newData = data.copy() else: newData = data.copy() newData = newData.query(options['timeperiod']) alphaMax = options['maxLambda'] / (2 * newData.shape[0]) alphas = np.linspace(1e-6, alphaMax, options['nLambdas']) l1RatioMax = options['maxL1Ratio'] l1Ratios = np.linspace(1e-6, l1RatioMax, options['nL1Ratios']) if(options['randomState'] == 'none'): elasticNetTest = ElasticNet(fit_intercept=True) else: elasticNetTest = ElasticNet(random_state=options['randomState'], fit_intercept=True) tuned_parameters = [{'alpha': alphas, 'l1_ratio': l1Ratios}] clf = GridSearchCV(elasticNetTest, tuned_parameters, cv=options['nFolds'], refit=True) clf.fit(newData[factorNames], newData[dependentVar]) elasticNetBest = clf.best_estimator_ alphaBest = clf.best_params_['alpha'] l1RatioBest = clf.best_params_['l1_ratio'] if (options['printLoadings']): print_timeperiod(newData, dependentVar, options) print('best lambda1 = ' + str(alphaBest * 2 * newData.shape[0] * l1RatioBest)) print('best lambda2 = ' + str(newData.shape[0] * alphaBest * (1 - l1RatioBest))) display_factor_loadings(elasticNetBest.intercept_, elasticNetBest.coef_, factorNames, options) if(options['returnModel']): return elasticNetBest def relaxed_lasso_regression(data, dependentVar, factorNames, options): """Return the factor loadings using lasso regression. ...and cross validating the choice of lambda INPUTS: data: pandas df, data matrix, should constain the date column and all of the factorNames columns dependentVar: string, name of dependent variable factorNames: list, elements should be strings, names of the independent variables options: dictionary, should constain at least two elements, timeperiod, and date timeperiod: string, if == all, means use entire dataframe, otherwise filter the df on this value date: name of datecol returnModel: boolean, if true, returns model printLoadings: boolean, if true, prints the coeficients maxLambda: float, max lambda value passed nLambdas: int, number of lambda values to try randomState: integer, sets random state seed nFolds: number of folds NOTE: SKLearn calles Lambda Alpha. Also, it uses a scaled version of LASSO argument, so here I scale when converting lambda to alpha Outputs: reg: regression object from sikitlearn also prints what was desired """ # Step 1: Build the LASSO regression # Check if you cross validate optionsNew = options optionsNew['printLoadings'] = False if(options['CV']): lassoModel = cross_validated_lasso_regression(data, dependentVar, factorNames, optionsNew) else: lassoModel = lasso_regression(data, dependentVar, factorNames, optionsNew) # Step 2: Extract Non-Zero Factor Loadings listNonZeroLoadings = [] for i in range(len(factorNames)): if (lassoModel.coef_[i] != 0): listNonZeroLoadings.append(factorNames[i]) # Step 2a: Check if the lambda value chosen is too large if(len(listNonZeroLoadings) == 0): print('Lambda Value Set To Big, Model is Null Model') reg = LinearRegression() reg.coef_ = np.zeros((len(factorNames),)) reg.intercept_ = 0.0 return reg # Step 3: Run OLS using just the non-zero coeficients from the LASSO # regression olsReg = linear_regression(data, dependentVar, listNonZeroLoadings, optionsNew) # Step 4: Average the two models together coefs = np.zeros((len(factorNames),)) for i in range(len(factorNames)): if(lassoModel.coef_[i] != 0): ind = listNonZeroLoadings.index(factorNames[i]) coefs[i] = (optionsNew['gamma'] * lassoModel.coef_[i] + (1 - optionsNew['gamma']) * olsReg.coef_[ind]) reg = LinearRegression() reg.coef_ = coefs reg.intercept_ = (optionsNew['gamma'] * lassoModel.intercept_ + (1 - optionsNew['gamma']) * olsReg.intercept_) if (options['printLoadings']): # Now print the results if(options['timeperiod'] == 'all'): newData = data.copy() else: newData = data.copy() newData = newData.query(options['timeperiod']) print_timeperiod(newData, dependentVar, options) if(options['CV']): print('best lambda = ' + str(lassoModel.alpha * 2 * newData.shape[0])) else: print('lambda = ' + str(options['lambda'])) # Now print the factor loadings display_factor_loadings(reg.intercept_, reg.coef_, factorNames, options) return reg def run_factor_model(data, dependentVar, factorNames, method, options): """Return a model object according to the method chosen. INPUTS: data: pandas df, must contain the columns specified in factorNames and dependentVar dependentVar: string, dependent variable factorNames: list of strings, names of independent variables method: string, name of method to be used. Supports OLS, LASSO, CVLASSO atm options: dictionary object, controls the hyperparameters of the method Outputs: out: model object """ # Make sure the options dictionary has the correct settings options['returnModel'] = True options['printLoadings'] = False if (method == 'OLS'): # run linear model return linear_regression(data, dependentVar, factorNames, options) if (method == 'LASSO'): return lasso_regression(data, dependentVar, factorNames, options) if (method == 'Ridge'): return ridge_regression(data, dependentVar, factorNames, options) if (method == 'CVLasso'): return cross_validated_lasso_regression(data, dependentVar, factorNames, options) if (method == 'CVRidge'): return cross_validated_ridge_regression(data, dependentVar, factorNames, options) if (method == 'CVElasticNet'): return cross_validated_elastic_net_regression(data, dependentVar, factorNames, options) if (method == 'BestSubset'): return best_subset_regression(data, dependentVar, factorNames, options) if (method == 'RelaxedLasso'): return relaxed_lasso_regression(data, dependentVar, factorNames, options) else: print('Method ' + method + ' not supported') def compute_trailing_factor_regressions(data, dependentVar, factorNames, window, method, options, dateCol='Date', printTime=False): """Create a time series of factor loadings using a trailing window. Returns a pandas df object. INPUTS: data: pandas df, must constain the columns dependentVar, and the set of columns factorNames dependentVar: string, names the dependent variable, must be a column in the dataframe data factorNames: list of string, elements must be members window: int, lookback window, measured in number of trading days method: string, can be OLS, LASSO or CVLasso options: dictionary, options dictionary dateCol: string, name of date column, also must be included in data printTime: boolean, if True, prints time it took to run the regressions Outputs: regressionValues: pandas df, rows should be different dates, columns should be factor loadings calculated using the trailing window """ if(printTime): start = time.time() options['returnModel'] = True options['printLoadings'] = False days = list(np.sort(data[dateCol].unique())) listOfFactorsAndDate = [dateCol] + factorNames regressionValues = pd.DataFrame(columns=listOfFactorsAndDate) for i in range(window, len(days)): # Filter the data filtered = data[(data[dateCol] <= days[i]) & (data[dateCol] >= days[i - window])] # Run the regression reg = run_factor_model(filtered, dependentVar, factorNames, method, options) # Append the regression values newRow = pd.DataFrame(reg.coef_) newRow = newRow.transpose() newRow.columns = factorNames newRow[dateCol] = days[i] regressionValues = regressionValues.append(newRow, sort=True) if(printTime): print('regression took ' + str((time.time() - start) / 60.) + ' minutes') return regressionValues def num_to_month(month): # Returns the name of the month when input is integer if (month == 1): return 'January' if (month == 2): return 'Febuary' if (month == 3): return 'March' if (month == 4): return 'April' if (month == 5): return 'May' if (month == 6): return 'June' if (month == 7): return 'July' if (month == 8): return 'August' if (month == 9): return 'September' if (month == 10): return 'October' if (month == 11): return 'November' if (month == 12): return 'December' def data_time_periods(data, dateName): """Figure out if the data is daily, weekly, monthly, etc. INPUTS: data: pandas df, has a date column in it with column name dateName dateName: string, name of column to be analysed """ secondToLast = data[dateName].tail(2)[:-1] last = data[dateName].tail(1) thingy = ((last.values - secondToLast.values).astype('timedelta64[D]') / np.timedelta64(1, 'D')) thingy = thingy[0] if (thingy > 200): return 'yearly' elif(thingy > 20): return 'monthly' elif(thingy > 5): return 'weekly' else: return 'daily'
# -*-coding:Latin-1 -* import os nb_u = input("Tapez un nombre pour obtenir sa table de multiplication"" ") nb = int(nb_u) MAX_u = input("Tapez le chiffre maximal pour lequel vous voulez obtenir sa table de multiplication"" ") MAX = int(MAX_u) def table_multiplication(nb, MAX): i = -1 while i<MAX: print(nb,"*",(i+1),"=", nb*(i+1)) i += 1 print (table_multiplication(nb,MAX)) os.system("pause")
#!/usr/bin/python import time import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) # Zaehlweise der GPIO Pins auf dem Raspberry GPIO.setup(2, GPIO.IN) # Pin 3 als Eingang - Button 1 GPIO.setup(3, GPIO.IN) # Pin 4 als Eingang - Button 2 # store button state in these variables, 0 means button is pressed button1 = 1 button2 = 1 while True: if (GPIO.input(2) == 0 and button1 != 0): print("button1") button1 = 0 time.sleep(0.3); if (GPIO.input(3) == 0 and button2 != 0): print("button2") button2 = 0 time.sleep(0.3); button1 = GPIO.input(2) button2 = GPIO.input(2)
# -*- coding: utf-8 -*- """ Created on Wed May 8 13:08:34 2019 @author: Harsh Anand """ """ Code Challenge Name: Bricks Filename: bricks.py Problem Statement: We want to make a row of bricks that is target inches long. We have a number of small bricks (1 inch each) and big bricks (5 inches each). Make a function that prints True if it is possible to make the exact target by choosing from the given bricks or False otherwise. Take list as input from user where its 1st element represents number of small bricks, middle element represents number of big bricks and 3rd element represents the target. Input: 2, 2, 11 Output: True """ num=list(map(int,input("Enter 1st element--> small bricks,2nd element-->big bricks and 3rd element-->target. :").split())) print(num) tot1=1*num[0] tot2=5*num[1] tot=tot1+tot2 if tot>=num[2]: print("True") else: print("False")
# -*- coding: utf-8 -*- """ Created on Thu May 9 16:26:02 2019 @author: Harsh Anand """ """ Two words are anagrams if you can rearrange the letters of one to spell the second. For example, the following words are anagrams: ['abets', 'baste', 'bates', 'beast', 'beats', 'betas', 'tabes'] Hint: How can you tell quickly if two words are anagrams? Dictionaries allow you to find a key quickly. """ li=[] lii=[] counter=0 while True: str1=input("enter string") if not str1: break li.append(str1) for i in li[0]: lii.append(i) lii.sort() print(lii) list1=[] for item in li: for j in item: list1.append(j) list1.sort() #print(list1) if list1==lii: counter+=1 else: counter=0 list1.clear() if counter>0: print("anagrams") else: print("NO anagrams")
""" Code Challenge 1 Write a python code to insert records to a mongo/sqlite/MySQL database named db_University for 10 students with fields like Student_Name, Student_Age, Student_Roll_no, Student_Branch. """ import mysql.connector from pandas import DataFrame # connect to MySQL server along with Database name conn = mysql.connector.connect(user='harsh_mysql', password='monu1234', host='db4free.net', database = 'mysqldb_harsh') c = conn.cursor() # STEP 2 #c.execute("DROP Table students;") # STEP 3 c.execute ("""CREATE TABLE students( name TEXT, age INTEGER, roll INTEGER, branch TEXT )""") # STEP 4 c.execute("INSERT INTO students VALUES ('Harsh',21,33,'cse')") c.execute("INSERT INTO students VALUES ('Harshit',20,34,'cse')") c.execute("INSERT INTO students VALUES ('Akash',19,20,'ece')") c.execute("INSERT INTO students VALUES ('Suresh',22,45,'ee')") c.execute("INSERT INTO students VALUES ('Alok',21,11,'cv')") c.execute("INSERT INTO students VALUES ('Harsha',20,31,'cse')") c.execute("INSERT INTO students VALUES ('Harshita',21,30,'cse')") c.execute("INSERT INTO students VALUES ('Akasha',17,24,'ece')") c.execute("INSERT INTO students VALUES ('Suresha',24,35,'ee')") c.execute("INSERT INTO students VALUES ('Aloka',20,13,'cv')") # c.execute("INSERT INTO employee VALUES ({},'{}', '{}', {})".format(idd, first,last,pay)) c.execute("SELECT * FROM students") print ( c.fetchall() ) c.execute("SELECT * FROM students") df_students = DataFrame(c.fetchall()) # putting the result into Dataframe df_students.columns = ["Name","Age","Roll","Branch"] """ Code Challenge 2 Perform similar steps as in the above code challenge but store the contents in an online mongo atlas database. """ import pymongo client = pymongo.MongoClient("mongodb://harsh_19:[email protected]:27017,cluster0-shard-00-01-aymha.mongodb.net:27017,cluster0-shard-00-02-aymha.mongodb.net:27017/test?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin&retryWrites=true") # --> drop the collection #mydb.collection_harsh.drop() mydb = client.db_harsh def add_students(Name,Age,Roll,Branch): #unique_employee = mydb.employees.find_one({"id":idd}) #if unique_employee: # return "Employee already exists" #else: mydb.collection_harsh.insert_one( { "st_name" : Name, "st_age" : Age, "st_roll" : Roll, "st_branch" : Branch }) return "Students added successfully" def fetch_all_students(): user = mydb.collection_harsh.find() for i in user: print (i) add_students('Harsh',21,33,'cse') add_students('Harshit',20,34,'cse') add_students('Akash',19,20,'ece') add_students('Suresh',22,45,'ee') add_students('Alok',21,11,'cv') add_students('Harsha',20,36,'cse') add_students('Harshita',19,39,'cse') add_students('Akasha',22,23,'ece') add_students('Suresha',21,41,'ee') add_students('Aloka',22,14,'cv') fetch_all_students() """ Code Challenge 3 In the Bid plus Code Challenege 1. BID NO 2. items 3. Quantity Required 4. Department Name And Address 5. Start Date/Time(Enter date and time in different columns) 6. End Date/Time(Enter date and time in different columns) Store the information into a database mySQL Database """ import pandas as pd from selenium import webdriver link="https://bidplus.gem.gov.in/bidlists" driver = webdriver.Chrome("E:\\Forsk\\chromedriver.exe") driver.get(link) right_table=driver.find_element_by_xpath('//*[@id="pagi_content"]') A=[] B=[] C=[] D=[] E=[] F=[] G=[] H=[] for i in range(1,11): for row in right_table.find_elements_by_xpath('//*[@id="pagi_content"]/div['+str(i)+']'): #print(row) states=row.find_elements_by_tag_name('p') i+=1 A.append(states[0].text.strip()) B.append(states[1].text.strip()) C.append(states[2].text.strip()) D.append(states[3].text.strip()) E.append(states[4].text.strip()) F.append(states[5].text.strip()) G.append(states[6].text.strip()) H.append(states[7].text.strip()) import mysql.connector conn = mysql.connector.connect(user='harsh_mysql', password='monu1234', host='db4free.net', database = 'mysqldb_harsh') c = conn.cursor() #c.execute("DROP Table bid;") c.execute ("""CREATE TABLE bid( bid_no VARCHAR(200), item VARCHAR(200), quantity VARCHAR(200), address VARCHAR(2000), start VARCHAR(200), end VARCHAR(200) )""") li_bid=list(zip(A,C,D,F,G,H)) for item in li_bid: #print(item[5]) c.execute("INSERT INTO bid VALUES ('{}','{}','{}','{}','{}','{}')".format(item[0],item[1],item[2],item[3],item[4],item[5])) c.execute("SELECT * FROM bid") print ( c.fetchall() ) c.execute("SELECT * FROM bid") # STEP 6 df_bid_mysql = DataFrame(c.fetchall()) df_bid_mysql.columns = ["bid","item","quantity","address","start","end"] """ Code Challenge 4 Scrap the data from the URL below and store in sqlite database https://www.icc-cricket.com/rankings/mens/team-rankings/odi """ from bs4 import BeautifulSoup import requests odi= "https://www.icc-cricket.com/rankings/mens/team-rankings/odi" source = requests.get(odi).text soup = BeautifulSoup(source,"lxml") #print (soup.prettify()) all_tables=soup.find_all('table') print (all_tables) right_table=soup.find('table',class_='table') print(right_table) A=[] B=[] C=[] D=[] E=[] for row in right_table.findAll('tr'): #print(row) cells = row.findAll('td') if len(cells)==5: A.append(cells[0].text.strip()) B.append(cells[1].text.strip()) C.append(cells[2].text.strip()) D.append(cells[3].text.strip()) E.append(cells[4].text.strip()) import sqlite3 from pandas import DataFrame conn = sqlite3.connect ( 'cricket.db' ) c = conn.cursor() #c.execute("DROP TABLE cricket;") c.execute ("""CREATE TABLE cricket( ranking INTEGER, Team TEXT, Match INTEGER, Points INTEGER, Rating INTEGER )""") li_cric=list(zip(A,B,C,D,E)) for item in li_cric: #print(item[4]) # or c.execute("INSERT INTO cricket VALUES ('{}','{}','{}','{}','{}')".format(item[0],item[1],item[2],item[3],item[4])) c.execute("INSERT INTO cricket VALUES (?,?,?,?,?)",(item)) c.execute("SELECT * FROM cricket") print ( c.fetchall() ) c.execute("SELECT * FROM cricket") df_cricket = DataFrame(c.fetchall()) df_cricket.columns = ["Rank","Team","Match","Points","Rating"] conn.commit() conn.close()
# -*- coding: utf-8 -*- """ Created on Tue May 7 14:10:31 2019 @author: Harsh Anand """ # Print all the numbers from 1 to 10 using condition in while loop i=1 while(i<11): print(i) i+=1 #Print all the numbers from 1 to 10 using while True loop x=1 while(True): print(x) x+=1 if x==11: break #Print all the even numbers from 1 to 10 using condition in while loop i=2 while(i<11): if(i%2==0): print("Even number",i) i+=1 #Print all the even numbers from 1 to 10 using while True loop i=2 while(True): if(i%2==0): print("Even number",i) if i==11: break i+=1 #Print all the odd numbers from 1 to 10 using condition in while loop i=1 while(i<11): if(i%2!=0): print("odd number",i) i+=1 #Print all the odd numbers from 1 to 10 using while True loop i=1 while(True): if i==11: break if(i%2!=0): print("odd number",i) i+=1
''' Q1. Human Activity Recognition Human Activity Recognition with Smartphones (Recordings of 30 study participants performing activities of daily living) (Click Here To Download Dataset): https://github.com/K-Vaid/Python-Codes/blob/master/Human_activity_recog.zip In an experiment with a group of 30 volunteers within an age bracket of 19 to 48 years, each person performed six activities (WALKING, WALKING UPSTAIRS, WALKING DOWNSTAIRS, SITTING, STANDING, LAYING) wearing a smartphone (Samsung Galaxy S II) on the waist. The experiments have been video-recorded to label the data manually. The obtained dataset has been randomly partitioned into two sets, where 70% of the volunteers was selected for generating the training data and 30% the test data. Attribute information For each record in the dataset the following is provided: Triaxial acceleration from the accelerometer (total acceleration) and the estimated body acceleration. Triaxial Angular velocity from the gyroscope. A 561-feature vector with time and frequency domain variables. Its activity labels. An identifier of the subject who carried out the experiment. Train a tree classifier to predict the labels from the test data set using the following approaches: (a) a decision tree approach, (b) a random forest approach and (c) a logistic regression. (d) KNN approach Examine the result by reporting the accuracy rates of all approach on both the testing and training data set. Compare the results. Which approach would you recommend and why? Perform feature selection and repeat the previous step. Does your accuracy improve? Plot two graph showing accuracy bar score of all the approaches taken with and without feature selection. ''' import pandas as pd dataset_test = pd.read_csv("test.csv") dataset_train = pd.read_csv("train.csv") features_test = dataset_test.drop(['Activity','subject'],axis=1) features_train = dataset_train.drop(['Activity','subject'],axis=1) labels_test = dataset_test['Activity'] labels_train = dataset_train['Activity'] #********************* label encoding ***************************** # Encoding categorical data from sklearn.preprocessing import LabelEncoder labelencoder = LabelEncoder() labels_train = labelencoder.fit_transform(labels_train) labels_test = labelencoder.fit_transform(labels_test) #optional #***************** Decision tree classifier **************************** from sklearn.tree import DecisionTreeClassifier classifier = DecisionTreeClassifier() classifier.fit(features_train, labels_train) labels_pred = classifier.predict(features_test) labels_pred_inverse = labelencoder.inverse_transform(labels_pred) labels_test_inverse = labelencoder.inverse_transform(labels_test) data_random=pd.DataFrame({'Actual':labels_test_inverse, 'Predicted':labels_pred_inverse}) print("Score for Decision tree on testing :",classifier.score(features_test,labels_test)) print("Score for Decision tree on training :",classifier.score(features_train,labels_train)) #**************** Random forest ****************************************** from sklearn.ensemble import RandomForestClassifier classifier = RandomForestClassifier(n_estimators=20, random_state=0) classifier.fit(features_train, labels_train) print("Score for Random Forest on testing :",classifier.score(features_test,labels_test)) print("Score for Random Forest on training :",classifier.score(features_train,labels_train)) #***************** kNN *************************************************** from sklearn.neighbors import KNeighborsClassifier classifier = KNeighborsClassifier(n_neighbors = 5, p = 2) #When p = 1, this is equivalent to using manhattan_distance (l1), and euclidean_distance (l2) for p = 2 classifier.fit(features_train, labels_train) print("Score for knn on testing :",classifier.score(features_test,labels_test)) print("Score for knn on training :",classifier.score(features_train,labels_train)) #***************** logistic regression ************************************* from sklearn.linear_model import LogisticRegression classifier = LogisticRegression() classifier.fit(features_train, labels_train) print("Score for knn on testing :",classifier.score(features_test,labels_test)) print("Score for knn on training :",classifier.score(features_train,labels_train)) #************ Perform feature selection and repeat the previous step. Does your accuracy improve? import statsmodels.api as sm regressor_OLS = sm.OLS(endog = labels_train, exog = features_train).fit() p_values = list(regressor_OLS.pvalues) index=[] #store the index which has pvalues less than 5% for item in p_values: if item <0.05: index.append(p_values.index(item)) #taking features features_train = features_train.iloc[:,index].values features_test = features_test.iloc[:,index].values #***************** Decision tree classifier **************************** from sklearn.tree import DecisionTreeClassifier classifier = DecisionTreeClassifier() classifier.fit(features_train, labels_train) labels_pred = classifier.predict(features_test) labels_pred_inverse = labelencoder.inverse_transform(labels_pred) labels_test_inverse = labelencoder.inverse_transform(labels_test) data_random=pd.DataFrame({'Actual':labels_test_inverse, 'Predicted':labels_pred_inverse}) print("Score for Decision tree on testing :",classifier.score(features_test,labels_test)) print("Score for Decision tree on training :",classifier.score(features_train,labels_train)) #**************** Random forest ****************************************** from sklearn.ensemble import RandomForestClassifier classifier = RandomForestClassifier(n_estimators=20, random_state=0) classifier.fit(features_train, labels_train) print("Score for Random Forest on testing :",classifier.score(features_test,labels_test)) print("Score for Random Forest on training :",classifier.score(features_train,labels_train)) #***************** kNN *************************************************** from sklearn.neighbors import KNeighborsClassifier classifier = KNeighborsClassifier(n_neighbors = 5, p = 2) #When p = 1, this is equivalent to using manhattan_distance (l1), and euclidean_distance (l2) for p = 2 classifier.fit(features_train, labels_train) print("Score for knn on testing :",classifier.score(features_test,labels_test)) print("Score for knn on training :",classifier.score(features_train,labels_train)) #***************** logistic regression ************************************* from sklearn.linear_model import LogisticRegression classifier = LogisticRegression() classifier.fit(features_train, labels_train) print("Score for knn on testing :",classifier.score(features_test,labels_test)) print("Score for knn on training :",classifier.score(features_train,labels_train)) ''' Q2. Code Challenge #Online Marketing (Click Here To Download Resource File) : http://openedx.forsk.in/c4x/Manipal_University/FL007/asset/online_marketing.sql Objective of this case study is to explore Online Lead Conversion for a Life Insurance company. Some people are interested in buying insurance products from this company hence they visit the site of this Life Insurance Company and fill out a survey asking about attributes like income, age etc. These people are then followed and some of them become customers from leads. Company have all the past data of who became customers from lead. Idea is to learn something from this data and when some new lead comes, assign a propensity of him/her converting to a customer based on attributes asked in the survey. This sort of problem is called as Predictive Modelling Concept: Predictive modelling is being used by companies and individuals all over the world to extract value from historical data. These are the mathematical algorithms, which are used to "learn" the patterns hidden on all this data. The term supervised learning or classification is also used which means you have past cases tagged or classified (Converted to Customer or Not) and you want to use this learning on new data. (machine learning) Here are the attributes of the survey: Attribute age (Age of the Lead) Job (Job Category e.g. Management) marital (Marital Status) education (Education of Lead) smoker (Is Lead smoker or not (Binary – Yes / No)) monthlyincome (Monthly Income) houseowner (Is home owner or not (Binary – Yes / No)) loan (Is having loan or not (Binary – Yes / No)) contact (Contact type e.g. Cellphone) mod (Days elapsed since survey was filled) monthlyhouseholdincome (Monthly Income of all family member) target_buy (altogether Is converted to customer or not (Binary –Yes /No). This is known as Target or Responseand this is what we are modelling.) Activities you need to perform: a. Handle the missing data and perform necessary data pre-processing. b. Summarise the data. c. Perform feature selection and train using prediction model. d. For a new lead, predict if it will convert to a successful lead or not. e. Use different classification techniques and compare accuracy score and also plot them in a bar graph. ''' import sqlite3 as sql conn = sql.connect('mydb.db') cursor = conn.cursor() file = open('online_marketing.sql','r') file_read = file.read() file.close() cursor.executescript(file_read) conn.commit() import pandas as pd data = pd.read_sql('select * from online_marketing',conn) #************************************************************************************************* #xampp -->open file & replace mod with mod_ and then crete database and import sql file import pandas as pd import mysql.connector as sql query = "select * from online_marketing" conn = sql.connect(host="localhost", user="root", password="", db = "online_market" ) data = pd.read_sql(query,conn)
# -*- coding: utf-8 -*- """ Created on Wed May 8 16:23:22 2019 @author: Harsh Anand """ """ Code Challenge Name: Unlucky 13 Filename: unlucky.py Problem Statement: Return the sum of the numbers in the array, returning 0 for an empty array. Except the number 13 is very unlucky, so it does not count and numbers that come immediately after a 13 also do not count Take input from user Input: 13, 1, 2, 13, 2, 1, 13 Output: 3 """ num=list(map(int,input("Enter number :").split(","))) print(num) li=[] for i in range(0,len(num)): if num[i]!=13: if num[i-1]!=13: li.append(num[i]) print(li) summ=0 for item in li: summ=summ+item print(summ)
r = int(input('Enter r:')) gotr = r * 2 mohit = gotr * 3.14 masahat = r ** 2 * 3.14 print('gotr:', gotr, 'mohit:', mohit, 'masahat:', masahat)
def fact(num): if num == 1: return 1 else: return(num*fact(num-1)) val = int(input("Enter any number ")) print("The required factorial is ", fact(val))
#!/usr/bin/env python # coding: utf-8 # In[2]: dict1 = {21: "FTP", 22: "SSH", 23: "telnet", 80: "http"} newdict = dict([(value, key) for key, value in dict1.items()]) print(dict1) print() print("keys: values") for i in newdict: print(i, " : ", newdict[i]) # In[11]: list1 = [(1,2),(3,4),(4,5),(5,6)] list2 = [] for tup in list1: res = sum(list(tup)) list2.append(res) print(list2) # In[12]: list1 = [(1,2,3),[1,2],['a','hit','less']] list2 = [] for i in list1: list2 = list2 + list(i) print(list2) # In[ ]: # In[ ]: # In[ ]:
def insertion(numbers): for i in range(1, len(numbers)): j = i #While loop to check if previous element is larger #If previous element is smaller, continue traversing while j > 0 and numbers[j-1] > numbers[j]: #Swap elements, decrement j numbers[j], numbers[j-1] = numbers[j-1], numbers[j] j -= 1 return numbers
# _*_ coding: utf-8 _*_ """题目:打印出如下图案(菱形): * *** ***** ******* ***** *** * """ def diamond(n): for i in range(1, 2*n): print(' ' * abs(i - n) + '*' * (2 * (n - abs(i -n)) -1)) diamond(7)
# -*- coding: UTF-8 -*- """两个 3 行 3 列的矩阵,实现其对应位置的数据相加,并返回一个新矩阵: X = [[12,7,3], [4 ,5,6], [7 ,8,9]] Y = [[5,8,1], [6,7,3], [4,5,9]]""" import numpy X = [[12,7,3], [4 ,5,6], [7 ,8,9]] Y = [[5,8,1], [6,7,3], [4,5,9]] def matrixadd(x, y): L1 = [] for i in range(len(x)): L2 = [] for j in range(len(x)): L2 += [x[i][j] + y[i][j]] L1 += [L2] return L1 def npadd(x, y): m = numpy.array(x) n = numpy.array(y) return m + n print(npadd(X, Y))
# _*_ coding: utf-8 _*_ """题目:利用递归方法求5!。""" def fact(n): def f(n, s): if n == 1: return s s *= n return f(n-1, s) return f(n, 1) print(fact(5))
starting_nums = [2,15,0,9,1,20] number_spoken = [] last_spoken = [] nums = dict() nums[1] = [1,2,3] #30000000 for i in range(0,30000000): if i < len(starting_nums): number_spoken.append(starting_nums[i]) else: previous_number = number_spoken[i-1] locations = [] for i in range(0,len(number_spoken)): if number_spoken[i] == previous_number: locations.append(i) if len(locations) == 1: number_spoken.append(0) else: last = locations[-1] previous = locations[-2] number_spoken.append(last - previous) print(number_spoken[-1]) print(nums)
for letra in "hola!": print("estamos en la letra: ", letra ) palabras = ["hola", "python", "pythondiario"] for i in palabras: print(i, len(i)) vuelta = 1 while vuelta < 10: print("vuelta" + str(vuelta)) vuelta = vuelta + 1 for vuelta in range(1, 10): print("vuelta" + str(vuelta))
nota1 = int(input("Nota del primer parcial?")) nota2 = int(input("Nota del segundo parcial?")) nota3 = int(input("Nota del tercer parcial?")) nota_Final = (nota1 + nota2 + nota3)/3 print(nota_Final)
partidos_g = int(input("cuantos partidos ganados? ")) partidos_p = int(input("Cuantos partidos perdidos? ")) partidos_emp = int(input("Cuantos partidos perdidos? ")) total = (partidos_g*3)+(partidos_emp*1) print("El equipo tuvo un total de ", total, "puntos")
import time def brute_force(elements): if len(elements) == 0: return [[]] first_element = elements[0] # Copy the array without first element rest = elements[1:] combs_without_first = brute_force(rest) combs_with_first = [] for comb in combs_without_first: comb_with_first = [*comb, first_element] combs_with_first.append(comb_with_first) # If combinations are still possible return [*combs_without_first, *combs_with_first] def try_all_possibilities(): file = open('resources\\actions_premiere_partie.csv') data = file.read() file.close() # Split file by lines file_lines = data.split('\n') # Remove line 0 del (file_lines[0]) formated_actions = [] for line in file_lines: str_elements = line.split(',') element = {'name': str_elements[0], 'cost': str_elements[1], 'benef': str_elements[2]} if float(element['cost']) > 0: formated_actions.append(element) print(f"Nous allons analyser une liste de {len(formated_actions)} actions") print(f"{len(file_lines)- len(formated_actions)} actions ont été retirées de par leur prix (0 ou - )") total = 2**len(formated_actions) print(f"Nous avions {len(formated_actions)} entrées") print(f"Nous devrions trouver {total} combinaisons selon les lois de l'algorithme") result = brute_force(formated_actions) print(f"Nous avons trouvé {len(result)} possibilités") return result def sort_to_fit_wallet(array_of_actions, money_to_spend): buyable_actions = [] for action in array_of_actions: if float(action['total_cost']) <= money_to_spend: buyable_actions.append(action) return buyable_actions def main(): wallet = 500 # Result of algorithm start_time = time.time() dict_combinations = try_all_possibilities() # Prepare array of dicts for cost, benefits combinations_with_properties = [] # loop through our list of dicts and creates for comb in dict_combinations: total_price = 0 benefice = 0 # For every action : for action in comb: total_price += float(action['cost']) # Calcul du bénéfice benefice += float(action['cost']) * float(action['benef']) / 100 combination = {'total_cost': total_price, 'benefice': benefice, 'action_list': comb} combinations_with_properties.append(combination) buyable_actions = sort_to_fit_wallet(combinations_with_properties, wallet) duration = time.time() - start_time print(f"Le calcul de possibilités a pris {duration} secondes") sorted_buyable_actions = sorted(buyable_actions, key=lambda action: action['benefice'], reverse=True) for i in range(3): print(f"\n{i + 1} - Bénéfice : {sorted_buyable_actions[i]['benefice']}\n" f"Coût : {sorted_buyable_actions[i]['total_cost']}\n" f"Actions à acheter : {sorted_buyable_actions[i]['action_list']}\n") if __name__ == '__main__': main()
from random import randint bilTebak = randint (0,100) print ("Halo... Nama saya Mr. Komputer :D") print ("Saya telah memilih bilangan secara acak dari 0 - 100") print ("Coba tebak, bilangan berapakah itu?? :)))") while True : bilAnda = int ( input ("Silahkan masukkan tebakkan Anda :")) if (bilAnda > 0) and (bilAnda < bilTebak): print ("Ups... Kurang tepat, bilangan Anda terlalu kecil") elif (bilAnda < 100) and (bilAnda > bilTebak): print ("Yahhh... Masih salah, bilangan Anda terlalu besar") continue elif (bilAnda == bilTebak): print ("Selamatttt tebakan Anda tepat :>") break else : print ("Ingat yaa, bilangan 0 - 100 :D ") continue
print ("Program input nama mahasiswa") status = True a = [] while (status == True): namaMhs = str ( input ("Masukkan nama mahasiswa/i : ")) a.append(namaMhs) konfirmasi = input ("Apakah Anda ingin menambahkan lagi? (y/n) : ") a.sort() if (konfirmasi != 'y'): print() for data in a: print (data, "(", len(data), "karakter", ")") status = False
class Loja(object): def __init__(self, estoque, caixa): self.estoque = estoque self.caixa = caixa self.aluguelHora = 5 self.aluguelDia = 25 self.aluguelSemana = 100 self.aluguelFamilia = 0 def receberPedido(self, tipoAluguel, qtdeBike, periodo): self.estoque -= qtdeBike self.qtdeBike = qtdeBike self.tipoAluguel = tipoAluguel # tipoAluguel = H - hora, D - dia, S - semana self.periodo = periodo # Horas, Dias ou Semanas try: if qtdeBike < 0: raise ValueError("Quantidade inválida.") if qtdeBike > self.estoque: raise SystemError("Quantidade inválida.") if qtdeBike >= 3 <= 5: if tipoAluguel == "H" or tipoAluguel == "h": print(f"Bicicletaria - Aluguel de {self.qtdeBike} bikes por {periodo} hora(s). Você ganhou um desconto de 30% por ter escolhido nosso plano Familia.") return ((qtdeBike*(self.aluguelHora*periodo))*0.70) if tipoAluguel == "D" or tipoAluguel == "d": print(f"Bicicletaria - Aluguel de {self.qtdeBike} bikes por {periodo} dia(s). Você ganhou um desconto de 30% por ter escolhido nosso plano Familia.") return ((qtdeBike*(self.aluguelDia*periodo))*0.70) if tipoAluguel == "S" or tipoAluguel == "s": print(f"Bicicletaria - Aluguel de {self.qtdeBike} bikes por {periodo} semana(s). Você ganhou um desconto de 30% por ter escolhido nosso plano Familia.") return ((qtdeBike*(self.aluguelSemana*periodo))*0.70) if qtdeBike < 3: if tipoAluguel == "H" or tipoAluguel == "h": print(f"Bicicletaria - Aluguel de {self.qtdeBike} bike(s) do tipo {self.tipoAluguel} pelo periodo de {periodo} hora(s).") return (qtdeBike*(self.aluguelHora*periodo)) if self.tipoAluguel == "D" or tipoAluguel == "d": print(f"Bicicletaria - Aluguel de {self.qtdeBike} bike(s) do tipo {self.tipoAluguel} pelo periodo de {periodo} dia(s).") return (qtdeBike*(self.aluguelDia*periodo)) if self.tipoAluguel == "S" or tipoAluguel == "s": print(f"Bicicletaria - Aluguel de {self.qtdeBike} bike(s) do tipo {self.tipoAluguel} pelo periodo de {periodo} semana(s).") return (qtdeBike*(self.aluguelSemana*periodo)) else: print("Tipo de aluguel, quantidade ou período inválido.") except ValueError: print("Bicicletaria - Quantidade de bike inválida. Deve-se escolher uma quantidade de bikes para aluguel maior que zero.") return 0 except SystemError: print(f"Bicicletaria - Quantidade de bikes indisponivel em estoque. Escolha uma quantidade de acordo com a disponibilidade {self.estoque}.") return 0 except: print(f"Bicicletaria - Pedido não efetuado. Quantidade de bikes disponiveis para locação: {self.estoque}.") def receberPagamento(self, valorConta, valorPgto): try: if valorPgto <= 0 or valorConta <= 0: raise ValueError("Valor inválido") if valorConta == valorPgto: self.caixa += valorPgto print(f"Bicicletaria - O valor da conta é R$ {valorConta}. O valor pago foi R$ {valorPgto}. Obrigado e volte sempre!") return (valorConta - valorPgto) if valorConta < valorPgto: self.caixa += valorConta print(f"Bicicletaria - O valor da conta é R$ {valorConta}. O valor pago foi R$ {valorPgto}. O valor do troco é R$ {valorPgto - valorConta}.") return (valorPgto - valorConta) if valorPgto < valorConta: self.caixa += valorPgto print(f"Bicicletaria - O valor da conta é R$ {valorConta}. O valor pago foi R$ {valorPgto}. Portanto, ainda há um saldo de R$ {valorConta - valorPgto} em aberto.") return (valorConta - valorPgto) print("Extrato de Locação de Bicicleta") print("Tipo Plano\tQtdeBike\tDuração da Locação\t") except ValueError: print(f"Valor inválido. Valor da Conta: R$ {valorConta}. Valor Pago: R$ {valorPgto}.") return valorConta except: print("Aconteceu alguma coisa. Favor realizar o pagamento. ") return valorConta class Cliente(object): def __init__(self, nome, saldoContaCorrente): self.nome = nome self.saldoContaCorrente = saldoContaCorrente self.contaLocacao = 0.0 def alugarBike(self, qtdeBike, objetoBicicletaria): try: if qtdeBike <= 0: raise ValueError("Quantidade inválida. Por favor escolha a quantidade de Bike(s) que deseja alugar. ") if not isinstance(objetoBicicletaria, Loja): raise SystemError("Não recebeu uma Bicicletaria ") self.contaLocacao += objetoBicicletaria.receberPedido(qtdeBike, self.tipoAluguel, self.periodo) except ValueError: print(f"Cliente {self.nome}. Impossivel realizar o pedido pois a quantidade escolhida {qtdeBike} é inválida.") return 0 except SystemError: print(f"Cliente {self.nome}. Impossivel realizar o pedido pois a bicicletaria não é válida.") return 0 except: print(f"Cliente - {self.nome}. Pedido não efetuado. Conta {self.contaLocacao}") return 0 def pagarConta(self, valorPgto, objetoBicicletaria): try: if valorPgto <= 0: raise ValueError("Valor inválido") if valorPgto > self.saldoContaCorrente: raise ArithmeticError("Valor da conta superior ao saldo disponivel em conta corrente para pagamento. ") if not isinstance(objetoBicicletaria, Loja): raise SystemError("Não recebeu uma Bicicletaria ") self.saldoContaCorrente -= valorPgto divida = objetoBicicletaria.receberPagamento(self.contaLocacao, valorPgto) if divida == 0: self.contaLocacao = 0 if divida > 0: self.contaLocacao = divida else: self.saldoContaCorrente -= divida self.contaLocacao = 0 print(f"Cliente{self.nome} - Pagamento de R$ {valorPgto} da conta de R$ {self.contaLocacao} feito. Conta: R$ {self.contaLocacao}. Saldo conta corrente: R$ {self.saldoContaCorrente}") except ValueError: print(f"Cliente - {self.nome}. Pagamento da conta {self.contaLocacao} não foi efetuado. {valorPgto} deve ser compativel com o valor da conta {self.contaLocacao} ") return 0 except ArithmeticError: print(f"Cliente - {self.nome}. Pagamento da conta {self.contaLocacao} não foi efetuado. {valorPgto} superior ao saldo da conta corrente {self.saldoContaCorrente} ") return 0 except SystemError: print(f"Cliente - {self.nome}. Pagamento da conta {self.contaLocacao} não foi efetuado pois a bicicletaria não é válida. Valor pagamento {valorPgto}. Saldo em conta {self.contaLocacao}. ") return 0 except: print(f"Cliente - {self.nome}. Pagamento da conta {self.contaLocacao} não foi efetuado. Conta {self.contaLocacao}, saldo conta corrente {self.saldoContaCorrente} ") return 0
""" This module contains functionality to retrieve the information needed to communicate with the ETC lwm2m server. Use it to obtain the lwm2m host name, identity, secret key, and endpoint. """ import http import binascii GET_LWM2M_SECURITY_INFO = 'GET_LWM2M_SECURITY_INFO' class RetVals: ''' Defines a set of integer constants for the values that can be returned by :py:func:`get_lwm2m_security_info`. Use these values to check the return value of :py:func:`get_lwm2m_security_info` to see if the operation was successful. ''' SUCCESS = 0 #: Indicates function was successful COMMUNICATION_ERROR = 18 #: Indicates function was unable to communicate with api server INTERNAL_SOFTWARE_ERROR = 19 #: Indicates an unknown software error has occurred def get_lwm2m_security_info(): """ This function will return the lwm2m host name, identity, secret key, and endpoint. **Returns**: A tuple of two entries :code:`(return_value, lwm2m_info)` * return_value: One of the integer values defined in :py:class:`RetVals` * lwm2m_info: A dictionary with the following format .. code:: python {'LWM2M_IDENTITY': bytearray, 'LWM2M_HOST_NAME': string, 'LWM2M_SECRET_KEY': bytearray, 'LWM2M_ENDPOINT': string} **Code Example:** .. code:: return_value, lwm2m_info = lwm2m.get_lwm2m_security_info() if return_value == lwm2m.RetVals.SUCCESS: identity = lwm2m_info['LWM2M_IDENTITY'] host_name = lwm2m_info['LWM2M_HOST_NAME'] secret_key = lwm2m_info['LWM2M_SECRET_KEY'] endpoint_name = lwm2m_info['LWM2M_ENDPOINT'] """ _, return_value, lwm2m_info = http.perform_get(GET_LWM2M_SECURITY_INFO) lwm2m_info["LWM2M_HOST_NAME"] = lwm2m_info["LWM2M_HOST_NAME"].encode("utf-8") lwm2m_info["LWM2M_ENDPOINT"] = lwm2m_info["LWM2M_ENDPOINT"].encode("utf-8") lwm2m_info["LWM2M_IDENTITY"] = bytearray(lwm2m_info["LWM2M_IDENTITY"].encode("utf-8"), 'utf8') lwm2m_info["LWM2M_SECRET_KEY"] = bytearray(binascii.a2b_hex(lwm2m_info["LWM2M_SECRET_KEY"].encode("utf-8"))) return return_value, lwm2m_info
'''This file contains all the functions responsible for mashing the various analysis results into the format that the result that the rest of the project is expecting (two keyword lists with tuples of keyword and weight). This is what implements the actual analyse function that we export in __init__.py ''' import nltk from keywords import extract_keywords from sentiment import analyse_sentiment from common import * #### TODO: # Do some sort of stemming somewhere around here (at least stem # away plurals!) or alternatively at the end of # extract_keywords. Also see non_aggressive_stemmer in # extract_keywords which aims to be the same thing but isn't # maybe we should focus on that # Some sort of database of keyword implications. like # pottermore -> harry potter, justin beaver -> justin bieber. # Probably weighted a percentage (0.8 or so) of the original keywords' weight def analyse_sentence(sentence): '''Takes a tweet and performs sentiment analysis on the given tweet, then gives the weight that was returned from the sentiment analysis TODO: Is this function neccesary? HALF-DEPRECATED''' sentiment = analyse_sentiment(sentence) keywordtuples = extract_keywords(sentence) return [(keyword,sentiment*weight) for (keyword,weight) in keywordtuples] def analyse_sentences_var_1(sentences): '''Does analysis of all sentences and returns a compilation of all results in the form of two lists in the magical and fantastical format we all know and love. ...''' hatekeywords = {} lovekeywords = {} for sentence in sentences: sentiment = analyse_sentiment(sentence) for (keyword, weight) in extract_keywords(sentence): a = lovekeywords if sentiment > 0.0 else hatekeywords # choose where to put keyword a[keyword] = a.get(keyword, 0.0) + weight*abs(sentiment) # only positive weights in end result return (lovekeywords.items(), hatekeywords.items()) def analyse_sentences_var_2_helper(sentences): '''Does analysis of all sentences and returns a compilation of all results in the form of one list of tuples where the weight might be negative or positive depending on the overall sentiment around the keyword.''' keywords = {} for sentence in sentences: for (keyword, weight) in analyse_sentence(sentence): keywords[keyword] = keywords.get(keyword, 0.0) + weight return keywords.items() def splittify(keywords): '''Takes a list of keywords with positive/negative weights and returns two lists on with all the keywords that had positive weigths and one with all the negative (or 0) weights.''' # Homework for the ones interested in the perversions of lists and functional # programming. (This just might be the Haskell way to do it..., or Lisp for that matter). return tuple(map(lambda x: list(filter(lambda a: a != None, x)), apply(zip, [((k,w), None) if w > 0.0 else (None, (k,-w)) for (k,w) in keywords]))) def analyse_sentences_var_2(sentences): '''This doesn't count love and hate separately but tries to, for each keyword, get only one value which is the total amount of love minus the total amount of hate (typing this felt kind of wierd...).''' a = splittify(analyse_sentences_var_2_helper(sentences)) return ([], []) if not a else a def analyse(tweets): '''Do the whole analysis shebang and return the results as one lovekeyword list and one hatekeyword list. Ex: (love, hate) = analyse(tweets) print love => [("cat", 34), ("fishing", 22), ("bear grylls", 33)] print hate => [("dog", 123), ("bear hunting", 44)]''' # print tweets # print map(nltk.sent_tokenize,tweets) # print reduce(lambda x,y: x+y,[['tweetlist'], ['lol dont like apples'], ['like reading books']]) #reduce(lambda x,y: x+y,map(nltk.sent_tokenize, tweets)) # split the list of tweets to a list of sentences and send it to analyse_sentences return analyse_sentences_var_2(reduce(lambda x,y: x+y, map(nltk.sent_tokenize, filter(isenglish, tweets)), [])) if __name__ == "__main__": print analyse(["Star Wars is the movie of the century","Bear Grylls is being tortured by us more and more"])
# Logistic Regression # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd import seaborn as sns # Importing the dataset featured_data = pd.read_excel('survey - USSD among FIsher women - final.xlsx') X = featured_data[['age','Education','Average Per day sales','Operate SMS','Debit Card','Heard about USSD','Customer request for digital payment','Traning for Mobile Banking']] Y = featured_data['Willingness to use Mobile Banking'] # Splitting the dataset into the Training set and Test set from sklearn.cross_validation import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size = 0.25, random_state = 0) # Feature Scaling from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_train = sc.fit_transform(X_train) X_test = sc.transform(X_test) # Fitting Logistic Regression to the Training set from sklearn.linear_model import LogisticRegression classifier = LogisticRegression(random_state = 0) classifier.fit(X_train, y_train) coff = classifier.coef_ print(coff) # Predicting the Test set results y_pred = classifier.predict(X_test) print(y_pred) # Making the Confusion Matrix from sklearn.metrics import confusion_matrix cm = confusion_matrix(y_test, y_pred) print(cm)
#program to print if the year is leap or not '''year = int(input("Enter the year : ")) if year% 4 == 0: print(year, "is a leap year") else: print(year, "is not a leap year") #progran to print multiplication table intered by the user a = int(input("Enter number for which the table is required : ")) for i in range(1,11): print(a ,"*", i, "=", a*i )''' #program to add 10 numbers using only one input statement add them to list '''list = [] i=1 while i <=10: a = input("Enter #" + str(i)) if a.isnumeric(): list.append(a) i = i+1 else: print(a, "is not in list") print("List of numbers = ", list)''' ## program to create a form name = input("Enter your name : ") age = input("Enter your age : ") mob_num = input("Enter mobile number : ") while True: if name =="": name = input("Name cannot be empty, enter your name again : ") elif name.isalpha() == False: name = input("Name can contain only alphabets, enter your name again : ") else: if age =="": age= input("age cannot be empty, enter your age again : ") elif age.isdigit() == False: age = input("Age can contain only numbers, enter your age again : ") elif int(age) < 19: age = input("Age can only be over 18, enter your age again : ") else: if mob_num =="": mob_num = input("Mobile number cannot be empty, enter your number again : ") elif mob_num.isdigit() == False: mob_num = input("Mobile Number can contain only numbers, enter your number again : ") else: print("Name = ", name , "\nAge = ", age, "\nMobile Number = ", mob_num) break #list of the list list = [23, 11, 69, 12, 34, 2, 6, 23, 43, 1233, 23, 222, 69, 23] print("list is ", list) a = int(input("Enter number to be removed")) for x in list: if x == a: list.remove(x) print("new list is", list)
def search(arr, n): while len(arr) > 0: midpoint = len(arr) / 2 if arr[midpoint] == n: return True elif arr[midpoint] > n: arr = arr[:midpoint] else: arr = arr[(midpoint + 1):] return False print search([1, 2, 3, 4, 5], 1) print search([1, 2, 3, 4, 5], 0)
#With a single integer as the input, generate the following until a = x [series of numbers as shown in below examples] a=int(input("enter a number")) num=1 lst=[] while len(lst)<a: if(num%2 !=0): lst.append(num) num+=1 print(lst)
# A queue based on two stacks class MyQueue(object): def __init__(self): self.vals = [[], []] def enqueue(self, val): self.vals[0].append(val) def _move(self): while len(self.vals[0]) > 0: self.vals[1].append(self.vals[0].pop()) def dequeue(self): if len(self.vals[1]) == 0: self._move() if len(self.vals[1]) > 0: return self.vals[1].pop() def size(self): return len(self.vals[0]) + len(self.vals[1]) def peek(self): if len(self.vals[1]) == 0: self._move() if len(self.vals[1]) > 0: return self.vals[1][-1] if __name__ == "__main__": q = MyQueue() for i in range(10): q.enqueue(i) for i in range(5): assert q.dequeue() == i assert q.peek() == 5 assert q.size() == 5
from collections import defaultdict def _count_paths(x, y, obstacles, memo=None): if memo is None: memo = defaultdict(int) if obstacles is not None and (x, y) in obstacles: return 0 if (x, y) in memo: return memo[(x, y)] elif x == 0 and y == 0: memo[(x, y)] = 1 return 1 elif x < 0 or y < 0: memo[(x, y)] = 0 return 0 return _count_paths(x - 1, y, obstacles, memo) + _count_paths(x, y - 1, obstacles, memo) def count_paths(N, obstacles=None): return _count_paths(N - 1, N - 1, obstacles) if __name__ == "__main__": print count_paths(3, [(1, 1)])
def _compress_intervals(intervals): if len(intervals) == 1: return intervals else: cur = intervals[0] rest = _compress_intervals(intervals[1:]) if cur[1] >= rest[0][0] and cur[1] < rest[0][1]: if cur[0] < rest[0][0]: rest[0][0] = cur[0] else: rest.insert(0, cur) return rest def is_covered(l, q): sorted_intervals = sorted(l, key=lambda item: item[1]) compressed_intervals = _compress_intervals(sorted_intervals) if compressed_intervals is not None: for interval in compressed_intervals: if q[0] >= interval[0] and q[1] < interval[1]: return True return False if __name__ == "__main__": l = [[1, 6], [3, 5], [7, 9]] q1 = (2, 4) q2 = (5, 7) assert is_covered(l, q1) == True assert is_covered(l, q2) == False
class SetOfStacks(object): def __init__(self, capacity=10): self.stack_set = [[]] self.cur = 0 self.capacity = capacity def push(self, val): if len(self.stack_set[self.cur]) >= self.capacity: self.stack_set.append([]) self.cur += 1 self.stack_set[self.cur].append(val) def pop(self, index=None): if index is None: index = self.cur val = None if len(self.stack_set[index]) > 0: val = self.stack_set[index].pop() if len(self.stack_set[index]) == 0 and self.cur > 0: self.stack_set.pop(index) self.cur -= 1 return val def pop_at(self, index): if type(index) is int and index >= 0 and index <= self.cur: return self.pop(index) if __name__ == "__main__": s = SetOfStacks() assert s.cur == 0 for i in range(30): s.push(i) assert s.cur == 2 for i in [19, 18, 17, 16, 15, 14, 13, 12, 11, 10]: assert s.pop_at(1) == i assert s.cur == 1 assert s.pop() == 29
# Given two sorted arrays, A and B, with A having enough buffer at the end to hold B, merges B into A in sorted order. def merge_sorted_arrays(A, B): cur_A = len(A) - len(B) - 1 cur_B = len(B) - 1 cur = len(A) - 1 while cur_A >= 0 and cur_B >= 0: if A[cur_A] > B[cur_B]: A[cur] = A[cur_A] cur_A -= 1 else: A[cur] = B[cur_B] cur_B -= 1 cur -= 1 if __name__ == "__main__": A = [10, 15, 18, 20, 21, 23, 25, None, None, None, None, None, None] B = [9, 11, 12, 13, 15, 16] merge_sorted_arrays(A, B) print A
class TowersOfHanoi(object): '''Implementation of Towers of Hanoi using lists as stacks.''' def __init__(self, num_disks): # Declare three stacks to represent the three rods self.towers = [[], [], []] # Initialize first rod with disks. Numbers represent disk size # with larger numbers signifying larger disks. append == push for disk in range(num_disks, 0, -1): self.towers[0].append(disk) def move(self, n, src=0, aux=1, dest=2): if n > 0: self.move(n - 1, src, dest, aux) self.towers[dest].append(self.towers[src].pop()) self.move(n - 1, aux, src, dest) if __name__ == "__main__": num_disks = 5 towers = TowersOfHanoi(5) print towers.towers towers.move(num_disks) print towers.towers
def _paint_fill(screen, x, y, color, new_color): if x >= 0 and x < len(screen) and y >= 0 and y < len(screen[0]) and screen[x][y] == color: screen[x][y] = new_color _paint_fill(screen, x - 1, y, color, new_color) _paint_fill(screen, x + 1, y, color, new_color) _paint_fill(screen, x, y - 1, color, new_color) _paint_fill(screen, x, y + 1, color, new_color) def paint_fill(screen, x, y, new_color): _paint_fill(screen, x, y, screen[x][y], new_color) if __name__ == "__main__": screen = [[0, 0, 0, 0], [0, 1, 1, 0], [0, 1, 1, 0], [0, 0, 0, 0]] paint_fill(screen, 0, 0, 2) print screen
#!/usr/bin/env python3 # created by: Ryan Walsh # created on: November 2020 # this program calculates numbers inserted by user def main(): # this program calculates numbers inserted by user # input first_number = int(input("Enter the first number:")) second_number = int(input("Enter the second number:")) # process total = first_number + second_number # output print() print("{0} + {1} = {2}".format(first_number, second_number, total)) if __name__ == "__main__": main()
#! /usr/bin/env python3 #-*- conding utf-8 -*- from PIL import Image import os """ This module contain the function: -black_and_white : Transform the image passed as parameter in a black and white Image, also called greyscale """ def black_and_white(img): """ for each pixel of the img the average of it's RGB component is applied to each RGB component wich result in a darker or brighter grey """ px = img.load() size_x, size_y = img.size for y in range (size_y): for x in range (size_x): ppx = px[x,y] average = int((ppx[0] + ppx[1] + ppx[2]) / 3) px[x,y] = (average, average, average) def GreyScale(img): """ Same result but faster and not mine :/ """ img.paste(img.convert("L")) if __name__ == "__main__": img = Image.open("../image/spidey.jpg") print ("Black and White : \n") black_and_white(img) img.show() os.system("pause")
import cs50 import csv from sys import argv, exit if len(argv) != 2: print("Usage: python3 import.py characters.csv") exit(1) db = cs50.SQL("sqlite:///students.db") the_characters = [] with open(argv[1], "r") as the_characters_csv: the_characters_reader = csv.DictReader(the_characters_csv) for row in the_characters_reader: the_characters.append(row) the_current_id = 1 for i in the_characters: the_current_name = i["name"].split(" ") the_current_house = i["house"] the_current_birth = int(i["birth"]) if len(the_current_name) == 2: db.execute("INSERT INTO students VALUES (?, ?, ?, ?, ?, ?);", the_current_id, the_current_name[0], None, the_current_name[1], the_current_house, the_current_birth) else: db.execute("INSERT INTO students VALUES (?, ?, ?, ?, ?, ?);", the_current_id, the_current_name[0], the_current_name[1], the_current_name[2], the_current_house, the_current_birth) the_current_id += 1 print(the_current_id, the_current_name, the_current_house, the_current_birth) # print(the_characters)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # python library for google earth plot # # author: Atsushi Sakai # # Copyright (c): 2015 Atsushi Sakai # # License : GPL Software License Agreement import simplekml import pandas import math class googleearthplot(object): def __init__(self): self.kml = simplekml.Kml() def PlotLineChartFromCSV(self, filepath, name="", color="red", width=5): """ Plot Line Chart from CSVfile """ print("[PlotLineChartFromCSV] plotting a line chart from csv file:" + filepath) data = pandas.read_csv(filepath) if "height" in data: self.PlotLineChart(data["lat"], data["lon"], heightList=data["height"], name=name, color=color, width=width) else: self.PlotLineChart(data["lat"], data["lon"], name=name, color=color, width=width) def PlotPoints(self, lat, lon, label, description="", color="red", labelScale=1, time="", id=""): """ Plot only label """ pnt = self.kml.newpoint(name=label, description=description ) pnt.coords = [(lat, lon)] pnt.style.labelstyle.color = self.GetColorObject(color) pnt.style.labelstyle.scale = labelScale pnt.timestamp.when = time print("[PlotPoint]" + label + ",lat:" + str(lat) + ",lon:" + str(lon) + ",time" + time) def PlotLineChart(self, latList, lonList, heightList=[], name="", color="red", width=5, altMode='relativeToGround'): """ Plot Line Chart """ ls = self.kml.newlinestring( name=name, description=name ) coords = [] if len(heightList) == 0: for (lat, lon) in zip(latList, lonList): coords.append((lon, lat)) else: for (lat, lon, height) in zip(latList, lonList, heightList): coords.append((lon, lat, height)) altModes = { 'absolute': simplekml.AltitudeMode.absolute, 'clampToGround': simplekml.AltitudeMode.clamptoground, 'relativeToGround': simplekml.AltitudeMode.relativetoground } ls.coords = coords ls.extrude = 1 ls.altitudemode = altModes[altMode] ls.style.linestyle.width = width ls.style.linestyle.color = self.GetColorObject(color) print("[PlotLineChart]name:" + name + ",color:" + color + ",width:" + str(width)) def PlotBarChart(self, lat, lon, num, size=1, name="", color="red", addLabel=False): """ Add Bar Chart size: unit:meterm, defalut:1m name: data name, default:""(empty string) color: bar chart color, default:red """ pol = self.kml.newpolygon( name=name, extrude=1, tessellate=1, description=str(num), visibility=1, # gxballoonvisibility=1, altitudemode="absolute" ) latShift = self.CalcLatFromMeter(size) lonShift = self.CalcLonFromMeter(size, lat) boundary = [] boundary.append((lon + lonShift, lat + latShift, num)) boundary.append((lon - lonShift, lat + latShift, num)) boundary.append((lon - lonShift, lat - latShift, num)) boundary.append((lon + lonShift, lat - latShift, num)) boundary.append((lon + lonShift, lat + latShift, num)) pol.outerboundaryis = boundary # Set Color colorObj = self.GetColorObject(color) pol.style.linestyle.color = colorObj pol.style.polystyle.color = colorObj if addLabel: self.PlotLabel(lat, lon, name + ":" + str(num), color=color) print("[PlotBarChart]lat:" + str(lat) + ",lon:" + str(lon)) def PlotLabel(self, lat, lon, label, color="red", labelScale=1): """ Plot only label """ pnt = self.kml.newpoint(name=label) pnt.coords = [(lon, lat)] pnt.style.labelstyle.color = self.GetColorObject(color) pnt.style.labelstyle.scale = labelScale pnt.style.iconstyle.scale = 0 # hide icon print("[PlotLabel]" + label) def PlotBarChartsFromCSV(self, filepath, addLabel=False): """ filepath: csvfile path """ print("[PlotBarChartsFromCSV]plotting bar charts from csv file:" + filepath) data = pandas.read_csv(filepath) # PlotBarChart nbar = 0 zipdata = zip(data["lat"], data["lon"], data["num"], data["size"], data["name"], data["color"]) for (lat, lon, num, size, name, color) in zipdata: self.PlotBarChart(lat, lon, num, size, name, color, addLabel=addLabel) nbar += 1 print("[PlotBarChartsFromCSV]" + str(nbar) + " bars have plotted") def PlotOverlayImg(self, filepath, xpixel, ypixel, name="ScreenOverlay"): """ filepath: file path xpixel ypixel name (option) """ print("[PlotOverlayImg] plotting image file:" + filepath + ",xpixel:" + str(xpixel) + ",ypixel" + str(ypixel)) screen = self.kml.newscreenoverlay(name=name) screen.icon.href = filepath screen.overlayxy = simplekml.OverlayXY(x=0, y=0, xunits=simplekml.Units.fraction, yunits=simplekml.Units.fraction) screen.screenxy = simplekml.ScreenXY(x=xpixel, y=ypixel, xunits=simplekml.Units.pixel, yunits=simplekml.Units.insetpixels) screen.size.x = -1 screen.size.y = -1 screen.size.xunits = simplekml.Units.fraction screen.size.yunits = simplekml.Units.fraction def GetColorObject(self, color): valiableStr = "simplekml.Color." + color colorObj = eval(valiableStr) return colorObj def CalcLatFromMeter(self, shift): return shift / 111263.283 # degree def CalcLonFromMeter(self, shift, lon): const = 6378150 * math.cos(lon / 180 * math.pi) * 2 * math.pi / 360 return shift / const # degree def GenerateKMLFile(self, filepath="sample.kml"): """Generate KML File""" self.kml.save(filepath) def PlotPlaneMovie(self, latList, lonList, heightList, headingList, deltatList, name="", timestretch=0.1, tilt=90.0, roll=0.0): tour = self.kml.newgxtour(name="Play me") playlist = tour.newgxplaylist() animatedupdate = playlist.newgxanimatedupdate(gxduration=1.0) for (lat, lon, height, heading, deltat) in zip(latList, lonList, heightList, headingList, deltatList): flyto = playlist.newgxflyto(gxduration=(timestretch * deltat), gxflytomode='smooth') flyto.camera.longitude = lon flyto.camera.latitude = lat flyto.camera.altitude = height flyto.camera.heading = heading flyto.camera.tilt = tilt flyto.camera.roll = roll if height == 0: flyto.camera.altitudemode = simplekml.AltitudeMode.clamptoground else: flyto.camera.altitudemode = simplekml.AltitudeMode.absolute print("[PlotPlaneMovie]name:" + name + " timestretch:" + str(timestretch) + " tilt:" + str(tilt) + " roll:" + str(roll)) if __name__ == '__main__': # A bar plot gep1 = googleearthplot() lon = 18.333868 # degree lat = -34.038274 # degree num = 100 # bar height size size = 1 # meter name = "barsample" color = "red" gep1.PlotBarChart(lat, lon, num, size, name, color) gep1.GenerateKMLFile(filepath="sample1.kml") # bar plot from csv file gep = googleearthplot() gep.PlotBarChartsFromCSV("sampledata/barchartsampledata.csv") gep.GenerateKMLFile(filepath="sample2.kml") # Plot line chart gep2 = googleearthplot() lat = [-77.6192, -77.6192, -77.6195, -77.6198, -77.6208, -77.6216, -77.6216, -77.6216] lon = [43.1725, 43.1725, 43.1728, 43.173, 43.1725, 43.1719, 43.1719, 43.1719, 43.1719] gep2.PlotLineChart(lat, lon, name="trajectory", color="pink") gep2.GenerateKMLFile(filepath="sample3.kml") # Plot line chart with height gep3 = googleearthplot() lat = [43.1725, 43.1725, 43.1728, 43.173, 43.1725, 43.1719, 43.1719] lon = [-77.6192, -77.6192, -77.6195, -77.6198, -77.6208, -77.6216] height = [10, 40, 60, 80, 100, 120, 140] gep3.PlotLineChart(lat, lon, heightList=height, name="trajectory2", color="aqua") gep3.GenerateKMLFile(filepath="sample4.kml") # line plot from csv file gep4 = googleearthplot() gep4.PlotLineChartFromCSV("sampledata/lineplotsampledata.csv", name="trajectory3", color="gold", width=10) gep4.GenerateKMLFile(filepath="sample5.kml") # line plot from csv file with height gep5 = googleearthplot() gep5.PlotLineChartFromCSV("sampledata/lineplotsampledata2.csv", name="trajectory4", color="orange", width=10) gep5.GenerateKMLFile(filepath="sample6.kml") # bar plot with label from csv file gep7 = googleearthplot() gep7.PlotBarChartsFromCSV("sampledata/barchartsampledata.csv", addLabel=True) gep7.GenerateKMLFile(filepath="sample7.kml") # Plot overlay image sample gep8 = googleearthplot() gep8.PlotOverlayImg("img/samplelogo.png", 200, 300, name="logo") gep8.GenerateKMLFile(filepath="sample8.kml") # Plot point lon = 18.333868 # degree lat = -34.038274 # degree gep9 = googleearthplot() gep9.PlotPoints(lat, lon, "point") gep9.GenerateKMLFile(filepath="sample9.kml") # Plot point chart gep10 = googleearthplot() lat = [ -77.6192, -77.6195, -77.6198, -77.6208, -77.6216] lon = [43.1725, 43.1728, 43.173, 43.1725, 43.1719, 43.1719] for (ilat,ilon) in zip(lat,lon): gep10.PlotPoints(ilat, ilon, "point") gep10.GenerateKMLFile(filepath="sample10.kml")
import numpy as np import cv2 as cv img = cv.imread("D:\Code\MyCode\img\logo.png") print(img.shape) res = cv.resize(img,None,fx=2, fy=2, interpolation = cv.INTER_CUBIC) print(res.shape) #或者 height, width = img.shape[:2] res = cv.resize(img,(2*width, 2*height), interpolation = cv.INTER_CUBIC) print(res.shape)
def F(x): if x == 0: l = 1 elif x == 1: l = 3 elif x ==2: l = 2 else: l = F(x-1)*F(x-3) return l
def main(): tupla = (3, 4, 'Não') tupla2 = 3, 4, 6, 'Sim', True print(tupla) print(tupla2) #vc usa tupla pra retornar valores que precisam de uma maior quantidade de retorno. main()
class Carro(object): tipo = None def __init__(self, caminho): self.caminho = caminho def andar(self): print('Andando pela', self.caminho) class Fusca(Carro): tipo = "Fusca" def correr(self): super(Fusca, self).andar() class Ferrari(Carro): tipo = "Ferrari" def andar(self): print('Correndo pra kct', 'pelo', self.caminho)
delattr(object, name) This is a relative of setattr(). The arguments are an object and a string. The string must be the name of one of the object’s attributes. The function deletes the named attribute, provided the object allows it. For example, delattr(x, 'foobar') is equivalent to del x.foobar.
""" filter(function,iterable)¶ Construct a list from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If iterable is a string or a tuple, the result also has that type; otherwise it is always a list. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed. Note that filter(function, iterable) is equivalent to [item for item in iterable if function(item)] if function is not None and [item for item in iterable if item] if function is None. The docs for python 3 say it returns an iterator "Construct an iterator from those elements of iterable for which function returns true." In python 2 it returned a list: see here. """
xrange(start,stop[,step]) This function is very similar to range(), but returns an xrange object instead of a list. This is an opaque sequence type which yields the same values as the corresponding list, without actually storing them all simultaneously. The advantage of xrange() over range() is minimal (since xrange() still has to create the values when asked for them) except when a very large range is used on a memory-starved machine or when all of the range’s elements are never used (such as when the loop is usually terminated with break). range creates a list, so if you do range(1, 10000000) it creates a list in memory with 10000000 elements. xrange is a generator, so it is a sequence object is a that evaluates lazily. One difference is that from versions of Python 3.0 and later, xrange doesn't exist, and range takes over the behavior of what was formerly xrange. So presumably you're asking about Python 2.x In Python 2.x, range() generates a list, possibly a very large one. Sometimes that's exactly what you need. But other times, you're just using the list as an iterable, perhaps as a counter, or simply as a way to make a loop go a fixed number of times. xrange(), usually more efficient for speed, and certainly for space, generates an iterable. So it's interchangeable in a for loop, for example. In general, if you're going to discard the list immediately after using it, you should be using the iterable form, not the list form. In Python 3.x, if you really need a list, you can trivially convert an iterable into a list with the list "function." mylist = list(range(4))
list([iterable]) Return a list whose items are the same and in the same order as iterable‘s items. iterable may be either a sequence, a container that supports iteration, or an iterator object. If iterable is already a list, a copy is made and returned, similar to iterable[:]. For instance, list('abc') returns ['a', 'b', 'c'] and list( (1, 2, 3) ) returns [1, 2, 3]. If no argument is given, returns a new empty list, []. list is a mutable sequence type, as documented in Sequence Types — str, unicode, list, tuple, bytearray, buffer, xrange. For other containers see the built in dict, set, and tuple classes, and the collections module.
""" repr(object) The str() function is meant to return representations of values which are fairly human-readable, while repr() is meant to generate representations which can be read by the interpreter (or will force a SyntaxError if there is no equivalent syntax) Return a string containing a printable representation of an object. This is the same value yielded by conversions (reverse quotes). It is sometimes useful to be able to access this operation as an ordinary function. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a __repr__() method. MORE: http://stackoverflow.com/questions/1436703/difference-between-str-and- repr-in-python ======== This is usually a question asked in many Python interviews: What is the difference between the __str__ and __repr__ methods of a Python object. The same question was asked by one of my colleagues, which got me researching. In short __repr__ goal is to be unambigous and __str__ is to be readable. The official Python documentation says __repr__ is used to compute the “official” string representation of an object and __str__ is used to compute the “informal” string representation of an object. The print statement and str() built-in function uses __str__ to display the string representation of the object while the repr() built-in function uses __repr__ to display the object. Using this definition let us take an example to understand what the two methods actually do. Lets create a datetime object: >>> import datetime today = datetime.datetime.now() When I use the built-in function str() to display today: >>> str(today) '2012-03-14 09:21:58.130922' You can see that the date was displayed as a string in a way that the user can understand the date and time. Now lets see when I use the built-in function repr(): >>> repr(today) 'datetime.datetime(2012, 3, 14, 9, 21, 58, 130922)' You can see that this also returned a string but the string was the “official” representation of a datetime object. What does official mean? Using the “official” string representation I can reconstruct the object: >>> eval('datetime.datetime(2012, 3, 14, 9, 21, 58, 130922)') datetime.datetime(2012, 3, 14, 9, 21, 58, 130922) The eval() built-in function accepts a string and converts it to a datetime object. Most functions while trying to get the string representation use the __str__ function, if missing uses __repr__. Thus in a general every class you code must have a __repr__ and if you think it would be useful to have a string version of the object, as in the case of datetime create a __str__ function. """
with open('file.txt', 'r') as f: # do stuff with f pass """ Python allows putting multiple open() statements in a single with. You comma-separate them. """ with open(newfile, 'w') as outfile, open(oldfile, 'r', encoding='utf-8') as infile: pass """ The argument mode points to a string beginning with one of the following sequences (Additional characters may follow these sequences.): ``r'' Open text file for reading. The stream is positioned at the beginning of the file. ``r+'' Open for reading and writing. The stream is positioned at the beginning of the file. ``w'' Truncate file to zero length or create text file for writing. The stream is positioned at the beginning of the file. ``w+'' Open for reading and writing. The file is created if it does not exist, otherwise it is truncated. The stream is positioned at the beginning of the file. ``a'' Open for writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subsequent writes to the file will always end up at the then current end of file, irrespective of any intervening fseek(3) or similar. ``a+'' Open for reading and writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subse- quent writes to the file will always end up at the then current end of file, irrespective of any intervening fseek(3) or similar. """
hex(x) Convert an integer number (of any size) to a lowercase hexadecimal string prefixed with “0x”, for example: >>> >>> hex(255) '0xff' >>> hex(-42) '-0x2a' >>> hex(1L) '0x1L' If x is not a Python int or long object, it has to define an __index__() method that returns an integer. See also int() for converting a hexadecimal string to an integer using a base of 16.
def lineformater(phrase): intro = ("who","why","why","how") if phrase.startswith(intro): return f"{phrase.capitalize()}?" else : return f"{phrase.capitalize()}." fineline = [] while True: user_input = input("say to format") if user_input == "\end": break else: fineline.append(lineformater(user_input)) #lol print(" ".join(fineline))
def jogar(): print("*********************************") print("***Bem vindo ao jogo da Forca!***") print("*********************************") palavra_secreta = "python" letras_acertadas = ["_","_","_","_","_","_"] enforcou = False acertou = False print("A palavra secreta contem {} letras".format(len(letras_acertadas))) print(letras_acertadas) while (not enforcou and not acertou ): chute = input ("Qual a letra?: ") chute = chute.strip() index = 0 for letra in palavra_secreta: if (chute.upper() == letra.upper()): letras_acertadas[index] = letra index = index + 1 print(letras_acertadas) print("Fim do jogo") if(__name__ == "__main__"): jogar()
# This is the number we'll find the factorial of - change it to test your code! number = 6 # We'll start with the product equal to the number product = number # TODO: Write a for loop that calculates the factorial of our number for i in range(1,number,1): product = product*i # TODO: print the factorial of your number print(product)
from tkinter import * from tkinter import messagebox from random import randint """ MINE SWEEPER GAME """ class initialScreen(): """ initial screen """ def __init__(window): window.root = Tk() window.root.title("Start Game") window.root.grid() window.finish = "N" """ screen size """ window.height = 8 window.width = 8 window.mines = 8 window.startbutton = Button(text="Begin Mine Sweeper Game", command=lambda: initialScreen.onclick(window)) window.startbutton.grid(column=4, row=5) window.root.mainloop() """ cancel button """ def onclick(window): window.finish = "Y" window.root.destroy() return window """ screen for the game """ class gameWindow(): def __init__(s, setup): s.height = setup.height s.width = setup.width s.mines = setup.mines s.root = Tk() s.root.title("Minesweeper") s.root.grid() l1 = Label(s.root, text="First:") s.finish = "N" s.maingrid = list() s.maingrid.append([]) for i in range(s.height): s.maingrid.append([]) for x in range(s.width): s.maingrid[i].append(" ") s.maingrid[i][x] = Button(height=0, width=3, font="TimesNewRoman 15 bold", text="*", bg="green", command=lambda i=i, x=x: gameWindow.onclick(s, i, x)) s.maingrid[i][x].bind("<Button-3>", lambda event="<Button-3>", i=i, x=x: gameWindow.rightclick(event, s, i, x)) s.maingrid[i][x].grid(row=i, column=x) s.maingrid[i][x].mine = "False" totals_squares = s.height * s.width s.scores_needed = totals_squares - s.mines s.score = 0 index_list = list() for i in range(totals_squares): index_list.append(i) """ storage of spaces chosen """ spaces_chosen = list() for i in range(s.mines): chosen_space = randint(0, len(index_list) - 1) spaces_chosen.append(index_list[chosen_space]) del index_list[chosen_space] for i in range(len(spaces_chosen)): xvalue = int(spaces_chosen[i] % s.width) ivalue = int(spaces_chosen[i] / s.width) s.maingrid[ivalue][xvalue].mine = "True" s.root.mainloop() """ when user clicks on the grid """ def onclick(s, i, x): color_list = ["PlaceHolder", "Green", "Black", "Blue", "Gray", "Red", "Purple", "Turquoise", "Maroon"] if s.maingrid[i][x]["text"] != "F" and s.maingrid[i][x]["relief"] != "sunken": if s.maingrid[i][x].mine == "False": s.score += 1 combinationsi = [1, -1, 0, 0, 1, 1, -1, -1] combinationsx = [0, 0, 1, -1, 1, -1, 1, -1] mine_count = 0 for combinations in range(len(combinationsi)): tempi = i + combinationsi[combinations] tempx = x + combinationsx[combinations] if tempi < s.height and tempx < s.width and tempi >= 0 and tempx >= 0: if s.maingrid[tempi][tempx].mine == "True": mine_count = mine_count + 1 if mine_count == 0: mine_count = "" s.maingrid[i][x].configure(text=mine_count, relief="sunken", bg="gray85") if str(mine_count).isdigit(): s.maingrid[i][x].configure(fg=color_list[mine_count]) if mine_count == "": for z in range(len(combinationsi)): if s.finish == "N": i_value = i + int(combinationsi[z]) x_value = x + int(combinationsx[z]) if i_value >= 0 and i_value < s.height and x_value >= 0 and x_value < s.width: if s.maingrid[i_value][x_value]["relief"] != "sunken": gameWindow.onclick(s, i_value, x_value) if s.score == s.scores_needed and s.finish == "N": messagebox.showinfo("Congratulations", "You won") s.finish = "Y" s.root.destroy() else: s.maingrid[i][x].configure(bg="Red", text="M") for a in range(len(s.maingrid)): for b in range(len(s.maingrid[a])): if s.maingrid[a][b].mine == "True": if s.maingrid[a][b]["text"] == "F": s.maingrid[a][b].configure(bg="Green") elif s.maingrid[a][b]["bg"] != "Red": s.maingrid[a][b].configure(bg="Pink", text="M") elif s.maingrid[a][b]["text"] == "F": s.maingrid[a][b].configure(bg="Yellow") messagebox.showinfo("GAME OVER", "You lost") s.root.destroy() """ handle mouse right click """ def rightclick(event, s, i, x): if s.maingrid[i][x]["relief"] != "sunken": if s.maingrid[i][x]["text"] == "": s.maingrid[i][x].config(text="F") elif s.maingrid[i][x]["text"] == "F": s.maingrid[i][x].config(text="?") else: s.maingrid[i][x].config(text="") """ initialise the game """ if __name__ == "__main__": setup = initialScreen() if setup.finish == "Y": game = gameWindow(setup) quit()
def calculatePie(n): pie =0 i =1 for i in range(n): x =4*i*i y= 4*i*i -1 z=float(x)/float(y) if(i==1): pie =1 pie =pie*z else: pie =pie*z newpie=2*pie print newpie calculatePie(5)
#!/usr/bin/env python3 ''' an async routine called wait_n that takes in 2 int arguments (in this order): n and max_delay. You will spawn wait_random n times with the specified max_delay ''' import random import asyncio from typing import List wait_random = __import__('0-basic_async_syntax').wait_random async def wait_n(n: int, max_delay: int) -> List[float]: ''' return the list of all the delays (float values). The list of the delays should be in ascending order without using sort() because of concurrency ''' lad = await asyncio.gather(*(wait_random(max_delay) for i in range(n))) return sorted(lad)
import sys import random from collections import deque class Node: def __init__(self, state, parent, path_length, dir): self.parent = parent self.path_length = path_length self.state = state self.dir = dir def get_parent(self): return self.parent def get_path_length(self): return self.path_length def get_state(self): return self.state def get_dir(self): return self.dir def print_puzzle(state): count = 1 for a in state: if count % size == 0: print(a + " ") else: print(a + " ", end="", flush=True) count += 1 def goal_test(state): return goal == state def get_children(state): (x, y) = get_coordinate(state) move = [] children = [] if (x + 1) < size: move.append(get_index(x + 1, y)) if (x - 1) >= 0: move.append(get_index(x - 1, y)) if (y + 1) < size: move.append(get_index(x, y + 1)) if (y - 1) >= 0: move.append(get_index(x, y - 1)) for a in range(0, len(move)): children.append(swap(state, state.index("0"), move[a])) return children def get_child_dir(state): (x, y) = get_coordinate(state) move = {} children = {} if (x + 1) < size: move[get_index(x + 1, y)] = "DOWN" if (x - 1) >= 0: move[get_index(x - 1, y)] = "UP" if (y + 1) < size: move[get_index(x, y + 1)] = "RIGHT" if (y - 1) >= 0: move[get_index(x, y - 1)] = "LEFT" for key in move: children[swap(state, state.index("0"), key)] = move[key] return children def get_coordinate(state): index = state.index("0") if index // size == 0: x = 0 elif index // size == 1: x = 1 elif index // size == 2: x = 2 elif index // size == 3: x = 3 else: x = 4 if index % size == 0: y = 0 elif index % size == 1: y = 1 elif index % size == 2: y = 2 elif index % size == 3: y = 3 else: y = 4 return x, y def get_index(x, y): index = 0 if x == 1: index += size elif x == 2: index += size * 2 elif x == 3: index += size * 3 elif x == 4: index += size * 4 if y == 1: index += 1 elif y == 2: index += 2 elif y == 3: index += 3 elif y == 4: index += 4 return index def swap(s, a, b): n = list(s) temp = n[a] n[a] = n[b] n[b] = temp return ''.join(n) def bfs_winnable(): children = [goal] fringe = deque() fringe.appendleft(goal) visited = set() visited.add(goal) while len(fringe) != 0: v = fringe.pop() c = get_children(v) for a in range(0, len(c)): if c[a] not in visited: fringe.appendleft(c[a]) visited.add(c[a]) children.append(c[a]) return children def bfs_winnable_set(): children = set() children.add(goal) fringe = deque() fringe.appendleft(goal) visited = set() visited.add(goal) while len(fringe) != 0: v = fringe.pop() c = get_children(v) for a in range(0, len(c)): if c[a] not in visited: fringe.appendleft(c[a]) visited.add(c[a]) children.add(c[a]) return children def random_state(): m = [] for i in range(0, size * size): r = str(random.randint(0, 8)) while r in m: r = str(random.randint(0, 8)) m.append(str(r)) return ''.join(m) def random_solvable(): rs = bfs_winnable() s = random.randint(0, len(rs) - 1) return rs[s] def print_path(state): start = Node(state, None, 0, None) fringe = deque() fringe.appendleft(start) visited = set() visited.add(start.get_state()) while len(fringe) != 0: v = fringe.pop() if goal_test(v.get_state()): print(v.get_path_length()) parents = list() p = v while p is not None: parents.append(p) p = p.get_parent() if parents: print_puzzle(parents.pop().get_state()) print() while parents: t = parents.pop() print_puzzle(t.get_state()) print(t.get_dir()) print() break c = get_child_dir(v.get_state()) temp = [] for e in c: add = Node(e, v, v.get_path_length() + 1, c[e]) temp.append(add) for a in range(0, len(c)): if temp[a].get_state() not in visited: fringe.appendleft(temp[a]) visited.add(temp[a].get_state()) def path(state): start = Node(state, None, 0, None) fringe = deque() fringe.appendleft(start) visited = set() visited.add(start.get_state()) while len(fringe) != 0: v = fringe.pop() if goal_test(v.get_state()): return v.get_path_length() c = get_child_dir(v.get_state()) temp = [] for e in c: add = Node(e, v, v.get_path_length() + 1, c[e]) temp.append(add) for a in range(0, len(c)): if temp[a].get_state() not in visited: fringe.appendleft(temp[a]) visited.add(temp[a].get_state()) def random_gen(): r = random.randint(100, 1000) solve = bfs_winnable_set() y = [] for a in range(1, r): b = random_state() if b in solve: y.append(path(b)) print("Longest Path Length:" + str(max(y))) print("Average Path Length:" + str(sum(y)/len(y))) print("Percent Solvable:" + str(len(y)/r * 100)) def longest_solvable(): fringe = deque() fringe.appendleft(goal) visited = set() last = "" while len(fringe) != 0: v = fringe.pop() for a in get_children(v): if a not in visited: fringe.appendleft(a) visited.add(a) last = a return last def print_path_dfs(state): start = Node(state, None, 0, None) fringe = list() fringe.append(start) visited = set() visited.add(start.get_state()) while len(fringe) != 0: v = fringe.pop() visited.add(v) if goal_test(v.get_state()): print(v.get_path_length()) parents = list() p = v while p is not None: parents.append(p) p = p.get_parent() if parents: print_puzzle(parents.pop().get_state()) print() while parents: t = parents.pop() print_puzzle(t.get_state()) print(t.get_dir()) print() break c = get_child_dir(v.get_state()) temp = [] for e in c: add = Node(e, v, v.get_path_length() + 1, c[e]) temp.append(add) for a in range(0, len(temp)): if temp[a].get_state() not in visited: fringe.append(temp[a]) visited.add(temp[a].get_state()) def moves(moves_away): start = Node(goal, None, 0, None) fringe = deque() fringe.appendleft(start) visited = set() visited.add(start.get_state()) count = 0 while len(fringe) != 0: v = fringe.pop() if v.get_path_length() == moves_away: count += 1 c = get_child_dir(v.get_state()) temp = [] for e in c: add = Node(e, v, v.get_path_length() + 1, c[e]) temp.append(add) for a in range(0, len(c)): if temp[a].get_state() not in visited: fringe.appendleft(temp[a]) visited.add(temp[a].get_state()) return count def parity_check(state): if state == goal: return 1 out_of_order = 0 temp = state[:state.index("0")] + state[state.index("0") + 1:] for a in range(0, len(temp)): for b in range(a, len(temp)): if temp[b] < temp[a]: out_of_order += 1 if size % 2 == 1: if out_of_order % 2 == 0: return 1 else: return 0 else: (x, y) = get_coordinate(state) if x % 2 == 0: if out_of_order % 2 == 1: return 0 else: return 1 else: if out_of_order % 2 == 0: return 0 else: return 1 size = 3 goal = "012345678" print_path("806547231")
""" Methods to add UTC datetimes""" import pandas as pd def add_utc_datetime(df: pd.DataFrame) -> pd.DataFrame: """ Make 'settlement_period_start_utc' from 'Settlement Day' and 'Settlement Period' settlement_period_start_utc is the datetime with utc timezone of the settle period :param df: datafrome containing 'Settlement Day' and 'Settlement Period' :return: dataframe with """ # only works for "Settlement Day" and "Settlement Period" right now if not ("Settlement Day" in df.columns and "Settlement Period" in df.columns): return df # get start of day in UTC settlement_day_start = pd.to_datetime(df["Settlement Day"]).dt.tz_localize(tz="Europe/London") settlement_day_start_utc = settlement_day_start.dt.tz_convert(tz="UTC") # add 30 minutes * `Settlement Period` to start of day UTC df["settlement_period_start_utc"] = settlement_day_start_utc + pd.to_timedelta( 30 * (df["Settlement Period"] - 1), "T" ) return df
#!/usr/bin/env python # coding=utf-8 __author__ = 'chenfengyuan' def find(arr: list, start, value): for i in range(start, len(arr)): if arr[i] == value: return i else: return None
#Anthony Barrante #ITP 100 #Area of a Circle Calculator #This program calculates the area of a circle using the mathematical formula: #Area=3.14*radius^2 Radius = float(input("Please enter the radius of the circle: ")) Area = float(3.14*Radius*Radius) print("Using the radius ",Radius, "the area of the circle equals ",Area)
#!/usr/bin/python -tt # Copyright 2010 Google Inc. # Licensed under the Apache License, Version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # Google's Python Class # http://code.google.com/edu/languages/google-python-class/ # Additional basic list exercises # D. Given a list of numbers, return a list where def remove_adjacent(nums): i=0 new=[] k=len(nums) for no in nums: if len(new) == 0 or no != new[-1]: new.append(no) return new # E. Given two lists sorted in increasing order, create and return a merged def linear_merge(list1, list2): new=list1+list2 new.sort() return new # Simple provided test() function used in main() to print # what each function returns vs. what it's supposed to return. def test(got, expected): if got == expected: prefix = ' OK ' else: prefix = ' X ' print '%s got: %s expected: %s' % (prefix, repr(got), repr(expected)) # Calls the above functions with interesting inputs. def main(): print 'remove_adjacent' test(remove_adjacent([1, 2, 2, 3]), [1, 2, 3]) test(remove_adjacent([2, 2, 3, 3, 3]), [2, 3]) test(remove_adjacent([]), []) print print 'linear_merge' test(linear_merge(['aa', 'xx', 'zz'], ['bb', 'cc']), ['aa', 'bb', 'cc', 'xx', 'zz']) test(linear_merge(['aa', 'xx'], ['bb', 'cc', 'zz']), ['aa', 'bb', 'cc', 'xx', 'zz']) test(linear_merge(['aa', 'aa'], ['aa', 'bb', 'bb']), ['aa', 'aa', 'aa', 'bb', 'bb']) if __name__ == '__main__': main()
#!/usr/bin/env python3 # -*- coding=utf-8 -*- # 打印list: names = ['小明','小红','小石'] for name in names: print(name) # 打印数字 0 - 9 for x in range(10): print(x)
from tkinter import * root = Tk() i = 0 operand = '' x = '' def insert(text): global i screen.insert(i,text) i += 1 def operate(operator): global operand global x operand = operator x = screen.get() screen.delete(0,END) def execute(): global operand global x if operand in '+-/x': if operand == '+': result = float(x) + float(screen.get()) elif operand == '-': result = float(x) - float(screen.get()) elif operand == '/': result = float(x)/float(screen.get()) else: result = float(x)* float(screen.get()) screen.delete(0,END) screen.insert(0, str(result)) num1 = Button(root,text = "1",command = lambda:insert("1")) num2 = Button(root,text = "2",command = lambda:insert("2")) num3 = Button(root,text = "3",command = lambda:insert("3")) num4 = Button(root,text = "4",command = lambda:insert("4")) num5 = Button(root,text = "5",command = lambda:insert("5")) num6 = Button(root,text = "6",command = lambda:insert("6")) num7 = Button(root,text = "7",command = lambda:insert("7")) num8 = Button(root,text = "8",command = lambda:insert("8")) num9 = Button(root,text = "9",command = lambda:insert("9")) dot = Button(root, text = ".",command = lambda:insert(".")) num0 = Button(root,text = "0",command = lambda:insert("0")) plus = Button(root, text = '+',command = lambda:operate("+")) plus.grid(row = 1, column = 3, ipadx = 10) minus = Button(root, text = '-',command = lambda:operate("-")) minus.grid(row = 2, column = 3, ipadx = 10) multi = Button(root, text = 'x',command = lambda:operate("x")) multi.grid(row = 3, column = 3, ipadx = 10) divide = Button(root, text = '/',command = lambda:operate("/")) divide.grid(row = 4, column = 3, ipadx = 10) sum = Button(root, text = "=",command = lambda:execute()) sum.grid(row = 4, column = 2, ipadx = 10) screen = Entry(root) screen.grid(row = 0, columnspan = 3) clear = Button(root,text = "CLEAR",command = lambda:screen.delete(0,END)) clear.grid(row = 0,column = 3,ipadx = 0) num1.grid(row = 1, column = 0,ipadx = 10) num2.grid(row = 1, column = 1,ipadx = 10) num3.grid(row = 1, column = 2,ipadx = 10) num4.grid(row = 2, column = 0,ipadx = 10) num5.grid(row = 2, column = 1,ipadx = 10) num6.grid(row = 2, column = 2,ipadx = 10) num7.grid(row = 3, column = 0,ipadx = 10) num8.grid(row = 3, column = 1,ipadx = 10) num9.grid(row = 3, column = 2,ipadx = 10) dot.grid(row = 4, column = 0, ipadx = 10) num0.grid(row = 4, column = 1,ipadx = 10) root.mainloop()
# ------------------------------------------------------------------------ # # Title: Assignment 07 # Description: Demo of pickling and error handling # ChangeLog (Who,When,What): # JEmbury, 12/1/19,Created started script # ------------------------------------------------------------------------ # import pickle # Data shopping_list = [] FileName = "AppData.dat" # Get info from user and save to list. Display input. print("How much money can you spend on Christmas gifts?") #try: # Get info from user name_str = str(input("Enter a name on your shopping list: ")) budget_int = int(input("Enter a budget for this person($): ")) # Save to list and print back to user shopping_list = [name_str, budget_int] print(shopping_list) # Store Data to binary file, begin pickling objFile = open(FileName, "ab") pickle.dump(shopping_list, objFile) objFile.close() # Read data from binary file objFile = open(FileName, "rb") objFileData = pickle.load(objFile) objFile.close() print(objFileData) # except ValueError as e: # print("Value entered for budget must be an integer!") # print("Built-In Python error info: ") # print(e,e.__doc__, type(e), sep='\n') # except Exception as e: # print("There was a non-specific error!") # print("Built-In Python error info: ") # print(e, e.__doc__, type(e), sep='\n')
#CH09-Lab01 가위, 바위, 보 게임 import random def match(c, m): if c == m : return '비겼습니다.' elif match_table[c] == m: return '졌습니다.' else: return '이겼습니다.' rps_dic = {1:'가위', 2:'바위', 3:'보'} match_table = {'가위':'보', '바위':'가위', '보':'바위'} computer = rps_dic[random.randint(1,3)] mine = input('가위, 바위, 보 입력: ') result = match(computer, mine) print(result)
#CH02-08. 지역 변수와 전역 변수 ################################################################## ##원의 면적을 계산 def calculate_area( ): result = 3.14 * r **2 return result r = float(input("원의 반지름: ")) area = calculate_area( ) print(area)
#CH03-05 연산자의 우선순위 ################################################################## #사용자로부터 3개의 수를 입력받아서 평균을 출력 x = int(input("첫 번째 수: ")) y = int(input("두 번째 수: ")) z = int(input("세 번째 수: ")) avg = (x + y + z) / 3 print("평균 =", avg)
#CH07-05. 리스트 항목 삭제하기 ################################################################## ##방법3: 리스트에서 pop( )을 이하여 항목을 삭제 cart=['사과', '세제', '화장지', '치약'] item = cart.pop( ) print(cart) print(item)
#CH06-Lab05 범인 찾기 게임 import random score = 0 while True : room = random.randint(1, 3) n = int(input("방 번호를 입력 하세요: ")) if n == room : print("범인 체포!") score += 10 break elif n > 3 : print(n,"번 방은 없습니다.") else: print("범인이 없습니다.") score -= 10 print("게임 종료") print("점수:", score,"점")
#CH10-Lab03 평균 강수량 통계 import csv # 입력 파일 출력 파일 열기 infile = open("D:\\weather_input.csv", "r") data = csv.reader(infile) count = 0 sum = 0 for line in data : count += 1 sum += float(line[2]) print("강원도 2009년 01월 부터 2019년 09월까지의 총 강수량: ", sum) print("강원도 2009년 01월 부터 2019년 09월까지의 평균 강수량: ", sum / count) infile.close( )
#CH02-08 수 입력받기 ################################################################## ##정수 2개 입력받기 ##x = int(input("첫 번째 정수를 입력하시오: ")) ##y = int(input("두 번째 정수를 입력하시오: ")) ##sum = x + y ##print(x, "과", y, "의 합은", sum, "입니다.") ################################################################### ##사용자로부터 2개의 정수를 받아서 사칙연산(+, -, *, /)의 결과를 출력 x = int(input("첫 번째 정수를 입력하시오: ")) y = int(input("두 번째 정수를 입력하시오: ")) print(x, "+", y, "=", x + y) print(x, "-", y, "=", x - y) print(x, "*", y, "=", x * y) print(x, "/", y, "=", x / y)
#CH03-Lab03 두 점 사이의 거리 구하기 x1 = int(input("x1: ")) y1 = int(input("y1: ")) x2 = int(input("x2: ")) y2 = int(input("y2: ")) print("두 점 사이의 거리=", ((x2-x1)**2 + (y2-y1)**2)**0.5)
#CH06-006. 조건 제어 반복을 좀 더 이해시켜 줄 예제 ################################################################## ##1부터 100까지의 합을 구하는 프로그램 count = 1 sum = 0 while count <= 100 : sum = sum + count count = count + 1 print("1부터 100까지의 합은",sum,"입니다.")
import re def adverbe(word): if word[-4:] == "ment": return 1 return 0 def split_to_word(text): separtion_punctuation = re.compile('[\s]+') text = separtion_punctuation.split(text) return text def open_file(file): file_ = open(file, 'r') content = file_.read() liste = split_to_word(content) file_.close() return liste Pluriels = open_file("input_file/Pluriels.txt") Pronom_personnel = open_file("input_file/Pronom_personnel.txt") Determinant = open_file("input_file/Determinant.txt") Pronom_personnel_negatif = open_file("input_file/Pronom_personnel_Neg.txt") agreement = ["arrangement"] def prepare_output(splitted_txt, output): tmp = '' word = split_to_word(splitted_txt) for i in range(len(word)): if word[i].lower() in Pronom_personnel: #if word[i+1] if word[i+1].lower() == 'y' or word[i+1].lower() == "n'y" or word[i+1].lower() == 'lui' or word[i+1].lower() == 'se' : output += word[i] + ' ' i += 1 if word[i+1].lower() == 'une' or word[i+1].lower() == 'me' or word[i+1].lower() == 'ne' or word[i+1].lower() == 'le' or word[i+1].lower() == "l'a" : output += word[i] + ' ' i = i +1 output += word[i] + ' <verbe>' + word[i+1] + '</verbe> ' tmp = word[i+1] elif word[i].lower() in Pluriels: output += word[i] + ' <pluriel>' + word[i+1] + '</pluriel> ' tmp = word[i+1] elif (adverbe(word[i].lower())): if not(word[i-1].lower() in Determinant): output += '<advrebe>' + word[i] + '</advrebe> ' else: output += word[i]+' ' elif tmp == word[i]: continue else: if word[i].lower() == 'y' or word[i].lower() == "n'y" or word[i].lower() == 'lui' or word[i].lower() == 'se ': i += 1 elif word[i].lower() == 'une' or word[i].lower() == 'me' or word[i].lower() == 'ne' or word[i].lower() == 'le' or word[i].lower() == "l'a" : i += 1 else: output += word[i]+' ' return output
class Solution: def isValid(self, s: str) -> bool: #뚜껑과 그릇이 딱 만나는 순간에도 같아야한다 stack = [] for char in s: if char == "(" or char == "{" or char == "[": stack.append(char) if char == ")" : #testcase ")"때문에 if not stack or stack[-1] != "(": return False stack.pop() if char == "}" : if not stack or stack[-1] != "{": return False stack.pop() if char == "]" : if not stack or stack[-1] != "[": return False stack.pop() if stack: # testcase "["때문에 return False return True
# 1. Ce valoare o sa contina variabila a după execuția codului ? a = 10 a += len(str(a)) print(a) #Raspuns a = 12 ###################################################################################################### # 2. Codul de mai jos conține o eroare, modificați codul astfel încît programul să funcționze corect. # "In padurea cu alune aveau casa" + 2 + "pitici" #Raspuns: # Prima metoda "In padurea cu alune aveau casa" + str(2) + "pitici" # A doua metoda f'"In padurea cu alune aveau casa" + {2} + "pitici"' ###################################################################################################### # 3. Ce valoare o sa contina variabila a dupa executia codului ? a = 10 a += 1 print(a) #Raspuns a = 11 ###################################################################################################### # 4. Codul de mai jos contine o erroare, Modificati codul ca nu apara erroare? a = int(input()) a += 1 print(a) ###################################################################################################### # 5. Scrieți un program care primește la input numele fisierului (text.txt, program.java) si intoarce # extensia lui (txt, java). Puteti sa folositi functia split() a = "text.txt" b = "program.java" a = a.split(".",1) b = b.split(".",1) print(a[-1]) print(b[-1]) ###################################################################################################### # 6.1 Ce valoare are expresia a[int(int('3' * 2) // 11] ? a = [int(int('3'*2)//11)] print(a) #Raspuns 6.1: a = [3] # 6.2 Adaugati o valoare nouă în lista a pe prima poziție. a = ['a', 'b', 'c', 'd'] a[0] = 'a1' print(a) # 6.3 Ștergeți ultimele 2 valori din lista. a = ['a', 'b', 'c', 'd'] del a[2] del a[-1] print(a) # 6.4 Ordonati lista a descrescator a = ['a', 'b', 'c', 'd'] a.sort(reverse=True) print(a) # 6.5 Creați o listă nouă b care sa conțină toate elementele din lista a cu excepția primelor 2 elemente. a = ['a', 'b', 'c', 'd'] b = a[2:4] print(b) # 7. Scrieți un program care afișează toate elementele din un invetar si calculează suma lor. elemente = {"scaune": 77, "mese": 66, "dulapuri": 1} suma = elemente.get('scaune') + elemente.get('mese') + elemente.get('dulapuri') print("Suma totala este: ",suma) print(list(elemente.keys()))
t#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Nov 2 02:51:42 2019 @author: utkarsh """ import numpy as np import pandas as pd import matplotlib.pyplot as plt plt.rcParams['figure.figsize'] = (20.0, 10.0) # Reading Data data = pd.read_csv('./dataSet/headbrain.csv') print(data.shape) data.head() # Collecting X and Y X = data['Head Size(cm^3)'].values Y = data['Brain Weight(grams)'].values # Mean X and Y mean_x = np.mean(X) mean_y = np.mean(Y) # Total number of values n = len(X) # Using the formula to calculate m and c numer = 0 denom = 0 for i in range(n): numer += (X[i] - mean_x) * (Y[i] - mean_y) denom += (X[i] - mean_x) ** 2 m = numer / denom c = mean_y - (m * mean_x) # Print coefficients print(m, c) # Plotting Values and Regression Line max_x = np.max(X) + 100 min_x = np.min(X) - 100 # Calculating line values x and y x = np.linspace(min_x, max_x, 1000) y = c + m * x # Ploting Line plt.plot(x, y, color='#52b920', label='Regression Line') # Ploting Scatter Points plt.scatter(X, Y, c='#ef4423', label='Scatter Plot') plt.xlabel('Head Size in cm3') plt.ylabel('Brain Weight in grams') plt.legend() plt.show() #R–squared value is the statistical measure to show how close the data are to the fitted regression line #ss_t is the total sum of squares and ss_r is the total sum of squares of residuals(relate them to the formula). ss_t = 0 ss_r = 0 for i in range(len(X)): y_pred = c + m * X[i] ss_t += (Y[i] - mean_y) ** 2 ss_r += (Y[i] - y_pred) ** 2 r2 = 1 - (ss_r/ss_t) print(r2)
# -*- coding: utf-8 -*- # scatter plot 2D scatter plot iris.plot(kind='scatter', x='sepal_length', y='sepal_width') ; plt.show() # 2-D Scatter plot with color-coding for each flower type/class. # Here 'sns' corresponds to seaborn. sns.set_style("whitegrid"); sns.FacetGrid(iris, hue="species", size=4) \ .map(plt.scatter, "sepal_length", "sepal_width") \ .add_legend(); plt.show(); # Notice that the blue points can be easily seperated # from red and green by drawing a line. # But red and green data points cannot be easily seperated. # Can we draw multiple 2-D scatter plots for each combination of features? # How many cobinations exist? 4C2 = 6 3D scatter plot import plotly.express as px iris = px.data.iris() fig = px.scatter_3d(iris, x='sepal_length', y='sepal_width', z='petal_width', color='species') fig.show() pair plot # pairwise scatter plot: Pair-Plot # Dis-advantages: ##Can be used when number of features are high. ##Cannot visualize higher dimensional patterns in 3-D and 4-D. #Only possible to view 2D patterns. plt.close(); sns.set_style("whitegrid"); sns.pairplot(iris, hue="species", size=3); plt.show() # NOTE: the diagnol elements are PDFs for each feature. PDFs are expalined below. **Observations** 1. petal_length and petal_width are the most useful features to identify various flower types. 2. While Setosa can be easily identified (linearly seperable), Virnica and Versicolor have some overlap (almost linearly seperable). 3. We can find "lines" and "if-else" conditions to build a simple model to classify the flower types. # What about 1-D scatter plot using just one feature? #1-D scatter plot of petal-length import numpy as np iris_setosa = iris.loc[iris["species"] == "setosa"]; iris_virginica = iris.loc[iris["species"] == "virginica"]; iris_versicolor = iris.loc[iris["species"] == "versicolor"]; #print(iris_setosa["petal_length"]) plt.plot(iris_setosa["petal_length"], np.zeros_like(iris_setosa['petal_length']), 'o') plt.plot(iris_versicolor["petal_length"], np.zeros_like(iris_versicolor['petal_length']), 'o') plt.plot(iris_virginica["petal_length"], np.zeros_like(iris_virginica['petal_length']), 'o') plt.show() #Disadvantages of 1-D scatter plot: Very hard to make sense as points #are overlapping a lot. #Are there better ways of visualizing 1-D scatter plots? Histogram using seaborn sns.FacetGrid(iris, hue="species", size=5) \ .map(sns.distplot, "petal_length") \ .add_legend(); plt.show(); # Histograms and Probability Density Functions (PDF) using KDE # How to compute PDFs using counts/frequencies of data points in each window. # How window width effects the PDF plot. # Interpreting a PDF: ## why is it called a density plot? ## Why is it called a probability plot? ## for each value of petal_length, what does the value on y-axis mean? # Notice that we can write a simple if..else condition as if(petal_length) < 2.5 then flower type is setosa. # Using just one feature, we can build a simple "model" suing if..else... statements. # Disadv of PDF: Can we say what percentage of versicolor points have a petal_length of less than 5? # Do some of these plots look like a bell-curve you studied in under-grad? # Gaussian/Normal distribution. # What is "normal" about normal distribution? # e.g: Hieghts of male students in a class. # One of the most frequent distributions in nature. # Plots of CDF of petal_length for various types of flowers. # Misclassification error if you use petal_length only. counts, bin_edges = np.histogram(iris_setosa['petal_length'], bins=10, density = True) pdf = counts/(sum(counts)) print(pdf); print(bin_edges) cdf = np.cumsum(pdf) plt.plot(bin_edges[1:],pdf) plt.plot(bin_edges[1:], cdf) # virginica counts, bin_edges = np.histogram(iris_virginica['petal_length'], bins=10, density = True) pdf = counts/(sum(counts)) print(pdf); print(bin_edges) cdf = np.cumsum(pdf) plt.plot(bin_edges[1:],pdf) plt.plot(bin_edges[1:], cdf) #versicolor counts, bin_edges = np.histogram(iris_versicolor['petal_length'], bins=10, density = True) pdf = counts/(sum(counts)) print(pdf); print(bin_edges) cdf = np.cumsum(pdf) plt.plot(bin_edges[1:],pdf) plt.plot(bin_edges[1:], cdf) plt.show(); Box Plot #Box-plot with whiskers: another method of visualizing the 1-D scatter plot more intuitivey. # The Concept of median, percentile, quantile. # How to draw the box in the box-plot? # How to draw whiskers: [no standard way] Could use min and max or use other complex statistical techniques. # IQR like idea. #NOTE: IN the plot below, a technique call inter-quartile range is used in plotting the whiskers. #Whiskers in the plot below donot correposnd to the min and max values. #Box-plot can be visualized as a PDF on the side-ways. sns.boxplot(x='species',y='petal_length', data=iris) plt.show() Violin plots # A violin plot combines the benefits of the previous two plots #and simplifies them # Denser regions of the data are fatter, and sparser ones thinner #in a violin plot sns.violinplot(x="species", y="petal_length", data=iris, size=8) plt.show() Multivariate prob density counter plot #2D Density plot, contors-plot sns.jointplot(x="petal_length", y="petal_width", data=iris_setosa, kind="kde"); plt.show();
def collect_by_value(obj, val_fn, only_values=False): """ Collect values in an arbitrary structure. Values can be strings or numbers. Takes: obj(iterable): arbitrary structure to scan val_fn(function): function to use against values include_key(bool): Collect the key as well Return: A list of found items. """ found = [] if type(obj) is list: for item in obj: if type(item) is list or type(item) is dict: found += collect_by_value(item, val_fn, only_values) elif val_fn(item): if only_values: found += [item] else: found += [obj] elif type(obj) is dict: for k,v in obj.items(): if type(v) is dict or type(v) is list: found += collect_by_value(v, val_fn, only_values) elif val_fn(v): if only_values: found += [v] else: found += [obj] else: if val_fn(obj): found += [obj] return found def collect_by_key(obj, key_fn, only_values=True): """ Collect values based on a key in an arbitrary structure. Takes: obj(iterable): arbitrary structure to scan key_fn(function): fuction touse against keys include_key(bool): Collect the key as well Return: A list of found items. """ found = [] if type(obj) is list: for item in obj: if type(item) is list or type(item) is dict: found += collect_by_key(item, key_fn, only_values) elif type(obj) is dict: for k,v in obj.items(): if key_fn(k): if only_values: if not v in found: found += [v] else: if not obj in found: found += [obj] elif type(v) is dict or type(v) is list: found += collect_by_key(v, key_fn, only_values) return found # --------------------------------- Tests -------------------------------------- struct = [ 42, { 'a' : 2, 'b' : [5, 2, 1], 'c' : 3 }, [4, 5, [7, 9, 1], 3] ] nested = { "h1" : { "h2" : 'test1', "h22" : 'test2', "h3" : { "h4" : 'test3' } } } assert collect_by_value( 1, val_fn=lambda v: v==1, only_values=False) == [1] assert collect_by_value([1, 2], val_fn=lambda v: v==1, only_values=False) == [[1, 2]] assert collect_by_value([1, 2], val_fn=lambda v: v==1, only_values=True) == [1] assert collect_by_value(struct, val_fn=lambda v: v==3, only_values=True) == [3, 3] assert collect_by_value(struct, val_fn=lambda v: v==1, only_values=False) == [[5, 2, 1], [7, 9, 1]] assert collect_by_value(struct, val_fn=lambda v: v==3, only_values=False) == [{ 'a' : 2, 'b' : [5, 2, 1], 'c' : 3 }, [4, 5, [7, 9, 1], 3]] assert collect_by_key({'a' : 1}, key_fn=lambda k: k=='a', only_values=False) == [{'a' : 1}] assert collect_by_key({'a' : 1}, key_fn=lambda k: k=='a', only_values=True) == [1] assert collect_by_key(struct, key_fn=lambda k: k=='b', only_values=False) == [{ 'a' : 2, 'b' : [5, 2, 1], 'c' : 3 }] assert collect_by_key(struct, key_fn=lambda k: k=='b', only_values=True) == [[5, 2, 1]] assert collect_by_key(struct, key_fn=lambda k: True, only_values=False) == [{ 'a' : 2, 'b' : [5, 2, 1], 'c' : 3 }] assert collect_by_key(struct, key_fn=lambda k: True, only_values=True) == [2, 3, [5, 2, 1]] # Order might change assert collect_by_key(nested, key_fn=lambda k: k=='h4', only_values=True) == ['test3'] assert collect_by_key(nested, key_fn=lambda k: k=='h4', only_values=False) == [{'h4' : 'test3'}] assert collect_by_key(nested, key_fn=lambda k: k.startswith('h2'), only_values=True) == ['test1','test2']
#Cómo se visualizaría en consola la respuesta cadena = 'En una zarzamorera estaba una mariposa zarzarrosa y alicantosa.' diccionario = {'Salvador Caracuel': 144} b = cadena.split('po') for i in b: if i in diccionario: diccionario[i] *= 78 else: diccionario[i] = 98 print(diccionario) ''' RPTA: {'sa zarzarrosa y alicantosa.': 98, 'Salvador Caracuel': 144, 'En una zarzamorera estaba una mari': 98} '''
matriz = [ ['A', 'B', 'C', 'D'], ['E', 'F', 'G', 'H'], ['I', 'J', 'K', 'L'], ['M', 'N', 'O', 'P'], ] for num in range(1,5): x = num % 2 if x == 0: print(matriz[x][num % 2]) ''' RPTA: A A '''
#Criar um algoritmo em PYTHON que leia o destino do passageiro, se a viagem inclui retorno (ida e volta) e informar o preço da passagem conforme a tabela a seguir: #1-Região Norte, 2-Região Nordeste, 3-Região Centro-Oeste, 4-Região Sul #Entrada de dados print("Digite um dos valores abaixo para selecionar a região\n") print("1 - Região Norte \n") print("2 - Região Nordeste \n") print("3 - Região Centro-Oeste \n") print("4 - Região Sul \n") regiao = int(input("Digite o código referrente a região: ")) while(regiao != 1 and regiao != 2 and regiao != 3 and regiao !=4): print("Digite uma região válida!") regiao = int(input("Digite o código referente a região")) passagem =input("Caso deseje uma passagem apenas para ida escreva sim, caso contrário escreva não: ") while(passagem != "sim" and passagem != "SIM" and passagem != "Sim" and passagem != "NÃO" and passagem != "não" and passagem != "Não"): print("Digite um valor válido para passagem apenas de ida!") passagem =input("Caso deseje uma passagem apenas para ida escreva sim, caso contrário escreva não") #Processamento / impressão dos dados if(passagem == "sim" or passagem == "SIM" or passagem == "Sim"): if(regiao == 1): print("Valor da passagem de ida para região norte R$:500,00") elif(regiao == 2): print("Valor da passagem de ida para região nordeste R$:350,00") elif(regiao == 3): print("Valor da passagem de ida para região centro-oeste R$:350,00") elif(regiao == 4): print("Valor da passagem de ida para região sul R$:300,00") elif(passagem == "não" or passagem == "NÃO" or passagem == "NÃO"): if(regiao == 1): print("Valor da passagem de ida e volta para região norte R$:900,00") elif(regiao == 2): print("Valor da passagem de ida e volta para região nordeste R$:650,00") elif(regiao == 3): print("Valor da passagem de ida e volta para região centro-oeste R$:600,00") elif(regiao == 4): print("Valor da passagem de ida e volta para região sul R$:550,00")
#Escreva um algoritmo em PYTHON que leia uma temperatura em gruas centígrados e apresente a temperatura convertida em graus Fahrenheit. #A fórmula de conversão é: F = (9 * C + 160) / 5 #Onde F é a temperatura em Fahrenheit e C é a temperatura em centígrados #Entrada de dados C = float(input("Digite a temperatura em graus centigrados: ")) #Processamento dos dados F = (9 * C + 160) / 5 #Impressão dos dados print("Temperatura em Fahrenheit: ",F)
#2)Uma P.G. (progressão geométrica) fica determinada pela sua razão (q) e pelo primeiro termo (a1). Escreva um algoritmo em PORTUGOL que seja capaz de determinar #qualquer termo de uma P.G., dado a razão e o primeiro termo. #Entrada de dados a1 = int(input("Digite o valor do primeiro termo: ")) q = int(input("Digite o valor da razão: ")) n = int(input("Digite o valor de n: ")) #processamento dos dados an = a1 * q ** (n-1) #impressão do processamento dos dados print("O valor da P.G. é: ",an)
#Antes de o racionamento de energia ser decretado, quase ninguém falava em quilowatts; mas, agora, todos incorporaram essa palavra em seu vocabulário. Sabendose #que 100 quilowatts de energia custa um sétimo do salário mínimo, fazer um algoritmo em PYTHON que receba o valor do salário mínimo e a quantidade de quilowatts gasta por uma residência e calcule (imprima). #- o valor em reais de cada quilowatt; #- o valor em reais a ser pago; #- o novo valor a ser pago por essa residência com um desconto de 10%. #Entrada de dados salarioMinimo = float(input("Digite o valor referente ao salário minimo: ")) while(salarioMinimo <= 0): print("Digite um valor válido para salario minímo!") salarioMinimo = float(input("Digite o valor referente ao salário minimo: ")) quantidadeQW = float(input("Digite o valor da quantidade de quilowatt gasto na residência: ")) while(quantidadeQW <= 0): print("Digite um valor válido para salario minímo!") quantidadeQW = float(input("Digite o valor da quantidade de quilowatt gasto na residência: ")) #Processamento dos dados valorQW = (salarioMinimo / 7) / 100 valorPago = quantidadeQW * valorQW desconto = valorPago * (10 / 100) novoValor = valorPago - desconto #Limitação de 2 casas decimais para os valores conversaoValorQW = round (valorQW,2) conversaoPG = round (valorPago,2) conversaoNV = round (novoValor,2) #Impressão do processamento print("Valor em reais de cada quilowatt R$:",conversaoValorQW) print("Valor em reais a ser pago R$:",conversaoPG) print("Valor a ser pago com desconto de 10% R$:",conversaoNV)
from Pilha import Pilha class Backtracking: def __init__(self,inicio,objetivo): self.inicio = inicio self.inicio.visitado = True self.objetivo = objetivo self.fronteira = Pilha(16) self.fronteira.empilhar(inicio) self.achou = False def buscar(self): topo = self.fronteira.getTopo() print('Topo {}'.format(topo.nome)) if topo == self.objetivo: self.achou = True print('Objetivo alcançado!') else: for a in topo.adjacentes: if self.achou == False: if a.letras.visitado == False: a.letras.visitado = True print('Estado visitado: {}'.format(a.letras.nome)) self.fronteira.empilhar(a.letras) Backtracking.buscar(self) print('Desempilhou: {}'.format(self.fronteira.desempilhar().nome)) from Mapa import Mapa mapa = Mapa() backtracking = Backtracking(mapa.A,mapa.H) backtracking.buscar()
class Pilha: def __init__(self,tamanho): self.tamanho = tamanho self.letras = [None] * self.tamanho self.topo = -1 def empilhar(self,letras): if not Pilha.pilhaCheia(self): self.topo += 1 self.letras[self.topo] = letras else: print('A pilha está cheia!') def desempilhar(self): if not Pilha.pilhaVazia(self): temp = self.letras[self.topo] self.topo -= 1 return temp else: print('A pilha já está vazia!') return None def getTopo(self): return self.letras[self.topo] def pilhaVazia(self): return (self.topo == -1) def pilhaCheia(self): return (self.topo == self.tamanho -1)
#Criar um algoritmo em PYTHON que efetue o cálculo do salário líquido de um professor. Os dados fornecidos serão: valor da hora aula, número de aulas dadas no #mês e percentual de desconto do INSS. #Entrada de dados valorHora = float(input("Digite o valor da hora aula: ")) #implementação de segurança garantindo que o valor informado será válido while(valorHora <= 0): print("Digite um valor válido para valor da hora aula!") valorHora = float(input("Digite o valor da hora aula: ")) numeroAulas = int(input("Digite a quantidade de aulas dadas: ")) #implementação de segurança garantindo que o valor informado será válido while(numeroAulas <= 0): print("Digite um valor válido para número de aulas!") numeroAulas = int(input("Digite a quantidade de aulas dadas: ")) taxaINSS = float(input("Digite o valor referene a taxa do INSS: ")) #implementação de segurança garantindo que o valor informado será válido while(taxaINSS <= 0): print("Digite um valor válido para taxa INSS!") taxaINSS = float(input("Digite o valor referene a taxa do INSS: ")) #Processamento dos dados salarioBruto = valorHora * numeroAulas conversaoSB = round(salarioBruto,2) desconto = salarioBruto * taxaINSS / 100 conversaoDesconto = round(desconto,2) salarioLiquido = salarioBruto - desconto conversaoSL = round(salarioLiquido,2) #Impressão dos dados print("Valor do salário bruto R$:",conversaoSB) print("Valor do desconto do INSS R$:",conversaoDesconto) print("Valor do salário liquido R$:",conversaoSL)
import math print(" COMPUTER ORGANIZATION ") print(" END SEMESTER ASSIGNMENT ") def read(address1,bits_in_B,bits_in_Cl,cache): l1=len(address1) extra_tag_length=int(l1-bits_in_B-bits_in_Cl) i2=32-l1 tag="" for i in range(i2): tag+="0" finaladress=tag+address1 tag+=address1[:extra_tag_length] # offset=finaladress[30:32] offset=finaladress[int(32-bits_in_B):] off=binaryToDecimal(offset) # index=finaladress[28:30] index=finaladress[int(32-bits_in_B-bits_in_Cl):int(32-bits_in_B)] for i in cache: if(binaryToDecimal(i.CacheLine)==binaryToDecimal(index)): if(tag==i.address): print("value = " + str(i.arrOfBlock[off])) else: print("Read Miss, value=0") def write(address1,data1,bits_in_B,bits_in_Cl,cache,B): l1=len(address1) extra_tag_length=int(l1-bits_in_B-bits_in_Cl) i2=32-l1 tag="" for i in range(i2): tag+="0" finaladress=tag+address1 tag+=address1[:extra_tag_length] # offset=finaladress[30:32] offset=finaladress[int(32-bits_in_B):] off=binaryToDecimal(offset) # index=finaladress[28:30] index=finaladress[int(32-bits_in_B-bits_in_Cl):int(32-bits_in_B)] for i in cache: if(binaryToDecimal(i.CacheLine)==binaryToDecimal(index)): if(tag==i.address): print("WRITE HIT!") i.arrOfBlock[off]=data1 else: print("WRITE MISS :(") for del1 in range(B): i.arrOfBlock[del1]=0 i.address=tag i.arrOfBlock[off]=data1 for i in cache: print("Adress Of Block : " + i.address) print("Index : " + i.CacheLine) for k in range(len(i.arrOfBlock)): print("offset value = " + decimalToBinary(k)+" , value = " +str(i.arrOfBlock[k])) print("Enter the size of your cache: ") S =int(input()) print("Enter the number of cache lines: ") Cl =int(input()) print("Enter the block size: ") B =int(input()) bits_in_Cl=math.log(Cl,2) bits_in_B=math.log(B,2) Adr_bits= 32- bits_in_Cl - bits_in_B def decimalToBinary(n): return bin(n).replace("0b", "") def binaryToDecimal(n): return int(n,2) class block: def __init__(self,CacheLine,arrOfBlock,address): self.CacheLine=CacheLine self.arrOfBlock=arrOfBlock self.address=address cache=[] for i in range(Cl): b1=[] adr="" for j in range(B): b1.append(decimalToBinary(0)) for j in range(int(Adr_bits)): adr+="0" b=block(decimalToBinary(i),b1,adr) cache.append(b) # for i in cache: # print(i.CacheLine,end=" ") # print(i.arrOfBlock,end=" ") # print(i.address) T=100 for j in range(T): print("1> Read, 2> Write, 3> Exit") Op=int(input()) if(Op==1): print("Enter address: ") address=input() read(address,bits_in_B,bits_in_Cl,cache) if(Op==2): print("Enter address: ") address1=input() print("Enter data: ") data1=int(input()) write(address1,data1,bits_in_B,bits_in_Cl,cache,B) if(Op==3): print("Rishit Gupta") print(" 2019091 ") print(" Thank You ") break
adapters = [] f = open("input.txt", "r") for line in f.readlines(): strippedLine = line.strip() print(strippedLine) adapters.append(int(strippedLine)) adapters.sort(reverse=True) adaptersMap = {} endJolt = adapters[0] endNode = {"jolt": endJolt - 3, "chains": {}, "from": {}} adaptersMap[endJolt] = endNode def addChainsSpecific(adaptersMap, jolt, toJolt): if (toJolt in adaptersMap): adaptersMap[toJolt]["chains"][jolt] = jolt adaptersMap[jolt]["from"][toJolt] = toJolt def addChains(adaptersMap, jolt): addChainsSpecific(adaptersMap, jolt, jolt + 1) addChainsSpecific(adaptersMap, jolt, jolt + 2) addChainsSpecific(adaptersMap, jolt, jolt + 3) for adapter in adapters: newNode = {"jolt": adapter, "chains": {}, "from": {}} adaptersMap[adapter] = newNode addChains(adaptersMap, adapter) print(adaptersMap) def multiplyNodes(adaptersMap, node): # print(node) if ("sum" in node): return node["sum"] if (len(node["chains"].items()) == 0): print("root node") node["sum"] = 1 adaptersMap[node["jolt"]] = node return 1 sum = 0 for chain in node["chains"]: # print(chain) sum = sum + multiplyNodes(adaptersMap, adaptersMap[chain]) if (node["jolt"] - 3 <= 0): sum = sum + 1 # straight to root print("can reach ground, jolt: " + str(node["jolt"]) + " sum: " + str(sum)) print(node) node["sum"] = sum adaptersMap[node["jolt"]] = node # print(adaptersMap) return sum print(adaptersMap) multipliedNodes = multiplyNodes(adaptersMap, adaptersMap[endJolt]) print("answer: " + str(multipliedNodes))
# f = open("exampleInput.txt", "r") f = open("input.txt", "r") cardPublicKey = 0 doorPublicKey = 0 for line in f.readlines(): strippedLine = line.strip() print(strippedLine) if cardPublicKey == 0: cardPublicKey = int(strippedLine) else: doorPublicKey = int(strippedLine) print(cardPublicKey) print(doorPublicKey) subjectNumber = 7 loopCount = 0 cardLoopSize = 0 doorLoopSize = 0 value = 1 while(doorLoopSize == 0 or cardLoopSize == 0): if value == cardPublicKey: # print("FOUND CARD: " + str(loopCount)) cardLoopSize = loopCount if value == doorPublicKey: # print("FOUND DOOR: " + str(loopCount)) doorLoopSize = loopCount loopCount = loopCount + 1 value = value * subjectNumber value = value % 20201227 # print(value) print("card loop size: "+ str(cardLoopSize)) # 15260454 print("door loop size: "+ str(doorLoopSize)) # 10476062 def transform(subjectNumber, loopSize): value = 1 for i in range(loopSize): value = value * subjectNumber value = value % 20201227 return value encryptionKeyFromCard = transform(doorPublicKey, cardLoopSize) print("encryptionKeyFromCard: " + str(encryptionKeyFromCard)) # 448851 # encryptionKeyFromDoor = transform(cardPublicKey, doorLoopSize) # print("encryptionKeyFromDoor: " + str(encryptionKeyFromDoor)) # 448851
import re def moveDir(pos, dir, value): if (dir == 0): pos[0] = pos[0] + value elif (dir == 180): pos[0] = pos[0] - value elif (dir == 90): pos[1] = pos[1] + value elif (dir == 270): pos[1] = pos[1] - value def rotateVec(vec, degrees): if (degrees == 0): #noop vec = vec elif (degrees == 180): vec = [-vec[0], -vec[1]] elif (degrees == 90): vec = [-vec[1], vec[0]] elif (degrees == 270): vec = [vec[1], -vec[0]] return vec # [NS / EW] pos = [0, 0] way = [1, 10] # dir = 90 f = open("input.txt", "r") for line in f.readlines(): strippedLine = line.strip() print(strippedLine) res = re.search("^(\w)(\d*)$", strippedLine) letter = res.group(1) value = int(res.group(2)) print("Letter: " + letter) print("Letter: " + str(value)) if (letter == 'F'): pos[0] = pos[0] + way[0] * value pos[1] = pos[1] + way[1] * value if (letter == 'N'): moveDir(way, 0, value) if (letter == 'E'): moveDir(way, 90, value) if (letter == 'S'): moveDir(way, 180, value) if (letter == 'W'): moveDir(way, 270, value) if (letter == 'L'): print("rotate vec left by " + str(value) + " aka " + str((360 - value) % 360)) way = rotateVec(way, (360 - value) % 360) # mod probably not required if (letter == 'R'): print("rotate vec right by " + str(value) + " aka " + str(value % 360)) way = rotateVec(way, value % 360) # print("dir: " + str(dir)) print(way) print(pos) print("final loc: ") print(pos) print("manhattan: " + str(abs(pos[0]) + abs(pos[1])))