How to use prep method in autotest

Best Python code snippet using autotest_python

classifier.py

Source:classifier.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2import DataPrep3import FeatureSelection4import numpy as np5import pandas as pd6import pickle7from sklearn.feature_extraction.text import CountVectorizer8from sklearn.feature_extraction.text import TfidfTransformer9from sklearn.feature_extraction.text import TfidfVectorizer10from sklearn.pipeline import Pipeline11from sklearn.naive_bayes import MultinomialNB12from sklearn.linear_model import LogisticRegression13from sklearn.linear_model import SGDClassifier14from sklearn import svm15from sklearn.ensemble import RandomForestClassifier16from sklearn.model_selection import KFold17from sklearn.metrics import confusion_matrix, f1_score, classification_report18from sklearn.model_selection import GridSearchCV19from sklearn.model_selection import learning_curve20import matplotlib.pyplot as plt21from sklearn.metrics import precision_recall_curve22from sklearn.metrics import average_precision_score23#string to test24doc_new = ['obama is running for president in 2016']25#the feature selection has been done in FeatureSelection.py module. here we will create models using those features for prediction26#first we will use bag of words techniques27#building classifier using naive bayes 28nb_pipeline = Pipeline([29 ('NBCV',FeatureSelection.countV),30 ('nb_clf',MultinomialNB())])31nb_pipeline.fit(DataPrep.train_news['Statement'],DataPrep.train_news['Label'])32predicted_nb = nb_pipeline.predict(DataPrep.test_news['Statement'])33np.mean(predicted_nb == DataPrep.test_news['Label'])34#building classifier using logistic regression35logR_pipeline = Pipeline([36 ('LogRCV',FeatureSelection.countV),37 ('LogR_clf',LogisticRegression())38 ])39logR_pipeline.fit(DataPrep.train_news['Statement'],DataPrep.train_news['Label'])40predicted_LogR = logR_pipeline.predict(DataPrep.test_news['Statement'])41np.mean(predicted_LogR == DataPrep.test_news['Label'])42#building Linear SVM classfier43svm_pipeline = Pipeline([44 ('svmCV',FeatureSelection.countV),45 ('svm_clf',svm.LinearSVC())46 ])47svm_pipeline.fit(DataPrep.train_news['Statement'],DataPrep.train_news['Label'])48predicted_svm = svm_pipeline.predict(DataPrep.test_news['Statement'])49np.mean(predicted_svm == DataPrep.test_news['Label'])50#using SVM Stochastic Gradient Descent on hinge loss51sgd_pipeline = Pipeline([52 ('svm2CV',FeatureSelection.countV),53 ('svm2_clf',SGDClassifier(loss='hinge', penalty='l2', alpha=1e-3, n_iter=5))54 ])55sgd_pipeline.fit(DataPrep.train_news['Statement'],DataPrep.train_news['Label'])56predicted_sgd = sgd_pipeline.predict(DataPrep.test_news['Statement'])57np.mean(predicted_sgd == DataPrep.test_news['Label'])58#random forest59random_forest = Pipeline([60 ('rfCV',FeatureSelection.countV),61 ('rf_clf',RandomForestClassifier(n_estimators=200,n_jobs=3))62 ])63 64random_forest.fit(DataPrep.train_news['Statement'],DataPrep.train_news['Label'])65predicted_rf = random_forest.predict(DataPrep.test_news['Statement'])66np.mean(predicted_rf == DataPrep.test_news['Label'])67#User defined functon for K-Fold cross validatoin68def build_confusion_matrix(classifier):69 70 k_fold = KFold(n_splits=5)71 scores = []72 confusion = np.array([[0,0],[0,0]])73 for train_ind, test_ind in k_fold.split(DataPrep.train_news):74 train_text = DataPrep.train_news.iloc[train_ind]['Statement'] 75 train_y = DataPrep.train_news.iloc[train_ind]['Label']76 77 test_text = DataPrep.train_news.iloc[test_ind]['Statement']78 test_y = DataPrep.train_news.iloc[test_ind]['Label']79 80 classifier.fit(train_text,train_y)81 predictions = classifier.predict(test_text)82 83 confusion += confusion_matrix(test_y,predictions)84 score = f1_score(test_y,predictions)85 scores.append(score)86 87 return (print('Total statements classified:', len(DataPrep.train_news)),88 print('Score:', sum(scores)/len(scores)),89 print('score length', len(scores)),90 print('Confusion matrix:'),91 print(confusion))92 93#K-fold cross validation for all classifiers94build_confusion_matrix(nb_pipeline)95build_confusion_matrix(logR_pipeline)96build_confusion_matrix(svm_pipeline)97build_confusion_matrix(sgd_pipeline)98build_confusion_matrix(random_forest)99#========================================================================================100#Bag of words confusion matrix and F1 scores101#Naive bayes102# [2118 2370]103# [1664 4088]104# f1-Score: 0.669611539651105#Logistic regression106# [2252 2236]107# [1933 3819]108# f1-Score: 0.646909097798109#svm110# [2260 2228]111# [2246 3506]112#f1-score: 0.610468748792113#sgdclassifier114# [2414 2074]115# [2042 3710]116# f1-Score: 0.640874558778117#random forest classifier118# [1821 2667]119# [1192 4560]120# f1-Score: 0.702651511011121#=========================================================================================122"""So far we have used bag of words technique to extract the features and passed those featuers into classifiers. We have also seen the123f1 scores of these classifiers. now lets enhance these features using term frequency weights with various n-grams124"""125##Now using n-grams126#naive-bayes classifier127nb_pipeline_ngram = Pipeline([128 ('nb_tfidf',FeatureSelection.tfidf_ngram),129 ('nb_clf',MultinomialNB())])130nb_pipeline_ngram.fit(DataPrep.train_news['Statement'],DataPrep.train_news['Label'])131predicted_nb_ngram = nb_pipeline_ngram.predict(DataPrep.test_news['Statement'])132np.mean(predicted_nb_ngram == DataPrep.test_news['Label'])133#logistic regression classifier134logR_pipeline_ngram = Pipeline([135 ('LogR_tfidf',FeatureSelection.tfidf_ngram),136 ('LogR_clf',LogisticRegression(penalty="l2",C=1))137 ])138logR_pipeline_ngram.fit(DataPrep.train_news['Statement'],DataPrep.train_news['Label'])139predicted_LogR_ngram = logR_pipeline_ngram.predict(DataPrep.test_news['Statement'])140np.mean(predicted_LogR_ngram == DataPrep.test_news['Label'])141#linear SVM classifier142svm_pipeline_ngram = Pipeline([143 ('svm_tfidf',FeatureSelection.tfidf_ngram),144 ('svm_clf',svm.LinearSVC())145 ])146svm_pipeline_ngram.fit(DataPrep.train_news['Statement'],DataPrep.train_news['Label'])147predicted_svm_ngram = svm_pipeline_ngram.predict(DataPrep.test_news['Statement'])148np.mean(predicted_svm_ngram == DataPrep.test_news['Label'])149#sgd classifier150sgd_pipeline_ngram = Pipeline([151 ('sgd_tfidf',FeatureSelection.tfidf_ngram),152 ('sgd_clf',SGDClassifier(loss='hinge', penalty='l2', alpha=1e-3, n_iter=5))153 ])154sgd_pipeline_ngram.fit(DataPrep.train_news['Statement'],DataPrep.train_news['Label'])155predicted_sgd_ngram = sgd_pipeline_ngram.predict(DataPrep.test_news['Statement'])156np.mean(predicted_sgd_ngram == DataPrep.test_news['Label'])157#random forest classifier158random_forest_ngram = Pipeline([159 ('rf_tfidf',FeatureSelection.tfidf_ngram),160 ('rf_clf',RandomForestClassifier(n_estimators=300,n_jobs=3))161 ])162 163random_forest_ngram.fit(DataPrep.train_news['Statement'],DataPrep.train_news['Label'])164predicted_rf_ngram = random_forest_ngram.predict(DataPrep.test_news['Statement'])165np.mean(predicted_rf_ngram == DataPrep.test_news['Label'])166#K-fold cross validation for all classifiers167build_confusion_matrix(nb_pipeline_ngram)168build_confusion_matrix(logR_pipeline_ngram)169build_confusion_matrix(svm_pipeline_ngram)170build_confusion_matrix(sgd_pipeline_ngram)171build_confusion_matrix(random_forest_ngram)172#========================================================================================173#n-grams & tfidf confusion matrix and F1 scores174#Naive bayes175# [841 3647]176# [427 5325]177# f1-Score: 0.723262051071178#Logistic regression179# [1617 2871]180# [1097 4655]181# f1-Score: 0.70113000531182#svm183# [2016 2472]184# [1524 4228]185# f1-Score: 0.67909201429186#sgdclassifier187# [ 10 4478]188# [ 13 5739]189# f1-Score: 0.718731637053190#random forest191# [1979 2509]192# [1630 4122]193# f1-Score: 0.665720333284194#=========================================================================================195print(classification_report(DataPrep.test_news['Label'], predicted_nb_ngram))196print(classification_report(DataPrep.test_news['Label'], predicted_LogR_ngram))197print(classification_report(DataPrep.test_news['Label'], predicted_svm_ngram))198print(classification_report(DataPrep.test_news['Label'], predicted_sgd_ngram))199print(classification_report(DataPrep.test_news['Label'], predicted_rf_ngram))200DataPrep.test_news['Label'].shape201"""202Out of all the models fitted, we would take 2 best performing model. we would call them candidate models203from the confusion matrix, we can see that random forest and logistic regression are best performing 204in terms of precision and recall (take a look into false positive and true negative counts which appeares205to be low compared to rest of the models)206"""207#grid-search parameter optimization208#random forest classifier parameters209parameters = {'rf_tfidf__ngram_range': [(1, 1), (1, 2),(1,3),(1,4),(1,5)],210 'rf_tfidf__use_idf': (True, False),211 'rf_clf__max_depth': (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)212}213gs_clf = GridSearchCV(random_forest_ngram, parameters, n_jobs=-1)214gs_clf = gs_clf.fit(DataPrep.train_news['Statement'][:10000],DataPrep.train_news['Label'][:10000])215gs_clf.best_score_216gs_clf.best_params_217gs_clf.cv_results_218#logistic regression parameters219parameters = {'LogR_tfidf__ngram_range': [(1, 1), (1, 2),(1,3),(1,4),(1,5)],220 'LogR_tfidf__use_idf': (True, False),221 'LogR_tfidf__smooth_idf': (True, False)222}223gs_clf = GridSearchCV(logR_pipeline_ngram, parameters, n_jobs=-1)224gs_clf = gs_clf.fit(DataPrep.train_news['Statement'][:10000],DataPrep.train_news['Label'][:10000])225gs_clf.best_score_226gs_clf.best_params_227gs_clf.cv_results_228#Linear SVM 229parameters = {'svm_tfidf__ngram_range': [(1, 1), (1, 2),(1,3),(1,4),(1,5)],230 'svm_tfidf__use_idf': (True, False),231 'svm_tfidf__smooth_idf': (True, False),232 'svm_clf__penalty': ('l1','l2'),233}234gs_clf = GridSearchCV(svm_pipeline_ngram, parameters, n_jobs=-1)235gs_clf = gs_clf.fit(DataPrep.train_news['Statement'][:10000],DataPrep.train_news['Label'][:10000])236gs_clf.best_score_237gs_clf.best_params_238gs_clf.cv_results_239#by running above commands we can find the model with best performing parameters240#running both random forest and logistic regression models again with best parameter found with GridSearch method241random_forest_final = Pipeline([242 ('rf_tfidf',TfidfVectorizer(stop_words='english',ngram_range=(1,3),use_idf=True,smooth_idf=True)),243 ('rf_clf',RandomForestClassifier(n_estimators=300,n_jobs=3,max_depth=10))244 ])245 246random_forest_final.fit(DataPrep.train_news['Statement'],DataPrep.train_news['Label'])247predicted_rf_final = random_forest_final.predict(DataPrep.test_news['Statement'])248np.mean(predicted_rf_final == DataPrep.test_news['Label'])249print(metrics.classification_report(DataPrep.test_news['Label'], predicted_rf_final))250logR_pipeline_final = Pipeline([251 #('LogRCV',countV_ngram),252 ('LogR_tfidf',TfidfVectorizer(stop_words='english',ngram_range=(1,5),use_idf=True,smooth_idf=False)),253 ('LogR_clf',LogisticRegression(penalty="l2",C=1))254 ])255logR_pipeline_final.fit(DataPrep.train_news['Statement'],DataPrep.train_news['Label'])256predicted_LogR_final = logR_pipeline_final.predict(DataPrep.test_news['Statement'])257np.mean(predicted_LogR_final == DataPrep.test_news['Label'])258#accuracy = 0.62259print(metrics.classification_report(DataPrep.test_news['Label'], predicted_LogR_final))260"""261by running both random forest and logistic regression with GridSearch's best parameter estimation, we found that for random 262forest model with n-gram has better accuracty than with the parameter estimated. The logistic regression model with best parameter 263has almost similar performance as n-gram model so logistic regression will be out choice of model for prediction.264"""265#saving best model to the disk266model_file = 'final_model.sav'267pickle.dump(logR_pipeline_ngram,open(model_file,'wb'))268#Plotting learing curve269def plot_learing_curve(pipeline,title):270 size = 10000271 cv = KFold(size, shuffle=True)272 273 X = DataPrep.train_news["Statement"]274 y = DataPrep.train_news["Label"]275 276 pl = pipeline277 pl.fit(X,y)278 279 train_sizes, train_scores, test_scores = learning_curve(pl, X, y, n_jobs=-1, cv=cv, train_sizes=np.linspace(.1, 1.0, 5), verbose=0)280 281 train_scores_mean = np.mean(train_scores, axis=1)282 train_scores_std = np.std(train_scores, axis=1)283 test_scores_mean = np.mean(test_scores, axis=1)284 test_scores_std = np.std(test_scores, axis=1)285 286 plt.figure()287 plt.title(title)288 plt.legend(loc="best")289 plt.xlabel("Training examples")290 plt.ylabel("Score")291 plt.gca().invert_yaxis()292 293 # box-like grid294 plt.grid()295 296 # plot the std deviation as a transparent range at each training set size297 plt.fill_between(train_sizes, train_scores_mean - train_scores_std, train_scores_mean + train_scores_std, alpha=0.1, color="r")298 plt.fill_between(train_sizes, test_scores_mean - test_scores_std, test_scores_mean + test_scores_std, alpha=0.1, color="g")299 300 # plot the average training and test score lines at each training set size301 plt.plot(train_sizes, train_scores_mean, 'o-', color="r", label="Training score")302 plt.plot(train_sizes, test_scores_mean, 'o-', color="g", label="Cross-validation score")303 304 # sizes the window for readability and displays the plot305 # shows error from 0 to 1.1306 plt.ylim(-.1,1.1)307 plt.show()308#below command will plot learing curves for each of the classifiers309plot_learing_curve(logR_pipeline_ngram,"Naive-bayes Classifier")310plot_learing_curve(nb_pipeline_ngram,"LogisticRegression Classifier")311plot_learing_curve(svm_pipeline_ngram,"SVM Classifier")312plot_learing_curve(sgd_pipeline_ngram,"SGD Classifier")313plot_learing_curve(random_forest_ngram,"RandomForest Classifier")314"""315by plotting the learning cureve for logistic regression, it can be seen that cross-validation score is stagnating throughout and it 316is unable to learn from data. Also we see that there are high errors that indicates model is simple and we may want to increase the317model complexity.318"""319#plotting Precision-Recall curve320def plot_PR_curve(classifier):321 322 precision, recall, thresholds = precision_recall_curve(DataPrep.test_news['Label'], classifier)323 average_precision = average_precision_score(DataPrep.test_news['Label'], classifier)324 325 plt.step(recall, precision, color='b', alpha=0.2,326 where='post')327 plt.fill_between(recall, precision, step='post', alpha=0.2,328 color='b')329 330 plt.xlabel('Recall')331 plt.ylabel('Precision')332 plt.ylim([0.0, 1.05])333 plt.xlim([0.0, 1.0])334 plt.title('2-class Random Forest Precision-Recall curve: AP={0:0.2f}'.format(335 average_precision))336 337plot_PR_curve(predicted_LogR_ngram)338plot_PR_curve(predicted_rf_ngram)339"""340Now let's extract the most informative feature from ifidf vectorizer for all fo the classifiers and see of there are any common341words that we can identify i.e. are these most informative feature acorss the classifiers are same? we will create a function that 342will extract top 50 features.343"""344def show_most_informative_features(model, vect, clf, text=None, n=50):345 # Extract the vectorizer and the classifier from the pipeline346 vectorizer = model.named_steps[vect]347 classifier = model.named_steps[clf]348 # Check to make sure that we can perform this computation349 if not hasattr(classifier, 'coef_'):350 raise TypeError(351 "Cannot compute most informative features on {}.".format(352 classifier.__class__.__name__353 )354 )355 356 if text is not None:357 # Compute the coefficients for the text358 tvec = model.transform([text]).toarray()359 else:360 # Otherwise simply use the coefficients361 tvec = classifier.coef_362 # Zip the feature names with the coefs and sort363 coefs = sorted(364 zip(tvec[0], vectorizer.get_feature_names()),365 reverse=True366 )367 368 # Get the top n and bottom n coef, name pairs369 topn = zip(coefs[:n], coefs[:-(n+1):-1])370 # Create the output string to return371 output = []372 # If text, add the predicted value to the output.373 if text is not None:374 output.append("\"{}\"".format(text))375 output.append(376 "Classified as: {}".format(model.predict([text]))377 )378 output.append("")379 # Create two columns with most negative and most positive features.380 for (cp, fnp), (cn, fnn) in topn:381 output.append(382 "{:0.4f}{: >15} {:0.4f}{: >15}".format(383 cp, fnp, cn, fnn384 )385 )386 #return "\n".join(output)387 print(output)388show_most_informative_features(logR_pipeline_ngram,vect='LogR_tfidf',clf='LogR_clf')389show_most_informative_features(nb_pipeline_ngram,vect='nb_tfidf',clf='nb_clf')390show_most_informative_features(svm_pipeline_ngram,vect='svm_tfidf',clf='svm_clf')...

Full Screen

Full Screen

test_promises.py

Source:test_promises.py Github

copy

Full Screen

1import datetime2from decimal import Decimal3from django.db.models.fields import (4 AutoField, BinaryField, BooleanField, CharField, DateField, DateTimeField,5 DecimalField, EmailField, FilePathField, FloatField, GenericIPAddressField,6 IntegerField, IPAddressField, NullBooleanField, PositiveBigIntegerField,7 PositiveIntegerField, PositiveSmallIntegerField, SlugField,8 SmallIntegerField, TextField, TimeField, URLField,9)10from django.db.models.fields.files import FileField, ImageField11from django.test import SimpleTestCase12from django.utils.functional import lazy13class PromiseTest(SimpleTestCase):14 def test_AutoField(self):15 lazy_func = lazy(lambda: 1, int)16 self.assertIsInstance(AutoField(primary_key=True).get_prep_value(lazy_func()), int)17 def test_BinaryField(self):18 lazy_func = lazy(lambda: b'', bytes)19 self.assertIsInstance(BinaryField().get_prep_value(lazy_func()), bytes)20 def test_BooleanField(self):21 lazy_func = lazy(lambda: True, bool)22 self.assertIsInstance(BooleanField().get_prep_value(lazy_func()), bool)23 def test_CharField(self):24 lazy_func = lazy(lambda: '', str)25 self.assertIsInstance(CharField().get_prep_value(lazy_func()), str)26 lazy_func = lazy(lambda: 0, int)27 self.assertIsInstance(CharField().get_prep_value(lazy_func()), str)28 def test_DateField(self):29 lazy_func = lazy(lambda: datetime.date.today(), datetime.date)30 self.assertIsInstance(DateField().get_prep_value(lazy_func()), datetime.date)31 def test_DateTimeField(self):32 lazy_func = lazy(lambda: datetime.datetime.now(), datetime.datetime)33 self.assertIsInstance(DateTimeField().get_prep_value(lazy_func()), datetime.datetime)34 def test_DecimalField(self):35 lazy_func = lazy(lambda: Decimal('1.2'), Decimal)36 self.assertIsInstance(DecimalField().get_prep_value(lazy_func()), Decimal)37 def test_EmailField(self):38 lazy_func = lazy(lambda: 'mailbox@domain.com', str)39 self.assertIsInstance(EmailField().get_prep_value(lazy_func()), str)40 def test_FileField(self):41 lazy_func = lazy(lambda: 'filename.ext', str)42 self.assertIsInstance(FileField().get_prep_value(lazy_func()), str)43 lazy_func = lazy(lambda: 0, int)44 self.assertIsInstance(FileField().get_prep_value(lazy_func()), str)45 def test_FilePathField(self):46 lazy_func = lazy(lambda: 'tests.py', str)47 self.assertIsInstance(FilePathField().get_prep_value(lazy_func()), str)48 lazy_func = lazy(lambda: 0, int)49 self.assertIsInstance(FilePathField().get_prep_value(lazy_func()), str)50 def test_FloatField(self):51 lazy_func = lazy(lambda: 1.2, float)52 self.assertIsInstance(FloatField().get_prep_value(lazy_func()), float)53 def test_ImageField(self):54 lazy_func = lazy(lambda: 'filename.ext', str)55 self.assertIsInstance(ImageField().get_prep_value(lazy_func()), str)56 def test_IntegerField(self):57 lazy_func = lazy(lambda: 1, int)58 self.assertIsInstance(IntegerField().get_prep_value(lazy_func()), int)59 def test_IPAddressField(self):60 lazy_func = lazy(lambda: '127.0.0.1', str)61 self.assertIsInstance(IPAddressField().get_prep_value(lazy_func()), str)62 lazy_func = lazy(lambda: 0, int)63 self.assertIsInstance(IPAddressField().get_prep_value(lazy_func()), str)64 def test_GenericIPAddressField(self):65 lazy_func = lazy(lambda: '127.0.0.1', str)66 self.assertIsInstance(GenericIPAddressField().get_prep_value(lazy_func()), str)67 lazy_func = lazy(lambda: 0, int)68 self.assertIsInstance(GenericIPAddressField().get_prep_value(lazy_func()), str)69 def test_NullBooleanField(self):70 lazy_func = lazy(lambda: True, bool)71 self.assertIsInstance(NullBooleanField().get_prep_value(lazy_func()), bool)72 def test_PositiveIntegerField(self):73 lazy_func = lazy(lambda: 1, int)74 self.assertIsInstance(PositiveIntegerField().get_prep_value(lazy_func()), int)75 def test_PositiveSmallIntegerField(self):76 lazy_func = lazy(lambda: 1, int)77 self.assertIsInstance(PositiveSmallIntegerField().get_prep_value(lazy_func()), int)78 def test_PositiveBigIntegerField(self):79 lazy_func = lazy(lambda: 1, int)80 self.assertIsInstance(PositiveBigIntegerField().get_prep_value(lazy_func()), int)81 def test_SlugField(self):82 lazy_func = lazy(lambda: 'slug', str)83 self.assertIsInstance(SlugField().get_prep_value(lazy_func()), str)84 lazy_func = lazy(lambda: 0, int)85 self.assertIsInstance(SlugField().get_prep_value(lazy_func()), str)86 def test_SmallIntegerField(self):87 lazy_func = lazy(lambda: 1, int)88 self.assertIsInstance(SmallIntegerField().get_prep_value(lazy_func()), int)89 def test_TextField(self):90 lazy_func = lazy(lambda: 'Abc', str)91 self.assertIsInstance(TextField().get_prep_value(lazy_func()), str)92 lazy_func = lazy(lambda: 0, int)93 self.assertIsInstance(TextField().get_prep_value(lazy_func()), str)94 def test_TimeField(self):95 lazy_func = lazy(lambda: datetime.datetime.now().time(), datetime.time)96 self.assertIsInstance(TimeField().get_prep_value(lazy_func()), datetime.time)97 def test_URLField(self):98 lazy_func = lazy(lambda: 'http://domain.com', str)...

Full Screen

Full Screen

cnf.py

Source:cnf.py Github

copy

Full Screen

1prep=input("Enter the preposition logic: ")2di=prep.find('<=>')3if di == -1:4 pass5else:6 print(di)7 prep=prep[0:di]+"=>"+prep[di+3:len(prep)]+" ^ "+prep[di+3:]+"=>"+prep[:di]8 print("\n1.Removing double implies: "+prep)9i=prep.find('=>')10while(i!=-1):11 if prep[i-1]!=")":12 prep=prep[0:i-1]+"!"+prep[i-1]+" v "+prep[i+2:]13 else:14 '''ib=prep.find('(')'''15 j=i16 while prep[j]!='(':17 j-=118 prep=prep[0:j]+"!"+prep[j:i]+" v "+prep[i+2:]19 i=prep.find('=>')20print("\n2.Removing single implies: "+prep)21n=prep.find('!(')22while(n!=-1):23 if prep[n+1]=='(':24 l=len(prep)25 prepn=prep26 prep=prepn[0:n+1]27 i=n+228 while(prepn[i]!='^' and prepn[i]!='v'):29 if(prepn[i]!='('):30 prep+=prepn[i]31 i+=132 if prepn[i]=='^':33 prep+=' v '34 elif prepn[i]=='v':35 prep+=' ^ '36 prep+='!'+prepn[i+1:prepn.find(')',i)]37 prep+=prepn[prepn.find(')',i)+1:]38 n=prep.find('!(')39print("\n3.Demorgan's Law: "+prep)40prep = prep.replace("! !", "")41print("\n4.Removing double negation: "+prep)42prepn=prep43prep=""44for i in prepn:45 if i!='(' and i!=')':46 prep+=i47print("\n5.Removing unwanted brackets: "+prep)48prepn=prep49prep="("50for i in prepn:51 if i=='^':52 prep+=') ^ ('53 else:54 prep+=i55prep+=')'...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run autotest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful