title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
Python Pandas – Check for Null values using notnull()
|
The notnull() method returns a Boolean value i.e. if the DataFrame is having null value(s), then False is returned, else True.
Let’s say the following is our CSV file with some NaN i.e. null values −
Let us first read the CSV file −
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\CarRecords.csv")
Checking for not null values −
res = dataFrame.notnull()
Now, on displaying the DataFrame, the CSV data will be displayed in the form of True and False i.e. boolean values because notnull() returns boolean. For Null values, False will get displayed. For Not-Null values, True will get displayed.
Following is the complete code −
import pandas as pd
# reading csv file
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\CarRecords.csv")
print("DataFrame...\n",dataFrame)
# count the rows and columns in a DataFrame
print("\nNumber of rows and column in our DataFrame = ",dataFrame.shape)
res = dataFrame.notnull()
print("\nDataFrame displaying False for Null (NaN) value = \n",res)
dataFrame = dataFrame.dropna()
print("\nDataFrame after removing null values...\n",dataFrame)
print("\n(Updated) Number of rows and column in our DataFrame = ",dataFrame.shape)
This will produce the following output −
DataFrame...
Car Place UnitsSold
0 Audi Bangalore 80.0
1 Porsche Mumbai 110.0
2 RollsRoyce Pune NaN
3 BMW Delhi 200.0
4 Mercedes Hyderabad 80.0
5 Lamborghini Chandigarh NaN
6 Audi Mumbai NaN
7 Mercedes Pune 120.0
8 Lamborghini Delhi 100.0
Number of rows and column in our DataFrame = (9, 3)
DataFrame displaying False for Null values =
Car Place UnitsSold
0 True True True
1 True True True
2 True True False
3 True True True
4 True True True
5 True True False
6 True True False
7 True True True
8 True True True
DataFrame after removing null values...
Car Place UnitsSold
0 Audi Bangalore 80.0
1 Porsche Mumbai 110.0
3 BMW Delhi 200.0
4 Mercedes Hyderabad 80.0
7 Mercedes Pune 120.0
8 Lamborghini Delhi 100.0
(Updated)Number of rows and column in our DataFrame = (6, 3)
|
[
{
"code": null,
"e": 1189,
"s": 1062,
"text": "The notnull() method returns a Boolean value i.e. if the DataFrame is having null value(s), then False is returned, else True."
},
{
"code": null,
"e": 1262,
"s": 1189,
"text": "Let’s say the following is our CSV file with some NaN i.e. null values −"
},
{
"code": null,
"e": 1295,
"s": 1262,
"text": "Let us first read the CSV file −"
},
{
"code": null,
"e": 1364,
"s": 1295,
"text": "dataFrame = pd.read_csv(\"C:\\\\Users\\\\amit_\\\\Desktop\\\\CarRecords.csv\")"
},
{
"code": null,
"e": 1395,
"s": 1364,
"text": "Checking for not null values −"
},
{
"code": null,
"e": 1421,
"s": 1395,
"text": "res = dataFrame.notnull()"
},
{
"code": null,
"e": 1660,
"s": 1421,
"text": "Now, on displaying the DataFrame, the CSV data will be displayed in the form of True and False i.e. boolean values because notnull() returns boolean. For Null values, False will get displayed. For Not-Null values, True will get displayed."
},
{
"code": null,
"e": 1693,
"s": 1660,
"text": "Following is the complete code −"
},
{
"code": null,
"e": 2227,
"s": 1693,
"text": "import pandas as pd\n\n# reading csv file\ndataFrame = pd.read_csv(\"C:\\\\Users\\\\amit_\\\\Desktop\\\\CarRecords.csv\")\nprint(\"DataFrame...\\n\",dataFrame)\n\n# count the rows and columns in a DataFrame\nprint(\"\\nNumber of rows and column in our DataFrame = \",dataFrame.shape)\n\nres = dataFrame.notnull()\nprint(\"\\nDataFrame displaying False for Null (NaN) value = \\n\",res)\n\ndataFrame = dataFrame.dropna()\nprint(\"\\nDataFrame after removing null values...\\n\",dataFrame)\nprint(\"\\n(Updated) Number of rows and column in our DataFrame = \",dataFrame.shape)"
},
{
"code": null,
"e": 2268,
"s": 2227,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 3419,
"s": 2268,
"text": "DataFrame...\n Car Place UnitsSold\n0 Audi Bangalore 80.0\n1 Porsche Mumbai 110.0\n2 RollsRoyce Pune NaN\n3 BMW Delhi 200.0\n4 Mercedes Hyderabad 80.0\n5 Lamborghini Chandigarh NaN\n6 Audi Mumbai NaN\n7 Mercedes Pune 120.0\n8 Lamborghini Delhi 100.0\n\nNumber of rows and column in our DataFrame = (9, 3)\n\nDataFrame displaying False for Null values =\n Car Place UnitsSold\n0 True True True\n1 True True True\n2 True True False\n3 True True True\n4 True True True\n5 True True False\n6 True True False\n7 True True True\n8 True True True\n\nDataFrame after removing null values...\n Car Place UnitsSold\n0 Audi Bangalore 80.0\n1 Porsche Mumbai 110.0\n3 BMW Delhi 200.0\n4 Mercedes Hyderabad 80.0\n7 Mercedes Pune 120.0\n8 Lamborghini Delhi 100.0\n\n(Updated)Number of rows and column in our DataFrame = (6, 3)"
}
] |
Classification on a large and noisy dataset with R | by Gabriel Pierobon | Towards Data Science
|
Some days ago I wrote an article describing a comprehensive supervised learning workflow in R with multiple modelling using packages caret and caretEnsemble. Back then I mentioned that the I was using was kind of an easy one, in the sense that it was fully numeric, perfectly filled (not a single missing value), no categorical features, no class imbalance (of course since it was a regression problem), and it was a fairly small dataset with just 8 predictors.
It felt almost like cheating but it really helped both for my first article written but also to go through the full workflow without much trouble and finally to do some multiple modelling using caretEnsemble.
So now I’ve decided to take this from easy difficulty to normal difficulty.
In that sense, I came across this dataset in the UCI Machine Learning Repository which I intend to use.
What is the new difficulty we come across with this dataset? Let me summarize it:
Target variable is categorical binomial, with a very high class imbalanceSize of the data set is fairly large. Training set is 60,000 x 171 and test set is 16,000 x 171Huge missing values issuePotential presence of outliers and and multicollinarityThere are specific cost associated to type 1 errors and type 2 errors, which requires that we minimize type 2 errors.
Target variable is categorical binomial, with a very high class imbalance
Size of the data set is fairly large. Training set is 60,000 x 171 and test set is 16,000 x 171
Huge missing values issue
Potential presence of outliers and and multicollinarity
There are specific cost associated to type 1 errors and type 2 errors, which requires that we minimize type 2 errors.
This is the description of the dataset and task included by the owner of the repository:
“The dataset consists of data collected from heavy Scania trucks in everyday usage. The system in focus is the Air Pressure system (APS) which generates pressurized air that are utilized in various functions in a truck, such as braking and gear changes. The datasets’ positive class consists of component failures for a specific component of the APS system. The negative class consists of trucks with failures for components not related to the APS. The data consists of a subset of all available data, selected by experts.
The attribute names of the data have been anonymized for proprietary reasons. It consists of both single numerical counters and histograms consisting of bins with different conditions. (...) In total there are 171 attributes, of which 7 are histogram variables. Missing values are denoted by “na”.
— Challenge metric
Cost-metric of miss-classification:
In this case Cost_1 refers to the cost that an unnecessary check needs to be done by an mechanic at an workshop, while Cost_2 refer to the cost of missing a faulty truck, which may cause a breakdown.
Total_cost = Cost_1 * No_Instances + Cost_2 * No_Instances
We’ll give it a try!
1.1) What are we trying to predict?
We need to predict the type of system failure. It can be either a failing component of the APS or a failing component not related to the APS. This is very important since our prediction errors can result in unnecessary spending by the company. Specifically we want to avoid type 2 errors (cost of missing a faulty truck, which may cause a breakdown).
2.2) What type of problem is it? Supervised or Unsupervised Learning? Classification or Regression? Binary or Multi-class? Uni-variate or Multi-variate?
It is a binary classification problem with multiple features.
2.3) What type of data do we have?
We have two csv files, one for training and one for testing. Both present 20 unimportant text lines before the actual data begins and we we will have to skip those lines when importing the data frame. There is one row for column names and missing values are denoted by “na”, so we will make sure we include that when we read the csv.
2.4) Import the dataset
training_data <- read.csv("aps_failure_traning_set.csv", skip = 20, na.strings = "na")test_data <- read.csv("aps_failure_test_set.csv", skip = 20, na.strings = "na")
We check the dimensions of both data sets:
dim(training_data)dim(test_data)[1] 60000 171[1] 16000 171
2.5) Activate packages to be used during the project
library(dplyr)library(caret)library(caretEnsemble)library(mice)library(doParallel)library(car)
2.1) View Data (str or dplyr’s glimpse). First look. Anything strange?
Specifying na.strings=”na" when we imported the sets allows R to recognize each feature as numeric. If we didn’t do that, the presence of na in each column would automatically result in them being categorized as character type.
Using the code below, we can see that other than our response variable class, all the other features are numeric.
glimpse(training_data)glimpse(test_data)
2.2) Is it a “tidy” dataset? Need to “gather” or “spread” it? Is it presented in a way we can work with?
It’s tidy. Each row is an observation, each column is a feature.
2.3) rownames and colnames ok? Should we change them?
I don’t see a reason to change them.
2.4) Check data types. Are they OK? If not, convert
We already assessed that data types are ok. Here you want to also check that the response variable is of the factor type, with the expected two levels.
2.5) What is our response/target variable? Class imbalance? Study it
Our target variable is class, with two levels: neg and pos. Positive class consists of component failures for a specific component of the APS system. The negative class consists of trucks with failures for components not related to the APS.
How many neg and pos do we have in each set?
summary(training_data$class)summary(test_data$class) neg pos 59000 1000 neg pos 15625 375
Let’s check proportions:
options(digits = 2)prop.table(table(training_data$class))prop.table(table(test_data$class))neg pos 0.983 0.017neg pos 0.977 0.023
Ok, looks like have a problem here. Class is totally imbalanced.
We could come up with a useless model that classified every observation as neg and get 97.7% accuracy, so let’s be careful with our accuracy score interpretation.
Later we’ll see how we can deal with class imbalance.
2.6) Rest of the features. Summary statistics. Understand your data
We are working with 171 features, so calling summary() on the entire dataset is not going to help a lot in terms of visual interpretation. Instead, we are going to create a data frame out of the summary() function. This will enable us to calculate some new statistics, specifically related to missing values, which as you will see, is another big issue of this data.
With this summary data frame we will also calculate the mean quartiles for all the data. This will also allow us to understand more about the distribution of the features and the average number of missing values.
options(scipen = 999)summary_df <- do.call(cbind, lapply(training_data[, 2:ncol(training_data)], summary))summary_df_t <- as.data.frame(round(t(summary_df),0))names(summary_df_t)[7] <- paste("Missing_values")summary_df_t_2 <- summary_df_t %>% mutate(obs = nrow(training_data), Missing_prop = Missing_values / obs)print(summary_df_t_2)
summary_df_t_2 %>% summarise(Min = mean(Min.), first_Q = mean(`1st Qu.`), Median = median(Median), Mean = mean(Mean), third_Q = mean(`3rd Qu.`), Max = max(Max.), mean_MV = mean(Missing_values), obs = mean(obs), mean_MV_perc = mean_MV / obs)
We can see above that the average number of missing values per feature is 5,000 out of 60,000 samples. This means we have 8.3% o missing values in average in each column. That is a lot!
Let’s check the same for our test set:
Again, we have 8.4% missing values. We’ll have to deal with them and there’s a specific section for that afterwards.
2.7) Categorical data/Factors: create count tables to understand different categories. Check all of them.
We are not working with any other categorical feature other than our response variable.
2.8) Unnecessary columns? Columns we can quickly understand we don’t need. Drop them
So far, we haven’t detected any column that we want to remove at this time. We will leave this for later.
2.9) Check for missing values. How many? Where? Delete them? Impute them?
Our features present more than 8% missing values in average.
Because it’s a lot of information we don’t want to lose, our approach is going to be to impute them. But first, we don’t want to use a technique to impute each of our two sets separately (train and test). It has to be a one time imputation using full information. In order to do this, we are going to combine both sets, work on them and then separate again.
#replicate our setstraining_data_bind <- training_datatest_data_bind <- test_data#create a new column "set" to label the observationstraining_data_bind$set <- "TRAIN"test_data_bind$set <- "TEST"#merge them into 1 single setfull_dataset <- rbind(training_data_bind, test_data_bind)dim(full_dataset)[1] 76000 172
We end up with a single set containing 76,000 samples (16,000 from test set and 60,000 from train set). The number of columns is 172 (171 features + 1 “set” column)
Missing values imputation
We are going to impute missing values using package mice. Here’s a nice explanation of how mice works
The following formula allows us to impute the full dataset using mean imputation:
set.seed(123)imputed_full <- mice(full_dataset, m=1, maxit = 5, method = "mean", seed = 500)
Now we store the imputed values:
full_imputed <- complete(imputed_full, 1)
We then check that we still maintain the same dimensions:
dim(full_imputed)[1] 76000 172
And now let’s check that we don’t have missing values:
(na_count_full_imputed <-data.frame(sapply(full_imputed, function(y) sum(length(which(is.na(y)))))))
Wait. If you run that code and look at each row, you will notice there are some features that still have missing values. Specifically there are 9 rows.
Let’s take a look at what is causing them:
issue_columns <- subset(imputed_full$loggedEvents, meth == "constant" | meth == "collinear")print(issue_columns)
I filtered the $loggedEvents attribute of the imputed data frame. Here we see that some features were tagged as constant or collinear. One of them is our set column (the one we used to combine the two sets into one), so we don’t worry about that one. The rest of them are mainly collinear variables and one constant variable. mice automatically skips those columns and lets us know of the issue. We will want to drop those features so we have a full dataset without missing values.
To do that, we first store the column names being careful not to store the set column name (we need it)
#create vector of column namesissue_columns_names <- as.character(issue_columns[, "out"])issue_columns_names <- issue_columns_names[-2]print(issue_columns_names)[1] "cd_000" "bt_000" "ah_000" "bu_000" "bv_000" "cq_000" "cf_000" "co_000"
We then use the stored vector to remove those columns from the data frame and store it as our final imputed data frame:
full_imputed_filtered <- full_imputed[ , !(names(full_imputed) %in% issue_columns_names)]dim(full_imputed_filtered)[1] 76000 164
Notice the number of columns reduced from 172 to 164.
Now we don’t have missing values any more! (check it!)
Finally, it’s time to separate our full imputed dataset into train and test sets again, and we need to separate it into the exact same samples that it was splitted before. In order to do that we just filter the data frame using our set column.
#subset the full_imputed_filtered datasettraining_data_imp <- subset(full_imputed_filtered, set == "TRAIN")test_data_imp <- subset(full_imputed_filtered, set == "TEST")#drop the "set" column, we don't need it anymoretraining_data_imp$set <- NULLtest_data_imp$set <- NULL#check dimensionsdim(training_data_imp)dim(test_data_imp)[1] 60000 163[1] 16000 163
Great!, we have our training and test set splitted and with no missing values!
2.10) Check for outliers and other inconsistent data points. Box-plots. Cooks’ distance. DBSCAN?
For this dataset we are going to use cook’s distance:
cooksd <- cooks.distance(glm(class ~ ., family = "binomial", data = training_data_imp))
Let’s plot the results:
plot(cooksd, pch="*", cex=2, main="Influential Obs by Cooks distance") abline(h = 4*mean(cooksd, na.rm=T), col="red")
In this plot, what seems to be a dark thick black line is actually all our data points. In the right-top corner we see also what seems to be 1 outlier, or a bunch of them grouped.
Let’s check how many are there:
outliers <- rownames(training_data_imp[cooksd > 4*mean(cooksd, na.rm=T), ])print(outliers)[1] "617" "3993" "5349" "10383" "10829" "18764" "19301" "21138" "22787" "24360" "24975" "29146" "30633" "33684"[15] "38785" "45978" "50283" "51003" "52573" "53283" "54957" "57186"
This is a total of 22 points that are considered outliers according to cook’s distance test.
Since this is a very low number of observations compared to our total 60,000 I decided not to remove them. This just seems to be variability in the measurement rather than experimental error.
2.11) Check for multicollinearity in numeric data
Last step ouf our EDA phase is to check for multicollinearity. We have already removed some collumns which mice detected as collinear. Here we will just do some analysis of how many bivariate relations have high correlation and if it’s a significant high proportion:
sum((correlation > 0.5 | correlation < -0.5) & correlation < 1) / (162*162)[1] 0.12sum((correlation > 0.7 | correlation < -0.7) & correlation < 1) / (162*162)[1] 0.047sum((correlation > 0.9 | correlation < -0.9) & correlation < 1) / (162*162)[1] 0.0055
This means that out of 26,244 possible variable correlations:
12% present scores higher than 0.5
4.7% higher than 0.7
and 0.55% higher than 0.9
I won’t go any further than this and consider multicollinearity not to be a big issue at this point.
We won’t also spend time engineering features in this already heavy feature loaded dataset. There is no additional information we could use.
We have now both our training and testing data sets ready for modelling. We have imputed missing values, removed collinear features and verified that outliers and multicollinearity is not a big deal that we should be concerned about.
Due to the size of the data, we will train a Logistic Regression model and a Naive Bayes model. Both are very fast compared to more advanced algorithms such as random forests, SVMs or gradient boosting models.
I’m not looking here to win the contest but to have an acceptable scoring just to demonstrate.
I’ll use caretEnsemble’s caretList()to train both at the same time and with the same resampling .
Notice I’m specifying “up”-sampling within trainControl(). This will take care of class imbalance. More about upsampling.
registerDoParallel(3)getDoParWorkers()set.seed(123)my_ctrl <- trainControl(method = "cv", number = 5, classProbs = TRUE, savePredictions = "final", index = createResample(training_data_imp$class, 3), sampling = "up", allowParallel = TRUE)model_list <- caretList(class ~ ., data = training_data_imp, methodList = c("glm", "nb"), metric = "Kappa", tuneList = NULL, continue_on_fail = FALSE, preProcess = c("center", "scale"), trControl = my_ctrl)
Our results:
Notice that our accuracy scores are lower than our usless predict-all-neg model that had 97,7%. The reason we don’t score higher is because we upsampled the data, thus generated new data points to fix the class imbalance. We did it as a parameter set within caret’s trainControl so I’m not showing any details of that, but by doing it, we have improved our ability to predict the positive class (in this case “neg”) in detriment of just looking to maximize accuracy.
Let’s quickly check the confusion matrices:
#Logistic Regression modelconfusionMatrix(predict(model_list$glm,test_data_imp, type = "raw"), test_data_imp$class)#Naive Bayes modelconfusionMatrix(predict(model_list$nb,test_data_imp, type = "raw"), test_data_imp$class)
According to the cost matrix for each type of error, our scoring is:
Logistic Regression model: 52 x 500 + 834 x 10 = 34,340
Naive Bayes Model: 42 x 500 + 498 x 10 = 25,980
This is fine-ish performance for this quick of a modelling. I bet that with some more work we can get very close to the best 3 contestants:
|
[
{
"code": null,
"e": 508,
"s": 46,
"text": "Some days ago I wrote an article describing a comprehensive supervised learning workflow in R with multiple modelling using packages caret and caretEnsemble. Back then I mentioned that the I was using was kind of an easy one, in the sense that it was fully numeric, perfectly filled (not a single missing value), no categorical features, no class imbalance (of course since it was a regression problem), and it was a fairly small dataset with just 8 predictors."
},
{
"code": null,
"e": 717,
"s": 508,
"text": "It felt almost like cheating but it really helped both for my first article written but also to go through the full workflow without much trouble and finally to do some multiple modelling using caretEnsemble."
},
{
"code": null,
"e": 793,
"s": 717,
"text": "So now I’ve decided to take this from easy difficulty to normal difficulty."
},
{
"code": null,
"e": 897,
"s": 793,
"text": "In that sense, I came across this dataset in the UCI Machine Learning Repository which I intend to use."
},
{
"code": null,
"e": 979,
"s": 897,
"text": "What is the new difficulty we come across with this dataset? Let me summarize it:"
},
{
"code": null,
"e": 1345,
"s": 979,
"text": "Target variable is categorical binomial, with a very high class imbalanceSize of the data set is fairly large. Training set is 60,000 x 171 and test set is 16,000 x 171Huge missing values issuePotential presence of outliers and and multicollinarityThere are specific cost associated to type 1 errors and type 2 errors, which requires that we minimize type 2 errors."
},
{
"code": null,
"e": 1419,
"s": 1345,
"text": "Target variable is categorical binomial, with a very high class imbalance"
},
{
"code": null,
"e": 1515,
"s": 1419,
"text": "Size of the data set is fairly large. Training set is 60,000 x 171 and test set is 16,000 x 171"
},
{
"code": null,
"e": 1541,
"s": 1515,
"text": "Huge missing values issue"
},
{
"code": null,
"e": 1597,
"s": 1541,
"text": "Potential presence of outliers and and multicollinarity"
},
{
"code": null,
"e": 1715,
"s": 1597,
"text": "There are specific cost associated to type 1 errors and type 2 errors, which requires that we minimize type 2 errors."
},
{
"code": null,
"e": 1804,
"s": 1715,
"text": "This is the description of the dataset and task included by the owner of the repository:"
},
{
"code": null,
"e": 2327,
"s": 1804,
"text": "“The dataset consists of data collected from heavy Scania trucks in everyday usage. The system in focus is the Air Pressure system (APS) which generates pressurized air that are utilized in various functions in a truck, such as braking and gear changes. The datasets’ positive class consists of component failures for a specific component of the APS system. The negative class consists of trucks with failures for components not related to the APS. The data consists of a subset of all available data, selected by experts."
},
{
"code": null,
"e": 2625,
"s": 2327,
"text": "The attribute names of the data have been anonymized for proprietary reasons. It consists of both single numerical counters and histograms consisting of bins with different conditions. (...) In total there are 171 attributes, of which 7 are histogram variables. Missing values are denoted by “na”."
},
{
"code": null,
"e": 2644,
"s": 2625,
"text": "— Challenge metric"
},
{
"code": null,
"e": 2680,
"s": 2644,
"text": "Cost-metric of miss-classification:"
},
{
"code": null,
"e": 2880,
"s": 2680,
"text": "In this case Cost_1 refers to the cost that an unnecessary check needs to be done by an mechanic at an workshop, while Cost_2 refer to the cost of missing a faulty truck, which may cause a breakdown."
},
{
"code": null,
"e": 2939,
"s": 2880,
"text": "Total_cost = Cost_1 * No_Instances + Cost_2 * No_Instances"
},
{
"code": null,
"e": 2960,
"s": 2939,
"text": "We’ll give it a try!"
},
{
"code": null,
"e": 2996,
"s": 2960,
"text": "1.1) What are we trying to predict?"
},
{
"code": null,
"e": 3347,
"s": 2996,
"text": "We need to predict the type of system failure. It can be either a failing component of the APS or a failing component not related to the APS. This is very important since our prediction errors can result in unnecessary spending by the company. Specifically we want to avoid type 2 errors (cost of missing a faulty truck, which may cause a breakdown)."
},
{
"code": null,
"e": 3500,
"s": 3347,
"text": "2.2) What type of problem is it? Supervised or Unsupervised Learning? Classification or Regression? Binary or Multi-class? Uni-variate or Multi-variate?"
},
{
"code": null,
"e": 3562,
"s": 3500,
"text": "It is a binary classification problem with multiple features."
},
{
"code": null,
"e": 3597,
"s": 3562,
"text": "2.3) What type of data do we have?"
},
{
"code": null,
"e": 3931,
"s": 3597,
"text": "We have two csv files, one for training and one for testing. Both present 20 unimportant text lines before the actual data begins and we we will have to skip those lines when importing the data frame. There is one row for column names and missing values are denoted by “na”, so we will make sure we include that when we read the csv."
},
{
"code": null,
"e": 3955,
"s": 3931,
"text": "2.4) Import the dataset"
},
{
"code": null,
"e": 4215,
"s": 3955,
"text": "training_data <- read.csv(\"aps_failure_traning_set.csv\", skip = 20, na.strings = \"na\")test_data <- read.csv(\"aps_failure_test_set.csv\", skip = 20, na.strings = \"na\")"
},
{
"code": null,
"e": 4258,
"s": 4215,
"text": "We check the dimensions of both data sets:"
},
{
"code": null,
"e": 4321,
"s": 4258,
"text": "dim(training_data)dim(test_data)[1] 60000 171[1] 16000 171"
},
{
"code": null,
"e": 4374,
"s": 4321,
"text": "2.5) Activate packages to be used during the project"
},
{
"code": null,
"e": 4469,
"s": 4374,
"text": "library(dplyr)library(caret)library(caretEnsemble)library(mice)library(doParallel)library(car)"
},
{
"code": null,
"e": 4540,
"s": 4469,
"text": "2.1) View Data (str or dplyr’s glimpse). First look. Anything strange?"
},
{
"code": null,
"e": 4768,
"s": 4540,
"text": "Specifying na.strings=”na\" when we imported the sets allows R to recognize each feature as numeric. If we didn’t do that, the presence of na in each column would automatically result in them being categorized as character type."
},
{
"code": null,
"e": 4882,
"s": 4768,
"text": "Using the code below, we can see that other than our response variable class, all the other features are numeric."
},
{
"code": null,
"e": 4923,
"s": 4882,
"text": "glimpse(training_data)glimpse(test_data)"
},
{
"code": null,
"e": 5028,
"s": 4923,
"text": "2.2) Is it a “tidy” dataset? Need to “gather” or “spread” it? Is it presented in a way we can work with?"
},
{
"code": null,
"e": 5093,
"s": 5028,
"text": "It’s tidy. Each row is an observation, each column is a feature."
},
{
"code": null,
"e": 5147,
"s": 5093,
"text": "2.3) rownames and colnames ok? Should we change them?"
},
{
"code": null,
"e": 5184,
"s": 5147,
"text": "I don’t see a reason to change them."
},
{
"code": null,
"e": 5236,
"s": 5184,
"text": "2.4) Check data types. Are they OK? If not, convert"
},
{
"code": null,
"e": 5388,
"s": 5236,
"text": "We already assessed that data types are ok. Here you want to also check that the response variable is of the factor type, with the expected two levels."
},
{
"code": null,
"e": 5457,
"s": 5388,
"text": "2.5) What is our response/target variable? Class imbalance? Study it"
},
{
"code": null,
"e": 5698,
"s": 5457,
"text": "Our target variable is class, with two levels: neg and pos. Positive class consists of component failures for a specific component of the APS system. The negative class consists of trucks with failures for components not related to the APS."
},
{
"code": null,
"e": 5743,
"s": 5698,
"text": "How many neg and pos do we have in each set?"
},
{
"code": null,
"e": 5843,
"s": 5743,
"text": "summary(training_data$class)summary(test_data$class) neg pos 59000 1000 neg pos 15625 375"
},
{
"code": null,
"e": 5868,
"s": 5843,
"text": "Let’s check proportions:"
},
{
"code": null,
"e": 6002,
"s": 5868,
"text": "options(digits = 2)prop.table(table(training_data$class))prop.table(table(test_data$class))neg pos 0.983 0.017neg pos 0.977 0.023"
},
{
"code": null,
"e": 6067,
"s": 6002,
"text": "Ok, looks like have a problem here. Class is totally imbalanced."
},
{
"code": null,
"e": 6230,
"s": 6067,
"text": "We could come up with a useless model that classified every observation as neg and get 97.7% accuracy, so let’s be careful with our accuracy score interpretation."
},
{
"code": null,
"e": 6284,
"s": 6230,
"text": "Later we’ll see how we can deal with class imbalance."
},
{
"code": null,
"e": 6352,
"s": 6284,
"text": "2.6) Rest of the features. Summary statistics. Understand your data"
},
{
"code": null,
"e": 6719,
"s": 6352,
"text": "We are working with 171 features, so calling summary() on the entire dataset is not going to help a lot in terms of visual interpretation. Instead, we are going to create a data frame out of the summary() function. This will enable us to calculate some new statistics, specifically related to missing values, which as you will see, is another big issue of this data."
},
{
"code": null,
"e": 6932,
"s": 6719,
"text": "With this summary data frame we will also calculate the mean quartiles for all the data. This will also allow us to understand more about the distribution of the features and the average number of missing values."
},
{
"code": null,
"e": 7339,
"s": 6932,
"text": "options(scipen = 999)summary_df <- do.call(cbind, lapply(training_data[, 2:ncol(training_data)], summary))summary_df_t <- as.data.frame(round(t(summary_df),0))names(summary_df_t)[7] <- paste(\"Missing_values\")summary_df_t_2 <- summary_df_t %>% mutate(obs = nrow(training_data), Missing_prop = Missing_values / obs)print(summary_df_t_2)"
},
{
"code": null,
"e": 7804,
"s": 7339,
"text": "summary_df_t_2 %>% summarise(Min = mean(Min.), first_Q = mean(`1st Qu.`), Median = median(Median), Mean = mean(Mean), third_Q = mean(`3rd Qu.`), Max = max(Max.), mean_MV = mean(Missing_values), obs = mean(obs), mean_MV_perc = mean_MV / obs)"
},
{
"code": null,
"e": 7990,
"s": 7804,
"text": "We can see above that the average number of missing values per feature is 5,000 out of 60,000 samples. This means we have 8.3% o missing values in average in each column. That is a lot!"
},
{
"code": null,
"e": 8029,
"s": 7990,
"text": "Let’s check the same for our test set:"
},
{
"code": null,
"e": 8146,
"s": 8029,
"text": "Again, we have 8.4% missing values. We’ll have to deal with them and there’s a specific section for that afterwards."
},
{
"code": null,
"e": 8252,
"s": 8146,
"text": "2.7) Categorical data/Factors: create count tables to understand different categories. Check all of them."
},
{
"code": null,
"e": 8340,
"s": 8252,
"text": "We are not working with any other categorical feature other than our response variable."
},
{
"code": null,
"e": 8425,
"s": 8340,
"text": "2.8) Unnecessary columns? Columns we can quickly understand we don’t need. Drop them"
},
{
"code": null,
"e": 8531,
"s": 8425,
"text": "So far, we haven’t detected any column that we want to remove at this time. We will leave this for later."
},
{
"code": null,
"e": 8605,
"s": 8531,
"text": "2.9) Check for missing values. How many? Where? Delete them? Impute them?"
},
{
"code": null,
"e": 8666,
"s": 8605,
"text": "Our features present more than 8% missing values in average."
},
{
"code": null,
"e": 9024,
"s": 8666,
"text": "Because it’s a lot of information we don’t want to lose, our approach is going to be to impute them. But first, we don’t want to use a technique to impute each of our two sets separately (train and test). It has to be a one time imputation using full information. In order to do this, we are going to combine both sets, work on them and then separate again."
},
{
"code": null,
"e": 9337,
"s": 9024,
"text": "#replicate our setstraining_data_bind <- training_datatest_data_bind <- test_data#create a new column \"set\" to label the observationstraining_data_bind$set <- \"TRAIN\"test_data_bind$set <- \"TEST\"#merge them into 1 single setfull_dataset <- rbind(training_data_bind, test_data_bind)dim(full_dataset)[1] 76000 172"
},
{
"code": null,
"e": 9502,
"s": 9337,
"text": "We end up with a single set containing 76,000 samples (16,000 from test set and 60,000 from train set). The number of columns is 172 (171 features + 1 “set” column)"
},
{
"code": null,
"e": 9528,
"s": 9502,
"text": "Missing values imputation"
},
{
"code": null,
"e": 9630,
"s": 9528,
"text": "We are going to impute missing values using package mice. Here’s a nice explanation of how mice works"
},
{
"code": null,
"e": 9712,
"s": 9630,
"text": "The following formula allows us to impute the full dataset using mean imputation:"
},
{
"code": null,
"e": 9889,
"s": 9712,
"text": "set.seed(123)imputed_full <- mice(full_dataset, m=1, maxit = 5, method = \"mean\", seed = 500)"
},
{
"code": null,
"e": 9922,
"s": 9889,
"text": "Now we store the imputed values:"
},
{
"code": null,
"e": 9964,
"s": 9922,
"text": "full_imputed <- complete(imputed_full, 1)"
},
{
"code": null,
"e": 10022,
"s": 9964,
"text": "We then check that we still maintain the same dimensions:"
},
{
"code": null,
"e": 10055,
"s": 10022,
"text": "dim(full_imputed)[1] 76000 172"
},
{
"code": null,
"e": 10110,
"s": 10055,
"text": "And now let’s check that we don’t have missing values:"
},
{
"code": null,
"e": 10211,
"s": 10110,
"text": "(na_count_full_imputed <-data.frame(sapply(full_imputed, function(y) sum(length(which(is.na(y)))))))"
},
{
"code": null,
"e": 10363,
"s": 10211,
"text": "Wait. If you run that code and look at each row, you will notice there are some features that still have missing values. Specifically there are 9 rows."
},
{
"code": null,
"e": 10406,
"s": 10363,
"text": "Let’s take a look at what is causing them:"
},
{
"code": null,
"e": 10543,
"s": 10406,
"text": "issue_columns <- subset(imputed_full$loggedEvents, meth == \"constant\" | meth == \"collinear\")print(issue_columns)"
},
{
"code": null,
"e": 11025,
"s": 10543,
"text": "I filtered the $loggedEvents attribute of the imputed data frame. Here we see that some features were tagged as constant or collinear. One of them is our set column (the one we used to combine the two sets into one), so we don’t worry about that one. The rest of them are mainly collinear variables and one constant variable. mice automatically skips those columns and lets us know of the issue. We will want to drop those features so we have a full dataset without missing values."
},
{
"code": null,
"e": 11129,
"s": 11025,
"text": "To do that, we first store the column names being careful not to store the set column name (we need it)"
},
{
"code": null,
"e": 11366,
"s": 11129,
"text": "#create vector of column namesissue_columns_names <- as.character(issue_columns[, \"out\"])issue_columns_names <- issue_columns_names[-2]print(issue_columns_names)[1] \"cd_000\" \"bt_000\" \"ah_000\" \"bu_000\" \"bv_000\" \"cq_000\" \"cf_000\" \"co_000\""
},
{
"code": null,
"e": 11486,
"s": 11366,
"text": "We then use the stored vector to remove those columns from the data frame and store it as our final imputed data frame:"
},
{
"code": null,
"e": 11655,
"s": 11486,
"text": "full_imputed_filtered <- full_imputed[ , !(names(full_imputed) %in% issue_columns_names)]dim(full_imputed_filtered)[1] 76000 164"
},
{
"code": null,
"e": 11709,
"s": 11655,
"text": "Notice the number of columns reduced from 172 to 164."
},
{
"code": null,
"e": 11764,
"s": 11709,
"text": "Now we don’t have missing values any more! (check it!)"
},
{
"code": null,
"e": 12008,
"s": 11764,
"text": "Finally, it’s time to separate our full imputed dataset into train and test sets again, and we need to separate it into the exact same samples that it was splitted before. In order to do that we just filter the data frame using our set column."
},
{
"code": null,
"e": 12366,
"s": 12008,
"text": "#subset the full_imputed_filtered datasettraining_data_imp <- subset(full_imputed_filtered, set == \"TRAIN\")test_data_imp <- subset(full_imputed_filtered, set == \"TEST\")#drop the \"set\" column, we don't need it anymoretraining_data_imp$set <- NULLtest_data_imp$set <- NULL#check dimensionsdim(training_data_imp)dim(test_data_imp)[1] 60000 163[1] 16000 163"
},
{
"code": null,
"e": 12445,
"s": 12366,
"text": "Great!, we have our training and test set splitted and with no missing values!"
},
{
"code": null,
"e": 12542,
"s": 12445,
"text": "2.10) Check for outliers and other inconsistent data points. Box-plots. Cooks’ distance. DBSCAN?"
},
{
"code": null,
"e": 12596,
"s": 12542,
"text": "For this dataset we are going to use cook’s distance:"
},
{
"code": null,
"e": 12742,
"s": 12596,
"text": "cooksd <- cooks.distance(glm(class ~ ., family = \"binomial\", data = training_data_imp))"
},
{
"code": null,
"e": 12766,
"s": 12742,
"text": "Let’s plot the results:"
},
{
"code": null,
"e": 12900,
"s": 12766,
"text": "plot(cooksd, pch=\"*\", cex=2, main=\"Influential Obs by Cooks distance\") abline(h = 4*mean(cooksd, na.rm=T), col=\"red\")"
},
{
"code": null,
"e": 13080,
"s": 12900,
"text": "In this plot, what seems to be a dark thick black line is actually all our data points. In the right-top corner we see also what seems to be 1 outlier, or a bunch of them grouped."
},
{
"code": null,
"e": 13112,
"s": 13080,
"text": "Let’s check how many are there:"
},
{
"code": null,
"e": 13386,
"s": 13112,
"text": "outliers <- rownames(training_data_imp[cooksd > 4*mean(cooksd, na.rm=T), ])print(outliers)[1] \"617\" \"3993\" \"5349\" \"10383\" \"10829\" \"18764\" \"19301\" \"21138\" \"22787\" \"24360\" \"24975\" \"29146\" \"30633\" \"33684\"[15] \"38785\" \"45978\" \"50283\" \"51003\" \"52573\" \"53283\" \"54957\" \"57186\""
},
{
"code": null,
"e": 13479,
"s": 13386,
"text": "This is a total of 22 points that are considered outliers according to cook’s distance test."
},
{
"code": null,
"e": 13671,
"s": 13479,
"text": "Since this is a very low number of observations compared to our total 60,000 I decided not to remove them. This just seems to be variability in the measurement rather than experimental error."
},
{
"code": null,
"e": 13721,
"s": 13671,
"text": "2.11) Check for multicollinearity in numeric data"
},
{
"code": null,
"e": 13988,
"s": 13721,
"text": "Last step ouf our EDA phase is to check for multicollinearity. We have already removed some collumns which mice detected as collinear. Here we will just do some analysis of how many bivariate relations have high correlation and if it’s a significant high proportion:"
},
{
"code": null,
"e": 14241,
"s": 13988,
"text": "sum((correlation > 0.5 | correlation < -0.5) & correlation < 1) / (162*162)[1] 0.12sum((correlation > 0.7 | correlation < -0.7) & correlation < 1) / (162*162)[1] 0.047sum((correlation > 0.9 | correlation < -0.9) & correlation < 1) / (162*162)[1] 0.0055"
},
{
"code": null,
"e": 14303,
"s": 14241,
"text": "This means that out of 26,244 possible variable correlations:"
},
{
"code": null,
"e": 14338,
"s": 14303,
"text": "12% present scores higher than 0.5"
},
{
"code": null,
"e": 14359,
"s": 14338,
"text": "4.7% higher than 0.7"
},
{
"code": null,
"e": 14385,
"s": 14359,
"text": "and 0.55% higher than 0.9"
},
{
"code": null,
"e": 14486,
"s": 14385,
"text": "I won’t go any further than this and consider multicollinearity not to be a big issue at this point."
},
{
"code": null,
"e": 14627,
"s": 14486,
"text": "We won’t also spend time engineering features in this already heavy feature loaded dataset. There is no additional information we could use."
},
{
"code": null,
"e": 14861,
"s": 14627,
"text": "We have now both our training and testing data sets ready for modelling. We have imputed missing values, removed collinear features and verified that outliers and multicollinearity is not a big deal that we should be concerned about."
},
{
"code": null,
"e": 15071,
"s": 14861,
"text": "Due to the size of the data, we will train a Logistic Regression model and a Naive Bayes model. Both are very fast compared to more advanced algorithms such as random forests, SVMs or gradient boosting models."
},
{
"code": null,
"e": 15166,
"s": 15071,
"text": "I’m not looking here to win the contest but to have an acceptable scoring just to demonstrate."
},
{
"code": null,
"e": 15264,
"s": 15166,
"text": "I’ll use caretEnsemble’s caretList()to train both at the same time and with the same resampling ."
},
{
"code": null,
"e": 15386,
"s": 15264,
"text": "Notice I’m specifying “up”-sampling within trainControl(). This will take care of class imbalance. More about upsampling."
},
{
"code": null,
"e": 16157,
"s": 15386,
"text": "registerDoParallel(3)getDoParWorkers()set.seed(123)my_ctrl <- trainControl(method = \"cv\", number = 5, classProbs = TRUE, savePredictions = \"final\", index = createResample(training_data_imp$class, 3), sampling = \"up\", allowParallel = TRUE)model_list <- caretList(class ~ ., data = training_data_imp, methodList = c(\"glm\", \"nb\"), metric = \"Kappa\", tuneList = NULL, continue_on_fail = FALSE, preProcess = c(\"center\", \"scale\"), trControl = my_ctrl)"
},
{
"code": null,
"e": 16170,
"s": 16157,
"text": "Our results:"
},
{
"code": null,
"e": 16637,
"s": 16170,
"text": "Notice that our accuracy scores are lower than our usless predict-all-neg model that had 97,7%. The reason we don’t score higher is because we upsampled the data, thus generated new data points to fix the class imbalance. We did it as a parameter set within caret’s trainControl so I’m not showing any details of that, but by doing it, we have improved our ability to predict the positive class (in this case “neg”) in detriment of just looking to maximize accuracy."
},
{
"code": null,
"e": 16681,
"s": 16637,
"text": "Let’s quickly check the confusion matrices:"
},
{
"code": null,
"e": 16903,
"s": 16681,
"text": "#Logistic Regression modelconfusionMatrix(predict(model_list$glm,test_data_imp, type = \"raw\"), test_data_imp$class)#Naive Bayes modelconfusionMatrix(predict(model_list$nb,test_data_imp, type = \"raw\"), test_data_imp$class)"
},
{
"code": null,
"e": 16972,
"s": 16903,
"text": "According to the cost matrix for each type of error, our scoring is:"
},
{
"code": null,
"e": 17028,
"s": 16972,
"text": "Logistic Regression model: 52 x 500 + 834 x 10 = 34,340"
},
{
"code": null,
"e": 17076,
"s": 17028,
"text": "Naive Bayes Model: 42 x 500 + 498 x 10 = 25,980"
}
] |
How can we sort a JTable on a particular column in Java?
|
A JTable is a subclass of JComponent class for displaying complex data structures. A JTable component can follow the Model View Controller (MVC) design pattern for displaying the data in rows and columns. A JTable can generate TableModelListener, TableColumnModelListener, ListSelectionListener, CellEditorListener, RowSorterListener interfaces. We can sort a JTable in a particular column by using the method setAutoCreateRowSorter() and set to true of JTable class.
import java.awt.*;
import javax.swing.*;
public final class JTableSorterTest extends JFrame {
private JTable table;
private JScrollPane scrollPane;
public JTableSorterTest() {
setTitle("JTableHeaderHide Test");
String[] columnNames = {"Name", "Age", "City"};
Object[][] data = {{"Raja", "35", "Hyderabad"}, {"Adithya", "25", "Chennai"}, {"Vineet", "23", "Mumbai"}, {"Archana", "32", "Pune"}, {"Krishna", "30", "Kolkata"}};
table = new JTable(data, columnNames);
scrollPane= new JScrollPane(table);
table.setAutoCreateRowSorter(true); // sorting of the rows on a particular column
add(scrollPane, BorderLayout.CENTER);
setSize(375, 250);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
new JTableSorterTest();
}
}
|
[
{
"code": null,
"e": 1530,
"s": 1062,
"text": "A JTable is a subclass of JComponent class for displaying complex data structures. A JTable component can follow the Model View Controller (MVC) design pattern for displaying the data in rows and columns. A JTable can generate TableModelListener, TableColumnModelListener, ListSelectionListener, CellEditorListener, RowSorterListener interfaces. We can sort a JTable in a particular column by using the method setAutoCreateRowSorter() and set to true of JTable class."
},
{
"code": null,
"e": 2429,
"s": 1530,
"text": "import java.awt.*;\nimport javax.swing.*;\npublic final class JTableSorterTest extends JFrame {\n private JTable table;\n private JScrollPane scrollPane;\n public JTableSorterTest() {\n setTitle(\"JTableHeaderHide Test\");\n String[] columnNames = {\"Name\", \"Age\", \"City\"};\n Object[][] data = {{\"Raja\", \"35\", \"Hyderabad\"}, {\"Adithya\", \"25\", \"Chennai\"}, {\"Vineet\", \"23\", \"Mumbai\"}, {\"Archana\", \"32\", \"Pune\"}, {\"Krishna\", \"30\", \"Kolkata\"}};\n table = new JTable(data, columnNames);\n scrollPane= new JScrollPane(table);\n table.setAutoCreateRowSorter(true); // sorting of the rows on a particular column\n add(scrollPane, BorderLayout.CENTER);\n setSize(375, 250);\n setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n setLocationRelativeTo(null);\n setVisible(true);\n }\n public static void main(String[] args) {\n new JTableSorterTest();\n }\n}"
}
] |
Get the minimum value from a list with multiple columns in MySQL?
|
Let us first create a table −
mysql> create table DemoTable756 (
Value1 int,
Value2 int,
Value3 int
);
Query OK, 0 rows affected (0.62 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable756 values(10,20,14);
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable756 values(20,34,17);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable756 values(200,134,789);
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable756 values(139,98,99);
Query OK, 1 row affected (0.17 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable756;
This will produce the following output -
+--------+--------+--------+
| Value1 | Value2 | Value3 |
+--------+--------+--------+
| 10 | 20 | 14 |
| 20 | 34 | 17 |
| 200 | 134 | 789 |
| 139 | 98 | 99 |
+--------+--------+--------+
4 rows in set (0.00 sec)
Following is the query to get minimum value from a list with multiple columns −
mysql> select least(Value1,Value2,Value3) from DemoTable756;
This will produce the following output -
+-----------------------------+
| least(Value1,Value2,Value3) |
+-----------------------------+
| 10 |
| 17 |
| 134 |
| 98 |
+-----------------------------+
4 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1092,
"s": 1062,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1211,
"s": 1092,
"text": "mysql> create table DemoTable756 (\n Value1 int,\n Value2 int,\n Value3 int\n);\nQuery OK, 0 rows affected (0.62 sec)"
},
{
"code": null,
"e": 1267,
"s": 1211,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1615,
"s": 1267,
"text": "mysql> insert into DemoTable756 values(10,20,14);\nQuery OK, 1 row affected (0.22 sec)\nmysql> insert into DemoTable756 values(20,34,17);\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into DemoTable756 values(200,134,789);\nQuery OK, 1 row affected (0.19 sec)\nmysql> insert into DemoTable756 values(139,98,99);\nQuery OK, 1 row affected (0.17 sec)"
},
{
"code": null,
"e": 1675,
"s": 1615,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1709,
"s": 1675,
"text": "mysql> select *from DemoTable756;"
},
{
"code": null,
"e": 1750,
"s": 1709,
"text": "This will produce the following output -"
},
{
"code": null,
"e": 2007,
"s": 1750,
"text": "+--------+--------+--------+\n| Value1 | Value2 | Value3 |\n+--------+--------+--------+\n| 10 | 20 | 14 |\n| 20 | 34 | 17 |\n| 200 | 134 | 789 |\n| 139 | 98 | 99 |\n+--------+--------+--------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2087,
"s": 2007,
"text": "Following is the query to get minimum value from a list with multiple columns −"
},
{
"code": null,
"e": 2148,
"s": 2087,
"text": "mysql> select least(Value1,Value2,Value3) from DemoTable756;"
},
{
"code": null,
"e": 2189,
"s": 2148,
"text": "This will produce the following output -"
},
{
"code": null,
"e": 2470,
"s": 2189,
"text": "+-----------------------------+\n| least(Value1,Value2,Value3) |\n+-----------------------------+\n| 10 |\n| 17 |\n| 134 |\n| 98 |\n+-----------------------------+\n4 rows in set (0.00 sec)"
}
] |
How to make the corners of a button round in iOS?
|
You might come across a scenarios where you received a UI where the buttons are rounded, and you might wonder how to do that? So here we will see how to make corners of a button round.
We will be seeing both the ways to make the button rounded, one using Storyboard and another programmatically.
Let’s get started! First we will make the corners of button rounded using Storyboard.
Step 1 − Open Xcode → New Projecr → Single View Application → Let’s name it “RoundedButton”
Step 2 − Open Main.storyboard and add a button as show below
Step 3 − Now select the button and tap on Utility area and update the User Defined Runtime Attributes to below value.
Now this value you can modify i.e increase or decrease based on requirement.
In the second method we are going to make the corner rounded Programmatically.
From the Main.storyboard get the @IBOutlet in ViewController.swift and name it “doButtonRounded” and update the same property layer.cornerRadius.
Use the below code for complete reference.
import UIKit
class ViewController: UIViewController {
@IBOutlet var doButtonRounded: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
doButtonRounded.layer.cornerRadius = 20
}
}
|
[
{
"code": null,
"e": 1247,
"s": 1062,
"text": "You might come across a scenarios where you received a UI where the buttons are rounded, and you might wonder how to do that? So here we will see how to make corners of a button round."
},
{
"code": null,
"e": 1358,
"s": 1247,
"text": "We will be seeing both the ways to make the button rounded, one using Storyboard and another programmatically."
},
{
"code": null,
"e": 1444,
"s": 1358,
"text": "Let’s get started! First we will make the corners of button rounded using Storyboard."
},
{
"code": null,
"e": 1536,
"s": 1444,
"text": "Step 1 − Open Xcode → New Projecr → Single View Application → Let’s name it “RoundedButton”"
},
{
"code": null,
"e": 1597,
"s": 1536,
"text": "Step 2 − Open Main.storyboard and add a button as show below"
},
{
"code": null,
"e": 1715,
"s": 1597,
"text": "Step 3 − Now select the button and tap on Utility area and update the User Defined Runtime Attributes to below value."
},
{
"code": null,
"e": 1792,
"s": 1715,
"text": "Now this value you can modify i.e increase or decrease based on requirement."
},
{
"code": null,
"e": 1871,
"s": 1792,
"text": "In the second method we are going to make the corner rounded Programmatically."
},
{
"code": null,
"e": 2017,
"s": 1871,
"text": "From the Main.storyboard get the @IBOutlet in ViewController.swift and name it “doButtonRounded” and update the same property layer.cornerRadius."
},
{
"code": null,
"e": 2060,
"s": 2017,
"text": "Use the below code for complete reference."
},
{
"code": null,
"e": 2270,
"s": 2060,
"text": "import UIKit\nclass ViewController: UIViewController {\n @IBOutlet var doButtonRounded: UIButton!\n override func viewDidLoad() {\n super.viewDidLoad()\n doButtonRounded.layer.cornerRadius = 20\n }\n}"
}
] |
Pseudo-terminal Utilities in Python
|
The Pseudo-terminal utility module pty is defined to handle pseudo-terminal concepts. Using this we can start another process, and also can read or write from controlling terminal using programs.
This module is highly platform oriented. We should use UNIX systems to perform these operations.
To use the pty module, we should import it using −
import pty
There are some modules of the pty module, these are −
This method is used to connect the child controlling terminal to pseudo-terminal. This method returns the pid and the fd. The child process gets the pid 0, but the fd is invalid. The return value of the parent is the pid of the child process and the fd holds the child controlling terminal.
This method is used to open a new pseudo-terminal pair. It returns a file descriptor for the master and the slave.
The spawn process is used to connect its controlling terminal with current processes standard io. The master_read and stdin_read read from the file descriptor. The default size is 1024 bytes.
import pty, os
def process_parent_child():
(process_id, fd) = pty.fork()
print("The Process ID for the Current process is: " + str(os.getpid()))
print("The Process ID for the Child process is: " + str(process_id))
process_parent_child()
master, slave = pty.openpty()
print('Name of the Master: ' + str(os.ttyname(master)))
print('Name of the Slave: ' + str(os.ttyname(slave)))
The Process ID for the Current process is: 12508
The Process ID for the Child process is: 12509
Name of the Master: /dev/ptmx
Name of the Slave: /dev/pts/2
|
[
{
"code": null,
"e": 1258,
"s": 1062,
"text": "The Pseudo-terminal utility module pty is defined to handle pseudo-terminal concepts. Using this we can start another process, and also can read or write from controlling terminal using programs."
},
{
"code": null,
"e": 1355,
"s": 1258,
"text": "This module is highly platform oriented. We should use UNIX systems to perform these operations."
},
{
"code": null,
"e": 1406,
"s": 1355,
"text": "To use the pty module, we should import it using −"
},
{
"code": null,
"e": 1418,
"s": 1406,
"text": "import pty\n"
},
{
"code": null,
"e": 1472,
"s": 1418,
"text": "There are some modules of the pty module, these are −"
},
{
"code": null,
"e": 1763,
"s": 1472,
"text": "This method is used to connect the child controlling terminal to pseudo-terminal. This method returns the pid and the fd. The child process gets the pid 0, but the fd is invalid. The return value of the parent is the pid of the child process and the fd holds the child controlling terminal."
},
{
"code": null,
"e": 1878,
"s": 1763,
"text": "This method is used to open a new pseudo-terminal pair. It returns a file descriptor for the master and the slave."
},
{
"code": null,
"e": 2070,
"s": 1878,
"text": "The spawn process is used to connect its controlling terminal with current processes standard io. The master_read and stdin_read read from the file descriptor. The default size is 1024 bytes."
},
{
"code": null,
"e": 2456,
"s": 2070,
"text": "import pty, os\ndef process_parent_child():\n (process_id, fd) = pty.fork()\n print(\"The Process ID for the Current process is: \" + str(os.getpid()))\n print(\"The Process ID for the Child process is: \" + str(process_id))\nprocess_parent_child()\nmaster, slave = pty.openpty()\nprint('Name of the Master: ' + str(os.ttyname(master)))\nprint('Name of the Slave: ' + str(os.ttyname(slave)))"
},
{
"code": null,
"e": 2613,
"s": 2456,
"text": "The Process ID for the Current process is: 12508\nThe Process ID for the Child process is: 12509\nName of the Master: /dev/ptmx\nName of the Slave: /dev/pts/2\n"
}
] |
Inter-Process Communication (IPC) in ElectronJS - GeeksforGeeks
|
03 Dec, 2021
ElectronJS is used for building Cross-Platform Native Desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux Operating Systems. It combines the Chromium engine and NodeJS into a Single Runtime. Several notable open-source projects such as Visual Studio Code, Slack, Atom, Postman and Brave Browser are developed using Electron.Electron can be categorized into two main processes:-
Main Process
Renderer Process
IPC in Electron: A single main process can have multiple renderer processes. Every Renderer Process can be thought of as a new tab in the Browser. In this tutorial, we will discuss how Electron communicates between these processes using Inter-Process Communication (IPC). Electron provides us with two IPC Modules to help communicate between the processes,
ipcMain:This Module is used to communicate from the Main Process to the Renderer Processes. It is defined and used in the Main Process. It handles all synchronous and asynchronous messages being sent from the renderer process.
ipcRenderer: This Module is used to communicate from the Renderer Processes to the Main Process. It is defined and used in the Renderer Processes. It provides the capability to send messages to and receive messages from the Main Process, synchronously and asynchronously.
It is strongly recommended to not perform heavy computations in the Renderer Processes to prevent the application from slowing down in performance and from being more resource-intensive. Instead, we should use IPC to distribute these tasks to the Main Process and let the Main Process handle any heavy computations in the application. There are three major differences between Synchronous Data Transfer and Asynchronous Data Transfer in IPC,
The ipc.send() method is used for Asynchronous Data Transfer, whereas for Synchronous Data Transfer ipc.sendSync() method is used instead.We need to specifically implement a callback function to handle the Response coming in from the Main Process in Asynchronous Data Transfer. In case of Synchronous Data Transfer we do not need to implement the callback function since ipc.sendSync() method will return the data.In the Main Process (main.js file), win.webContents.send() method is used for Asynchronous Data Transfer. This can be replaced with event.returnValue() method for Synchronous Data Transfer.
The ipc.send() method is used for Asynchronous Data Transfer, whereas for Synchronous Data Transfer ipc.sendSync() method is used instead.
We need to specifically implement a callback function to handle the Response coming in from the Main Process in Asynchronous Data Transfer. In case of Synchronous Data Transfer we do not need to implement the callback function since ipc.sendSync() method will return the data.
In the Main Process (main.js file), win.webContents.send() method is used for Asynchronous Data Transfer. This can be replaced with event.returnValue() method for Synchronous Data Transfer.
Note: This Tutorial also assumes you are familiar with the prerequisites as covered in the above-mentioned link.Project Structure: Let’s start with the building blocks of the Tutorial,
Step 1: Check whether node and npm are installed. If not then visit below articles:Installation of Node.js on WindowsInstallation of Node.js on Linux
Installation of Node.js on Windows
Installation of Node.js on Linux
Step 2: Navigate to an Empty Directory to setup the project, and run the following command,
npm init
Follow the steps given to generate the package.json file
Step 3: Make sure that the Electron is installed if not then install it now.
Step 4: Create a main.js file according to the project structure. This file is the Main Process and acts as an entry point into the application.
javascript
const { app, BrowserWindow } = require('electron')let win; function createWindow() { // Create the browser window. win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }) // and load the index.html of the app. win.loadFile('src/index.html') // Open the DevTools. // win.webContents.openDevTools() //Quit app when main BrowserWindow Instance is closed win.on('closed', function () { app.quit(); });} // This method will be called when the Electron has finished// initialization and is ready to create browser windows.// Some APIs can only be used after this event occurs.app.whenReady().then(createWindow) // Quit when all windows are closed.app.on('window-all-closed', () => { // On macOS it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit() }}) app.on('activate', () => { // On macOS it's common to re-create a window in the app when the // dock icon is clicked and there are no other windows open. if (BrowserWindow.getAllWindows().length === 0) { createWindow() }})
Step 5: Create the index.html file within the src directory. The index.html is rendered in its individual Process by the main.js file on Application Startup. Every Renderer Process can have its own associated CSS and JavaScript file as well. In index.html
html
<!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>Hello World!</title> <!-- https://electronjs.org/docs/tutorial/security#csp-meta-tag --> <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" /></head> <body> <h1>Hello Geeks!</h1> <div> We are using node <script> document.write(process.versions.node) </script>, Chrome <script> document.write(process.versions.chrome) </script>, and Electron <script> document.write(process.versions.electron) </script>. </div> <script src="index.js"></script></body> </html>
Step 6:To launch the Electron Application, run the Command, “start” being the script which we have defined in the package.json file.
npm start
Output:
Asynchronous Data Transfer: Since we have set up the Basic Electron Application, let us define a new BrowserWindow Instance which will render a new webpage. This new webpage is going to be the new-window.html file. We will then implement Asynchronous IPC to communicate data between new-window.html file and index.html file.
new-window.html:
html
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>New Window</title> <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" /></head><body> <div>New Window Opened !</div> <br> <input type="text"> <button id="submit">Pass Value to Main Window</button> <script src="new-window.js"></script></body></html>
index.html: As of now, this webpage is not being called from anywhere within the application. To change this insert the following code into index.html file just above the script tag.
html
<h3>Aynschronous Message Sending</h3><div> Value Received From Renderer Process - <span id="value"></span></div><br><button id="new"> Click Me to Open New Window</button>
index.js:
javascript
const electron = require('electron')const path = require('path')// BrowserWindow Instance is a part of the Main Process,// To fetch its instance from the Main Process,// Use electron.remoteconst BrowserWindow = electron.remote.BrowserWindow var update = document.getElementById('value');var button = document.getElementById('new'); button.addEventListener('click', function (event) { // Linking to new-window.html const newPath = path.join('file://', __dirname, 'new-window.html'); let win = new BrowserWindow({ // To display the Default Frame of the Window // consisting of default Menu frame: true, // Makes the Renderer Window Sticky, // Will always stay on top despite focus change alwaysOnTop: true, width: 600, height: 400, webPreferences: { nodeIntegration: true } }); // Destroy the BrowserWindow Instance on close win.on('close', function () { win = null; }); // win.webContents.openDevTools(); win.loadURL(newPath); win.show();});
Output: With this our GUI is ready. Upon launching the application.
To pass the data from the “input” tag in new-window.html to index.html using Asynchronous IPC perform the following steps:
Step 1: In new-window.js file,
javascript
const electron = require('electron')const remote = electron.remote;// Import the ipcRenderer Module from Electronconst ipc = electron.ipcRenderer; var input = document.querySelector('input');var submit = document.getElementById('submit'); // Adding Click EventListener to the Buttonsubmit.addEventListener('click', function () { console.log(input.value); // Calling the ipcRenderer.send() // To send the value from the input tag with // a Unique Key to the main process // Asynchronously ipc.send('update-value', input.value); remote.getCurrentWindow().close();});
Step 2: In the main.js file, import the ipcMain module from electron.
const ipcMain = require('electron').ipcMain
Add the following at the end of the file,
javascript
// Responsible for Communication of data from Main// process to the Renderer Process// Received the value send from the new-window.js file// Identifies the data passed based on the Key// Which was set in the ipc.send() method in new-window.js file ipcMain.on('update-value', function (event, arg) { console.log(arg); // Passing the data from Main Process to index.html // BrowserWindow Instance, value will be received in // the index.js based on the Key set here. Using the // 'win.webContents.send' method for Asynchronous Data Transfer win.webContents.send('updateValue', arg);});
Step 3: In index.js file, import the ipcRenderer module from electron
const ipc = electron.ipcRenderer;
Add the following at the end of the file,
javascript
// Using the ipcRenderer.on() method// Implementing the Callback Function for Asynchronous IPC,// To receive the data based on the key set in the main.js fileipc.on('updateValue', function(event, arg) { console.log(arg); // Updating the value of the HTML Tag with the Data Received // In Case the Data Received is not a Number and is // some arbitrary Value,display will show as NaN (Not a Number) update.innerHTML = Number(arg);});
Output: We have successfully Implemented Asynchronous IPC.
Synchronous Data Transfer: We will now implement Synchronous IPC between the Main Process and Renderer Process and visualize the differences between them as explained above.
Step 1: In the index.html file add the following code just after the button tag and before the script tag.
html
<br><h3>Synchronous Message Sending</h3><div>Value Received From Main Process - <span id="received"></span></div><br><button id="send"> Click Me for Synchronous Message</button>
Step 2: The ‘Click Me for Synchronous Message’ button does not have functionality associated with it. We will add EventListener to the button by adding the following code in the index.js file.
javascript
var received = document.getElementById('received')var button2 = document.getElementById('send'); // Adding Click EventListener to button2// For Synchronous Message Transfer we are using the 'ipc.sendSync' method// We do not need to Implemented any Callbacks to handle the Response// The 'ipc.sendSync' method will return the data from the Main Processbutton2.addEventListener('click', function(event) { // Setting the Key and the Message to be sent to the Main Process const data = ipc.sendSync('synchronous', 'Message to Main Window'); // Setting the Data received to the <span> tag received.innerHTML = data;});
Step 3: In the main.js file, add the following code at the end of the file,
javascript
ipcMain.on('synchronous', (event, arg) => { // Using this method instead of 'win.webContents.send' // for Synchronous Message Transfer // The Value of arg = 'Message to Main Window' // In case we do not use 'event.returnValue', We will // get the following Error // 'Uncaught Error: Unable to deserialize cloned data due to // invalid or unsupported version.' event.returnValue = 'Synchronous Message Sent';});
Output:
sagar0719kumar
clintra
ElectronJS
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Express.js express.Router() Function
Difference between promise and async await in Node.js
Express.js res.render() Function
Mongoose | findByIdAndUpdate() Function
Mongoose Populate() Method
Express.js express.Router() Function
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
|
[
{
"code": null,
"e": 24119,
"s": 24091,
"text": "\n03 Dec, 2021"
},
{
"code": null,
"e": 24583,
"s": 24119,
"text": "ElectronJS is used for building Cross-Platform Native Desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux Operating Systems. It combines the Chromium engine and NodeJS into a Single Runtime. Several notable open-source projects such as Visual Studio Code, Slack, Atom, Postman and Brave Browser are developed using Electron.Electron can be categorized into two main processes:- "
},
{
"code": null,
"e": 24596,
"s": 24583,
"text": "Main Process"
},
{
"code": null,
"e": 24613,
"s": 24596,
"text": "Renderer Process"
},
{
"code": null,
"e": 24970,
"s": 24613,
"text": "IPC in Electron: A single main process can have multiple renderer processes. Every Renderer Process can be thought of as a new tab in the Browser. In this tutorial, we will discuss how Electron communicates between these processes using Inter-Process Communication (IPC). Electron provides us with two IPC Modules to help communicate between the processes,"
},
{
"code": null,
"e": 25197,
"s": 24970,
"text": "ipcMain:This Module is used to communicate from the Main Process to the Renderer Processes. It is defined and used in the Main Process. It handles all synchronous and asynchronous messages being sent from the renderer process."
},
{
"code": null,
"e": 25469,
"s": 25197,
"text": "ipcRenderer: This Module is used to communicate from the Renderer Processes to the Main Process. It is defined and used in the Renderer Processes. It provides the capability to send messages to and receive messages from the Main Process, synchronously and asynchronously."
},
{
"code": null,
"e": 25913,
"s": 25469,
"text": "It is strongly recommended to not perform heavy computations in the Renderer Processes to prevent the application from slowing down in performance and from being more resource-intensive. Instead, we should use IPC to distribute these tasks to the Main Process and let the Main Process handle any heavy computations in the application. There are three major differences between Synchronous Data Transfer and Asynchronous Data Transfer in IPC, "
},
{
"code": null,
"e": 26517,
"s": 25913,
"text": "The ipc.send() method is used for Asynchronous Data Transfer, whereas for Synchronous Data Transfer ipc.sendSync() method is used instead.We need to specifically implement a callback function to handle the Response coming in from the Main Process in Asynchronous Data Transfer. In case of Synchronous Data Transfer we do not need to implement the callback function since ipc.sendSync() method will return the data.In the Main Process (main.js file), win.webContents.send() method is used for Asynchronous Data Transfer. This can be replaced with event.returnValue() method for Synchronous Data Transfer."
},
{
"code": null,
"e": 26656,
"s": 26517,
"text": "The ipc.send() method is used for Asynchronous Data Transfer, whereas for Synchronous Data Transfer ipc.sendSync() method is used instead."
},
{
"code": null,
"e": 26933,
"s": 26656,
"text": "We need to specifically implement a callback function to handle the Response coming in from the Main Process in Asynchronous Data Transfer. In case of Synchronous Data Transfer we do not need to implement the callback function since ipc.sendSync() method will return the data."
},
{
"code": null,
"e": 27123,
"s": 26933,
"text": "In the Main Process (main.js file), win.webContents.send() method is used for Asynchronous Data Transfer. This can be replaced with event.returnValue() method for Synchronous Data Transfer."
},
{
"code": null,
"e": 27309,
"s": 27123,
"text": "Note: This Tutorial also assumes you are familiar with the prerequisites as covered in the above-mentioned link.Project Structure: Let’s start with the building blocks of the Tutorial, "
},
{
"code": null,
"e": 27459,
"s": 27309,
"text": "Step 1: Check whether node and npm are installed. If not then visit below articles:Installation of Node.js on WindowsInstallation of Node.js on Linux"
},
{
"code": null,
"e": 27494,
"s": 27459,
"text": "Installation of Node.js on Windows"
},
{
"code": null,
"e": 27527,
"s": 27494,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27619,
"s": 27527,
"text": "Step 2: Navigate to an Empty Directory to setup the project, and run the following command,"
},
{
"code": null,
"e": 27628,
"s": 27619,
"text": "npm init"
},
{
"code": null,
"e": 27685,
"s": 27628,
"text": "Follow the steps given to generate the package.json file"
},
{
"code": null,
"e": 27764,
"s": 27685,
"text": "Step 3: Make sure that the Electron is installed if not then install it now. "
},
{
"code": null,
"e": 27911,
"s": 27764,
"text": "Step 4: Create a main.js file according to the project structure. This file is the Main Process and acts as an entry point into the application. "
},
{
"code": null,
"e": 27922,
"s": 27911,
"text": "javascript"
},
{
"code": "const { app, BrowserWindow } = require('electron')let win; function createWindow() { // Create the browser window. win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }) // and load the index.html of the app. win.loadFile('src/index.html') // Open the DevTools. // win.webContents.openDevTools() //Quit app when main BrowserWindow Instance is closed win.on('closed', function () { app.quit(); });} // This method will be called when the Electron has finished// initialization and is ready to create browser windows.// Some APIs can only be used after this event occurs.app.whenReady().then(createWindow) // Quit when all windows are closed.app.on('window-all-closed', () => { // On macOS it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit() }}) app.on('activate', () => { // On macOS it's common to re-create a window in the app when the // dock icon is clicked and there are no other windows open. if (BrowserWindow.getAllWindows().length === 0) { createWindow() }})",
"e": 29085,
"s": 27922,
"text": null
},
{
"code": null,
"e": 29341,
"s": 29085,
"text": "Step 5: Create the index.html file within the src directory. The index.html is rendered in its individual Process by the main.js file on Application Startup. Every Renderer Process can have its own associated CSS and JavaScript file as well. In index.html"
},
{
"code": null,
"e": 29346,
"s": 29341,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <meta charset=\"UTF-8\"> <title>Hello World!</title> <!-- https://electronjs.org/docs/tutorial/security#csp-meta-tag --> <meta http-equiv=\"Content-Security-Policy\" content=\"script-src 'self' 'unsafe-inline';\" /></head> <body> <h1>Hello Geeks!</h1> <div> We are using node <script> document.write(process.versions.node) </script>, Chrome <script> document.write(process.versions.chrome) </script>, and Electron <script> document.write(process.versions.electron) </script>. </div> <script src=\"index.js\"></script></body> </html>",
"e": 30018,
"s": 29346,
"text": null
},
{
"code": null,
"e": 30151,
"s": 30018,
"text": "Step 6:To launch the Electron Application, run the Command, “start” being the script which we have defined in the package.json file."
},
{
"code": null,
"e": 30161,
"s": 30151,
"text": "npm start"
},
{
"code": null,
"e": 30169,
"s": 30161,
"text": "Output:"
},
{
"code": null,
"e": 30494,
"s": 30169,
"text": "Asynchronous Data Transfer: Since we have set up the Basic Electron Application, let us define a new BrowserWindow Instance which will render a new webpage. This new webpage is going to be the new-window.html file. We will then implement Asynchronous IPC to communicate data between new-window.html file and index.html file."
},
{
"code": null,
"e": 30511,
"s": 30494,
"text": "new-window.html:"
},
{
"code": null,
"e": 30516,
"s": 30511,
"text": "html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <title>New Window</title> <meta http-equiv=\"Content-Security-Policy\" content=\"script-src 'self' 'unsafe-inline';\" /></head><body> <div>New Window Opened !</div> <br> <input type=\"text\"> <button id=\"submit\">Pass Value to Main Window</button> <script src=\"new-window.js\"></script></body></html>",
"e": 30909,
"s": 30516,
"text": null
},
{
"code": null,
"e": 31094,
"s": 30909,
"text": "index.html: As of now, this webpage is not being called from anywhere within the application. To change this insert the following code into index.html file just above the script tag. "
},
{
"code": null,
"e": 31099,
"s": 31094,
"text": "html"
},
{
"code": "<h3>Aynschronous Message Sending</h3><div> Value Received From Renderer Process - <span id=\"value\"></span></div><br><button id=\"new\"> Click Me to Open New Window</button>",
"e": 31275,
"s": 31099,
"text": null
},
{
"code": null,
"e": 31285,
"s": 31275,
"text": "index.js:"
},
{
"code": null,
"e": 31296,
"s": 31285,
"text": "javascript"
},
{
"code": "const electron = require('electron')const path = require('path')// BrowserWindow Instance is a part of the Main Process,// To fetch its instance from the Main Process,// Use electron.remoteconst BrowserWindow = electron.remote.BrowserWindow var update = document.getElementById('value');var button = document.getElementById('new'); button.addEventListener('click', function (event) { // Linking to new-window.html const newPath = path.join('file://', __dirname, 'new-window.html'); let win = new BrowserWindow({ // To display the Default Frame of the Window // consisting of default Menu frame: true, // Makes the Renderer Window Sticky, // Will always stay on top despite focus change alwaysOnTop: true, width: 600, height: 400, webPreferences: { nodeIntegration: true } }); // Destroy the BrowserWindow Instance on close win.on('close', function () { win = null; }); // win.webContents.openDevTools(); win.loadURL(newPath); win.show();});",
"e": 32365,
"s": 31296,
"text": null
},
{
"code": null,
"e": 32433,
"s": 32365,
"text": "Output: With this our GUI is ready. Upon launching the application."
},
{
"code": null,
"e": 32557,
"s": 32433,
"text": "To pass the data from the “input” tag in new-window.html to index.html using Asynchronous IPC perform the following steps: "
},
{
"code": null,
"e": 32588,
"s": 32557,
"text": "Step 1: In new-window.js file,"
},
{
"code": null,
"e": 32599,
"s": 32588,
"text": "javascript"
},
{
"code": "const electron = require('electron')const remote = electron.remote;// Import the ipcRenderer Module from Electronconst ipc = electron.ipcRenderer; var input = document.querySelector('input');var submit = document.getElementById('submit'); // Adding Click EventListener to the Buttonsubmit.addEventListener('click', function () { console.log(input.value); // Calling the ipcRenderer.send() // To send the value from the input tag with // a Unique Key to the main process // Asynchronously ipc.send('update-value', input.value); remote.getCurrentWindow().close();});",
"e": 33186,
"s": 32599,
"text": null
},
{
"code": null,
"e": 33256,
"s": 33186,
"text": "Step 2: In the main.js file, import the ipcMain module from electron."
},
{
"code": null,
"e": 33300,
"s": 33256,
"text": "const ipcMain = require('electron').ipcMain"
},
{
"code": null,
"e": 33342,
"s": 33300,
"text": "Add the following at the end of the file,"
},
{
"code": null,
"e": 33353,
"s": 33342,
"text": "javascript"
},
{
"code": "// Responsible for Communication of data from Main// process to the Renderer Process// Received the value send from the new-window.js file// Identifies the data passed based on the Key// Which was set in the ipc.send() method in new-window.js file ipcMain.on('update-value', function (event, arg) { console.log(arg); // Passing the data from Main Process to index.html // BrowserWindow Instance, value will be received in // the index.js based on the Key set here. Using the // 'win.webContents.send' method for Asynchronous Data Transfer win.webContents.send('updateValue', arg);});",
"e": 33947,
"s": 33353,
"text": null
},
{
"code": null,
"e": 34017,
"s": 33947,
"text": "Step 3: In index.js file, import the ipcRenderer module from electron"
},
{
"code": null,
"e": 34051,
"s": 34017,
"text": "const ipc = electron.ipcRenderer;"
},
{
"code": null,
"e": 34093,
"s": 34051,
"text": "Add the following at the end of the file,"
},
{
"code": null,
"e": 34104,
"s": 34093,
"text": "javascript"
},
{
"code": "// Using the ipcRenderer.on() method// Implementing the Callback Function for Asynchronous IPC,// To receive the data based on the key set in the main.js fileipc.on('updateValue', function(event, arg) { console.log(arg); // Updating the value of the HTML Tag with the Data Received // In Case the Data Received is not a Number and is // some arbitrary Value,display will show as NaN (Not a Number) update.innerHTML = Number(arg);});",
"e": 34557,
"s": 34104,
"text": null
},
{
"code": null,
"e": 34616,
"s": 34557,
"text": "Output: We have successfully Implemented Asynchronous IPC."
},
{
"code": null,
"e": 34790,
"s": 34616,
"text": "Synchronous Data Transfer: We will now implement Synchronous IPC between the Main Process and Renderer Process and visualize the differences between them as explained above."
},
{
"code": null,
"e": 34897,
"s": 34790,
"text": "Step 1: In the index.html file add the following code just after the button tag and before the script tag."
},
{
"code": null,
"e": 34902,
"s": 34897,
"text": "html"
},
{
"code": "<br><h3>Synchronous Message Sending</h3><div>Value Received From Main Process - <span id=\"received\"></span></div><br><button id=\"send\"> Click Me for Synchronous Message</button>",
"e": 35082,
"s": 34902,
"text": null
},
{
"code": null,
"e": 35275,
"s": 35082,
"text": "Step 2: The ‘Click Me for Synchronous Message’ button does not have functionality associated with it. We will add EventListener to the button by adding the following code in the index.js file."
},
{
"code": null,
"e": 35286,
"s": 35275,
"text": "javascript"
},
{
"code": "var received = document.getElementById('received')var button2 = document.getElementById('send'); // Adding Click EventListener to button2// For Synchronous Message Transfer we are using the 'ipc.sendSync' method// We do not need to Implemented any Callbacks to handle the Response// The 'ipc.sendSync' method will return the data from the Main Processbutton2.addEventListener('click', function(event) { // Setting the Key and the Message to be sent to the Main Process const data = ipc.sendSync('synchronous', 'Message to Main Window'); // Setting the Data received to the <span> tag received.innerHTML = data;});",
"e": 35914,
"s": 35286,
"text": null
},
{
"code": null,
"e": 35990,
"s": 35914,
"text": "Step 3: In the main.js file, add the following code at the end of the file,"
},
{
"code": null,
"e": 36001,
"s": 35990,
"text": "javascript"
},
{
"code": "ipcMain.on('synchronous', (event, arg) => { // Using this method instead of 'win.webContents.send' // for Synchronous Message Transfer // The Value of arg = 'Message to Main Window' // In case we do not use 'event.returnValue', We will // get the following Error // 'Uncaught Error: Unable to deserialize cloned data due to // invalid or unsupported version.' event.returnValue = 'Synchronous Message Sent';});",
"e": 36421,
"s": 36001,
"text": null
},
{
"code": null,
"e": 36429,
"s": 36421,
"text": "Output:"
},
{
"code": null,
"e": 36444,
"s": 36429,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 36452,
"s": 36444,
"text": "clintra"
},
{
"code": null,
"e": 36463,
"s": 36452,
"text": "ElectronJS"
},
{
"code": null,
"e": 36471,
"s": 36463,
"text": "Node.js"
},
{
"code": null,
"e": 36488,
"s": 36471,
"text": "Web Technologies"
},
{
"code": null,
"e": 36586,
"s": 36488,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36595,
"s": 36586,
"text": "Comments"
},
{
"code": null,
"e": 36608,
"s": 36595,
"text": "Old Comments"
},
{
"code": null,
"e": 36645,
"s": 36608,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 36699,
"s": 36645,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 36732,
"s": 36699,
"text": "Express.js res.render() Function"
},
{
"code": null,
"e": 36772,
"s": 36732,
"text": "Mongoose | findByIdAndUpdate() Function"
},
{
"code": null,
"e": 36799,
"s": 36772,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 36836,
"s": 36799,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 36898,
"s": 36836,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 36941,
"s": 36898,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 37002,
"s": 36941,
"text": "Difference between var, let and const keywords in JavaScript"
}
] |
How to create a sticky image with CSS?
|
Following is the code to create a sticky image with CSS −
Live Demo
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
img {
position: sticky;
top: 0;
width: 300px;
height: 300px;
}
</style>
</head>
<body>
<h1>Some header text</h1>
<img src="https://i.picsum.photos/id/721/400/400.jpg">
<h1>Some header text</h1>
<h1>Some header text</h1>
<h1>Some header text</h1>
<p style="font-size: 40px;">Lorem ipsum dolor sit amet consectetur adipisicing elit. Fugiat odio ratione officia quod qui blanditiis animi! Repudiandae culpa recusandae dolor id soluta porro commodi quidem, incidunt voluptatum vitae similique nesciunt obcaecati odit enim repellat doloribus. Explicabo quisquam in beatae earum?</p>
</body>
</html>
The above code will produce the following output −
On scrolling down a little the image will stay at its place as shown in the below output −
|
[
{
"code": null,
"e": 1120,
"s": 1062,
"text": "Following is the code to create a sticky image with CSS −"
},
{
"code": null,
"e": 1131,
"s": 1120,
"text": " Live Demo"
},
{
"code": null,
"e": 1844,
"s": 1131,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<style>\nimg {\n position: sticky;\n top: 0;\n width: 300px;\n height: 300px;\n}\n</style>\n</head>\n<body>\n<h1>Some header text</h1>\n<img src=\"https://i.picsum.photos/id/721/400/400.jpg\">\n<h1>Some header text</h1>\n<h1>Some header text</h1>\n<h1>Some header text</h1>\n<p style=\"font-size: 40px;\">Lorem ipsum dolor sit amet consectetur adipisicing elit. Fugiat odio ratione officia quod qui blanditiis animi! Repudiandae culpa recusandae dolor id soluta porro commodi quidem, incidunt voluptatum vitae similique nesciunt obcaecati odit enim repellat doloribus. Explicabo quisquam in beatae earum?</p>\n</body>\n</html>"
},
{
"code": null,
"e": 1895,
"s": 1844,
"text": "The above code will produce the following output −"
},
{
"code": null,
"e": 1986,
"s": 1895,
"text": "On scrolling down a little the image will stay at its place as shown in the below output −"
}
] |
How to count and sum a field between 2 dates in MongoDB?
|
Use aggregation gteandlte along with $sum to count and sum a field between 2 dates. Let us first create a collection with documents −
> db.countandsumdemo.insertOne({"Value":10,"created_at":ISODate('2019-10-11')});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e038e6df5e889d7a51994fa")
}
> db.countandsumdemo.insertOne({"Value":50,"created_at":ISODate('2019-01-31')});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e038e77f5e889d7a51994fb")
}
> db.countandsumdemo.insertOne({"Value":100,"created_at":ISODate('2019-06-31')});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e038e8af5e889d7a51994fc")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.countandsumdemo.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5e038e6df5e889d7a51994fa"),
"Value" : 10,
"created_at" : ISODate("2019-10-11T00:00:00Z")
}
{
"_id" : ObjectId("5e038e77f5e889d7a51994fb"),
"Value" : 50,
"created_at" : ISODate("2019-01-31T00:00:00Z")
}
{
"_id" : ObjectId("5e038e8af5e889d7a51994fc"),
"Value" : 100,
"created_at" : ISODate("2019-07-01T00:00:00Z")
}
Following is the query to count and sum a field between 2 dates −
> db.countandsumdemo.aggregate(
... [{
... $match: {
... created_at: {
... $gte: new Date('2019-05-01'),
... $lte: new Date('2019-12-31')
... }
... }
... }, {
... $group: {
... _id: null,
... SUM: {
... $sum: "$Value"
... },
... COUNT: {
... $sum: 1
... }
... }
... }]
... );
This will produce the following output −
{ "_id" : null, "SUM" : 110, "COUNT" : 2 }
|
[
{
"code": null,
"e": 1196,
"s": 1062,
"text": "Use aggregation gteandlte along with $sum to count and sum a field between 2 dates. Let us first create a collection with documents −"
},
{
"code": null,
"e": 1695,
"s": 1196,
"text": "> db.countandsumdemo.insertOne({\"Value\":10,\"created_at\":ISODate('2019-10-11')});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e038e6df5e889d7a51994fa\")\n}\n> db.countandsumdemo.insertOne({\"Value\":50,\"created_at\":ISODate('2019-01-31')});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e038e77f5e889d7a51994fb\")\n}\n> db.countandsumdemo.insertOne({\"Value\":100,\"created_at\":ISODate('2019-06-31')});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e038e8af5e889d7a51994fc\")\n}"
},
{
"code": null,
"e": 1794,
"s": 1695,
"text": "Following is the query to display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1832,
"s": 1794,
"text": "> db.countandsumdemo.find().pretty();"
},
{
"code": null,
"e": 1873,
"s": 1832,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2234,
"s": 1873,
"text": "{\n \"_id\" : ObjectId(\"5e038e6df5e889d7a51994fa\"),\n \"Value\" : 10,\n \"created_at\" : ISODate(\"2019-10-11T00:00:00Z\")\n}\n{\n \"_id\" : ObjectId(\"5e038e77f5e889d7a51994fb\"),\n \"Value\" : 50,\n \"created_at\" : ISODate(\"2019-01-31T00:00:00Z\")\n}\n{\n \"_id\" : ObjectId(\"5e038e8af5e889d7a51994fc\"),\n \"Value\" : 100,\n \"created_at\" : ISODate(\"2019-07-01T00:00:00Z\")\n}"
},
{
"code": null,
"e": 2300,
"s": 2234,
"text": "Following is the query to count and sum a field between 2 dates −"
},
{
"code": null,
"e": 2663,
"s": 2300,
"text": "> db.countandsumdemo.aggregate(\n... [{\n... $match: {\n... created_at: {\n... $gte: new Date('2019-05-01'),\n... $lte: new Date('2019-12-31')\n... }\n... }\n... }, {\n... $group: {\n... _id: null,\n... SUM: {\n... $sum: \"$Value\"\n... },\n... COUNT: {\n... $sum: 1\n... }\n... }\n... }]\n... );"
},
{
"code": null,
"e": 2704,
"s": 2663,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2747,
"s": 2704,
"text": "{ \"_id\" : null, \"SUM\" : 110, \"COUNT\" : 2 }"
}
] |
How to map C++ enums to strings?
|
Here we will see how to map some enum type data to a string in C++. There is no such direct function to do so. But we can create our own function to convert enum to string.
We shall create a function that takes an enum value as the argument, and we manually return the enum names as a string from that function.
Live Demo
#include <iostream>
using namespace std;
enum Animal {Tiger, Elephant, Bat, Dog, Cat, Mouse};
string enum_to_string(Animal type) {
switch(type) {
case Tiger:
return "Tiger";
case Elephant:
return "Elephant";
case Bat:
return "Bat";
case Dog:
return "Dog";
case Cat:
return "Cat";
case Mouse:
return "Mouse";
default:
return "Invalid animal";
}
}
int main() {
cout << "The Animal is : " << enum_to_string(Dog) << " Its number: " << Dog <<endl;
cout << "The Animal is : " << enum_to_string(Mouse) << " Its number: " << Mouse << endl;
cout << "The Animal is : " << enum_to_string(Elephant) << " Its number: " << Elephant;
}
The Animal is : Dog Its number: 3
The Animal is : Mouse Its number: 5
The Animal is : Elephant Its number: 1
|
[
{
"code": null,
"e": 1235,
"s": 1062,
"text": "Here we will see how to map some enum type data to a string in C++. There is no such direct function to do so. But we can create our own function to convert enum to string."
},
{
"code": null,
"e": 1374,
"s": 1235,
"text": "We shall create a function that takes an enum value as the argument, and we manually return the enum names as a string from that function."
},
{
"code": null,
"e": 1385,
"s": 1374,
"text": " Live Demo"
},
{
"code": null,
"e": 2129,
"s": 1385,
"text": "#include <iostream>\nusing namespace std;\n\nenum Animal {Tiger, Elephant, Bat, Dog, Cat, Mouse};\n\nstring enum_to_string(Animal type) {\n switch(type) {\n case Tiger:\n return \"Tiger\";\n case Elephant:\n return \"Elephant\";\n case Bat:\n return \"Bat\";\n case Dog:\n return \"Dog\";\n case Cat:\n return \"Cat\";\n case Mouse:\n return \"Mouse\";\n default:\n return \"Invalid animal\";\n }\n}\n\nint main() {\n cout << \"The Animal is : \" << enum_to_string(Dog) << \" Its number: \" << Dog <<endl;\n cout << \"The Animal is : \" << enum_to_string(Mouse) << \" Its number: \" << Mouse << endl;\n cout << \"The Animal is : \" << enum_to_string(Elephant) << \" Its number: \" << Elephant;\n}"
},
{
"code": null,
"e": 2238,
"s": 2129,
"text": "The Animal is : Dog Its number: 3\nThe Animal is : Mouse Its number: 5\nThe Animal is : Elephant Its number: 1"
}
] |
JavaScript - Date getTime() Method
|
Javascript date getTime() method returns the numeric value corresponding to the time for the specified date according to universal time. The value returned by the getTime method is the number of milliseconds since 1 January 1970 00:00:00.
You can use this method to help assign a date and time to another Date object.
Its syntax is as follows −
Date.getTime()
Returns the numeric value corresponding to the time for the specified date according to universal time.
Try the following example.
<html>
<head>
<title>JavaScript getTime Method</title>
</head>
<body>
<script type = "text/javascript">
var dt = new Date( "December 25, 1995 23:15:20" );
document.write("getTime() : " + dt.getTime() );
</script>
</body>
</html>
25 Lectures
2.5 hours
Anadi Sharma
74 Lectures
10 hours
Lets Kode It
72 Lectures
4.5 hours
Frahaan Hussain
70 Lectures
4.5 hours
Frahaan Hussain
46 Lectures
6 hours
Eduonix Learning Solutions
88 Lectures
14 hours
Eduonix Learning Solutions
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2705,
"s": 2466,
"text": "Javascript date getTime() method returns the numeric value corresponding to the time for the specified date according to universal time. The value returned by the getTime method is the number of milliseconds since 1 January 1970 00:00:00."
},
{
"code": null,
"e": 2784,
"s": 2705,
"text": "You can use this method to help assign a date and time to another Date object."
},
{
"code": null,
"e": 2811,
"s": 2784,
"text": "Its syntax is as follows −"
},
{
"code": null,
"e": 2827,
"s": 2811,
"text": "Date.getTime()\n"
},
{
"code": null,
"e": 2931,
"s": 2827,
"text": "Returns the numeric value corresponding to the time for the specified date according to universal time."
},
{
"code": null,
"e": 2958,
"s": 2931,
"text": "Try the following example."
},
{
"code": null,
"e": 3249,
"s": 2958,
"text": "<html>\n <head>\n <title>JavaScript getTime Method</title>\n </head>\n \n <body> \n <script type = \"text/javascript\">\n var dt = new Date( \"December 25, 1995 23:15:20\" );\n document.write(\"getTime() : \" + dt.getTime() ); \n </script> \n </body>\n</html>"
},
{
"code": null,
"e": 3284,
"s": 3249,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3298,
"s": 3284,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3332,
"s": 3298,
"text": "\n 74 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 3346,
"s": 3332,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3381,
"s": 3346,
"text": "\n 72 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3398,
"s": 3381,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3433,
"s": 3398,
"text": "\n 70 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3450,
"s": 3433,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3483,
"s": 3450,
"text": "\n 46 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3511,
"s": 3483,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3545,
"s": 3511,
"text": "\n 88 Lectures \n 14 hours \n"
},
{
"code": null,
"e": 3573,
"s": 3545,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3580,
"s": 3573,
"text": " Print"
},
{
"code": null,
"e": 3591,
"s": 3580,
"text": " Add Notes"
}
] |
Python Program to delete a file
|
29 Dec, 2020
Ever wanted to delete a file, that too from a Python program, with a few lines of code? Well, you are in the right place. Today we are going to learn how we are going to be deleting a file by using Python.
Note: We will be importing the os library and going to use the os.remove() function to remove the desired file. If you don’t have os library, then open Command Prompt and write pip install os, to install the required os library.
Below is the Python implementation –
import osprint ("Enter 'quit' for exiting the program")filename = input('Enter the name of the file, that is to be deleted : ')if filename == 'quit': exit()else: print ('\nStarting the removal of the file !') os.remove(filename) print ('\nFile, ', filename, 'The file deletion is successfully completed !!')
Output:The desired file to be deleted:
Sample run of the program
When we enter the name of the file to be deleted:
The deletion:
The Working:
Python os-module-programs
python-os-module
python-utility
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Split string into list of characters
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n29 Dec, 2020"
},
{
"code": null,
"e": 258,
"s": 52,
"text": "Ever wanted to delete a file, that too from a Python program, with a few lines of code? Well, you are in the right place. Today we are going to learn how we are going to be deleting a file by using Python."
},
{
"code": null,
"e": 487,
"s": 258,
"text": "Note: We will be importing the os library and going to use the os.remove() function to remove the desired file. If you don’t have os library, then open Command Prompt and write pip install os, to install the required os library."
},
{
"code": null,
"e": 524,
"s": 487,
"text": "Below is the Python implementation –"
},
{
"code": "import osprint (\"Enter 'quit' for exiting the program\")filename = input('Enter the name of the file, that is to be deleted : ')if filename == 'quit': exit()else: print ('\\nStarting the removal of the file !') os.remove(filename) print ('\\nFile, ', filename, 'The file deletion is successfully completed !!') ",
"e": 865,
"s": 524,
"text": null
},
{
"code": null,
"e": 904,
"s": 865,
"text": "Output:The desired file to be deleted:"
},
{
"code": null,
"e": 930,
"s": 904,
"text": "Sample run of the program"
},
{
"code": null,
"e": 980,
"s": 930,
"text": "When we enter the name of the file to be deleted:"
},
{
"code": null,
"e": 994,
"s": 980,
"text": "The deletion:"
},
{
"code": null,
"e": 1007,
"s": 994,
"text": "The Working:"
},
{
"code": null,
"e": 1033,
"s": 1007,
"text": "Python os-module-programs"
},
{
"code": null,
"e": 1050,
"s": 1033,
"text": "python-os-module"
},
{
"code": null,
"e": 1065,
"s": 1050,
"text": "python-utility"
},
{
"code": null,
"e": 1072,
"s": 1065,
"text": "Python"
},
{
"code": null,
"e": 1088,
"s": 1072,
"text": "Python Programs"
},
{
"code": null,
"e": 1186,
"s": 1088,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1218,
"s": 1186,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1245,
"s": 1218,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1266,
"s": 1245,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1289,
"s": 1266,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1345,
"s": 1289,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1367,
"s": 1345,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 1406,
"s": 1367,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 1444,
"s": 1406,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 1481,
"s": 1444,
"text": "Python Program for Fibonacci numbers"
}
] |
Eigenvalues and Eigenvectors in MATLAB
|
20 Nov, 2021
Eigenvalues and Eigenvectors are properties of a square matrix.
Let is an N*N matrix, X be a vector of size N*1 and be a scalar.
Then the values X, satisfying the equation are eigenvectors and eigenvalues of matrix A respectively.
A matrix of size N*N possess N eigenvalues
Every eigenvalue corresponds to an eigenvector.
Matlab allows the users to find eigenvalues and eigenvectors of matrix using eig() method. Different syntaxes of eig() method are:
e = eig(A)
[V,D] = eig(A)
[V,D,W] = eig(A)
e = eig(A,B)
Let us discuss the above syntaxes in detail:
It returns the vector of eigenvalues of square matrix A.
Matlab
% Square matrix of size 3*3A = [0 1 2; 1 0 -1; 2 -1 0];disp("Matrix");disp(A); % Eigenvalues of matrix Ae = eig(A);disp("Eigenvalues");disp(e);
Output :
It returns the diagonal matrix D having diagonals as eigenvalues.
It also returns the matrix of right vectors as V.
Normal eigenvectors are termed as right eigenvectors.
V is a collection of N eigenvectors of each N*1 size(A is N*N size) that satisfies A*V = V*D
Matlab
% Square matrix of size 3*3A = [8 -6 2; -6 7 -4; 2 -4 3];disp("Matrix");disp(A); % Eigenvalues and right eigenvectors of matrix A[V,D] = eig(A);disp("Diagonal matrix of Eigenvalues");disp(D);disp("Right eigenvectors")disp(V);
Output :
Along with the diagonal matrix of eigenvalues D and right eigenvectors V, it also returns the left eigenvectors of matrix A.
A left eigenvector u is a 1*N matrix that satisfies the equation u*A = k*u, where k is a left eigenvalue of matrix A.
W is the collection of N left eigenvectors of A that satisfies W’*A = D*W’.
Matlab
% Square matrix of size 3*3A = [10 -6 2; -6 7 -4; 2 -4 3];disp("Matrix :");disp(A); % Eigenvalues and right and left eigenvectors % of matrix A[V,D,W] = eig(A);disp("Diagonal matrix of Eigenvalues :");disp(D);disp("Right eigenvectors :")disp(V);disp("Left eigenvectors :")disp(W);
Output :
It returns the generalized eigenvalues of two square matrices A and B of the same size.
A generalized eigenvalue λ and a corresponding eigenvector v satisfy Av=λBv.
Matlab
% Square matrix A and B of size 3*3A = [10 -6 2; -6 7 -4; 2 -4 3];B = [8 6 1; 6 17 2; -1 4 3]; disp("Matrix A:");disp(A);disp("Matrix B:");disp(B); % Generalized eigen values % of matrices A and Be = eig(A,B);disp("Generalized eigenvalues :")disp(e);
Output :
surindertarika1234
Picked
Advanced Computer Subject
MATLAB
Matrix
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Monte Carlo Tree Search (MCTS)
Copying Files to and from Docker Containers
Basics of API Testing Using Postman
Markov Decision Process
Getting Started with System Design
How to Find Index of Element in Array in MATLAB?
How to Remove Nan Values from a Matrix in MATLAB?
Edge detection using Prewitt, Scharr and Sobel Operator
Installing MATLAB on Linux
Turn a Matrix into a Row Vector in MATLAB
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Nov, 2021"
},
{
"code": null,
"e": 92,
"s": 28,
"text": "Eigenvalues and Eigenvectors are properties of a square matrix."
},
{
"code": null,
"e": 158,
"s": 92,
"text": "Let is an N*N matrix, X be a vector of size N*1 and be a scalar."
},
{
"code": null,
"e": 264,
"s": 158,
"text": "Then the values X, satisfying the equation are eigenvectors and eigenvalues of matrix A respectively."
},
{
"code": null,
"e": 307,
"s": 264,
"text": "A matrix of size N*N possess N eigenvalues"
},
{
"code": null,
"e": 355,
"s": 307,
"text": "Every eigenvalue corresponds to an eigenvector."
},
{
"code": null,
"e": 486,
"s": 355,
"text": "Matlab allows the users to find eigenvalues and eigenvectors of matrix using eig() method. Different syntaxes of eig() method are:"
},
{
"code": null,
"e": 497,
"s": 486,
"text": "e = eig(A)"
},
{
"code": null,
"e": 512,
"s": 497,
"text": "[V,D] = eig(A)"
},
{
"code": null,
"e": 529,
"s": 512,
"text": "[V,D,W] = eig(A)"
},
{
"code": null,
"e": 542,
"s": 529,
"text": "e = eig(A,B)"
},
{
"code": null,
"e": 587,
"s": 542,
"text": "Let us discuss the above syntaxes in detail:"
},
{
"code": null,
"e": 644,
"s": 587,
"text": "It returns the vector of eigenvalues of square matrix A."
},
{
"code": null,
"e": 651,
"s": 644,
"text": "Matlab"
},
{
"code": "% Square matrix of size 3*3A = [0 1 2; 1 0 -1; 2 -1 0];disp(\"Matrix\");disp(A); % Eigenvalues of matrix Ae = eig(A);disp(\"Eigenvalues\");disp(e);",
"e": 802,
"s": 651,
"text": null
},
{
"code": null,
"e": 811,
"s": 802,
"text": "Output :"
},
{
"code": null,
"e": 877,
"s": 811,
"text": "It returns the diagonal matrix D having diagonals as eigenvalues."
},
{
"code": null,
"e": 927,
"s": 877,
"text": "It also returns the matrix of right vectors as V."
},
{
"code": null,
"e": 981,
"s": 927,
"text": "Normal eigenvectors are termed as right eigenvectors."
},
{
"code": null,
"e": 1074,
"s": 981,
"text": "V is a collection of N eigenvectors of each N*1 size(A is N*N size) that satisfies A*V = V*D"
},
{
"code": null,
"e": 1081,
"s": 1074,
"text": "Matlab"
},
{
"code": "% Square matrix of size 3*3A = [8 -6 2; -6 7 -4; 2 -4 3];disp(\"Matrix\");disp(A); % Eigenvalues and right eigenvectors of matrix A[V,D] = eig(A);disp(\"Diagonal matrix of Eigenvalues\");disp(D);disp(\"Right eigenvectors\")disp(V);",
"e": 1314,
"s": 1081,
"text": null
},
{
"code": null,
"e": 1323,
"s": 1314,
"text": "Output :"
},
{
"code": null,
"e": 1448,
"s": 1323,
"text": "Along with the diagonal matrix of eigenvalues D and right eigenvectors V, it also returns the left eigenvectors of matrix A."
},
{
"code": null,
"e": 1566,
"s": 1448,
"text": "A left eigenvector u is a 1*N matrix that satisfies the equation u*A = k*u, where k is a left eigenvalue of matrix A."
},
{
"code": null,
"e": 1642,
"s": 1566,
"text": "W is the collection of N left eigenvectors of A that satisfies W’*A = D*W’."
},
{
"code": null,
"e": 1649,
"s": 1642,
"text": "Matlab"
},
{
"code": "% Square matrix of size 3*3A = [10 -6 2; -6 7 -4; 2 -4 3];disp(\"Matrix :\");disp(A); % Eigenvalues and right and left eigenvectors % of matrix A[V,D,W] = eig(A);disp(\"Diagonal matrix of Eigenvalues :\");disp(D);disp(\"Right eigenvectors :\")disp(V);disp(\"Left eigenvectors :\")disp(W);",
"e": 1938,
"s": 1649,
"text": null
},
{
"code": null,
"e": 1947,
"s": 1938,
"text": "Output :"
},
{
"code": null,
"e": 2035,
"s": 1947,
"text": "It returns the generalized eigenvalues of two square matrices A and B of the same size."
},
{
"code": null,
"e": 2112,
"s": 2035,
"text": "A generalized eigenvalue λ and a corresponding eigenvector v satisfy Av=λBv."
},
{
"code": null,
"e": 2119,
"s": 2112,
"text": "Matlab"
},
{
"code": "% Square matrix A and B of size 3*3A = [10 -6 2; -6 7 -4; 2 -4 3];B = [8 6 1; 6 17 2; -1 4 3]; disp(\"Matrix A:\");disp(A);disp(\"Matrix B:\");disp(B); % Generalized eigen values % of matrices A and Be = eig(A,B);disp(\"Generalized eigenvalues :\")disp(e);",
"e": 2390,
"s": 2119,
"text": null
},
{
"code": null,
"e": 2399,
"s": 2390,
"text": "Output :"
},
{
"code": null,
"e": 2418,
"s": 2399,
"text": "surindertarika1234"
},
{
"code": null,
"e": 2425,
"s": 2418,
"text": "Picked"
},
{
"code": null,
"e": 2451,
"s": 2425,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 2458,
"s": 2451,
"text": "MATLAB"
},
{
"code": null,
"e": 2465,
"s": 2458,
"text": "Matrix"
},
{
"code": null,
"e": 2472,
"s": 2465,
"text": "Matrix"
},
{
"code": null,
"e": 2570,
"s": 2472,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2606,
"s": 2570,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 2650,
"s": 2606,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 2686,
"s": 2650,
"text": "Basics of API Testing Using Postman"
},
{
"code": null,
"e": 2710,
"s": 2686,
"text": "Markov Decision Process"
},
{
"code": null,
"e": 2745,
"s": 2710,
"text": "Getting Started with System Design"
},
{
"code": null,
"e": 2794,
"s": 2745,
"text": "How to Find Index of Element in Array in MATLAB?"
},
{
"code": null,
"e": 2844,
"s": 2794,
"text": "How to Remove Nan Values from a Matrix in MATLAB?"
},
{
"code": null,
"e": 2900,
"s": 2844,
"text": "Edge detection using Prewitt, Scharr and Sobel Operator"
},
{
"code": null,
"e": 2927,
"s": 2900,
"text": "Installing MATLAB on Linux"
}
] |
Merge Overlapping Intervals
|
04 Jul, 2022
Given a set of time intervals in any order, merge all overlapping intervals into one and output the result which should have only mutually exclusive intervals.
Example:
Input: Intervals = {{1,3},{2,4},{6,8},{9,10}}Output: {{1, 4}, {6, 8}, {9, 10}}Explanation: Given intervals: [1,3],[2,4],[6,8],[9,10], we have only two overlapping intervals here,[1,3] and [2,4]. Therefore we will merge these two and return [1,4],[6,8], [9,10].
Input: Intervals = {{6,8},{1,9},{2,4},{4,7}}Output: {{1, 9}}
<div id=”video_content”></div>
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Naive approach: A simple approach is to start from the first interval and compare it with all other intervals for overlapping, if it overlaps with any other interval, then remove the other interval from the list and merge the other into the first interval. Repeat the same steps for the remaining intervals after the first. This approach cannot be implemented in better than O(n^2) time.
Time complexity: O(n2)Auxiliary Space: O(1)
Efficient approach: The idea to solve this problem is, first sort the intervals according to the starting time. Once we have the sorted intervals, we can combine all intervals in a linear traversal. The idea is, in sorted array of intervals, if interval[i] doesn’t overlap with interval[i-1], then interval[i+1] cannot overlap with interval[i-1] because starting time of interval[i+1] must be greater than or equal to interval[i].
Algorithm:
Sort the intervals based on the increasing order of starting time.Push the first interval into a stack.For each interval do the following:If the current interval does not overlap with the top of the stack then, push the current interval into the stack.If the current interval overlap with the top of the stack then, update the stack top with the ending time of the current interval.The end stack contains the merged intervals.
Sort the intervals based on the increasing order of starting time.
Push the first interval into a stack.
For each interval do the following:If the current interval does not overlap with the top of the stack then, push the current interval into the stack.If the current interval overlap with the top of the stack then, update the stack top with the ending time of the current interval.
If the current interval does not overlap with the top of the stack then, push the current interval into the stack.
If the current interval overlap with the top of the stack then, update the stack top with the ending time of the current interval.
The end stack contains the merged intervals.
Below is an implementation of the above approach.
C++
Java
C#
Python3
// A C++ program for merging overlapping intervals#include <bits/stdc++.h>using namespace std; // An interval has start time and end timestruct Interval { int start, end;}; // Compares two intervals according to their starting time.// This is needed for sorting the intervals using library// function std::sort(). See http://goo.gl/iGspVbool compareInterval(Interval i1, Interval i2){ return (i1.start < i2.start);} // The main function that takes a set of intervals, merges// overlapping intervals and prints the resultvoid mergeIntervals(Interval arr[], int n){ // Test if the given set has at least one interval if (n <= 0) return; // Create an empty stack of intervals stack<Interval> s; // sort the intervals in increasing order of start time sort(arr, arr + n, compareInterval); // push the first interval to stack s.push(arr[0]); // Start from the next interval and merge if necessary for (int i = 1; i < n; i++) { // get interval from stack top Interval top = s.top(); // if current interval is not overlapping with stack // top, push it to the stack if (top.end < arr[i].start) s.push(arr[i]); // Otherwise update the ending time of top if ending // of current interval is more else if (top.end < arr[i].end) { top.end = arr[i].end; s.pop(); s.push(top); } } // Print contents of stack cout << "\n The Merged Intervals are: "; while (!s.empty()) { Interval t = s.top(); cout << "[" << t.start << "," << t.end << "] "; s.pop(); } return;} // Driver programint main(){ Interval arr[] = { { 6, 8 }, { 1, 9 }, { 2, 4 }, { 4, 7 } }; int n = sizeof(arr) / sizeof(arr[0]); mergeIntervals(arr, n); return 0;}
// A Java program for merging overlapping intervalsimport java.util.Arrays;import java.util.Comparator;import java.util.Stack;public class MergeOverlappingIntervals { // The main function that takes a set of intervals, merges // overlapping intervals and prints the result public static void mergeIntervals(Interval arr[]) { // Test if the given set has at least one interval if (arr.length <= 0) return; // Create an empty stack of intervals Stack<Interval> stack=new Stack<>(); // sort the intervals in increasing order of start time Arrays.sort(arr,new Comparator<Interval>(){ public int compare(Interval i1,Interval i2) { return i1.start-i2.start; } }); // push the first interval to stack stack.push(arr[0]); // Start from the next interval and merge if necessary for (int i = 1 ; i < arr.length; i++) { // get interval from stack top Interval top = stack.peek(); // if current interval is not overlapping with stack top, // push it to the stack if (top.end < arr[i].start) stack.push(arr[i]); // Otherwise update the ending time of top if ending of current // interval is more else if (top.end < arr[i].end) { top.end = arr[i].end; stack.pop(); stack.push(top); } } // Print contents of stack System.out.print("The Merged Intervals are: "); while (!stack.isEmpty()) { Interval t = stack.pop(); System.out.print("["+t.start+","+t.end+"] "); } } public static void main(String args[]) { Interval arr[]=new Interval[4]; arr[0]=new Interval(6,8); arr[1]=new Interval(1,9); arr[2]=new Interval(2,4); arr[3]=new Interval(4,7); mergeIntervals(arr); }} class Interval{ int start,end; Interval(int start, int end) { this.start=start; this.end=end; }}// This code is contributed by Gaurav Tiwari
// A C# program for merging overlapping intervals using System;using System.Collections;using System.Collections.Generic; public class MergeOverlappingIntervals{ // sort the intervals in increasing order of start time class sortHelper : IComparer { int IComparer.Compare(object a, object b) { Interval first = (Interval)a; Interval second = (Interval)b; if (first.start == second.start) { return first.end - second.end; } return first.start - second.start; } } // The main function that takes a set of intervals, merges // overlapping intervals and prints the result public static void mergeIntervals(Interval []arr) { // Test if the given set has at least one interval if (arr.Length <= 0) return; Array.Sort(arr, new sortHelper()); // Create an empty stack of intervals Stack stack = new Stack(); // Push the first interval to stack stack.Push(arr[0]); // Start from the next interval and merge if necessary for (int i = 1 ; i < arr.Length; i++) { // get interval from stack top Interval top = (Interval)stack.Peek(); // if current interval is not overlapping with stack top, // Push it to the stack if (top.end < arr[i].start) stack.Push(arr[i]); // Otherwise update the ending time of top if ending of current // interval is more else if (top.end < arr[i].end) { top.end = arr[i].end; stack.Pop(); stack.Push(top); } } // Print contents of stack Console.Write("The Merged Intervals are: "); while (stack.Count != 0) { Interval t = (Interval)stack.Pop(); Console.Write("[" + t.start + "," + t.end + "] "); } } // Driver code public static void Main() { Interval []arr = new Interval[4]; arr[0] = new Interval(6, 8); arr[1] = new Interval(1, 9); arr[2] = new Interval(2, 4); arr[3] = new Interval(4, 7); mergeIntervals(arr); } } public class Interval { public int start,end; public Interval(int start, int end) { this.start = start; this.end = end; } } // This code is contributed by rutvik_56.
def mergeIntervals(intervals): # Sort the array on the basis of start values of intervals. intervals.sort() stack = [] # insert first interval into stack stack.append(intervals[0]) for i in intervals[1:]: # Check for overlapping interval, # if interval overlap if stack[-1][0] <= i[0] <= stack[-1][-1]: stack[-1][-1] = max(stack[-1][-1], i[-1]) else: stack.append(i) print("The Merged Intervals are :", end=" ") for i in range(len(stack)): print(stack[i], end=" ") arr = [[6, 8], [1, 9], [2, 4], [4, 7]]mergeIntervals(arr)
The Merged Intervals are: [1,9]
Time complexity: O(n*log(n)), which is for sorting. Once the array of intervals is sorted, merging takes linear time.Auxiliary Space: O(n)
Space optimized approach: The above solution requires O(n) extra space for the stack. We can avoid the use of extra space by doing merge operations in place. Below are detailed steps.
Sort all intervals in increasing order of start time.Traverse sorted intervals starting from the first interval, Do the following for every interval.If the current interval is not the first interval and it overlaps with the previous interval, then merge it with the previous interval. Keep doing it while the interval overlaps with the previous one. Otherwise, Add the current interval to the output list of intervals.
Sort all intervals in increasing order of start time.
Traverse sorted intervals starting from the first interval,
Do the following for every interval.If the current interval is not the first interval and it overlaps with the previous interval, then merge it with the previous interval. Keep doing it while the interval overlaps with the previous one. Otherwise, Add the current interval to the output list of intervals.
If the current interval is not the first interval and it overlaps with the previous interval, then merge it with the previous interval. Keep doing it while the interval overlaps with the previous one.
Otherwise, Add the current interval to the output list of intervals.
Below is the implementation of the above approach:
C++
C
Java
Python3
// C++ program to merge overlapping Intervals in// O(n Log n) time and O(1) extra space.#include <bits/stdc++.h>using namespace std; // An Intervalstruct Interval { int s, e;}; // Function used in sortbool mycomp(Interval a, Interval b) { return a.s < b.s; } void mergeIntervals(Interval arr[], int n){ // Sort Intervals in increasing order of // start time sort(arr, arr + n, mycomp); int index = 0; // Stores index of last element // in output array (modified arr[]) // Traverse all input Intervals for (int i = 1; i < n; i++) { // If this is not first Interval and overlaps // with the previous one if (arr[index].e >= arr[i].s) { // Merge previous and current Intervals arr[index].e = max(arr[index].e, arr[i].e); } else { index++; arr[index] = arr[i]; } } // Now arr[0..index-1] stores the merged Intervals cout << "\n The Merged Intervals are: "; for (int i = 0; i <= index; i++) cout << "[" << arr[i].s << ", " << arr[i].e << "] ";} // Driver programint main(){ Interval arr[] = { { 6, 8 }, { 1, 9 }, { 2, 4 }, { 4, 7 } }; int n = sizeof(arr) / sizeof(arr[0]); mergeIntervals(arr, n); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// C program to merge overlapping Intervals in// O(n Log n) time and O(1) extra space.#include <stdbool.h>#include <stdio.h>#include <stdlib.h> // An Intervaltypedef struct Interval { int s, e;} Interval; // Function used in sortint mycomp(const void* a, const void* b){ Interval* data_1 = (Interval*)a; Interval* data_2 = (Interval*)b; return (data_1->s - data_2->s);} // Find maximum between two numbers.int max(int num1, int num2){ return (num1 > num2) ? num1 : num2;} void mergeIntervals(Interval arr[], int n){ // Sort Intervals in increasing order of // start time qsort(arr, n, sizeof(Interval), mycomp); int index = 0; // Stores index of last element // in output array (modified arr[]) // Traverse all input Intervals for (int i = 1; i < n; i++) { // If this is not first Interval and overlaps // with the previous one if (arr[index].e >= arr[i].s) { // Merge previous and current Intervals arr[index].e = max(arr[index].e, arr[i].e); } else { index++; arr[index] = arr[i]; } } // Now arr[0..index-1] stores the merged Intervals printf("\n The Merged Intervals are: "); for (int i = 0; i <= index; i++) printf("[%d, %d]", arr[i].s, arr[i].e);} // Driver programint main(){ Interval arr[] = { { 6, 8 }, { 1, 9 }, { 2, 4 }, { 4, 7 } }; int n = sizeof(arr) / sizeof(arr[0]); mergeIntervals(arr, n); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// Java program to merge overlapping Intervals in// O(n Log n) time and O(1) extra space import java.util.Arrays;import java.util.Comparator; // An Intervalclass Interval{ int start,end; Interval(int start, int end) { this.start=start; this.end=end; }} public class MergeOverlappingIntervals { // Function that takes a set of intervals, merges // overlapping intervals and prints the result public static void mergeIntervals(Interval arr[]) { // Sort Intervals in increasing order of // start time Arrays.sort(arr,new Comparator<Interval>(){ public int compare(Interval i1,Interval i2) { return i1.start - i2.start; } }); int index = 0; // Stores index of last element // in output array (modified arr[]) // Traverse all input Intervals for (int i=1; i<arr.length; i++) { // If this is not first Interval and overlaps // with the previous one if (arr[index].end >= arr[i].start) { // Merge previous and current Intervals arr[index].end = Math.max(arr[index].end, arr[i].end); } else { index++; arr[index] = arr[i]; } } // Now arr[0..index-1] stores the merged Intervals System.out.print("The Merged Intervals are: "); for (int i = 0; i <= index; i++) { System.out.print("[" + arr[i].start + "," + arr[i].end + "]"); } } // Driver Code public static void main(String args[]) { Interval arr[]=new Interval[4]; arr[0]=new Interval(6,8); arr[1]=new Interval(1,9); arr[2]=new Interval(2,4); arr[3]=new Interval(4,7); mergeIntervals(arr); }} // This code is contributed by Gaurav Tiwari // This code was fixed by Subham Mukhopadhyay
# Python program to merge overlapping Intervals in# O(n Log n) time and O(1) extra space def mergeIntervals(arr): # Sorting based on the increasing order # of the start intervals arr.sort(key=lambda x: x[0]) # Stores index of last element # in output array (modified arr[]) index = 0 # Traverse all input Intervals starting from # second interval for i in range(1, len(arr)): # If this is not first Interval and overlaps # with the previous one, Merge previous and # current Intervals if (arr[index][1] >= arr[i][0]): arr[index][1] = max(arr[index][1], arr[i][1]) else: index = index + 1 arr[index] = arr[i] print("The Merged Intervals are :", end=" ") for i in range(index+1): print(arr[i], end=" ") # Driver codearr = [[6, 8], [1, 9], [2, 4], [4, 7]]mergeIntervals(arr)
The Merged Intervals are: [1, 9]
Time Complexity: O(n*log(n))Auxiliary Space Complexity: O(1)
Thanks to Gaurav Ahirwar for suggesting this method.
This article is compiled by Ravi Chandra Enaganti. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
_Gaurav_Tiwari
Thirumalaisrinivasan
sreejithsankar55
sukhoi33
rutvik_56
subhmukh1811
gulshankumarar231
himanshu6003
adityakumar129
isha307
harendrakumar123
Amazon
Google
Arrays
Stack
Amazon
Google
Arrays
Stack
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Write a program to reverse an array or string
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Largest Sum Contiguous Subarray
Stack in Python
Stack Class in Java
Check for Balanced Brackets in an expression (well-formedness) using Stack
Introduction to Data Structures
Stack | Set 2 (Infix to Postfix)
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n04 Jul, 2022"
},
{
"code": null,
"e": 214,
"s": 54,
"text": "Given a set of time intervals in any order, merge all overlapping intervals into one and output the result which should have only mutually exclusive intervals."
},
{
"code": null,
"e": 223,
"s": 214,
"text": "Example:"
},
{
"code": null,
"e": 484,
"s": 223,
"text": "Input: Intervals = {{1,3},{2,4},{6,8},{9,10}}Output: {{1, 4}, {6, 8}, {9, 10}}Explanation: Given intervals: [1,3],[2,4],[6,8],[9,10], we have only two overlapping intervals here,[1,3] and [2,4]. Therefore we will merge these two and return [1,4],[6,8], [9,10]."
},
{
"code": null,
"e": 546,
"s": 484,
"text": "Input: Intervals = {{6,8},{1,9},{2,4},{4,7}}Output: {{1, 9}} "
},
{
"code": null,
"e": 577,
"s": 546,
"text": "<div id=”video_content”></div>"
},
{
"code": null,
"e": 586,
"s": 577,
"text": "Chapters"
},
{
"code": null,
"e": 613,
"s": 586,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 663,
"s": 613,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 686,
"s": 663,
"text": "captions off, selected"
},
{
"code": null,
"e": 694,
"s": 686,
"text": "English"
},
{
"code": null,
"e": 718,
"s": 694,
"text": "This is a modal window."
},
{
"code": null,
"e": 787,
"s": 718,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 809,
"s": 787,
"text": "End of dialog window."
},
{
"code": null,
"e": 1197,
"s": 809,
"text": "Naive approach: A simple approach is to start from the first interval and compare it with all other intervals for overlapping, if it overlaps with any other interval, then remove the other interval from the list and merge the other into the first interval. Repeat the same steps for the remaining intervals after the first. This approach cannot be implemented in better than O(n^2) time."
},
{
"code": null,
"e": 1241,
"s": 1197,
"text": "Time complexity: O(n2)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1672,
"s": 1241,
"text": "Efficient approach: The idea to solve this problem is, first sort the intervals according to the starting time. Once we have the sorted intervals, we can combine all intervals in a linear traversal. The idea is, in sorted array of intervals, if interval[i] doesn’t overlap with interval[i-1], then interval[i+1] cannot overlap with interval[i-1] because starting time of interval[i+1] must be greater than or equal to interval[i]."
},
{
"code": null,
"e": 1683,
"s": 1672,
"text": "Algorithm:"
},
{
"code": null,
"e": 2111,
"s": 1683,
"text": "Sort the intervals based on the increasing order of starting time.Push the first interval into a stack.For each interval do the following:If the current interval does not overlap with the top of the stack then, push the current interval into the stack.If the current interval overlap with the top of the stack then, update the stack top with the ending time of the current interval.The end stack contains the merged intervals. "
},
{
"code": null,
"e": 2178,
"s": 2111,
"text": "Sort the intervals based on the increasing order of starting time."
},
{
"code": null,
"e": 2216,
"s": 2178,
"text": "Push the first interval into a stack."
},
{
"code": null,
"e": 2496,
"s": 2216,
"text": "For each interval do the following:If the current interval does not overlap with the top of the stack then, push the current interval into the stack.If the current interval overlap with the top of the stack then, update the stack top with the ending time of the current interval."
},
{
"code": null,
"e": 2611,
"s": 2496,
"text": "If the current interval does not overlap with the top of the stack then, push the current interval into the stack."
},
{
"code": null,
"e": 2742,
"s": 2611,
"text": "If the current interval overlap with the top of the stack then, update the stack top with the ending time of the current interval."
},
{
"code": null,
"e": 2788,
"s": 2742,
"text": "The end stack contains the merged intervals. "
},
{
"code": null,
"e": 2838,
"s": 2788,
"text": "Below is an implementation of the above approach."
},
{
"code": null,
"e": 2842,
"s": 2838,
"text": "C++"
},
{
"code": null,
"e": 2847,
"s": 2842,
"text": "Java"
},
{
"code": null,
"e": 2850,
"s": 2847,
"text": "C#"
},
{
"code": null,
"e": 2858,
"s": 2850,
"text": "Python3"
},
{
"code": "// A C++ program for merging overlapping intervals#include <bits/stdc++.h>using namespace std; // An interval has start time and end timestruct Interval { int start, end;}; // Compares two intervals according to their starting time.// This is needed for sorting the intervals using library// function std::sort(). See http://goo.gl/iGspVbool compareInterval(Interval i1, Interval i2){ return (i1.start < i2.start);} // The main function that takes a set of intervals, merges// overlapping intervals and prints the resultvoid mergeIntervals(Interval arr[], int n){ // Test if the given set has at least one interval if (n <= 0) return; // Create an empty stack of intervals stack<Interval> s; // sort the intervals in increasing order of start time sort(arr, arr + n, compareInterval); // push the first interval to stack s.push(arr[0]); // Start from the next interval and merge if necessary for (int i = 1; i < n; i++) { // get interval from stack top Interval top = s.top(); // if current interval is not overlapping with stack // top, push it to the stack if (top.end < arr[i].start) s.push(arr[i]); // Otherwise update the ending time of top if ending // of current interval is more else if (top.end < arr[i].end) { top.end = arr[i].end; s.pop(); s.push(top); } } // Print contents of stack cout << \"\\n The Merged Intervals are: \"; while (!s.empty()) { Interval t = s.top(); cout << \"[\" << t.start << \",\" << t.end << \"] \"; s.pop(); } return;} // Driver programint main(){ Interval arr[] = { { 6, 8 }, { 1, 9 }, { 2, 4 }, { 4, 7 } }; int n = sizeof(arr) / sizeof(arr[0]); mergeIntervals(arr, n); return 0;}",
"e": 4694,
"s": 2858,
"text": null
},
{
"code": "// A Java program for merging overlapping intervalsimport java.util.Arrays;import java.util.Comparator;import java.util.Stack;public class MergeOverlappingIntervals { // The main function that takes a set of intervals, merges // overlapping intervals and prints the result public static void mergeIntervals(Interval arr[]) { // Test if the given set has at least one interval if (arr.length <= 0) return; // Create an empty stack of intervals Stack<Interval> stack=new Stack<>(); // sort the intervals in increasing order of start time Arrays.sort(arr,new Comparator<Interval>(){ public int compare(Interval i1,Interval i2) { return i1.start-i2.start; } }); // push the first interval to stack stack.push(arr[0]); // Start from the next interval and merge if necessary for (int i = 1 ; i < arr.length; i++) { // get interval from stack top Interval top = stack.peek(); // if current interval is not overlapping with stack top, // push it to the stack if (top.end < arr[i].start) stack.push(arr[i]); // Otherwise update the ending time of top if ending of current // interval is more else if (top.end < arr[i].end) { top.end = arr[i].end; stack.pop(); stack.push(top); } } // Print contents of stack System.out.print(\"The Merged Intervals are: \"); while (!stack.isEmpty()) { Interval t = stack.pop(); System.out.print(\"[\"+t.start+\",\"+t.end+\"] \"); } } public static void main(String args[]) { Interval arr[]=new Interval[4]; arr[0]=new Interval(6,8); arr[1]=new Interval(1,9); arr[2]=new Interval(2,4); arr[3]=new Interval(4,7); mergeIntervals(arr); }} class Interval{ int start,end; Interval(int start, int end) { this.start=start; this.end=end; }}// This code is contributed by Gaurav Tiwari ",
"e": 6923,
"s": 4694,
"text": null
},
{
"code": "// A C# program for merging overlapping intervals using System;using System.Collections;using System.Collections.Generic; public class MergeOverlappingIntervals{ // sort the intervals in increasing order of start time class sortHelper : IComparer { int IComparer.Compare(object a, object b) { Interval first = (Interval)a; Interval second = (Interval)b; if (first.start == second.start) { return first.end - second.end; } return first.start - second.start; } } // The main function that takes a set of intervals, merges // overlapping intervals and prints the result public static void mergeIntervals(Interval []arr) { // Test if the given set has at least one interval if (arr.Length <= 0) return; Array.Sort(arr, new sortHelper()); // Create an empty stack of intervals Stack stack = new Stack(); // Push the first interval to stack stack.Push(arr[0]); // Start from the next interval and merge if necessary for (int i = 1 ; i < arr.Length; i++) { // get interval from stack top Interval top = (Interval)stack.Peek(); // if current interval is not overlapping with stack top, // Push it to the stack if (top.end < arr[i].start) stack.Push(arr[i]); // Otherwise update the ending time of top if ending of current // interval is more else if (top.end < arr[i].end) { top.end = arr[i].end; stack.Pop(); stack.Push(top); } } // Print contents of stack Console.Write(\"The Merged Intervals are: \"); while (stack.Count != 0) { Interval t = (Interval)stack.Pop(); Console.Write(\"[\" + t.start + \",\" + t.end + \"] \"); } } // Driver code public static void Main() { Interval []arr = new Interval[4]; arr[0] = new Interval(6, 8); arr[1] = new Interval(1, 9); arr[2] = new Interval(2, 4); arr[3] = new Interval(4, 7); mergeIntervals(arr); } } public class Interval { public int start,end; public Interval(int start, int end) { this.start = start; this.end = end; } } // This code is contributed by rutvik_56.",
"e": 9129,
"s": 6923,
"text": null
},
{
"code": "def mergeIntervals(intervals): # Sort the array on the basis of start values of intervals. intervals.sort() stack = [] # insert first interval into stack stack.append(intervals[0]) for i in intervals[1:]: # Check for overlapping interval, # if interval overlap if stack[-1][0] <= i[0] <= stack[-1][-1]: stack[-1][-1] = max(stack[-1][-1], i[-1]) else: stack.append(i) print(\"The Merged Intervals are :\", end=\" \") for i in range(len(stack)): print(stack[i], end=\" \") arr = [[6, 8], [1, 9], [2, 4], [4, 7]]mergeIntervals(arr)",
"e": 9738,
"s": 9129,
"text": null
},
{
"code": null,
"e": 9772,
"s": 9738,
"text": " The Merged Intervals are: [1,9] "
},
{
"code": null,
"e": 9911,
"s": 9772,
"text": "Time complexity: O(n*log(n)), which is for sorting. Once the array of intervals is sorted, merging takes linear time.Auxiliary Space: O(n)"
},
{
"code": null,
"e": 10096,
"s": 9911,
"text": "Space optimized approach: The above solution requires O(n) extra space for the stack. We can avoid the use of extra space by doing merge operations in place. Below are detailed steps. "
},
{
"code": null,
"e": 10524,
"s": 10096,
"text": "Sort all intervals in increasing order of start time.Traverse sorted intervals starting from the first interval, Do the following for every interval.If the current interval is not the first interval and it overlaps with the previous interval, then merge it with the previous interval. Keep doing it while the interval overlaps with the previous one. Otherwise, Add the current interval to the output list of intervals."
},
{
"code": null,
"e": 10578,
"s": 10524,
"text": "Sort all intervals in increasing order of start time."
},
{
"code": null,
"e": 10639,
"s": 10578,
"text": "Traverse sorted intervals starting from the first interval, "
},
{
"code": null,
"e": 10954,
"s": 10639,
"text": "Do the following for every interval.If the current interval is not the first interval and it overlaps with the previous interval, then merge it with the previous interval. Keep doing it while the interval overlaps with the previous one. Otherwise, Add the current interval to the output list of intervals."
},
{
"code": null,
"e": 11164,
"s": 10954,
"text": "If the current interval is not the first interval and it overlaps with the previous interval, then merge it with the previous interval. Keep doing it while the interval overlaps with the previous one. "
},
{
"code": null,
"e": 11234,
"s": 11164,
"text": " Otherwise, Add the current interval to the output list of intervals."
},
{
"code": null,
"e": 11285,
"s": 11234,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 11289,
"s": 11285,
"text": "C++"
},
{
"code": null,
"e": 11291,
"s": 11289,
"text": "C"
},
{
"code": null,
"e": 11296,
"s": 11291,
"text": "Java"
},
{
"code": null,
"e": 11304,
"s": 11296,
"text": "Python3"
},
{
"code": "// C++ program to merge overlapping Intervals in// O(n Log n) time and O(1) extra space.#include <bits/stdc++.h>using namespace std; // An Intervalstruct Interval { int s, e;}; // Function used in sortbool mycomp(Interval a, Interval b) { return a.s < b.s; } void mergeIntervals(Interval arr[], int n){ // Sort Intervals in increasing order of // start time sort(arr, arr + n, mycomp); int index = 0; // Stores index of last element // in output array (modified arr[]) // Traverse all input Intervals for (int i = 1; i < n; i++) { // If this is not first Interval and overlaps // with the previous one if (arr[index].e >= arr[i].s) { // Merge previous and current Intervals arr[index].e = max(arr[index].e, arr[i].e); } else { index++; arr[index] = arr[i]; } } // Now arr[0..index-1] stores the merged Intervals cout << \"\\n The Merged Intervals are: \"; for (int i = 0; i <= index; i++) cout << \"[\" << arr[i].s << \", \" << arr[i].e << \"] \";} // Driver programint main(){ Interval arr[] = { { 6, 8 }, { 1, 9 }, { 2, 4 }, { 4, 7 } }; int n = sizeof(arr) / sizeof(arr[0]); mergeIntervals(arr, n); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 12627,
"s": 11304,
"text": null
},
{
"code": "// C program to merge overlapping Intervals in// O(n Log n) time and O(1) extra space.#include <stdbool.h>#include <stdio.h>#include <stdlib.h> // An Intervaltypedef struct Interval { int s, e;} Interval; // Function used in sortint mycomp(const void* a, const void* b){ Interval* data_1 = (Interval*)a; Interval* data_2 = (Interval*)b; return (data_1->s - data_2->s);} // Find maximum between two numbers.int max(int num1, int num2){ return (num1 > num2) ? num1 : num2;} void mergeIntervals(Interval arr[], int n){ // Sort Intervals in increasing order of // start time qsort(arr, n, sizeof(Interval), mycomp); int index = 0; // Stores index of last element // in output array (modified arr[]) // Traverse all input Intervals for (int i = 1; i < n; i++) { // If this is not first Interval and overlaps // with the previous one if (arr[index].e >= arr[i].s) { // Merge previous and current Intervals arr[index].e = max(arr[index].e, arr[i].e); } else { index++; arr[index] = arr[i]; } } // Now arr[0..index-1] stores the merged Intervals printf(\"\\n The Merged Intervals are: \"); for (int i = 0; i <= index; i++) printf(\"[%d, %d]\", arr[i].s, arr[i].e);} // Driver programint main(){ Interval arr[] = { { 6, 8 }, { 1, 9 }, { 2, 4 }, { 4, 7 } }; int n = sizeof(arr) / sizeof(arr[0]); mergeIntervals(arr, n); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 14176,
"s": 12627,
"text": null
},
{
"code": "// Java program to merge overlapping Intervals in// O(n Log n) time and O(1) extra space import java.util.Arrays;import java.util.Comparator; // An Intervalclass Interval{ int start,end; Interval(int start, int end) { this.start=start; this.end=end; }} public class MergeOverlappingIntervals { // Function that takes a set of intervals, merges // overlapping intervals and prints the result public static void mergeIntervals(Interval arr[]) { // Sort Intervals in increasing order of // start time Arrays.sort(arr,new Comparator<Interval>(){ public int compare(Interval i1,Interval i2) { return i1.start - i2.start; } }); int index = 0; // Stores index of last element // in output array (modified arr[]) // Traverse all input Intervals for (int i=1; i<arr.length; i++) { // If this is not first Interval and overlaps // with the previous one if (arr[index].end >= arr[i].start) { // Merge previous and current Intervals arr[index].end = Math.max(arr[index].end, arr[i].end); } else { index++; arr[index] = arr[i]; } } // Now arr[0..index-1] stores the merged Intervals System.out.print(\"The Merged Intervals are: \"); for (int i = 0; i <= index; i++) { System.out.print(\"[\" + arr[i].start + \",\" + arr[i].end + \"]\"); } } // Driver Code public static void main(String args[]) { Interval arr[]=new Interval[4]; arr[0]=new Interval(6,8); arr[1]=new Interval(1,9); arr[2]=new Interval(2,4); arr[3]=new Interval(4,7); mergeIntervals(arr); }} // This code is contributed by Gaurav Tiwari // This code was fixed by Subham Mukhopadhyay",
"e": 16203,
"s": 14176,
"text": null
},
{
"code": "# Python program to merge overlapping Intervals in# O(n Log n) time and O(1) extra space def mergeIntervals(arr): # Sorting based on the increasing order # of the start intervals arr.sort(key=lambda x: x[0]) # Stores index of last element # in output array (modified arr[]) index = 0 # Traverse all input Intervals starting from # second interval for i in range(1, len(arr)): # If this is not first Interval and overlaps # with the previous one, Merge previous and # current Intervals if (arr[index][1] >= arr[i][0]): arr[index][1] = max(arr[index][1], arr[i][1]) else: index = index + 1 arr[index] = arr[i] print(\"The Merged Intervals are :\", end=\" \") for i in range(index+1): print(arr[i], end=\" \") # Driver codearr = [[6, 8], [1, 9], [2, 4], [4, 7]]mergeIntervals(arr)",
"e": 17099,
"s": 16203,
"text": null
},
{
"code": null,
"e": 17134,
"s": 17099,
"text": " The Merged Intervals are: [1, 9] "
},
{
"code": null,
"e": 17195,
"s": 17134,
"text": "Time Complexity: O(n*log(n))Auxiliary Space Complexity: O(1)"
},
{
"code": null,
"e": 17249,
"s": 17195,
"text": "Thanks to Gaurav Ahirwar for suggesting this method. "
},
{
"code": null,
"e": 17426,
"s": 17249,
"text": "This article is compiled by Ravi Chandra Enaganti. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 17441,
"s": 17426,
"text": "_Gaurav_Tiwari"
},
{
"code": null,
"e": 17462,
"s": 17441,
"text": "Thirumalaisrinivasan"
},
{
"code": null,
"e": 17479,
"s": 17462,
"text": "sreejithsankar55"
},
{
"code": null,
"e": 17488,
"s": 17479,
"text": "sukhoi33"
},
{
"code": null,
"e": 17498,
"s": 17488,
"text": "rutvik_56"
},
{
"code": null,
"e": 17511,
"s": 17498,
"text": "subhmukh1811"
},
{
"code": null,
"e": 17529,
"s": 17511,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 17542,
"s": 17529,
"text": "himanshu6003"
},
{
"code": null,
"e": 17557,
"s": 17542,
"text": "adityakumar129"
},
{
"code": null,
"e": 17565,
"s": 17557,
"text": "isha307"
},
{
"code": null,
"e": 17582,
"s": 17565,
"text": "harendrakumar123"
},
{
"code": null,
"e": 17589,
"s": 17582,
"text": "Amazon"
},
{
"code": null,
"e": 17596,
"s": 17589,
"text": "Google"
},
{
"code": null,
"e": 17603,
"s": 17596,
"text": "Arrays"
},
{
"code": null,
"e": 17609,
"s": 17603,
"text": "Stack"
},
{
"code": null,
"e": 17616,
"s": 17609,
"text": "Amazon"
},
{
"code": null,
"e": 17623,
"s": 17616,
"text": "Google"
},
{
"code": null,
"e": 17630,
"s": 17623,
"text": "Arrays"
},
{
"code": null,
"e": 17636,
"s": 17630,
"text": "Stack"
},
{
"code": null,
"e": 17734,
"s": 17636,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 17749,
"s": 17734,
"text": "Arrays in Java"
},
{
"code": null,
"e": 17795,
"s": 17749,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 17863,
"s": 17795,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 17907,
"s": 17863,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 17939,
"s": 17907,
"text": "Largest Sum Contiguous Subarray"
},
{
"code": null,
"e": 17955,
"s": 17939,
"text": "Stack in Python"
},
{
"code": null,
"e": 17975,
"s": 17955,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 18050,
"s": 17975,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
},
{
"code": null,
"e": 18082,
"s": 18050,
"text": "Introduction to Data Structures"
}
] |
How to get all CSS styles that are applied directly to an element using JavaScript ?
|
15 Jul, 2020
The CSS of an element can be obtained using the getComputedStyle element function in JavaScript. It returns a JavaScript object containing CSS properties and their values. This object is indexed and iterable over the property names. The getPropertyValue(property) is used to get the value of a property.
In the below code, passing your element object to the getCSS( element ) gets all the properties using getComputedStyle(element) and getPropertyValue(property) and write them in a separate division. You can scroll the results to see all the properties.
Example 1: The following example demonstrates getting all properties of <div> element with id=’srcDiv’.
HTML
<!DOCTYPE html><html> <head> <style> #srcDiv { width: 450px; font-family: sans-serif; text-align: justify; justify-content: center; color: green; } #resDiv { height: 300px; overflow: scroll; } </style> <script> function getCSS(element) { var css_data = ''; var css_obj = getComputedStyle(element); for (var i = 0; i < css_obj.length; i++) { css_data += css_obj[i] + ':' + css_obj.getPropertyValue(css_obj[i]) + ';<br>'; } document.getElementById('resDiv') .innerHTML = css_data; return; } </script></head> <body> <img src="logo.png" /><br /> <h3> How to get all the CSS of an element </h3> <br /> <div id="srcDiv"> This is a demo paragraph for explaining "How to get all the CSS of an element". Properties which are applied on this division will appear in the next division on pressing the button below. </div> <br /><br /> <button onclick="getCSS(document .getElementById('srcDiv'))"> Get CSS </button> <br /><br /> <div id="resDiv"></div></body> </html>
Output: On clicking the ‘Get CSS’ button, the output shows.
Example 2: Below is an example to obtain the property of an <input> element with id=’inputTxt’.
HTML
<!DOCTYPE html><html> <head> <style> #srcDiv { width: 450px; font-family: sans-serif; text-align: justify; justify-content: center; color: green; } #inputTxt { color: red; } #resDiv { height: 300px; width: 600px; overflow: scroll; } </style> <script> function getCSS(element) { var css_data = ''; var css_obj = getComputedStyle(element); for (var i = 0; i < css_obj.length; i++) { css_data += css_obj[i] + ':' + css_obj .getPropertyValue(css_obj[i]) + ';<br>'; } document.getElementById('resDiv') .innerHTML = css_data; return; } </script></head> <body> <img src="logo.png" /><br /> <h3> How to get all the CSS of an element </h3> <div id="srcDiv"> This is a demo paragraph for explaining "How to get all the CSS of an element". Properties which are applied on the input field will appear in the next division on pressing the button below. </div> <br /> <input id="inputTxt" type="number" placeholder="Input Number" /> <button onclick="getCSS(document .getElementById('inputTxt'))"> Get Input CSS </button> <br /><br /> <div id="resDiv"></div></body> </html>
Output: On clicking the ‘Get Input CSS’ button, the following output shows.
Note: Please note that the object being passed into the getCSS() function in each example.
CSS-Misc
HTML-Misc
JavaScript-Misc
Picked
CSS
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Jul, 2020"
},
{
"code": null,
"e": 332,
"s": 28,
"text": "The CSS of an element can be obtained using the getComputedStyle element function in JavaScript. It returns a JavaScript object containing CSS properties and their values. This object is indexed and iterable over the property names. The getPropertyValue(property) is used to get the value of a property."
},
{
"code": null,
"e": 584,
"s": 332,
"text": "In the below code, passing your element object to the getCSS( element ) gets all the properties using getComputedStyle(element) and getPropertyValue(property) and write them in a separate division. You can scroll the results to see all the properties."
},
{
"code": null,
"e": 688,
"s": 584,
"text": "Example 1: The following example demonstrates getting all properties of <div> element with id=’srcDiv’."
},
{
"code": null,
"e": 693,
"s": 688,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> #srcDiv { width: 450px; font-family: sans-serif; text-align: justify; justify-content: center; color: green; } #resDiv { height: 300px; overflow: scroll; } </style> <script> function getCSS(element) { var css_data = ''; var css_obj = getComputedStyle(element); for (var i = 0; i < css_obj.length; i++) { css_data += css_obj[i] + ':' + css_obj.getPropertyValue(css_obj[i]) + ';<br>'; } document.getElementById('resDiv') .innerHTML = css_data; return; } </script></head> <body> <img src=\"logo.png\" /><br /> <h3> How to get all the CSS of an element </h3> <br /> <div id=\"srcDiv\"> This is a demo paragraph for explaining \"How to get all the CSS of an element\". Properties which are applied on this division will appear in the next division on pressing the button below. </div> <br /><br /> <button onclick=\"getCSS(document .getElementById('srcDiv'))\"> Get CSS </button> <br /><br /> <div id=\"resDiv\"></div></body> </html>",
"e": 2075,
"s": 693,
"text": null
},
{
"code": null,
"e": 2135,
"s": 2075,
"text": "Output: On clicking the ‘Get CSS’ button, the output shows."
},
{
"code": null,
"e": 2231,
"s": 2135,
"text": "Example 2: Below is an example to obtain the property of an <input> element with id=’inputTxt’."
},
{
"code": null,
"e": 2236,
"s": 2231,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> #srcDiv { width: 450px; font-family: sans-serif; text-align: justify; justify-content: center; color: green; } #inputTxt { color: red; } #resDiv { height: 300px; width: 600px; overflow: scroll; } </style> <script> function getCSS(element) { var css_data = ''; var css_obj = getComputedStyle(element); for (var i = 0; i < css_obj.length; i++) { css_data += css_obj[i] + ':' + css_obj .getPropertyValue(css_obj[i]) + ';<br>'; } document.getElementById('resDiv') .innerHTML = css_data; return; } </script></head> <body> <img src=\"logo.png\" /><br /> <h3> How to get all the CSS of an element </h3> <div id=\"srcDiv\"> This is a demo paragraph for explaining \"How to get all the CSS of an element\". Properties which are applied on the input field will appear in the next division on pressing the button below. </div> <br /> <input id=\"inputTxt\" type=\"number\" placeholder=\"Input Number\" /> <button onclick=\"getCSS(document .getElementById('inputTxt'))\"> Get Input CSS </button> <br /><br /> <div id=\"resDiv\"></div></body> </html>",
"e": 3762,
"s": 2236,
"text": null
},
{
"code": null,
"e": 3838,
"s": 3762,
"text": "Output: On clicking the ‘Get Input CSS’ button, the following output shows."
},
{
"code": null,
"e": 3929,
"s": 3838,
"text": "Note: Please note that the object being passed into the getCSS() function in each example."
},
{
"code": null,
"e": 3938,
"s": 3929,
"text": "CSS-Misc"
},
{
"code": null,
"e": 3948,
"s": 3938,
"text": "HTML-Misc"
},
{
"code": null,
"e": 3964,
"s": 3948,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 3971,
"s": 3964,
"text": "Picked"
},
{
"code": null,
"e": 3975,
"s": 3971,
"text": "CSS"
},
{
"code": null,
"e": 3980,
"s": 3975,
"text": "HTML"
},
{
"code": null,
"e": 3991,
"s": 3980,
"text": "JavaScript"
},
{
"code": null,
"e": 4008,
"s": 3991,
"text": "Web Technologies"
},
{
"code": null,
"e": 4013,
"s": 4008,
"text": "HTML"
}
] |
Aptitude - Profit & Loss Online Quiz
|
Following quiz provides Multiple Choice Questions (MCQs) related to Profit & Loss. You will have to read all the given answers and click over the correct answer. If you are not sure about the answer then you can check the answer using Show Answer button. You can use Next Quiz button to check new set of questions in the quiz.
Q 1 - A book shop offers a book at an increase of 10%. On the off chance that he had purchased it at 4% less and sold it for Rs. 6 more, he would have picked up 75/4 %. The expense cost of the book is:
A - 130
B - 140
C - 150
D - 160
Let the C.P. be Rs x.Then, S.P. =Rs (110/100 * x) =Rs 11x/10.
New C.P. = 96% of Rs x=Rs (96/100 * x) =Rs 24x/25.
New S.P. =Rs (11x/10+6).
∴ (11x/10+6) =475/4% of 24x/25⇒11x+60/10=475/400*24x/25=57x/50
⇒550x+3000=570x
⇒20x=3000⇒x=150.
∴ C.P. =Rs 150.
Q 2 - Ravi purchases some toffee at 2 for a rupee and offers them at 5 for a rupee. His misfortune percent is:
A - 120%
B - 90%
C - 60%
D - 25%
Let the no. of toffees bought be (2*5)= 10
C.P of 10 toffees = (1/2*10) = 5
S.P of 10 toffees = (1/5 *10) = 2
Loss% = (3/5 *100) % = 60%
Q 3 - A man offers an article at lost 10%. Had he purchased it at 20% less, and sold it for rs. 55 more, he could have increased 40%. What is the expense cost of the articles?
A - 200
B - 225
C - 250
D - none of these
Let the C.P be Rs. x, then ,S.P = (90/100 *x) = Rs. 9x/10
New C.P = 80% of Rs. x =(80/100*x) = rs. 4x/5
New S.P = 140% of Rs. 4x/5 = (140/100*4x/5) = 28x/25
∴ 28x/25 = 9x/10 +55 ⇒ 56x =45x+2750 ⇒ 11x= 2750
X= 250
∴ C.P = Rs. 250
Q 4 - Raman purchased a fountain at 9/10 of its stamped value and sold it at 8% more than its stamped cost. His increase percent is:
A - 8%
B - 10%
C - 18%
D - 20%
Let the marked price of the geyser be Rs. x.
C.P = Rs. 9x/10 and S.P = 108% of Rs. x = Rs. (108/100*x) = 27X/25
Gain = (27x/25-9x/10) = (108x-90x /100) = Rs. 9x/50
∴ Gain % = (9x/50 * 10/9x*100) % =20%
Q 5 - By selling a Book for Rs.20, a man loses one eleventh of what it costs him. The cost of the Book is
A - 22
B - 21
C - 20
D - 19
Let us assume cost price is X
i.e., X - 20 = ( 1)/11 X
=>X=22
Q 6 - When a plot is sold for Rs. 33,300, the owner loses 10%. At what price must that plot be sold in order to gain 10%?
A - 41000
B - 40700
C - 41350
D - 41700
Let X be the selling price
90: 33300 = 110: X
=>X=33300x110/( 90)=40700
Q 7 - Profit after selling a commodity for Rs. 650 is same loss after selling it for Rs. 550.Its cost is
A - 620
B - 625
C - 600
D - 575
Let C.P. =X
650-X=X-550
=>2X=1200
=>X=600
Q 8 - Rs. 680 is separated among A, B, C such that A gets 2/3 of what B gets and B gets 1/4 of what C gets. At that point their shares are separately:-
A - 75, 325, 280
B - 80 ,120, 480
C - 90 ,210, 380
D - 100, 200, 380
Explanation
Suppose C gets Rs. x. then B gets Rs. x/4 and gets Rs. (2/3*x/4)= x/6.
∴x/6+x/4+x=680
=>2x+3x+12x=8160
=> 17x= 8160
=> x=480
∴ A gets rs. 80, B gets rs. 120 and C gets rs. 480
Q 9 - A couch set conveying a deal value ticket of rs. 5000 is sold at a rebate of 4%, accordingly increasing 20% .the merchants expense cost of the couch set is:
A - Rs. 3600
B - Rs. 3800
C - Rs. 4000
D - Rs. 4200
M.P = Rs. 5000 and discount =4%
∴ S.P = 96% of Rs. 5000 = (96/100*5000) = Rs. 4800, gain=20%
∴ C.P = Rs. (100/120*4800) = Rs. 4000.
Q 10 - A retailer gives two progressive rebates on an articles checked Rs. 450. The principal rebate gives Rs. 450. The primary rebate given is 10%. In the event that the client pays rs. 344.25 For the article, the second rebate given is:
A - 10%
B - 12%
C - 14%
D - 15%
Let the second discount be x%. then,
90% of (100-x)% of rs. 450 = rs. 344.25
⇒ 90/100* (100-x)/100*450 = 344.25
⇒ 100-x = 34425/405 = 85
⇒ x = (100-85) =15%
∴ second discount is 15%
|
[
{
"code": null,
"e": 4353,
"s": 4026,
"text": "Following quiz provides Multiple Choice Questions (MCQs) related to Profit & Loss. You will have to read all the given answers and click over the correct answer. If you are not sure about the answer then you can check the answer using Show Answer button. You can use Next Quiz button to check new set of questions in the quiz."
},
{
"code": null,
"e": 4555,
"s": 4353,
"text": "Q 1 - A book shop offers a book at an increase of 10%. On the off chance that he had purchased it at 4% less and sold it for Rs. 6 more, he would have picked up 75/4 %. The expense cost of the book is:"
},
{
"code": null,
"e": 4563,
"s": 4555,
"text": "A - 130"
},
{
"code": null,
"e": 4571,
"s": 4563,
"text": "B - 140"
},
{
"code": null,
"e": 4579,
"s": 4571,
"text": "C - 150"
},
{
"code": null,
"e": 4587,
"s": 4579,
"text": "D - 160"
},
{
"code": null,
"e": 4838,
"s": 4587,
"text": "Let the C.P. be Rs x.Then, S.P. =Rs (110/100 * x) =Rs 11x/10.\nNew C.P. = 96% of Rs x=Rs (96/100 * x) =Rs 24x/25.\nNew S.P. =Rs (11x/10+6).\n∴ (11x/10+6) =475/4% of 24x/25⇒11x+60/10=475/400*24x/25=57x/50\n⇒550x+3000=570x\n⇒20x=3000⇒x=150.\n∴ C.P. =Rs 150."
},
{
"code": null,
"e": 4950,
"s": 4838,
"text": "Q 2 - Ravi purchases some toffee at 2 for a rupee and offers them at 5 for a rupee. His misfortune percent is: "
},
{
"code": null,
"e": 4959,
"s": 4950,
"text": "A - 120%"
},
{
"code": null,
"e": 4967,
"s": 4959,
"text": "B - 90%"
},
{
"code": null,
"e": 4975,
"s": 4967,
"text": "C - 60%"
},
{
"code": null,
"e": 4983,
"s": 4975,
"text": "D - 25%"
},
{
"code": null,
"e": 5120,
"s": 4983,
"text": "Let the no. of toffees bought be (2*5)= 10\nC.P of 10 toffees = (1/2*10) = 5\nS.P of 10 toffees = (1/5 *10) = 2\nLoss% = (3/5 *100) % = 60%"
},
{
"code": null,
"e": 5296,
"s": 5120,
"text": "Q 3 - A man offers an article at lost 10%. Had he purchased it at 20% less, and sold it for rs. 55 more, he could have increased 40%. What is the expense cost of the articles?"
},
{
"code": null,
"e": 5304,
"s": 5296,
"text": "A - 200"
},
{
"code": null,
"e": 5312,
"s": 5304,
"text": "B - 225"
},
{
"code": null,
"e": 5320,
"s": 5312,
"text": "C - 250"
},
{
"code": null,
"e": 5338,
"s": 5320,
"text": "D - none of these"
},
{
"code": null,
"e": 5572,
"s": 5338,
"text": "Let the C.P be Rs. x, then ,S.P = (90/100 *x) = Rs. 9x/10\nNew C.P = 80% of Rs. x =(80/100*x) = rs. 4x/5\nNew S.P = 140% of Rs. 4x/5 = (140/100*4x/5) = 28x/25\n∴ 28x/25 = 9x/10 +55 ⇒ 56x =45x+2750 ⇒ 11x= 2750\nX= 250\n∴ C.P = Rs. 250"
},
{
"code": null,
"e": 5705,
"s": 5572,
"text": "Q 4 - Raman purchased a fountain at 9/10 of its stamped value and sold it at 8% more than its stamped cost. His increase percent is:"
},
{
"code": null,
"e": 5712,
"s": 5705,
"text": "A - 8%"
},
{
"code": null,
"e": 5720,
"s": 5712,
"text": "B - 10%"
},
{
"code": null,
"e": 5728,
"s": 5720,
"text": "C - 18%"
},
{
"code": null,
"e": 5736,
"s": 5728,
"text": "D - 20%"
},
{
"code": null,
"e": 5940,
"s": 5736,
"text": "Let the marked price of the geyser be Rs. x.\nC.P = Rs. 9x/10 and S.P = 108% of Rs. x = Rs. (108/100*x) = 27X/25\nGain = (27x/25-9x/10) = (108x-90x /100) = Rs. 9x/50\n∴ Gain % = (9x/50 * 10/9x*100) % =20%"
},
{
"code": null,
"e": 6046,
"s": 5940,
"text": "Q 5 - By selling a Book for Rs.20, a man loses one eleventh of what it costs him. The cost of the Book is"
},
{
"code": null,
"e": 6053,
"s": 6046,
"text": "A - 22"
},
{
"code": null,
"e": 6060,
"s": 6053,
"text": "B - 21"
},
{
"code": null,
"e": 6067,
"s": 6060,
"text": "C - 20"
},
{
"code": null,
"e": 6074,
"s": 6067,
"text": "D - 19"
},
{
"code": null,
"e": 6136,
"s": 6074,
"text": "Let us assume cost price is X\ni.e., X - 20 = ( 1)/11 X\n=>X=22"
},
{
"code": null,
"e": 6258,
"s": 6136,
"text": "Q 6 - When a plot is sold for Rs. 33,300, the owner loses 10%. At what price must that plot be sold in order to gain 10%?"
},
{
"code": null,
"e": 6268,
"s": 6258,
"text": "A - 41000"
},
{
"code": null,
"e": 6278,
"s": 6268,
"text": "B - 40700"
},
{
"code": null,
"e": 6288,
"s": 6278,
"text": "C - 41350"
},
{
"code": null,
"e": 6298,
"s": 6288,
"text": "D - 41700"
},
{
"code": null,
"e": 6370,
"s": 6298,
"text": "Let X be the selling price\n90: 33300 = 110: X\n=>X=33300x110/( 90)=40700"
},
{
"code": null,
"e": 6475,
"s": 6370,
"text": "Q 7 - Profit after selling a commodity for Rs. 650 is same loss after selling it for Rs. 550.Its cost is"
},
{
"code": null,
"e": 6483,
"s": 6475,
"text": "A - 620"
},
{
"code": null,
"e": 6491,
"s": 6483,
"text": "B - 625"
},
{
"code": null,
"e": 6499,
"s": 6491,
"text": "C - 600"
},
{
"code": null,
"e": 6507,
"s": 6499,
"text": "D - 575"
},
{
"code": null,
"e": 6549,
"s": 6507,
"text": "Let C.P. =X\n650-X=X-550\n=>2X=1200\n=>X=600"
},
{
"code": null,
"e": 6702,
"s": 6549,
"text": "Q 8 - Rs. 680 is separated among A, B, C such that A gets 2/3 of what B gets and B gets 1/4 of what C gets. At that point their shares are separately:- "
},
{
"code": null,
"e": 6720,
"s": 6702,
"text": "A - 75, 325, 280 "
},
{
"code": null,
"e": 6738,
"s": 6720,
"text": "B - 80 ,120, 480 "
},
{
"code": null,
"e": 6756,
"s": 6738,
"text": "C - 90 ,210, 380 "
},
{
"code": null,
"e": 6775,
"s": 6756,
"text": "D - 100, 200, 380 "
},
{
"code": null,
"e": 6787,
"s": 6775,
"text": "Explanation"
},
{
"code": null,
"e": 6964,
"s": 6787,
"text": "Suppose C gets Rs. x. then B gets Rs. x/4 and gets Rs. (2/3*x/4)= x/6.\n∴x/6+x/4+x=680\n=>2x+3x+12x=8160\n=> 17x= 8160\n=> x=480\n∴ A gets rs. 80, B gets rs. 120 and C gets rs. 480\n"
},
{
"code": null,
"e": 7128,
"s": 6964,
"text": "Q 9 - A couch set conveying a deal value ticket of rs. 5000 is sold at a rebate of 4%, accordingly increasing 20% .the merchants expense cost of the couch set is: "
},
{
"code": null,
"e": 7141,
"s": 7128,
"text": "A - Rs. 3600"
},
{
"code": null,
"e": 7154,
"s": 7141,
"text": "B - Rs. 3800"
},
{
"code": null,
"e": 7167,
"s": 7154,
"text": "C - Rs. 4000"
},
{
"code": null,
"e": 7180,
"s": 7167,
"text": "D - Rs. 4200"
},
{
"code": null,
"e": 7314,
"s": 7180,
"text": "M.P = Rs. 5000 and discount =4%\n∴ S.P = 96% of Rs. 5000 = (96/100*5000) = Rs. 4800, gain=20%\n∴ C.P = Rs. (100/120*4800) = Rs. 4000."
},
{
"code": null,
"e": 7553,
"s": 7314,
"text": "Q 10 - A retailer gives two progressive rebates on an articles checked Rs. 450. The principal rebate gives Rs. 450. The primary rebate given is 10%. In the event that the client pays rs. 344.25 For the article, the second rebate given is:"
},
{
"code": null,
"e": 7561,
"s": 7553,
"text": "A - 10%"
},
{
"code": null,
"e": 7569,
"s": 7561,
"text": "B - 12%"
},
{
"code": null,
"e": 7577,
"s": 7569,
"text": "C - 14%"
},
{
"code": null,
"e": 7585,
"s": 7577,
"text": "D - 15%"
}
] |
SQL - COUNT Function
|
SQL COUNT function is the simplest function and very useful in counting the number of records, which are expected to be returned by a SELECT statement.
To understand COUNT function, consider an employee_tbl table, which is having the following records −
SQL> SELECT * FROM employee_tbl;
+------+------+------------+--------------------+
| id | name | work_date | daily_typing_pages |
+------+------+------------+--------------------+
| 1 | John | 2007-01-24 | 250 |
| 2 | Ram | 2007-05-27 | 220 |
| 3 | Jack | 2007-05-06 | 170 |
| 3 | Jack | 2007-04-06 | 100 |
| 4 | Jill | 2007-04-06 | 220 |
| 5 | Zara | 2007-06-06 | 300 |
| 5 | Zara | 2007-02-06 | 350 |
+------+------+------------+--------------------+
7 rows in set (0.00 sec)
Now suppose based on the above table you want to count total number of rows in this table, then you can do it as follows −
SQL>SELECT COUNT(*) FROM employee_tbl ;
+----------+
| COUNT(*) |
+----------+
| 7 |
+----------+
1 row in set (0.01 sec)
Similarly, if you want to count the number of records for Zara, then it can be done as follows −
SQL>SELECT COUNT(*) FROM employee_tbl
-> WHERE name="Zara";
+----------+
| COUNT(*) |
+----------+
| 2 |
+----------+
1 row in set (0.04 sec)
NOTE − All the SQL queries are case insensitive, so it does not make any difference if you give ZARA or Zara in WHERE CONDITION.
|
[
{
"code": null,
"e": 2739,
"s": 2587,
"text": "SQL COUNT function is the simplest function and very useful in counting the number of records, which are expected to be returned by a SELECT statement."
},
{
"code": null,
"e": 2842,
"s": 2739,
"text": "To understand COUNT function, consider an employee_tbl table, which is having the following records −"
},
{
"code": null,
"e": 3450,
"s": 2842,
"text": "SQL> SELECT * FROM employee_tbl;\n+------+------+------------+--------------------+\n| id | name | work_date | daily_typing_pages |\n+------+------+------------+--------------------+\n| 1 | John | 2007-01-24 | 250 |\n| 2 | Ram | 2007-05-27 | 220 |\n| 3 | Jack | 2007-05-06 | 170 |\n| 3 | Jack | 2007-04-06 | 100 |\n| 4 | Jill | 2007-04-06 | 220 |\n| 5 | Zara | 2007-06-06 | 300 |\n| 5 | Zara | 2007-02-06 | 350 |\n+------+------+------------+--------------------+\n7 rows in set (0.00 sec)"
},
{
"code": null,
"e": 3573,
"s": 3450,
"text": "Now suppose based on the above table you want to count total number of rows in this table, then you can do it as follows −"
},
{
"code": null,
"e": 3702,
"s": 3573,
"text": "SQL>SELECT COUNT(*) FROM employee_tbl ;\n+----------+\n| COUNT(*) |\n+----------+\n| 7 |\n+----------+\n1 row in set (0.01 sec)"
},
{
"code": null,
"e": 3799,
"s": 3702,
"text": "Similarly, if you want to count the number of records for Zara, then it can be done as follows −"
},
{
"code": null,
"e": 3951,
"s": 3799,
"text": "SQL>SELECT COUNT(*) FROM employee_tbl\n -> WHERE name=\"Zara\";\n+----------+\n| COUNT(*) |\n+----------+\n| 2 |\n+----------+\n1 row in set (0.04 sec)"
}
] |
HTML | <link> target Attribute
|
13 Dec, 2021
The HTML <link> target Attribute is used to specify the window or a frame where the linked document is loaded. It is not supported by HTML 5.
Syntax:
<link target="_blank|_self|_parent|_top|framename">
Attribute Values:
_blank: It opens the link in a new window.
_self: It is the default value. It opens the linked document in the same frame.
_parent: It opens the linked document in the parent frameset.
_top: It opens the linked document in the full body of the window.
framename: It opens the linked document in the named frame.
Example:
<!DOCTYPE html> <html> <head> <title> HTML link target Attribute </title></head> <body> <center> <h1 style="color:green;"> GeeksforGeeks </h1> <h2> HTML <link> target Attribute </h2> <link href="geeksforgeeks.org" target="_blank"> </center> </body> </html>
Output:
Supported Browsers: The HTML <link> target attribute is not supported by any browsers.
chhabradhanvi
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
CSS to put icon inside an input element in a form
Design a Tribute Page using HTML & CSS
Types of CSS (Cascading Style Sheet)
How to Insert Form Data into Database using PHP ?
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n13 Dec, 2021"
},
{
"code": null,
"e": 195,
"s": 53,
"text": "The HTML <link> target Attribute is used to specify the window or a frame where the linked document is loaded. It is not supported by HTML 5."
},
{
"code": null,
"e": 203,
"s": 195,
"text": "Syntax:"
},
{
"code": null,
"e": 255,
"s": 203,
"text": "<link target=\"_blank|_self|_parent|_top|framename\">"
},
{
"code": null,
"e": 273,
"s": 255,
"text": "Attribute Values:"
},
{
"code": null,
"e": 316,
"s": 273,
"text": "_blank: It opens the link in a new window."
},
{
"code": null,
"e": 396,
"s": 316,
"text": "_self: It is the default value. It opens the linked document in the same frame."
},
{
"code": null,
"e": 458,
"s": 396,
"text": "_parent: It opens the linked document in the parent frameset."
},
{
"code": null,
"e": 525,
"s": 458,
"text": "_top: It opens the linked document in the full body of the window."
},
{
"code": null,
"e": 585,
"s": 525,
"text": "framename: It opens the linked document in the named frame."
},
{
"code": null,
"e": 594,
"s": 585,
"text": "Example:"
},
{
"code": "<!DOCTYPE html> <html> <head> <title> HTML link target Attribute </title></head> <body> <center> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h2> HTML <link> target Attribute </h2> <link href=\"geeksforgeeks.org\" target=\"_blank\"> </center> </body> </html> ",
"e": 964,
"s": 594,
"text": null
},
{
"code": null,
"e": 972,
"s": 964,
"text": "Output:"
},
{
"code": null,
"e": 1059,
"s": 972,
"text": "Supported Browsers: The HTML <link> target attribute is not supported by any browsers."
},
{
"code": null,
"e": 1073,
"s": 1059,
"text": "chhabradhanvi"
},
{
"code": null,
"e": 1089,
"s": 1073,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 1094,
"s": 1089,
"text": "HTML"
},
{
"code": null,
"e": 1111,
"s": 1094,
"text": "Web Technologies"
},
{
"code": null,
"e": 1116,
"s": 1111,
"text": "HTML"
},
{
"code": null,
"e": 1214,
"s": 1116,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1238,
"s": 1214,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 1288,
"s": 1238,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 1327,
"s": 1288,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 1364,
"s": 1327,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 1414,
"s": 1364,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 1447,
"s": 1414,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 1508,
"s": 1447,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1551,
"s": 1508,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 1623,
"s": 1551,
"text": "Differences between Functional Components and Class Components in React"
}
] |
Program to find remainder when large number is divided by 11
|
13 Apr, 2021
Given a number n, the task is to find the remainder when n is divided by 11. The input of number may be very large.Examples:
Input : str = 13589234356546756
Output : 6
Input : str = 3435346456547566345436457867978
Output : 4
Since the given number can be very large, we can not use n % 11. There are some steps that needs to be used to find remainder:
1. Store number in string.
2. Count length of number string.
3. Convert string character one by one
into digit and check if it's less than
11. Then continue for next character
otherwise take remainder and use
remainder for next number.
4. We get remainder.
Ex. str = "1345"
len = 4
rem = 3
C++
Java
Python3
C#
PHP
Javascript
// CPP implementation to find remainder// when a large number is divided by 11#include <bits/stdc++.h>using namespace std; // Function to return remainderint remainder(string str){ // len is variable to store the // length of number string. int len = str.length(); int num, rem = 0; // loop that find remainder for (int i = 0; i < len; i++) { num = rem * 10 + (str[i] - '0'); rem = num % 11; } return rem;} // Driver codeint main(){ string str = "3435346456547566345436457867978"; cout << remainder(str); return 0;}
// JAVA implementation to find remainder// when a large number is divided by 11import java.io.*; class GFG{ // Function to return remainder static int remainder(String str) { // len is variable to store the // length of number string. int len = str.length(); int num, rem = 0; // loop that find remainder for (int i = 0; i < len; i++) { num = rem * 10 + (str.charAt(i) - '0'); rem = num % 11; } return rem; } // Driver code public static void main(String args[]) { String str = "3435346456547566345436457867978"; System.out.println(remainder(str)); }} /*This code is contributed by Nikita Tiwari.*/
# Python 3 implementation to find remainder# when a large number is divided by 11 # Function to return remainderdef remainder(st) : # len is variable to store the # length of number string. ln = len(st) rem = 0 # loop that find remainder for i in range(0, ln) : num = rem * 10 + (int)(st[i]) rem = num % 11 return rem # Driver codest = "3435346456547566345436457867978"print(remainder(st)) # This code is contributed by Nikita Tiwari.
// C# implementation to find remainder// when a large number is divided by 11using System; class GFG{ // Function to return remainder static int remainder(string str) { // len is variable to store the // length of number string. int len = str.Length; int num, rem = 0; // loop that find remainder for (int i = 0; i < len; i++) { num = rem * 10 + (str[i] - '0'); rem = num % 11; } return rem; } // Driver code public static void Main() { string str = "3435346456547566345436457867978"; Console.WriteLine(remainder(str)); }} // This code is contributed by vt_m.
<?php// PHP implementation to find remainder// when a large number is divided by 11 // Function to return remainderfunction remainder($str){ // len is variable to store the // length of number string. $len = strlen($str); $num; $rem = 0; // loop that find remainder for ($i = 0; $i < $len; $i++) { $num = $rem * 10 + ($str[$i] - '0'); $rem = $num % 11; } return $rem;} // Driver code$str = "3435346456547566345436457867978";echo(remainder($str)); // This code is contributed by Ajit.?>
<script>// Javascript implementation to find remainder// when a large number is divided by 11 // Function to return remainderfunction remainder(str){ // len is variable to store the // length of number string. let len = str.length; let num; let rem = 0; // loop that find remainder for (let i = 0; i < len; i++) { num = rem * 10 + (str[i] - '0'); rem = num % 11; } return rem;} // Driver codelet str = "3435346456547566345436457867978";document.write(remainder(str)); // This code is contributed by _saurabh_jaiswal.</script>
Output:
4
Time Complexity: O(L ) where L is length of the string
Auxiliary Space: O(L )
vaibhav2992
vt_m
jit_t
ujjwalgoel1103
_saurabh_jaiswal
divisibility
large-numbers
Mathematical
Strings
Strings
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Merge two sorted arrays
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Check for Balanced Brackets in an expression (well-formedness) using Stack
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n13 Apr, 2021"
},
{
"code": null,
"e": 180,
"s": 54,
"text": "Given a number n, the task is to find the remainder when n is divided by 11. The input of number may be very large.Examples: "
},
{
"code": null,
"e": 281,
"s": 180,
"text": "Input : str = 13589234356546756\nOutput : 6\n\nInput : str = 3435346456547566345436457867978\nOutput : 4"
},
{
"code": null,
"e": 410,
"s": 281,
"text": "Since the given number can be very large, we can not use n % 11. There are some steps that needs to be used to find remainder: "
},
{
"code": null,
"e": 712,
"s": 410,
"text": "1. Store number in string.\n2. Count length of number string.\n3. Convert string character one by one \ninto digit and check if it's less than\n11. Then continue for next character \notherwise take remainder and use \nremainder for next number.\n4. We get remainder.\n\nEx. str = \"1345\"\n len = 4\n rem = 3"
},
{
"code": null,
"e": 716,
"s": 712,
"text": "C++"
},
{
"code": null,
"e": 721,
"s": 716,
"text": "Java"
},
{
"code": null,
"e": 729,
"s": 721,
"text": "Python3"
},
{
"code": null,
"e": 732,
"s": 729,
"text": "C#"
},
{
"code": null,
"e": 736,
"s": 732,
"text": "PHP"
},
{
"code": null,
"e": 747,
"s": 736,
"text": "Javascript"
},
{
"code": "// CPP implementation to find remainder// when a large number is divided by 11#include <bits/stdc++.h>using namespace std; // Function to return remainderint remainder(string str){ // len is variable to store the // length of number string. int len = str.length(); int num, rem = 0; // loop that find remainder for (int i = 0; i < len; i++) { num = rem * 10 + (str[i] - '0'); rem = num % 11; } return rem;} // Driver codeint main(){ string str = \"3435346456547566345436457867978\"; cout << remainder(str); return 0;}",
"e": 1313,
"s": 747,
"text": null
},
{
"code": "// JAVA implementation to find remainder// when a large number is divided by 11import java.io.*; class GFG{ // Function to return remainder static int remainder(String str) { // len is variable to store the // length of number string. int len = str.length(); int num, rem = 0; // loop that find remainder for (int i = 0; i < len; i++) { num = rem * 10 + (str.charAt(i) - '0'); rem = num % 11; } return rem; } // Driver code public static void main(String args[]) { String str = \"3435346456547566345436457867978\"; System.out.println(remainder(str)); }} /*This code is contributed by Nikita Tiwari.*/",
"e": 2057,
"s": 1313,
"text": null
},
{
"code": "# Python 3 implementation to find remainder# when a large number is divided by 11 # Function to return remainderdef remainder(st) : # len is variable to store the # length of number string. ln = len(st) rem = 0 # loop that find remainder for i in range(0, ln) : num = rem * 10 + (int)(st[i]) rem = num % 11 return rem # Driver codest = \"3435346456547566345436457867978\"print(remainder(st)) # This code is contributed by Nikita Tiwari.",
"e": 2561,
"s": 2057,
"text": null
},
{
"code": "// C# implementation to find remainder// when a large number is divided by 11using System; class GFG{ // Function to return remainder static int remainder(string str) { // len is variable to store the // length of number string. int len = str.Length; int num, rem = 0; // loop that find remainder for (int i = 0; i < len; i++) { num = rem * 10 + (str[i] - '0'); rem = num % 11; } return rem; } // Driver code public static void Main() { string str = \"3435346456547566345436457867978\"; Console.WriteLine(remainder(str)); }} // This code is contributed by vt_m.",
"e": 3278,
"s": 2561,
"text": null
},
{
"code": "<?php// PHP implementation to find remainder// when a large number is divided by 11 // Function to return remainderfunction remainder($str){ // len is variable to store the // length of number string. $len = strlen($str); $num; $rem = 0; // loop that find remainder for ($i = 0; $i < $len; $i++) { $num = $rem * 10 + ($str[$i] - '0'); $rem = $num % 11; } return $rem;} // Driver code$str = \"3435346456547566345436457867978\";echo(remainder($str)); // This code is contributed by Ajit.?>",
"e": 3827,
"s": 3278,
"text": null
},
{
"code": "<script>// Javascript implementation to find remainder// when a large number is divided by 11 // Function to return remainderfunction remainder(str){ // len is variable to store the // length of number string. let len = str.length; let num; let rem = 0; // loop that find remainder for (let i = 0; i < len; i++) { num = rem * 10 + (str[i] - '0'); rem = num % 11; } return rem;} // Driver codelet str = \"3435346456547566345436457867978\";document.write(remainder(str)); // This code is contributed by _saurabh_jaiswal.</script>",
"e": 4419,
"s": 3827,
"text": null
},
{
"code": null,
"e": 4428,
"s": 4419,
"text": "Output: "
},
{
"code": null,
"e": 4430,
"s": 4428,
"text": "4"
},
{
"code": null,
"e": 4485,
"s": 4430,
"text": "Time Complexity: O(L ) where L is length of the string"
},
{
"code": null,
"e": 4508,
"s": 4485,
"text": "Auxiliary Space: O(L )"
},
{
"code": null,
"e": 4520,
"s": 4508,
"text": "vaibhav2992"
},
{
"code": null,
"e": 4525,
"s": 4520,
"text": "vt_m"
},
{
"code": null,
"e": 4531,
"s": 4525,
"text": "jit_t"
},
{
"code": null,
"e": 4546,
"s": 4531,
"text": "ujjwalgoel1103"
},
{
"code": null,
"e": 4563,
"s": 4546,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 4576,
"s": 4563,
"text": "divisibility"
},
{
"code": null,
"e": 4590,
"s": 4576,
"text": "large-numbers"
},
{
"code": null,
"e": 4603,
"s": 4590,
"text": "Mathematical"
},
{
"code": null,
"e": 4611,
"s": 4603,
"text": "Strings"
},
{
"code": null,
"e": 4619,
"s": 4611,
"text": "Strings"
},
{
"code": null,
"e": 4632,
"s": 4619,
"text": "Mathematical"
},
{
"code": null,
"e": 4730,
"s": 4632,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4760,
"s": 4730,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 4803,
"s": 4760,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 4863,
"s": 4803,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 4878,
"s": 4863,
"text": "C++ Data Types"
},
{
"code": null,
"e": 4902,
"s": 4878,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 4948,
"s": 4902,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 4973,
"s": 4948,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 5033,
"s": 4973,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 5048,
"s": 5033,
"text": "C++ Data Types"
}
] |
PostgreSQL – COALESCE
|
28 Aug, 2020
In PostgreSQL, the COALESCE function returns the first non-null argument. It is generally used with the SELECT statement to handle null values effectively.
Syntax: COALESCE (argument_1, argument_2, ...);
The COALESCE function accepts an unlimited number of arguments. It returns the first argument that is not null. If all arguments are null, the COALESCE function will return null. he COALESCE function evaluates arguments from left to right until it finds the first non-null argument. All the remaining arguments from the first non-null argument are not evaluated.
Example:For the purpose of demonstration let’s first create a table (say, items) using the below statement:
CREATE TABLE items (
ID serial PRIMARY KEY,
product VARCHAR (100) NOT NULL,
price NUMERIC NOT NULL,
discount NUMERIC
);
There are four fields in the items table:
id: the primary key that identifies the item in the items table.
product: the product name.
price: the price of the product.
discount: the discount of the product.
Now we insert some records into the items table using INSERT statement as follows:
INSERT INTO items (product, price, discount)
VALUES
('A', 1000, 10),
('B', 1500, 20),
('C', 800, 5),
('D', 500, NULL);
Finally we query the net prices of the products using the following:
SELECT
product,
(price - discount) AS net_price
FROM
items;
This will lead to the following:f you look at the fourth row, you will notice that the net price of the product D is null which seems not correct. The issue is the discount of the product D is null, therefore when we take the null value to calculate the net price, PostgreSQL returns null. The get the right price, we need to assume that if the discount is null, it is zero. Then we can use the COALESCE function as follows:
SELECT
product,
(price - COALESCE(discount, 0)) AS net_price
FROM
items;
Output:
postgreSQL-operators
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - Psql commands
PostgreSQL - Change Column Type
PostgreSQL - For Loops
PostgreSQL - Function Returning A Table
PostgreSQL - LIMIT with OFFSET clause
PostgreSQL - ARRAY_AGG() Function
PostgreSQL - DROP INDEX
PostgreSQL - Create Auto-increment Column using SERIAL
PostgreSQL - Copy Table
How to use PostgreSQL Database in Django?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Aug, 2020"
},
{
"code": null,
"e": 184,
"s": 28,
"text": "In PostgreSQL, the COALESCE function returns the first non-null argument. It is generally used with the SELECT statement to handle null values effectively."
},
{
"code": null,
"e": 232,
"s": 184,
"text": "Syntax: COALESCE (argument_1, argument_2, ...);"
},
{
"code": null,
"e": 595,
"s": 232,
"text": "The COALESCE function accepts an unlimited number of arguments. It returns the first argument that is not null. If all arguments are null, the COALESCE function will return null. he COALESCE function evaluates arguments from left to right until it finds the first non-null argument. All the remaining arguments from the first non-null argument are not evaluated."
},
{
"code": null,
"e": 703,
"s": 595,
"text": "Example:For the purpose of demonstration let’s first create a table (say, items) using the below statement:"
},
{
"code": null,
"e": 839,
"s": 703,
"text": "CREATE TABLE items (\n ID serial PRIMARY KEY,\n product VARCHAR (100) NOT NULL,\n price NUMERIC NOT NULL,\n discount NUMERIC\n);"
},
{
"code": null,
"e": 881,
"s": 839,
"text": "There are four fields in the items table:"
},
{
"code": null,
"e": 946,
"s": 881,
"text": "id: the primary key that identifies the item in the items table."
},
{
"code": null,
"e": 973,
"s": 946,
"text": "product: the product name."
},
{
"code": null,
"e": 1006,
"s": 973,
"text": "price: the price of the product."
},
{
"code": null,
"e": 1045,
"s": 1006,
"text": "discount: the discount of the product."
},
{
"code": null,
"e": 1128,
"s": 1045,
"text": "Now we insert some records into the items table using INSERT statement as follows:"
},
{
"code": null,
"e": 1263,
"s": 1128,
"text": "INSERT INTO items (product, price, discount)\nVALUES\n ('A', 1000, 10),\n ('B', 1500, 20),\n ('C', 800, 5),\n ('D', 500, NULL);"
},
{
"code": null,
"e": 1332,
"s": 1263,
"text": "Finally we query the net prices of the products using the following:"
},
{
"code": null,
"e": 1404,
"s": 1332,
"text": "SELECT\n product,\n (price - discount) AS net_price\nFROM\n items;"
},
{
"code": null,
"e": 1829,
"s": 1404,
"text": "This will lead to the following:f you look at the fourth row, you will notice that the net price of the product D is null which seems not correct. The issue is the discount of the product D is null, therefore when we take the null value to calculate the net price, PostgreSQL returns null. The get the right price, we need to assume that if the discount is null, it is zero. Then we can use the COALESCE function as follows:"
},
{
"code": null,
"e": 1914,
"s": 1829,
"text": "SELECT\n product,\n (price - COALESCE(discount, 0)) AS net_price\nFROM\n items;"
},
{
"code": null,
"e": 1922,
"s": 1914,
"text": "Output:"
},
{
"code": null,
"e": 1943,
"s": 1922,
"text": "postgreSQL-operators"
},
{
"code": null,
"e": 1954,
"s": 1943,
"text": "PostgreSQL"
},
{
"code": null,
"e": 2052,
"s": 1954,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2079,
"s": 2052,
"text": "PostgreSQL - Psql commands"
},
{
"code": null,
"e": 2111,
"s": 2079,
"text": "PostgreSQL - Change Column Type"
},
{
"code": null,
"e": 2134,
"s": 2111,
"text": "PostgreSQL - For Loops"
},
{
"code": null,
"e": 2174,
"s": 2134,
"text": "PostgreSQL - Function Returning A Table"
},
{
"code": null,
"e": 2212,
"s": 2174,
"text": "PostgreSQL - LIMIT with OFFSET clause"
},
{
"code": null,
"e": 2246,
"s": 2212,
"text": "PostgreSQL - ARRAY_AGG() Function"
},
{
"code": null,
"e": 2270,
"s": 2246,
"text": "PostgreSQL - DROP INDEX"
},
{
"code": null,
"e": 2325,
"s": 2270,
"text": "PostgreSQL - Create Auto-increment Column using SERIAL"
},
{
"code": null,
"e": 2349,
"s": 2325,
"text": "PostgreSQL - Copy Table"
}
] |
What are shift operators in C++?
|
The bitwise shift operators are the right-shift operator (>>), which moves the bits of shift_expression to the right, and the left-shift operator (<<), which moves the bits of shift_expression to the left.
The left-shift operator causes the bits in shift-expression to be shifted to the left by the number of positions specified by additive-expression. The bit positions that have been vacated by the shift operation are zero-filled. A left shift is a logical shift (the bits that are shifted off the end are discarded, including the sign bit).
The right-shift operator causes the bit pattern in shift-expression to be shifted to the right by the number of positions specified by additive-expression. For unsigned numbers, the bit positions that have been vacated by the shift operation are zero-filled. For signed numbers, the sign bit is used to fill the vacated bit positions. In other words, if the number is positive, 0 is used, and if the number is negative, 1 is used.
#include<iostream>
using namespace std;
int main() {
int a = 1, b = 3;
// a right now is 00000001
// Left shifting it by 3 will make it 00001000, ie, 8
a = a << 3;
cout << a << endl;
// Right shifting a by 2 will make it 00000010, ie, 2
a = a >> 2;
cout << a << endl;
return 0;
}
This will give the output −
8
2
Note that these operators behave very differently with negative numbers. The result of a right-shift of a signed negative number is implementation-dependent. If you left-shift a signed number so that the sign bit is affected, the result is undefined.
There are also 2 complex operators that can be used to assign the value directly to the value on left. These are the <<= operator and the >>= operator.
Refer to https://msdn.microsoft.com/en-us/library/336xbhcz.aspx for a much detailed inspection of the shift operators.
|
[
{
"code": null,
"e": 1268,
"s": 1062,
"text": "The bitwise shift operators are the right-shift operator (>>), which moves the bits of shift_expression to the right, and the left-shift operator (<<), which moves the bits of shift_expression to the left."
},
{
"code": null,
"e": 1607,
"s": 1268,
"text": "The left-shift operator causes the bits in shift-expression to be shifted to the left by the number of positions specified by additive-expression. The bit positions that have been vacated by the shift operation are zero-filled. A left shift is a logical shift (the bits that are shifted off the end are discarded, including the sign bit)."
},
{
"code": null,
"e": 2038,
"s": 1607,
"text": "The right-shift operator causes the bit pattern in shift-expression to be shifted to the right by the number of positions specified by additive-expression. For unsigned numbers, the bit positions that have been vacated by the shift operation are zero-filled. For signed numbers, the sign bit is used to fill the vacated bit positions. In other words, if the number is positive, 0 is used, and if the number is negative, 1 is used."
},
{
"code": null,
"e": 2353,
"s": 2038,
"text": "#include<iostream>\nusing namespace std;\nint main() {\n int a = 1, b = 3;\n \n // a right now is 00000001\n // Left shifting it by 3 will make it 00001000, ie, 8\n a = a << 3;\n cout << a << endl;\n \n // Right shifting a by 2 will make it 00000010, ie, 2\n a = a >> 2;\n cout << a << endl;\n return 0;\n}"
},
{
"code": null,
"e": 2381,
"s": 2353,
"text": "This will give the output −"
},
{
"code": null,
"e": 2385,
"s": 2381,
"text": "8\n2"
},
{
"code": null,
"e": 2636,
"s": 2385,
"text": "Note that these operators behave very differently with negative numbers. The result of a right-shift of a signed negative number is implementation-dependent. If you left-shift a signed number so that the sign bit is affected, the result is undefined."
},
{
"code": null,
"e": 2788,
"s": 2636,
"text": "There are also 2 complex operators that can be used to assign the value directly to the value on left. These are the <<= operator and the >>= operator."
},
{
"code": null,
"e": 2907,
"s": 2788,
"text": "Refer to https://msdn.microsoft.com/en-us/library/336xbhcz.aspx for a much detailed inspection of the shift operators."
}
] |
What is the difference between String.Copy() and String.Clone() methods in C#?
|
The String.Copy() method creates a new instance of String. This is same as the specified String.
The following is an example of Copy() method −
Live Demo
using System;
class Demo {
static void Main(String[] args) {
string str1 = "mark";
string str2 = "marcus";
Console.WriteLine("str1 = '{0}'", str1);
Console.WriteLine("str2 = '{0}'", str2);
Console.WriteLine("After using String.Copy...");
str2 = String.Copy(str1);
Console.WriteLine("str1 = '{0}'", str1);
Console.WriteLine("str2 = '{0}'", str2);
}
}
str1 = 'mark'
str2 = 'marcus'
After using String.Copy...
str1 = 'mark'
str2 = 'mark'
The String.Clone() method returns a reference to the instance of String. The following is an example of Clone() method −
Live Demo
using System;
class Demo {
static void Main(String[] args) {
string str1 = "amy";
string str2 = "emma";
Console.WriteLine("str1 = '{0}'", str1);
Console.WriteLine("str2 = '{0}'", str2);
Console.WriteLine("After using String.Clone...");
str2 = (String)str1.Clone();
Console.WriteLine("str1 = '{0}'", str1);
Console.WriteLine("str2 = '{0}'", str2);
}
}
str1 = 'amy'
str2 = 'emma'
After using String.Clone...
str1 = 'amy'
str2 = 'amy'
|
[
{
"code": null,
"e": 1159,
"s": 1062,
"text": "The String.Copy() method creates a new instance of String. This is same as the specified String."
},
{
"code": null,
"e": 1206,
"s": 1159,
"text": "The following is an example of Copy() method −"
},
{
"code": null,
"e": 1217,
"s": 1206,
"text": " Live Demo"
},
{
"code": null,
"e": 1625,
"s": 1217,
"text": "using System;\nclass Demo {\n static void Main(String[] args) {\n\n string str1 = \"mark\";\n string str2 = \"marcus\";\n\n Console.WriteLine(\"str1 = '{0}'\", str1);\n Console.WriteLine(\"str2 = '{0}'\", str2);\n\n Console.WriteLine(\"After using String.Copy...\");\n str2 = String.Copy(str1);\n\n Console.WriteLine(\"str1 = '{0}'\", str1);\n Console.WriteLine(\"str2 = '{0}'\", str2);\n }\n}"
},
{
"code": null,
"e": 1710,
"s": 1625,
"text": "str1 = 'mark'\nstr2 = 'marcus'\nAfter using String.Copy...\nstr1 = 'mark'\nstr2 = 'mark'"
},
{
"code": null,
"e": 1831,
"s": 1710,
"text": "The String.Clone() method returns a reference to the instance of String. The following is an example of Clone() method −"
},
{
"code": null,
"e": 1842,
"s": 1831,
"text": " Live Demo"
},
{
"code": null,
"e": 2256,
"s": 1842,
"text": "using System;\nclass Demo {\n static void Main(String[] args) {\n \n string str1 = \"amy\";\n string str2 = \"emma\";\n\n Console.WriteLine(\"str1 = '{0}'\", str1);\n Console.WriteLine(\"str2 = '{0}'\", str2);\n\n Console.WriteLine(\"After using String.Clone...\");\n str2 = (String)str1.Clone();\n\n Console.WriteLine(\"str1 = '{0}'\", str1);\n Console.WriteLine(\"str2 = '{0}'\", str2);\n }\n}"
},
{
"code": null,
"e": 2337,
"s": 2256,
"text": "str1 = 'amy'\nstr2 = 'emma'\nAfter using String.Clone...\nstr1 = 'amy'\nstr2 = 'amy'"
}
] |
turtle.showturtle() function in Python - GeeksforGeeks
|
28 Jul, 2020
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
This method is used to makes the turtle visible. It doesn’t require any argument.
Syntax:
turtle.showturtle()
or
turtle.st()
Below is the implementation of the above method with an example :
Example:
Python3
# import packageimport turtle # set speed to slowest for# better understandingsturtle.speed(1) # motionturtle.forward(100)turtle.right(90) # hide the turtleturtle.hideturtle() # motionturtle.forward(100)turtle.right(90)turtle.forward(100)turtle.right(90) # show the turtleturtle.showturtle() # motionturtle.forward(100)turtle.right(90)
Output :
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Reading and Writing to text files in Python
sum() function in Python
How to drop one or multiple columns in Pandas Dataframe
|
[
{
"code": null,
"e": 24369,
"s": 24341,
"text": "\n28 Jul, 2020"
},
{
"code": null,
"e": 24586,
"s": 24369,
"text": "The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support."
},
{
"code": null,
"e": 24668,
"s": 24586,
"text": "This method is used to makes the turtle visible. It doesn’t require any argument."
},
{
"code": null,
"e": 24676,
"s": 24668,
"text": "Syntax:"
},
{
"code": null,
"e": 24714,
"s": 24676,
"text": "turtle.showturtle() \nor \nturtle.st()\n"
},
{
"code": null,
"e": 24780,
"s": 24714,
"text": "Below is the implementation of the above method with an example :"
},
{
"code": null,
"e": 24789,
"s": 24780,
"text": "Example:"
},
{
"code": null,
"e": 24797,
"s": 24789,
"text": "Python3"
},
{
"code": "# import packageimport turtle # set speed to slowest for# better understandingsturtle.speed(1) # motionturtle.forward(100)turtle.right(90) # hide the turtleturtle.hideturtle() # motionturtle.forward(100)turtle.right(90)turtle.forward(100)turtle.right(90) # show the turtleturtle.showturtle() # motionturtle.forward(100)turtle.right(90)",
"e": 25139,
"s": 24797,
"text": null
},
{
"code": null,
"e": 25148,
"s": 25139,
"text": "Output :"
},
{
"code": null,
"e": 25162,
"s": 25148,
"text": "Python-turtle"
},
{
"code": null,
"e": 25169,
"s": 25162,
"text": "Python"
},
{
"code": null,
"e": 25267,
"s": 25169,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25276,
"s": 25267,
"text": "Comments"
},
{
"code": null,
"e": 25289,
"s": 25276,
"text": "Old Comments"
},
{
"code": null,
"e": 25307,
"s": 25289,
"text": "Python Dictionary"
},
{
"code": null,
"e": 25342,
"s": 25307,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 25364,
"s": 25342,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 25396,
"s": 25364,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25426,
"s": 25396,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 25468,
"s": 25426,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 25511,
"s": 25468,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 25555,
"s": 25511,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 25580,
"s": 25555,
"text": "sum() function in Python"
}
] |
How to reset a form using jQuery with .reset() method? - GeeksforGeeks
|
03 Aug, 2021
Reset gets anything back to its original state. JQuery doesn’t have a reset() method, but native JavaScript does. So, we convert the jQuery element to a JavaScript object.
JavaScript reset(): The reset() method resets the values of all elements in a form (same as clicking the Reset button).
// type-1
<input type="reset">
// type-1
<input type="reset">
// type-2
<input type="button" onclick="this.form.reset();">
// type-2
<input type="button" onclick="this.form.reset();">
// type-3
<input type="button" onclick="formname.reset();">
// type-3
<input type="button" onclick="formname.reset();">
The button itself resets the form but, the type-1 and type-2, the reset button should be inside the form and type-3 can be either out or in.But a reset button is a far better choice. (type-1)
<input type="reset">
<input type="reset">
Syntax for reset():formObject.reset()
formObject.reset()
Syntax to convert jQuery element to a JavaScript object.$(selector)[0].reset()or$(selector).get(0).reset()
$(selector)[0].reset()
or
$(selector).get(0).reset()
If we don’t want to convert the jQuery element to a JavaScript object then we can use the trigger().
As trigger() method triggers the specified event and the default behavior of an event (like form submission) for the selected elements.Syntax
$(selector).trigger(event, eventObj, ...)
Example:
<!DOCTYPE html><html> <head> <title>Try jQuery Online</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script> $(document).ready(function() { $("button").click(function() { //$("#d").trigger("reset"); //$("#d").get(0).reset(); $("#d")[0].reset() }); }); </script></head> <body> <center> <h1 style="color:green">GeeksforGeeks</h1> <h4> Click on "Submit" to submit and remaining resets to get form to original state. </h4> <form id="d" action="/cgi-bin/test.cgi" name="geek"> <table cellspacing="0" cellpadding="3" border="1"> <tr> <td align="center">Username</td> <td> <input type="text" name="name" /> </td> </tr> <tr> <td align="center">Email</td> <td> <input type="text" name="name" /> </td> </tr> <tr> <td align="center">Password</td> <td> <input type="password" /> </td> </tr> <tr> <td align="center"></td> <td> <input type="submit" value="Submit" /> </td> </tr> <tr> <td align="center"></td> <td> <input type="reset" value="reset button" /> </td> </tr> </table> </form> <br> <input type="button" value="reset() outside form" onclick="geek.reset();" /> <button>resetby jQuery</button> </center></body> </html>
Output
jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.
jQuery-Misc
Picked
JQuery
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
jQuery | ajax() Method
jQuery | children() with Examples
How to check whether a checkbox is checked in jQuery?
How to prevent Body from scrolling when a modal is opened using jQuery ?
How to change the background color of the active nav-item?
Installation of Node.js on Linux
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 25699,
"s": 25671,
"text": "\n03 Aug, 2021"
},
{
"code": null,
"e": 25871,
"s": 25699,
"text": "Reset gets anything back to its original state. JQuery doesn’t have a reset() method, but native JavaScript does. So, we convert the jQuery element to a JavaScript object."
},
{
"code": null,
"e": 25991,
"s": 25871,
"text": "JavaScript reset(): The reset() method resets the values of all elements in a form (same as clicking the Reset button)."
},
{
"code": null,
"e": 26023,
"s": 25991,
"text": "// type-1\n<input type=\"reset\">\n"
},
{
"code": null,
"e": 26055,
"s": 26023,
"text": "// type-1\n<input type=\"reset\">\n"
},
{
"code": null,
"e": 26116,
"s": 26055,
"text": "// type-2\n<input type=\"button\" onclick=\"this.form.reset();\">"
},
{
"code": null,
"e": 26177,
"s": 26116,
"text": "// type-2\n<input type=\"button\" onclick=\"this.form.reset();\">"
},
{
"code": null,
"e": 26237,
"s": 26177,
"text": "// type-3\n<input type=\"button\" onclick=\"formname.reset();\">"
},
{
"code": null,
"e": 26297,
"s": 26237,
"text": "// type-3\n<input type=\"button\" onclick=\"formname.reset();\">"
},
{
"code": null,
"e": 26489,
"s": 26297,
"text": "The button itself resets the form but, the type-1 and type-2, the reset button should be inside the form and type-3 can be either out or in.But a reset button is a far better choice. (type-1)"
},
{
"code": null,
"e": 26510,
"s": 26489,
"text": "<input type=\"reset\">"
},
{
"code": null,
"e": 26531,
"s": 26510,
"text": "<input type=\"reset\">"
},
{
"code": null,
"e": 26569,
"s": 26531,
"text": "Syntax for reset():formObject.reset()"
},
{
"code": null,
"e": 26588,
"s": 26569,
"text": "formObject.reset()"
},
{
"code": null,
"e": 26695,
"s": 26588,
"text": "Syntax to convert jQuery element to a JavaScript object.$(selector)[0].reset()or$(selector).get(0).reset()"
},
{
"code": null,
"e": 26718,
"s": 26695,
"text": "$(selector)[0].reset()"
},
{
"code": null,
"e": 26721,
"s": 26718,
"text": "or"
},
{
"code": null,
"e": 26748,
"s": 26721,
"text": "$(selector).get(0).reset()"
},
{
"code": null,
"e": 26849,
"s": 26748,
"text": "If we don’t want to convert the jQuery element to a JavaScript object then we can use the trigger()."
},
{
"code": null,
"e": 26991,
"s": 26849,
"text": "As trigger() method triggers the specified event and the default behavior of an event (like form submission) for the selected elements.Syntax"
},
{
"code": null,
"e": 27033,
"s": 26991,
"text": "$(selector).trigger(event, eventObj, ...)"
},
{
"code": null,
"e": 27042,
"s": 27033,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Try jQuery Online</title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script> $(document).ready(function() { $(\"button\").click(function() { //$(\"#d\").trigger(\"reset\"); //$(\"#d\").get(0).reset(); $(\"#d\")[0].reset() }); }); </script></head> <body> <center> <h1 style=\"color:green\">GeeksforGeeks</h1> <h4> Click on \"Submit\" to submit and remaining resets to get form to original state. </h4> <form id=\"d\" action=\"/cgi-bin/test.cgi\" name=\"geek\"> <table cellspacing=\"0\" cellpadding=\"3\" border=\"1\"> <tr> <td align=\"center\">Username</td> <td> <input type=\"text\" name=\"name\" /> </td> </tr> <tr> <td align=\"center\">Email</td> <td> <input type=\"text\" name=\"name\" /> </td> </tr> <tr> <td align=\"center\">Password</td> <td> <input type=\"password\" /> </td> </tr> <tr> <td align=\"center\"></td> <td> <input type=\"submit\" value=\"Submit\" /> </td> </tr> <tr> <td align=\"center\"></td> <td> <input type=\"reset\" value=\"reset button\" /> </td> </tr> </table> </form> <br> <input type=\"button\" value=\"reset() outside form\" onclick=\"geek.reset();\" /> <button>resetby jQuery</button> </center></body> </html>",
"e": 28986,
"s": 27042,
"text": null
},
{
"code": null,
"e": 28993,
"s": 28986,
"text": "Output"
},
{
"code": null,
"e": 29261,
"s": 28993,
"text": "jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples."
},
{
"code": null,
"e": 29273,
"s": 29261,
"text": "jQuery-Misc"
},
{
"code": null,
"e": 29280,
"s": 29273,
"text": "Picked"
},
{
"code": null,
"e": 29287,
"s": 29280,
"text": "JQuery"
},
{
"code": null,
"e": 29304,
"s": 29287,
"text": "Web Technologies"
},
{
"code": null,
"e": 29331,
"s": 29304,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 29429,
"s": 29331,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29438,
"s": 29429,
"text": "Comments"
},
{
"code": null,
"e": 29451,
"s": 29438,
"text": "Old Comments"
},
{
"code": null,
"e": 29474,
"s": 29451,
"text": "jQuery | ajax() Method"
},
{
"code": null,
"e": 29508,
"s": 29474,
"text": "jQuery | children() with Examples"
},
{
"code": null,
"e": 29562,
"s": 29508,
"text": "How to check whether a checkbox is checked in jQuery?"
},
{
"code": null,
"e": 29635,
"s": 29562,
"text": "How to prevent Body from scrolling when a modal is opened using jQuery ?"
},
{
"code": null,
"e": 29694,
"s": 29635,
"text": "How to change the background color of the active nav-item?"
},
{
"code": null,
"e": 29727,
"s": 29694,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29769,
"s": 29727,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 29812,
"s": 29769,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 29874,
"s": 29812,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
How to write custom Python Exceptions with Error Codes and Error Messages?
|
We can write custom exception classes with error codes and error messages as follows:
class ErrorCode(Exception):
def __init__(self, code):
self.code = code
try:
raise ErrorCode(401)
except ErrorCode as e:
print "Received error with code:", e.code
We get output
C:/Users/TutorialsPoint1/~.py
Received error with code: 401
We can also write custom exceptions with arguments, error codes and error messages as follows:
class ErrorArgs(Exception):
def __init__(self, *args):
self.args = [a for a in args]
try:
raise ErrorArgs(403, "foo", "bar")
except ErrorArgs as e:
print "%d: %s , %s" % (e.args[0], e.args[1], e.args[2])
We get following output
C:/Users/TutorialsPoint1/~.py
403: foo , bar
|
[
{
"code": null,
"e": 1148,
"s": 1062,
"text": "We can write custom exception classes with error codes and error messages as follows:"
},
{
"code": null,
"e": 1334,
"s": 1148,
"text": "class ErrorCode(Exception):\n def __init__(self, code):\n self.code = code\n \ntry:\n raise ErrorCode(401)\nexcept ErrorCode as e:\n print \"Received error with code:\", e.code"
},
{
"code": null,
"e": 1348,
"s": 1334,
"text": "We get output"
},
{
"code": null,
"e": 1408,
"s": 1348,
"text": "C:/Users/TutorialsPoint1/~.py\nReceived error with code: 401"
},
{
"code": null,
"e": 1503,
"s": 1408,
"text": "We can also write custom exceptions with arguments, error codes and error messages as follows:"
},
{
"code": null,
"e": 1727,
"s": 1503,
"text": "class ErrorArgs(Exception):\n def __init__(self, *args):\n self.args = [a for a in args]\ntry:\n raise ErrorArgs(403, \"foo\", \"bar\")\nexcept ErrorArgs as e:\n print \"%d: %s , %s\" % (e.args[0], e.args[1], e.args[2])"
},
{
"code": null,
"e": 1751,
"s": 1727,
"text": "We get following output"
},
{
"code": null,
"e": 1796,
"s": 1751,
"text": "C:/Users/TutorialsPoint1/~.py\n403: foo , bar"
}
] |
Interaction effect in multiple regression | by Sufyan Khot | Towards Data Science
|
Interaction effect is present in statistics as well in marketing. In marketing, this same concept is referred to as the synergy effect. Interaction effect means that two or more features/variables combined have a significantly larger effect on a feature as compared to the sum of the individual variables alone. This effect is important to understand in regression as we try to study the effect of several variables on a single response variable.
A linear regression equation can be expressed as follows:
Here, we try to find the linear relation between the independent variables (X1 and X2) with the response variable Y and ε is the irreducible error. To check whether there is any significant statistical relation between the predictor and response variables, we conduct hypothesis testing. If we conduct this test for the predictor variable X1, we will have two hypotheses:
Null hypothesis(H0): There is no relationship between X1 and Y ( β1 = 0)
Alternative hypothesis(H1): There is a relationship between X1and Y ( β1≠ 0)
We then decide whether or not to reject the null hypothesis based on the p-value. P-value is the probability of the results of the test, given the null hypothesis is true.
For example, if we get a non-zero value of β1 in our test results, this indicates that there is a relationship between X1 and Y. But if the p-value is large, this indicates that there is a high probability that we might get a non-zero value for β1 even when the null hypothesis is actually true. In such a case, we fail to reject the null hypothesis and conclude that there is no relation between the predictor and response variable. But if the p-value is low (generally p-value cutoff is considered to be 0.05) then even a small non-zero value of β1 indicates a significant relation between the predictor and response variable.
If we conclude that there is a relationship between X1 and Y, we consider that for each unit increase of X1, Y increases/decreases by β1 units. In the linear equation above, we assume that the effect of X1 on Y is independent of X2. This is also called as the additive assumption in linear regression.
But what if the effect of X1 on Y is also dependent on X2? We can see such relations in many business problems. Consider for example we want to find out the return on investment for two different investment types. The linear regression equation for this example will be:
In this example, there is a possibility that there would be greater profit if we invest in both types of investments partially rather than investing in one completely. For example, if we have 1000 units of money to invest, investing 500 units of money in both the investments can lead to greater profit as compared to investing 1000 units completely in either of the investment types. In such a case, investment1’s relation with ROI will be dependent on investment2. This relation can be included in our equation as follows:
In the equation above, we have included the ‘interaction” between investment1 and investment2 for the prediction of total return on investment. We can include such interactions for any linear regression equation
The above equation can be rewritten as:
Here, β3 is the coefficient of the interaction term. Again, to verify the presence of an interaction effect in regression, we conduct a hypothesis test and check the p-value for our coefficient (in this case β3).
Now let us see how we can verify the presence of interaction effect in a data set. We will be using the Auto data set as our example. The data set can be downloaded from here. Let us have a look at the data set
import pandas as pddata = pd.read_csv('data/auto-mpg.csv')
Converting the data set to numeric and filling in the missing values
#removing irrelevant 'car name' columndata.drop('car name',axis=1,inplace=True)#converting all columns to numericfor col in data.columns: data[col] = pd.to_numeric(data[col], errors ='coerce')#replacing missing values in horsepower with its medianhorse_med = data['horsepower'].median()data['horsepower'] = data['horsepower'].fillna(horse_med)
Let us fit an OLS(Ordinary Least Squares) model on this data set. This model is present in the statsmodels library.
from statsmodels.regression import linear_modelX = data.drop('mpg', axis=1)y = data['mpg']model = linear_model.OLS(y, X).fit()
From this model we can get the coefficient values and also if they are statistically significant to be included in the model.
model.summary()
Below is the snapshot of the model summary.
In the above model summary, we can see that except acceleration, all other features have a p-value less than 0.05 and are statistically significant. Even if acceleration standalone is not helpful in the prediction of mpg, we are interested in finding out whether acceleration after interacting with other variables is having an effect on mpg. Also, we are interested to know the presence of all significant interaction terms.
We first need to create all possible interaction terms. This is possible in python by using PolynomialFeatures from sklearn library
from sklearn.preprocessing import PolynomialFeatures#generating interaction termsx_interaction = PolynomialFeatures(2, interaction_only=True, include_bias=False).fit_transform(X)#creating a new dataframe with the interaction terms includedinteraction_df = pd.DataFrame(x_interaction, columns = ['cylinders','displacement','horsepower','weight','acceleration','year','origin', 'cylinders:displacement','cylinders:horsepower','cylinders:weight','cylinders:acceleration', 'cylinders:year','cylinders:origin','displacement:horsepower','displacement:weight', 'displacement:acceleration','displacement:year','displacement:origin','horsepower:weight', 'horsepower:acceleration','horsepower:year','horsepower:origin','weight:acceleration', 'weight:year','weight:origin','acceleration:year','acceleration:origin','year:origin'])
As the new dataframe is created which includes the interaction terms, we can fit a new model to it and see which interaction terms are significant.
interaction_model = linear_model.OLS(y, interaction_df).fit()
Now we need only those interaction terms which are statistically significant (having p-value less than 0.05)
interaction_model.pvalues[interaction_model.pvalues < 0.05]
As we can see there is a presence of interaction terms. Also, acceleration alone is not significant but its interaction with horsepower and year proves to be very important for the prediction of mpg.
It is important to note that in the example above, the p-value of acceleration is high but it is included in interaction terms. In such a case, we have to include the main effects of acceleration in the model i.e. the coefficient of acceleration even when it is not statistically significant due to the hierarchy principle. Hierarchy principle states that if there are two features X1 and X2 in an interaction term, we have to include both of their coefficients(β1 and β2) in the model even when the p-values associated to them are very high.
|
[
{
"code": null,
"e": 618,
"s": 171,
"text": "Interaction effect is present in statistics as well in marketing. In marketing, this same concept is referred to as the synergy effect. Interaction effect means that two or more features/variables combined have a significantly larger effect on a feature as compared to the sum of the individual variables alone. This effect is important to understand in regression as we try to study the effect of several variables on a single response variable."
},
{
"code": null,
"e": 676,
"s": 618,
"text": "A linear regression equation can be expressed as follows:"
},
{
"code": null,
"e": 1048,
"s": 676,
"text": "Here, we try to find the linear relation between the independent variables (X1 and X2) with the response variable Y and ε is the irreducible error. To check whether there is any significant statistical relation between the predictor and response variables, we conduct hypothesis testing. If we conduct this test for the predictor variable X1, we will have two hypotheses:"
},
{
"code": null,
"e": 1121,
"s": 1048,
"text": "Null hypothesis(H0): There is no relationship between X1 and Y ( β1 = 0)"
},
{
"code": null,
"e": 1199,
"s": 1121,
"text": "Alternative hypothesis(H1): There is a relationship between X1and Y ( β1≠ 0)"
},
{
"code": null,
"e": 1371,
"s": 1199,
"text": "We then decide whether or not to reject the null hypothesis based on the p-value. P-value is the probability of the results of the test, given the null hypothesis is true."
},
{
"code": null,
"e": 2000,
"s": 1371,
"text": "For example, if we get a non-zero value of β1 in our test results, this indicates that there is a relationship between X1 and Y. But if the p-value is large, this indicates that there is a high probability that we might get a non-zero value for β1 even when the null hypothesis is actually true. In such a case, we fail to reject the null hypothesis and conclude that there is no relation between the predictor and response variable. But if the p-value is low (generally p-value cutoff is considered to be 0.05) then even a small non-zero value of β1 indicates a significant relation between the predictor and response variable."
},
{
"code": null,
"e": 2302,
"s": 2000,
"text": "If we conclude that there is a relationship between X1 and Y, we consider that for each unit increase of X1, Y increases/decreases by β1 units. In the linear equation above, we assume that the effect of X1 on Y is independent of X2. This is also called as the additive assumption in linear regression."
},
{
"code": null,
"e": 2573,
"s": 2302,
"text": "But what if the effect of X1 on Y is also dependent on X2? We can see such relations in many business problems. Consider for example we want to find out the return on investment for two different investment types. The linear regression equation for this example will be:"
},
{
"code": null,
"e": 3098,
"s": 2573,
"text": "In this example, there is a possibility that there would be greater profit if we invest in both types of investments partially rather than investing in one completely. For example, if we have 1000 units of money to invest, investing 500 units of money in both the investments can lead to greater profit as compared to investing 1000 units completely in either of the investment types. In such a case, investment1’s relation with ROI will be dependent on investment2. This relation can be included in our equation as follows:"
},
{
"code": null,
"e": 3310,
"s": 3098,
"text": "In the equation above, we have included the ‘interaction” between investment1 and investment2 for the prediction of total return on investment. We can include such interactions for any linear regression equation"
},
{
"code": null,
"e": 3350,
"s": 3310,
"text": "The above equation can be rewritten as:"
},
{
"code": null,
"e": 3563,
"s": 3350,
"text": "Here, β3 is the coefficient of the interaction term. Again, to verify the presence of an interaction effect in regression, we conduct a hypothesis test and check the p-value for our coefficient (in this case β3)."
},
{
"code": null,
"e": 3774,
"s": 3563,
"text": "Now let us see how we can verify the presence of interaction effect in a data set. We will be using the Auto data set as our example. The data set can be downloaded from here. Let us have a look at the data set"
},
{
"code": null,
"e": 3833,
"s": 3774,
"text": "import pandas as pddata = pd.read_csv('data/auto-mpg.csv')"
},
{
"code": null,
"e": 3902,
"s": 3833,
"text": "Converting the data set to numeric and filling in the missing values"
},
{
"code": null,
"e": 4249,
"s": 3902,
"text": "#removing irrelevant 'car name' columndata.drop('car name',axis=1,inplace=True)#converting all columns to numericfor col in data.columns: data[col] = pd.to_numeric(data[col], errors ='coerce')#replacing missing values in horsepower with its medianhorse_med = data['horsepower'].median()data['horsepower'] = data['horsepower'].fillna(horse_med)"
},
{
"code": null,
"e": 4365,
"s": 4249,
"text": "Let us fit an OLS(Ordinary Least Squares) model on this data set. This model is present in the statsmodels library."
},
{
"code": null,
"e": 4492,
"s": 4365,
"text": "from statsmodels.regression import linear_modelX = data.drop('mpg', axis=1)y = data['mpg']model = linear_model.OLS(y, X).fit()"
},
{
"code": null,
"e": 4618,
"s": 4492,
"text": "From this model we can get the coefficient values and also if they are statistically significant to be included in the model."
},
{
"code": null,
"e": 4634,
"s": 4618,
"text": "model.summary()"
},
{
"code": null,
"e": 4678,
"s": 4634,
"text": "Below is the snapshot of the model summary."
},
{
"code": null,
"e": 5104,
"s": 4678,
"text": "In the above model summary, we can see that except acceleration, all other features have a p-value less than 0.05 and are statistically significant. Even if acceleration standalone is not helpful in the prediction of mpg, we are interested in finding out whether acceleration after interacting with other variables is having an effect on mpg. Also, we are interested to know the presence of all significant interaction terms."
},
{
"code": null,
"e": 5236,
"s": 5104,
"text": "We first need to create all possible interaction terms. This is possible in python by using PolynomialFeatures from sklearn library"
},
{
"code": null,
"e": 6326,
"s": 5236,
"text": "from sklearn.preprocessing import PolynomialFeatures#generating interaction termsx_interaction = PolynomialFeatures(2, interaction_only=True, include_bias=False).fit_transform(X)#creating a new dataframe with the interaction terms includedinteraction_df = pd.DataFrame(x_interaction, columns = ['cylinders','displacement','horsepower','weight','acceleration','year','origin', 'cylinders:displacement','cylinders:horsepower','cylinders:weight','cylinders:acceleration', 'cylinders:year','cylinders:origin','displacement:horsepower','displacement:weight', 'displacement:acceleration','displacement:year','displacement:origin','horsepower:weight', 'horsepower:acceleration','horsepower:year','horsepower:origin','weight:acceleration', 'weight:year','weight:origin','acceleration:year','acceleration:origin','year:origin'])"
},
{
"code": null,
"e": 6474,
"s": 6326,
"text": "As the new dataframe is created which includes the interaction terms, we can fit a new model to it and see which interaction terms are significant."
},
{
"code": null,
"e": 6536,
"s": 6474,
"text": "interaction_model = linear_model.OLS(y, interaction_df).fit()"
},
{
"code": null,
"e": 6645,
"s": 6536,
"text": "Now we need only those interaction terms which are statistically significant (having p-value less than 0.05)"
},
{
"code": null,
"e": 6705,
"s": 6645,
"text": "interaction_model.pvalues[interaction_model.pvalues < 0.05]"
},
{
"code": null,
"e": 6905,
"s": 6705,
"text": "As we can see there is a presence of interaction terms. Also, acceleration alone is not significant but its interaction with horsepower and year proves to be very important for the prediction of mpg."
}
] |
Stack Operations | Practice | GeeksforGeeks
|
This Java module deals with Stacks, Queues, and ArrayLists. We'll perform various operations on them.
Given a stack of integers and Q queries. The task is to perform operation on stack according to the query.
Note: use push() to add element in the stack, peek() to get topmost element without removal, pop() gives topmost element with removal, search() to return position if found else -1.
Input Format:
First line of input contains nubmer of testcases T. For each testcase, first line of input contains Q, number of queries. Next line contains Q queries seperated by space. Queries are as:
i x : (adds element x in the stack).
r : (returns and removes the topmost element from the stack).
h : Prints the topmost element.
f y : (check if the element y is present or not in the stack). Print "Yes" if present, else "No".
i x : (adds element x in the stack).
i x : (adds element x in the stack).
r : (returns and removes the topmost element from the stack).
r : (returns and removes the topmost element from the stack).
h : Prints the topmost element.
h : Prints the topmost element.
f y : (check if the element y is present or not in the stack). Print "Yes" if present, else "No".
f y : (check if the element y is present or not in the stack). Print "Yes" if present, else "No".
Output Format:
For each testcase, perform Q queries and print the output wherever required.
Your Task:
Your task is to complete functions insert(), remove(), headOf_Stack() and find(), to insert, remove returning top element and findiing the elment in stack respectively.
Constraints:
1 <= T <= 100
1 <= Q <= 103
Example:
Input:
2
6
i 2 i 4 i 3 i 5 h f 8
4
i 3 i 4 r f 3
Output:
5
No
Yes
Explanation:
Testcase 1: Inserting 2, 4, 3, and 5 onto the stack. Returning top element which is 5. Finding 8 will give No, as 8 is not in the stack.
0
rahul8781 month ago
--------------------JAVA-SOLUTION------------------------
class Geeks
{
// Function to insert element to stack
public static void insert(Stack<Integer> st, int x)
{
st.push(x);
}
// Function to pop element from stack
public static void remove(Stack<Integer> st)
{
int x = st.pop();
}
// Function to return top of stack
public static void headOf_Stack(Stack<Integer> st)
{
int x = st.peek();
System.out.println(x + " ");
}
// Function to find the element in stack
public static void find(Stack<Integer> st, int val)
{
if(st.contains(val)){
System.out.println("Yes");
}
else{
System.out.println("No");
}
}
}
0
emmanueluluabuike3 months ago
Simple Java Solution
// Function to insert element to stack
public static void insert(Stack<Integer> st, int x)
{
// Your code here
st.push(x);
}
// Function to pop element from stack
I changed this from void to int
public static int remove(Stack<Integer> st)
{
int x = st.pop();// Your code here
return x;
}
// Function to return top of stack
public static void headOf_Stack(Stack<Integer> st)
{
int x = st.peek();// Your code here
System.out.println(x + " ");
}
// Function to find the element in stack
public static void find(Stack<Integer> st, int val)
{
if(st.contains(val)){
System.out.println("Yes");
}
else{
System.out.println("No");
}
}
0
feyza3 months ago
class Geeks{ // Function to insert element to stack public static void insert(Stack<Integer> st, int x) { st.push(x); } // Function to pop element from stack public static void remove(Stack<Integer> st) { st.pop(); } // Function to return top of stack public static void headOf_Stack(Stack<Integer> st) { int x = st.peek(); System.out.println(x + " "); } // Function to find the element in stack public static void find(Stack<Integer> st, int val) { if(st.contains(val)){ System.out.println("Yes"); } else{ System.out.println("No"); } }}
+1
o36csbhch5stx2bnu7nqk1lty2talmptprfody7l4 months ago
#Python code for this problem#
#DM on insta for queries#
0_tausif_raza_0 ← iD
class Stack():
def __init__(self):
self.items=[]
def isEmp(self):
if self.items==[]:
return True
else:
return False
def push(self,data):
self.items.append(data)
def Spop(self):
x=len(self.items)
po=self.items.pop(x-1)
print('po',po)
def show(self):
print(self.items)
def search(self,data):
if data in self.items:
return "Yes"
else:
return "No"
s1=Stack()
# all the operations performed manually
#you can delete this part and add a menu or add your own commands
s1.push("hi")
s1.push(2)
s1.push(3)
s1.push(4)
s1.show()
print(s1.search(10))
print(s1.search(3))
s1.isEmp()
-1
ja90806 months ago
class Geeks{ // Function to insert element to stack public static void insert(Stack<Integer> st, int x) { st.push(x); } // Function to pop element from stack public static void remove(Stack<Integer> st) { st.pop(); } // Function to return top of stack public static void headOf_Stack(Stack<Integer> st) { int x = st.peek(); System.out.println(x + " "); } // Function to find the element in stack public static void find(Stack<Integer> st, int val) { int a =0; Stack<Integer> temp = new Stack<Integer>(); while(!st.empty()){ if(st.peek()==val){ a=1; break; } temp.push(st.peek()); st.pop(); } while(!temp.empty()){ st.push(temp.peek()); temp.pop(); } if(a==1){ System.out.println("Yes"); } else{ System.out.println("No"); } }}
0
shubhmish2236 months ago
// { Driver Code Starts
//Initial Template for Java
import java.util.*;
// } Driver Code Ends
//User function Template for Java
// Helper class to implement functions
// insert : to insert element to stack
// remove : to pop element from stack
// headOf_Stack : to return top of stack
// find : to find the element in stack
class Geeks
{
// Function to insert element to stack
public static void insert(Stack<Integer> st, int x)
{
st.push(x);// Your code here
}
// Function to pop element from stack
public static void remove(Stack<Integer> st)
{
st.pop() ;// Your code here
}
// Function to return top of stack
public static void headOf_Stack(Stack<Integer> st)
{
int x =Integer()st.peek() // Your code here
System.out.println(x + " ");
}
// Function to find the element in stack
public static void find(Stack<Integer> st, int val)
{
if(st.search(val)!=-1){
System.out.println("Yes");
}
else{
System.out.println("No");
}
}
}
// { Driver Code Starts.
// Driver class with Driver code
class GFG
{
// Driver code
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-- > 0)
{
// Declaring stack of integers
Stack <Integer> st = new Stack<Integer>();
int q = sc.nextInt();
// Working with queries
while(q-- > 0)
{
char ch = sc.next().charAt(0);
Geeks obj = new Geeks();
if(ch == 'i')
{
int x = sc.nextInt();
obj.insert(st, x);
}
if(ch == 'r')
{
obj.remove(st);
}
if(ch == 'h')
{
obj.headOf_Stack(st);
}
if(ch == 'f')
{
int x = sc.nextInt();
obj.find(st, x);
}
}
// System.out.println();
}
}
} // } Driver Code Ends
-12
vtu179137 months ago
0
Mukund Sadani11 months ago
Mukund Sadani
Correct Answer.Correct AnswerExecution Time:0.35
class Geeks{ // Function to insert element to stack public static void insert(Stack<integer> st, int x) { // Your code here st.push(x);
}
// Function to pop element from stack public static void remove(Stack<integer> st) { if(!st.isEmpty()){ int x = st.pop(); }
}
// Function to return top of stack public static void headOf_Stack(Stack<integer> st) { if(!st.isEmpty()){ int x = st.peek(); System.out.println(x + " "); } }
// Function to find the element in stack public static void find(Stack<integer> st, int val) {
if(st.search(val)>0){ System.out.println("Yes"); } else{ System.out.println("No"); }
}}
0
Debojyoti Sinha1 year ago
Debojyoti Sinha
Correct Answer.Correct AnswerExecution Time:0.47
class Geeks{ public static void insert(Stack<integer> st, int x) { st.push(x); } public static void remove(Stack<integer> st) { int x = st.pop(); } public static void headOf_Stack(Stack<integer> st) { int x = st.peek(); System.out.println(x + " "); } public static void find(Stack<integer> st, int val) { if(st.contains(val)) { System.out.println("Yes"); } else { System.out.println("No"); } }}
0
Amir Ansari1 year ago
Amir Ansari
Correct AnswerExecution Time:0.37class Geeks{ // Function to insert element to stack public static void insert(Stack<integer> st, int x) { // Your code here st.push(x);
}
// Function to pop element from stack public static void remove(Stack<integer> st) { if(!st.isEmpty()){ int x = st.pop();// Your code here }
}
// Function to return top of stack public static void headOf_Stack(Stack<integer> st) { if(!st.isEmpty()){ int x = st.peek();// Your code here System.out.println(x + " "); } }
// Function to find the element in stack public static void find(Stack<integer> st, int val) {
if(st.search(val)> 0){ System.out.println("Yes"); } else{ System.out.println("No"); }
}}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 328,
"s": 226,
"text": "This Java module deals with Stacks, Queues, and ArrayLists. We'll perform various operations on them."
},
{
"code": null,
"e": 435,
"s": 328,
"text": "Given a stack of integers and Q queries. The task is to perform operation on stack according to the query."
},
{
"code": null,
"e": 616,
"s": 435,
"text": "Note: use push() to add element in the stack, peek() to get topmost element without removal, pop() gives topmost element with removal, search() to return position if found else -1."
},
{
"code": null,
"e": 817,
"s": 616,
"text": "Input Format:\nFirst line of input contains nubmer of testcases T. For each testcase, first line of input contains Q, number of queries. Next line contains Q queries seperated by space. Queries are as:"
},
{
"code": null,
"e": 1056,
"s": 817,
"text": "\n\ni x : (adds element x in the stack).\n\n\nr : (returns and removes the topmost element from the stack).\n\n\nh : Prints the topmost element.\n\n\nf y : (check if the element y is present or not in the stack). Print \"Yes\" if present, else \"No\".\n\n"
},
{
"code": null,
"e": 1095,
"s": 1056,
"text": "\ni x : (adds element x in the stack).\n"
},
{
"code": null,
"e": 1132,
"s": 1095,
"text": "i x : (adds element x in the stack)."
},
{
"code": null,
"e": 1196,
"s": 1132,
"text": "\nr : (returns and removes the topmost element from the stack).\n"
},
{
"code": null,
"e": 1258,
"s": 1196,
"text": "r : (returns and removes the topmost element from the stack)."
},
{
"code": null,
"e": 1292,
"s": 1258,
"text": "\nh : Prints the topmost element.\n"
},
{
"code": null,
"e": 1324,
"s": 1292,
"text": "h : Prints the topmost element."
},
{
"code": null,
"e": 1424,
"s": 1324,
"text": "\nf y : (check if the element y is present or not in the stack). Print \"Yes\" if present, else \"No\".\n"
},
{
"code": null,
"e": 1522,
"s": 1424,
"text": "f y : (check if the element y is present or not in the stack). Print \"Yes\" if present, else \"No\"."
},
{
"code": null,
"e": 1614,
"s": 1522,
"text": "Output Format:\nFor each testcase, perform Q queries and print the output wherever required."
},
{
"code": null,
"e": 1794,
"s": 1614,
"text": "Your Task:\nYour task is to complete functions insert(), remove(), headOf_Stack() and find(), to insert, remove returning top element and findiing the elment in stack respectively."
},
{
"code": null,
"e": 1835,
"s": 1794,
"text": "Constraints:\n1 <= T <= 100\n1 <= Q <= 103"
},
{
"code": null,
"e": 1893,
"s": 1835,
"text": "Example:\nInput:\n2\n6\ni 2 i 4 i 3 i 5 h f 8\n4\ni 3 i 4 r f 3"
},
{
"code": null,
"e": 1910,
"s": 1893,
"text": "Output:\n5\nNo\nYes"
},
{
"code": null,
"e": 2060,
"s": 1910,
"text": "Explanation:\nTestcase 1: Inserting 2, 4, 3, and 5 onto the stack. Returning top element which is 5. Finding 8 will give No, as 8 is not in the stack."
},
{
"code": null,
"e": 2062,
"s": 2060,
"text": "0"
},
{
"code": null,
"e": 2082,
"s": 2062,
"text": "rahul8781 month ago"
},
{
"code": null,
"e": 2887,
"s": 2082,
"text": "--------------------JAVA-SOLUTION------------------------\nclass Geeks\n{\n // Function to insert element to stack\n public static void insert(Stack<Integer> st, int x)\n {\n st.push(x);\n \n }\n \n // Function to pop element from stack\n public static void remove(Stack<Integer> st)\n {\n int x = st.pop();\n \n }\n \n // Function to return top of stack\n public static void headOf_Stack(Stack<Integer> st)\n {\n int x = st.peek();\n System.out.println(x + \" \");\n }\n \n // Function to find the element in stack\n public static void find(Stack<Integer> st, int val)\n {\n \n if(st.contains(val)){\n System.out.println(\"Yes\");\n }\n else{\n System.out.println(\"No\");\n }\n \n }\n}"
},
{
"code": null,
"e": 2889,
"s": 2887,
"text": "0"
},
{
"code": null,
"e": 2919,
"s": 2889,
"text": "emmanueluluabuike3 months ago"
},
{
"code": null,
"e": 2940,
"s": 2919,
"text": "Simple Java Solution"
},
{
"code": null,
"e": 3757,
"s": 2940,
"text": "// Function to insert element to stack\n public static void insert(Stack<Integer> st, int x)\n {\n // Your code here\n st.push(x);\n }\n \n // Function to pop element from stack\n I changed this from void to int\n public static int remove(Stack<Integer> st)\n {\n int x = st.pop();// Your code here\n return x;\n }\n \n // Function to return top of stack\n public static void headOf_Stack(Stack<Integer> st)\n {\n int x = st.peek();// Your code here\n System.out.println(x + \" \");\n }\n \n // Function to find the element in stack\n public static void find(Stack<Integer> st, int val)\n {\n if(st.contains(val)){\n System.out.println(\"Yes\");\n }\n else{\n System.out.println(\"No\");\n }\n \n }"
},
{
"code": null,
"e": 3759,
"s": 3757,
"text": "0"
},
{
"code": null,
"e": 3777,
"s": 3759,
"text": "feyza3 months ago"
},
{
"code": null,
"e": 4449,
"s": 3777,
"text": "class Geeks{ // Function to insert element to stack public static void insert(Stack<Integer> st, int x) { st.push(x); } // Function to pop element from stack public static void remove(Stack<Integer> st) { st.pop(); } // Function to return top of stack public static void headOf_Stack(Stack<Integer> st) { int x = st.peek(); System.out.println(x + \" \"); } // Function to find the element in stack public static void find(Stack<Integer> st, int val) { if(st.contains(val)){ System.out.println(\"Yes\"); } else{ System.out.println(\"No\"); } }}"
},
{
"code": null,
"e": 4452,
"s": 4449,
"text": "+1"
},
{
"code": null,
"e": 4505,
"s": 4452,
"text": "o36csbhch5stx2bnu7nqk1lty2talmptprfody7l4 months ago"
},
{
"code": null,
"e": 4536,
"s": 4505,
"text": "#Python code for this problem#"
},
{
"code": null,
"e": 4562,
"s": 4536,
"text": "#DM on insta for queries#"
},
{
"code": null,
"e": 4584,
"s": 4562,
"text": "0_tausif_raza_0 ← iD"
},
{
"code": null,
"e": 4601,
"s": 4586,
"text": "class Stack():"
},
{
"code": null,
"e": 4625,
"s": 4601,
"text": " def __init__(self):"
},
{
"code": null,
"e": 4647,
"s": 4625,
"text": " self.items=[]"
},
{
"code": null,
"e": 4690,
"s": 4669,
"text": " def isEmp(self):"
},
{
"code": null,
"e": 4717,
"s": 4690,
"text": " if self.items==[]:"
},
{
"code": null,
"e": 4741,
"s": 4717,
"text": " return True"
},
{
"code": null,
"e": 4755,
"s": 4741,
"text": " else:"
},
{
"code": null,
"e": 4780,
"s": 4755,
"text": " return False"
},
{
"code": null,
"e": 4807,
"s": 4782,
"text": " def push(self,data):"
},
{
"code": null,
"e": 4839,
"s": 4807,
"text": " self.items.append(data)"
},
{
"code": null,
"e": 4863,
"s": 4843,
"text": " def Spop(self):"
},
{
"code": null,
"e": 4889,
"s": 4863,
"text": " x=len(self.items)"
},
{
"code": null,
"e": 4920,
"s": 4889,
"text": " po=self.items.pop(x-1)"
},
{
"code": null,
"e": 4943,
"s": 4920,
"text": " print('po',po)"
},
{
"code": null,
"e": 4965,
"s": 4945,
"text": " def show(self):"
},
{
"code": null,
"e": 4991,
"s": 4965,
"text": " print(self.items)"
},
{
"code": null,
"e": 5020,
"s": 4993,
"text": " def search(self,data):"
},
{
"code": null,
"e": 5051,
"s": 5020,
"text": " if data in self.items:"
},
{
"code": null,
"e": 5076,
"s": 5051,
"text": " return \"Yes\""
},
{
"code": null,
"e": 5090,
"s": 5076,
"text": " else:"
},
{
"code": null,
"e": 5114,
"s": 5090,
"text": " return \"No\""
},
{
"code": null,
"e": 5127,
"s": 5116,
"text": "s1=Stack()"
},
{
"code": null,
"e": 5167,
"s": 5127,
"text": "# all the operations performed manually"
},
{
"code": null,
"e": 5233,
"s": 5167,
"text": "#you can delete this part and add a menu or add your own commands"
},
{
"code": null,
"e": 5249,
"s": 5235,
"text": "s1.push(\"hi\")"
},
{
"code": null,
"e": 5260,
"s": 5249,
"text": "s1.push(2)"
},
{
"code": null,
"e": 5271,
"s": 5260,
"text": "s1.push(3)"
},
{
"code": null,
"e": 5282,
"s": 5271,
"text": "s1.push(4)"
},
{
"code": null,
"e": 5292,
"s": 5282,
"text": "s1.show()"
},
{
"code": null,
"e": 5313,
"s": 5292,
"text": "print(s1.search(10))"
},
{
"code": null,
"e": 5333,
"s": 5313,
"text": "print(s1.search(3))"
},
{
"code": null,
"e": 5350,
"s": 5333,
"text": "s1.isEmp() "
},
{
"code": null,
"e": 5353,
"s": 5350,
"text": "-1"
},
{
"code": null,
"e": 5372,
"s": 5353,
"text": "ja90806 months ago"
},
{
"code": null,
"e": 6377,
"s": 5372,
"text": "class Geeks{ // Function to insert element to stack public static void insert(Stack<Integer> st, int x) { st.push(x); } // Function to pop element from stack public static void remove(Stack<Integer> st) { st.pop(); } // Function to return top of stack public static void headOf_Stack(Stack<Integer> st) { int x = st.peek(); System.out.println(x + \" \"); } // Function to find the element in stack public static void find(Stack<Integer> st, int val) { int a =0; Stack<Integer> temp = new Stack<Integer>(); while(!st.empty()){ if(st.peek()==val){ a=1; break; } temp.push(st.peek()); st.pop(); } while(!temp.empty()){ st.push(temp.peek()); temp.pop(); } if(a==1){ System.out.println(\"Yes\"); } else{ System.out.println(\"No\"); } }} "
},
{
"code": null,
"e": 6379,
"s": 6377,
"text": "0"
},
{
"code": null,
"e": 6404,
"s": 6379,
"text": "shubhmish2236 months ago"
},
{
"code": null,
"e": 8481,
"s": 6404,
"text": "// { Driver Code Starts\n//Initial Template for Java\nimport java.util.*;\n\n\n // } Driver Code Ends\n//User function Template for Java\n\n// Helper class to implement functions\n// insert : to insert element to stack\n// remove : to pop element from stack\n// headOf_Stack : to return top of stack\n// find : to find the element in stack\nclass Geeks\n{\n // Function to insert element to stack\n public static void insert(Stack<Integer> st, int x)\n {\n st.push(x);// Your code here\n \n }\n \n // Function to pop element from stack\n public static void remove(Stack<Integer> st)\n {\n st.pop() ;// Your code here\n \n }\n \n // Function to return top of stack\n public static void headOf_Stack(Stack<Integer> st)\n {\n int x =Integer()st.peek() // Your code here\n System.out.println(x + \" \");\n }\n \n // Function to find the element in stack\n public static void find(Stack<Integer> st, int val)\n {\n \n if(st.search(val)!=-1){\n System.out.println(\"Yes\");\n }\n else{\n System.out.println(\"No\");\n }\n \n }\n}\n\n\n// { Driver Code Starts.\n\n// Driver class with Driver code\nclass GFG \n{\n\t// Driver code\n\tpublic static void main (String[] args) \n\t{\n\t\tScanner sc = new Scanner(System.in);\n\t\tint t = sc.nextInt();\n\t\t\n\t\twhile(t-- > 0)\n\t\t{\n\t\t // Declaring stack of integers\n\t\t Stack <Integer> st = new Stack<Integer>();\n\t\t \n\t\t int q = sc.nextInt();\n\t\t \n\t\t // Working with queries\n\t\t while(q-- > 0)\n\t\t {\n\t\t char ch = sc.next().charAt(0);\n\t\t Geeks obj = new Geeks();\n\t\t if(ch == 'i')\n\t\t {\n\t\t int x = sc.nextInt();\n\t\t obj.insert(st, x);\n\t\t }\n\t\t \n\t\t if(ch == 'r')\n\t\t {\n\t\t obj.remove(st);\n\t\t }\n\t\t \n\t\t if(ch == 'h')\n\t\t {\n\t\t obj.headOf_Stack(st);\n\t\t }\n\t\t if(ch == 'f')\n\t\t {\n\t\t int x = sc.nextInt();\n\t\t obj.find(st, x);\n\t\t }\n\t\t \n\t\t \n\t\t }\n\t\t // System.out.println();\n\t\t }\n\t}\n} // } Driver Code Ends"
},
{
"code": null,
"e": 8485,
"s": 8481,
"text": "-12"
},
{
"code": null,
"e": 8506,
"s": 8485,
"text": "vtu179137 months ago"
},
{
"code": null,
"e": 8508,
"s": 8506,
"text": "0"
},
{
"code": null,
"e": 8535,
"s": 8508,
"text": "Mukund Sadani11 months ago"
},
{
"code": null,
"e": 8549,
"s": 8535,
"text": "Mukund Sadani"
},
{
"code": null,
"e": 8598,
"s": 8549,
"text": "Correct Answer.Correct AnswerExecution Time:0.35"
},
{
"code": null,
"e": 8757,
"s": 8598,
"text": "class Geeks{ // Function to insert element to stack public static void insert(Stack<integer> st, int x) { // Your code here st.push(x);"
},
{
"code": null,
"e": 8763,
"s": 8757,
"text": " }"
},
{
"code": null,
"e": 8918,
"s": 8763,
"text": " // Function to pop element from stack public static void remove(Stack<integer> st) { if(!st.isEmpty()){ int x = st.pop(); }"
},
{
"code": null,
"e": 8924,
"s": 8918,
"text": " }"
},
{
"code": null,
"e": 9124,
"s": 8924,
"text": " // Function to return top of stack public static void headOf_Stack(Stack<integer> st) { if(!st.isEmpty()){ int x = st.peek(); System.out.println(x + \" \"); } }"
},
{
"code": null,
"e": 9229,
"s": 9124,
"text": " // Function to find the element in stack public static void find(Stack<integer> st, int val) {"
},
{
"code": null,
"e": 9365,
"s": 9229,
"text": " if(st.search(val)>0){ System.out.println(\"Yes\"); } else{ System.out.println(\"No\"); }"
},
{
"code": null,
"e": 9372,
"s": 9365,
"text": " }}"
},
{
"code": null,
"e": 9374,
"s": 9372,
"text": "0"
},
{
"code": null,
"e": 9400,
"s": 9374,
"text": "Debojyoti Sinha1 year ago"
},
{
"code": null,
"e": 9416,
"s": 9400,
"text": "Debojyoti Sinha"
},
{
"code": null,
"e": 9465,
"s": 9416,
"text": "Correct Answer.Correct AnswerExecution Time:0.47"
},
{
"code": null,
"e": 10020,
"s": 9465,
"text": "class Geeks{ public static void insert(Stack<integer> st, int x) { st.push(x); } public static void remove(Stack<integer> st) { int x = st.pop(); } public static void headOf_Stack(Stack<integer> st) { int x = st.peek(); System.out.println(x + \" \"); } public static void find(Stack<integer> st, int val) { if(st.contains(val)) { System.out.println(\"Yes\"); } else { System.out.println(\"No\"); } }}"
},
{
"code": null,
"e": 10022,
"s": 10020,
"text": "0"
},
{
"code": null,
"e": 10044,
"s": 10022,
"text": "Amir Ansari1 year ago"
},
{
"code": null,
"e": 10056,
"s": 10044,
"text": "Amir Ansari"
},
{
"code": null,
"e": 10248,
"s": 10056,
"text": "Correct AnswerExecution Time:0.37class Geeks{ // Function to insert element to stack public static void insert(Stack<integer> st, int x) { // Your code here st.push(x);"
},
{
"code": null,
"e": 10254,
"s": 10248,
"text": " }"
},
{
"code": null,
"e": 10433,
"s": 10254,
"text": " // Function to pop element from stack public static void remove(Stack<integer> st) { if(!st.isEmpty()){ int x = st.pop();// Your code here }"
},
{
"code": null,
"e": 10439,
"s": 10433,
"text": " }"
},
{
"code": null,
"e": 10656,
"s": 10439,
"text": " // Function to return top of stack public static void headOf_Stack(Stack<integer> st) { if(!st.isEmpty()){ int x = st.peek();// Your code here System.out.println(x + \" \"); } }"
},
{
"code": null,
"e": 10761,
"s": 10656,
"text": " // Function to find the element in stack public static void find(Stack<integer> st, int val) {"
},
{
"code": null,
"e": 10897,
"s": 10761,
"text": " if(st.search(val)> 0){ System.out.println(\"Yes\"); } else{ System.out.println(\"No\"); }"
},
{
"code": null,
"e": 10904,
"s": 10897,
"text": " }}"
},
{
"code": null,
"e": 11050,
"s": 10904,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 11086,
"s": 11050,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 11096,
"s": 11086,
"text": "\nProblem\n"
},
{
"code": null,
"e": 11106,
"s": 11096,
"text": "\nContest\n"
},
{
"code": null,
"e": 11169,
"s": 11106,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 11317,
"s": 11169,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 11525,
"s": 11317,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 11631,
"s": 11525,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Calculate square of a number without using *, / and pow() - GeeksforGeeks
|
23 Mar, 2022
Given an integer n, calculate the square of a number without using *, / and pow().
Examples :
Input: n = 5
Output: 25
Input: 7
Output: 49
Input: n = 12
Output: 144
A Simple Solution is to repeatedly add n to result.
Below is the implementation of this idea.
C++
Java
Python3
C#
PHP
Javascript
// Simple solution to calculate square without// using * and pow()#include <iostream>using namespace std; int square(int n){ // handle negative input if (n < 0) n = -n; // Initialize result int res = n; // Add n to res n-1 times for (int i = 1; i < n; i++) res += n; return res;} // Driver codeint main(){ for (int n = 1; n <= 5; n++) cout << "n = " << n << ", n^2 = " << square(n) << endl; return 0;}
// Java Simple solution to calculate// square without using * and pow()import java.io.*; class GFG { public static int square(int n) { // handle negative input if (n < 0) n = -n; // Initialize result int res = n; // Add n to res n-1 times for (int i = 1; i < n; i++) res += n; return res; } // Driver code public static void main(String[] args) { for (int n = 1; n <= 5; n++) System.out.println("n = " + n + ", n^2 = " + square(n)); }} // This code is contributed by sunnysingh
# Simple solution to# calculate square without# using * and pow() def square(n): # handle negative input if (n < 0): n = -n # Initialize result res = n # Add n to res n-1 times for i in range(1, n): res += n return res # Driver Codefor n in range(1, 6): print("n =", n, end=", ") print("n^2 =", square(n)) # This code is contributed by# Smitha Dinesh Semwal
// C# Simple solution to calculate// square without using * and pow()using System; class GFG { public static int square(int n) { // handle negative input if (n < 0) n = -n; // Initialize result int res = n; // Add n to res n-1 times for (int i = 1; i < n; i++) res += n; return res; } // Driver code public static void Main() { for (int n = 1; n <= 5; n++) Console.WriteLine("n = " + n + ", n^2 = " + square(n)); }} // This code is contributed by Sam007
<?php// PHP implementation to// calculate square// without using * and pow() function square($n){ // handle negative input if ($n < 0) $n = -$n; // Initialize result $res = $n; // Add n to res n-1 timesfor ($i = 1; $i < $n; $i++) $res += $n; return $res;} // Driver Codefor ($n = 1; $n<=5; $n++) echo "n = ", $n, ", ", "n^2 = ", square($n), "\n "; // This code is contributed by Ajit?>
<script> // Simple solution to calculate square without// using * and pow() function square(n){ // handle negative input if (n < 0) n = -n; // Initialize result let res = n; // Add n to res n-1 times for (let i = 1; i < n; i++) res += n; return res;} // Driver code for (let n = 1; n <= 5; n++) document.write("n= " + n +", n^2 = " + square(n) + "<br>"); //This code is contributed by Mayank Tyagi </script>
n = 1, n^2 = 1
n = 2, n^2 = 4
n = 3, n^2 = 9
n = 4, n^2 = 16
n = 5, n^2 = 25
The time complexity of the above solution is O(n).
Approach 2:
We can do it in O(Logn) time using bitwise operators. The idea is based on the following fact.
square(n) = 0 if n == 0
if n is even
square(n) = 4*square(n/2)
if n is odd
square(n) = 4*square(floor(n/2)) + 4*floor(n/2) + 1
Examples
square(6) = 4*square(3)
square(3) = 4*(square(1)) + 4*1 + 1 = 9
square(7) = 4*square(3) + 4*3 + 1 = 4*9 + 4*3 + 1 = 49
How does this work?
If n is even, it can be written as
n = 2*x
n2 = (2*x)2 = 4*x2
If n is odd, it can be written as
n = 2*x + 1
n2 = (2*x + 1)2 = 4*x2 + 4*x + 1
floor(n/2) can be calculated using a bitwise right shift operator. 2*x and 4*x can be calculated
Below is the implementation based on the above idea.
C++
Java
Python3
C#
PHP
Javascript
// Square of a number using bitwise operators#include <bits/stdc++.h>using namespace std; int square(int n){ // Base case if (n == 0) return 0; // Handle negative number if (n < 0) n = -n; // Get floor(n/2) using right shift int x = n >> 1; // If n is odd if (n & 1) return ((square(x) << 2) + (x << 2) + 1); else // If n is even return (square(x) << 2);} // Driver Codeint main(){ // Function calls for (int n = 1; n <= 5; n++) cout << "n = " << n << ", n^2 = " << square(n) << endl; return 0;}
// Square of a number using// bitwise operatorsclass GFG { static int square(int n) { // Base case if (n == 0) return 0; // Handle negative number if (n < 0) n = -n; // Get floor(n/2) using // right shift int x = n >> 1; // If n is odd ; if (n % 2 != 0) return ((square(x) << 2) + (x << 2) + 1); else // If n is even return (square(x) << 2); } // Driver code public static void main(String args[]) { // Function calls for (int n = 1; n <= 5; n++) System.out.println("n = " + n + " n^2 = " + square(n)); }} // This code is contributed by Sam007
# Square of a number using bitwise# operators def square(n): # Base case if (n == 0): return 0 # Handle negative number if (n < 0): n = -n # Get floor(n/2) using # right shift x = n >> 1 # If n is odd if (n & 1): return ((square(x) << 2) + (x << 2) + 1) # If n is even else: return (square(x) << 2) # Driver Codefor n in range(1, 6): print("n = ", n, " n^2 = ", square(n))# This code is contributed by Sam007
// Square of a number using bitwise// operatorsusing System; class GFG { static int square(int n) { // Base case if (n == 0) return 0; // Handle negative number if (n < 0) n = -n; // Get floor(n/2) using // right shift int x = n >> 1; // If n is odd ; if (n % 2 != 0) return ((square(x) << 2) + (x << 2) + 1); else // If n is even return (square(x) << 2); } // Driver code static void Main() { for (int n = 1; n <= 5; n++) Console.WriteLine("n = " + n + " n^2 = " + square(n)); }} // This code is contributed by Sam0007.
<?php// Square of a number using// bitwise operators function square($n){ // Base case if ($n==0) return 0; // Handle negative number if ($n < 0) $n = -$n; // Get floor(n/2) // using right shift $x = $n >> 1; // If n is odd if ($n & 1) return ((square($x) << 2) + ($x << 2) + 1); else // If n is even return (square($x) << 2);} // Driver Code for ($n = 1; $n <= 5; $n++) echo "n = ", $n, ", n^2 = ", square($n),"\n"; // This code is contributed by ajit?>
<script> // Square of a number using bitwise operators function square(n){ // Base case if (n == 0) return 0; // Handle negative number if (n < 0) n = -n; // Get floor(n/2) using right shift let x = n >> 1; // If n is odd if (n & 1) return ((square(x) << 2) + (x << 2) + 1); else // If n is even return (square(x) << 2);} // Driver Code // Function calls for (let n = 1; n <= 5; n++) document.write("n = " + n + ", n^2 = " + square(n) +"<br>"); //This code is contributed by Mayank Tyagi </script>
n = 1, n^2 = 1
n = 2, n^2 = 4
n = 3, n^2 = 9
n = 4, n^2 = 16
n = 5, n^2 = 25
The time complexity of the above solution is O(Logn).
Approach 3:
For a given number `num` we get square of it by multiplying number as `num * num`.
Now write one of `num` in square `num * num` in terms of power of `2`. Check below examples.
Eg: num = 10, square(num) = 10 * 10
= 10 * (8 + 2) = (10 * 8) + (10 * 2)
num = 15, square(num) = 15 * 15
= 15 * (8 + 4 + 2 + 1) = (15 * 8) + (15 * 4) + (15 * 2) + (15 * 1)
Multiplication with power of 2's can be done by left shift bitwise operator.
Below is the implementation based on the above idea.
C++
Java
Python3
C#
Javascript
// Simple solution to calculate square without// using * and pow()#include <iostream>using namespace std; int square(int num){ // handle negative input if (num < 0) num = -num; // Initialize result int result = 0, times = num; while (times > 0) { int possibleShifts = 0, currTimes = 1; while ((currTimes << 1) <= times) { currTimes = currTimes << 1; ++possibleShifts; } result = result + (num << possibleShifts); times = times - currTimes; } return result;} // Driver codeint main(){ // Function calls for (int n = 10; n <= 15; ++n) cout << "n = " << n << ", n^2 = " << square(n) << endl; return 0;} // This code is contributed by sanjay235
// Simple solution to calculate square// without using * and pow()import java.io.*; class GFG{ public static int square(int num){ // Handle negative input if (num < 0) num = -num; // Initialize result int result = 0, times = num; while (times > 0) { int possibleShifts = 0, currTimes = 1; while ((currTimes << 1) <= times) { currTimes = currTimes << 1; ++possibleShifts; } result = result + (num << possibleShifts); times = times - currTimes; } return result;} // Driver codepublic static void main(String[] args){ for(int n = 10; n <= 15; ++n) { System.out.println("n = " + n + ", n^2 = " + square(n)); }}} // This code is contributed by RohitOberoi
# Simple solution to calculate square without# using * and pow()def square(num): # Handle negative input if (num < 0): num = -num # Initialize result result, times = 0, num while (times > 0): possibleShifts, currTimes = 0, 1 while ((currTimes << 1) <= times): currTimes = currTimes << 1 possibleShifts += 1 result = result + (num << possibleShifts) times = times - currTimes return result # Driver Code # Function callsfor n in range(10, 16): print("n =", n, ", n^2 =", square(n)) # This code is contributed by divyesh072019
// Simple solution to calculate square// without using * and pow()using System;class GFG { static int square(int num) { // Handle negative input if (num < 0) num = -num; // Initialize result int result = 0, times = num; while (times > 0) { int possibleShifts = 0, currTimes = 1; while ((currTimes << 1) <= times) { currTimes = currTimes << 1; ++possibleShifts; } result = result + (num << possibleShifts); times = times - currTimes; } return result; } static void Main() { for(int n = 10; n <= 15; ++n) { Console.WriteLine("n = " + n + ", n^2 = " + square(n)); } }} // This code is contributed by divyeshrabadiy07
<script> // Simple solution to calculate square without// using * and pow() function square(num){ // handle negative input if (num < 0) num = -num; // Initialize result let result = 0, times = num; while (times > 0) { let possibleShifts = 0, currTimes = 1; while ((currTimes << 1) <= times) { currTimes = currTimes << 1; ++possibleShifts; } result = result + (num << possibleShifts); times = times - currTimes; } return result;} // Driver code // Function calls for (let n = 10; n <= 15; ++n) document.write("n = " + n + ", n^2 = " + square(n) + "<br>"); //This code is contributed by Mayank Tyagi </script>
n = 10, n^2 = 100
n = 11, n^2 = 121
n = 12, n^2 = 144
n = 13, n^2 = 169
n = 14, n^2 = 196
n = 15, n^2 = 225
The time complexity of the above solution is O(Log n). Thanks to Sanjay for approach 3 solution.
This article is contributed by Ujjwal Jain. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
C++
// Simple solution to calculate square without// using * and pow()#include <iostream>using namespace std; int square(int num){ // handle negative input if (num < 0) num = -num; // Initialize power of 2 and result int power = 0, result = 0; int temp = num; while (temp) { if (temp & 1) { // result=result+(num*(2^power)) result += (num << power); } power++; // temp=temp/2 temp = temp >> 1; } return result;} // Driver codeint main(){ // Function calls for (int n = 10; n <= 15; ++n) cout << "n = " << n << ", n^2 = " << square(n) << endl; return 0;} // This code is contributed by Aditya Verma
n = 10, n^2 = 100
n = 11, n^2 = 121
n = 12, n^2 = 144
n = 13, n^2 = 169
n = 14, n^2 = 196
n = 15, n^2 = 225
Sam007
jit_t
nidhi_biet
sanjay035
RohitOberoi
divyeshrabadiya07
divyesh072019
geeksvishal
mayanktyagi1709
123adiverma
Bit Magic
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Set, Clear and Toggle a given bit of a number in C
Program to find parity
Write an Efficient Method to Check if a Number is Multiple of 3
Hamming code Implementation in C/C++
Check whether K-th bit is set or not
Implementation of Bit Stuffing and Bit Destuffing
Count total bits in a number
Builtin functions of GCC compiler
Check for Integer Overflow
Bit Tricks for Competitive Programming
|
[
{
"code": null,
"e": 24934,
"s": 24906,
"text": "\n23 Mar, 2022"
},
{
"code": null,
"e": 25018,
"s": 24934,
"text": "Given an integer n, calculate the square of a number without using *, / and pow(). "
},
{
"code": null,
"e": 25030,
"s": 25018,
"text": "Examples : "
},
{
"code": null,
"e": 25102,
"s": 25030,
"text": "Input: n = 5\nOutput: 25\n\nInput: 7\nOutput: 49\n\nInput: n = 12\nOutput: 144"
},
{
"code": null,
"e": 25155,
"s": 25102,
"text": "A Simple Solution is to repeatedly add n to result. "
},
{
"code": null,
"e": 25198,
"s": 25155,
"text": "Below is the implementation of this idea. "
},
{
"code": null,
"e": 25202,
"s": 25198,
"text": "C++"
},
{
"code": null,
"e": 25207,
"s": 25202,
"text": "Java"
},
{
"code": null,
"e": 25215,
"s": 25207,
"text": "Python3"
},
{
"code": null,
"e": 25218,
"s": 25215,
"text": "C#"
},
{
"code": null,
"e": 25222,
"s": 25218,
"text": "PHP"
},
{
"code": null,
"e": 25233,
"s": 25222,
"text": "Javascript"
},
{
"code": "// Simple solution to calculate square without// using * and pow()#include <iostream>using namespace std; int square(int n){ // handle negative input if (n < 0) n = -n; // Initialize result int res = n; // Add n to res n-1 times for (int i = 1; i < n; i++) res += n; return res;} // Driver codeint main(){ for (int n = 1; n <= 5; n++) cout << \"n = \" << n << \", n^2 = \" << square(n) << endl; return 0;}",
"e": 25698,
"s": 25233,
"text": null
},
{
"code": "// Java Simple solution to calculate// square without using * and pow()import java.io.*; class GFG { public static int square(int n) { // handle negative input if (n < 0) n = -n; // Initialize result int res = n; // Add n to res n-1 times for (int i = 1; i < n; i++) res += n; return res; } // Driver code public static void main(String[] args) { for (int n = 1; n <= 5; n++) System.out.println(\"n = \" + n + \", n^2 = \" + square(n)); }} // This code is contributed by sunnysingh",
"e": 26323,
"s": 25698,
"text": null
},
{
"code": "# Simple solution to# calculate square without# using * and pow() def square(n): # handle negative input if (n < 0): n = -n # Initialize result res = n # Add n to res n-1 times for i in range(1, n): res += n return res # Driver Codefor n in range(1, 6): print(\"n =\", n, end=\", \") print(\"n^2 =\", square(n)) # This code is contributed by# Smitha Dinesh Semwal",
"e": 26727,
"s": 26323,
"text": null
},
{
"code": "// C# Simple solution to calculate// square without using * and pow()using System; class GFG { public static int square(int n) { // handle negative input if (n < 0) n = -n; // Initialize result int res = n; // Add n to res n-1 times for (int i = 1; i < n; i++) res += n; return res; } // Driver code public static void Main() { for (int n = 1; n <= 5; n++) Console.WriteLine(\"n = \" + n + \", n^2 = \" + square(n)); }} // This code is contributed by Sam007",
"e": 27326,
"s": 26727,
"text": null
},
{
"code": "<?php// PHP implementation to// calculate square// without using * and pow() function square($n){ // handle negative input if ($n < 0) $n = -$n; // Initialize result $res = $n; // Add n to res n-1 timesfor ($i = 1; $i < $n; $i++) $res += $n; return $res;} // Driver Codefor ($n = 1; $n<=5; $n++) echo \"n = \", $n, \", \", \"n^2 = \", square($n), \"\\n \"; // This code is contributed by Ajit?>",
"e": 27749,
"s": 27326,
"text": null
},
{
"code": "<script> // Simple solution to calculate square without// using * and pow() function square(n){ // handle negative input if (n < 0) n = -n; // Initialize result let res = n; // Add n to res n-1 times for (let i = 1; i < n; i++) res += n; return res;} // Driver code for (let n = 1; n <= 5; n++) document.write(\"n= \" + n +\", n^2 = \" + square(n) + \"<br>\"); //This code is contributed by Mayank Tyagi </script>",
"e": 28222,
"s": 27749,
"text": null
},
{
"code": null,
"e": 28300,
"s": 28222,
"text": "n = 1, n^2 = 1\nn = 2, n^2 = 4\nn = 3, n^2 = 9\nn = 4, n^2 = 16\nn = 5, n^2 = 25\n"
},
{
"code": null,
"e": 28352,
"s": 28300,
"text": "The time complexity of the above solution is O(n). "
},
{
"code": null,
"e": 28364,
"s": 28352,
"text": "Approach 2:"
},
{
"code": null,
"e": 28459,
"s": 28364,
"text": "We can do it in O(Logn) time using bitwise operators. The idea is based on the following fact."
},
{
"code": null,
"e": 28740,
"s": 28459,
"text": " square(n) = 0 if n == 0\n if n is even \n square(n) = 4*square(n/2) \n if n is odd\n square(n) = 4*square(floor(n/2)) + 4*floor(n/2) + 1 \n\nExamples\n square(6) = 4*square(3)\n square(3) = 4*(square(1)) + 4*1 + 1 = 9\n square(7) = 4*square(3) + 4*3 + 1 = 4*9 + 4*3 + 1 = 49"
},
{
"code": null,
"e": 28761,
"s": 28740,
"text": "How does this work? "
},
{
"code": null,
"e": 28912,
"s": 28761,
"text": "If n is even, it can be written as\n n = 2*x \n n2 = (2*x)2 = 4*x2\nIf n is odd, it can be written as \n n = 2*x + 1\n n2 = (2*x + 1)2 = 4*x2 + 4*x + 1"
},
{
"code": null,
"e": 29010,
"s": 28912,
"text": "floor(n/2) can be calculated using a bitwise right shift operator. 2*x and 4*x can be calculated "
},
{
"code": null,
"e": 29064,
"s": 29010,
"text": "Below is the implementation based on the above idea. "
},
{
"code": null,
"e": 29068,
"s": 29064,
"text": "C++"
},
{
"code": null,
"e": 29073,
"s": 29068,
"text": "Java"
},
{
"code": null,
"e": 29081,
"s": 29073,
"text": "Python3"
},
{
"code": null,
"e": 29084,
"s": 29081,
"text": "C#"
},
{
"code": null,
"e": 29088,
"s": 29084,
"text": "PHP"
},
{
"code": null,
"e": 29099,
"s": 29088,
"text": "Javascript"
},
{
"code": "// Square of a number using bitwise operators#include <bits/stdc++.h>using namespace std; int square(int n){ // Base case if (n == 0) return 0; // Handle negative number if (n < 0) n = -n; // Get floor(n/2) using right shift int x = n >> 1; // If n is odd if (n & 1) return ((square(x) << 2) + (x << 2) + 1); else // If n is even return (square(x) << 2);} // Driver Codeint main(){ // Function calls for (int n = 1; n <= 5; n++) cout << \"n = \" << n << \", n^2 = \" << square(n) << endl; return 0;}",
"e": 29681,
"s": 29099,
"text": null
},
{
"code": "// Square of a number using// bitwise operatorsclass GFG { static int square(int n) { // Base case if (n == 0) return 0; // Handle negative number if (n < 0) n = -n; // Get floor(n/2) using // right shift int x = n >> 1; // If n is odd ; if (n % 2 != 0) return ((square(x) << 2) + (x << 2) + 1); else // If n is even return (square(x) << 2); } // Driver code public static void main(String args[]) { // Function calls for (int n = 1; n <= 5; n++) System.out.println(\"n = \" + n + \" n^2 = \" + square(n)); }} // This code is contributed by Sam007",
"e": 30427,
"s": 29681,
"text": null
},
{
"code": "# Square of a number using bitwise# operators def square(n): # Base case if (n == 0): return 0 # Handle negative number if (n < 0): n = -n # Get floor(n/2) using # right shift x = n >> 1 # If n is odd if (n & 1): return ((square(x) << 2) + (x << 2) + 1) # If n is even else: return (square(x) << 2) # Driver Codefor n in range(1, 6): print(\"n = \", n, \" n^2 = \", square(n))# This code is contributed by Sam007",
"e": 30931,
"s": 30427,
"text": null
},
{
"code": "// Square of a number using bitwise// operatorsusing System; class GFG { static int square(int n) { // Base case if (n == 0) return 0; // Handle negative number if (n < 0) n = -n; // Get floor(n/2) using // right shift int x = n >> 1; // If n is odd ; if (n % 2 != 0) return ((square(x) << 2) + (x << 2) + 1); else // If n is even return (square(x) << 2); } // Driver code static void Main() { for (int n = 1; n <= 5; n++) Console.WriteLine(\"n = \" + n + \" n^2 = \" + square(n)); }} // This code is contributed by Sam0007.",
"e": 31647,
"s": 30931,
"text": null
},
{
"code": "<?php// Square of a number using// bitwise operators function square($n){ // Base case if ($n==0) return 0; // Handle negative number if ($n < 0) $n = -$n; // Get floor(n/2) // using right shift $x = $n >> 1; // If n is odd if ($n & 1) return ((square($x) << 2) + ($x << 2) + 1); else // If n is even return (square($x) << 2);} // Driver Code for ($n = 1; $n <= 5; $n++) echo \"n = \", $n, \", n^2 = \", square($n),\"\\n\"; // This code is contributed by ajit?>",
"e": 32191,
"s": 31647,
"text": null
},
{
"code": "<script> // Square of a number using bitwise operators function square(n){ // Base case if (n == 0) return 0; // Handle negative number if (n < 0) n = -n; // Get floor(n/2) using right shift let x = n >> 1; // If n is odd if (n & 1) return ((square(x) << 2) + (x << 2) + 1); else // If n is even return (square(x) << 2);} // Driver Code // Function calls for (let n = 1; n <= 5; n++) document.write(\"n = \" + n + \", n^2 = \" + square(n) +\"<br>\"); //This code is contributed by Mayank Tyagi </script>",
"e": 32774,
"s": 32191,
"text": null
},
{
"code": null,
"e": 32852,
"s": 32774,
"text": "n = 1, n^2 = 1\nn = 2, n^2 = 4\nn = 3, n^2 = 9\nn = 4, n^2 = 16\nn = 5, n^2 = 25\n"
},
{
"code": null,
"e": 32906,
"s": 32852,
"text": "The time complexity of the above solution is O(Logn)."
},
{
"code": null,
"e": 32918,
"s": 32906,
"text": "Approach 3:"
},
{
"code": null,
"e": 33404,
"s": 32918,
"text": "For a given number `num` we get square of it by multiplying number as `num * num`. \nNow write one of `num` in square `num * num` in terms of power of `2`. Check below examples.\n\nEg: num = 10, square(num) = 10 * 10 \n = 10 * (8 + 2) = (10 * 8) + (10 * 2)\n num = 15, square(num) = 15 * 15 \n = 15 * (8 + 4 + 2 + 1) = (15 * 8) + (15 * 4) + (15 * 2) + (15 * 1)\n\nMultiplication with power of 2's can be done by left shift bitwise operator."
},
{
"code": null,
"e": 33458,
"s": 33404,
"text": "Below is the implementation based on the above idea. "
},
{
"code": null,
"e": 33462,
"s": 33458,
"text": "C++"
},
{
"code": null,
"e": 33467,
"s": 33462,
"text": "Java"
},
{
"code": null,
"e": 33475,
"s": 33467,
"text": "Python3"
},
{
"code": null,
"e": 33478,
"s": 33475,
"text": "C#"
},
{
"code": null,
"e": 33489,
"s": 33478,
"text": "Javascript"
},
{
"code": "// Simple solution to calculate square without// using * and pow()#include <iostream>using namespace std; int square(int num){ // handle negative input if (num < 0) num = -num; // Initialize result int result = 0, times = num; while (times > 0) { int possibleShifts = 0, currTimes = 1; while ((currTimes << 1) <= times) { currTimes = currTimes << 1; ++possibleShifts; } result = result + (num << possibleShifts); times = times - currTimes; } return result;} // Driver codeint main(){ // Function calls for (int n = 10; n <= 15; ++n) cout << \"n = \" << n << \", n^2 = \" << square(n) << endl; return 0;} // This code is contributed by sanjay235",
"e": 34239,
"s": 33489,
"text": null
},
{
"code": "// Simple solution to calculate square// without using * and pow()import java.io.*; class GFG{ public static int square(int num){ // Handle negative input if (num < 0) num = -num; // Initialize result int result = 0, times = num; while (times > 0) { int possibleShifts = 0, currTimes = 1; while ((currTimes << 1) <= times) { currTimes = currTimes << 1; ++possibleShifts; } result = result + (num << possibleShifts); times = times - currTimes; } return result;} // Driver codepublic static void main(String[] args){ for(int n = 10; n <= 15; ++n) { System.out.println(\"n = \" + n + \", n^2 = \" + square(n)); }}} // This code is contributed by RohitOberoi",
"e": 35082,
"s": 34239,
"text": null
},
{
"code": "# Simple solution to calculate square without# using * and pow()def square(num): # Handle negative input if (num < 0): num = -num # Initialize result result, times = 0, num while (times > 0): possibleShifts, currTimes = 0, 1 while ((currTimes << 1) <= times): currTimes = currTimes << 1 possibleShifts += 1 result = result + (num << possibleShifts) times = times - currTimes return result # Driver Code # Function callsfor n in range(10, 16): print(\"n =\", n, \", n^2 =\", square(n)) # This code is contributed by divyesh072019",
"e": 35691,
"s": 35082,
"text": null
},
{
"code": "// Simple solution to calculate square// without using * and pow()using System;class GFG { static int square(int num) { // Handle negative input if (num < 0) num = -num; // Initialize result int result = 0, times = num; while (times > 0) { int possibleShifts = 0, currTimes = 1; while ((currTimes << 1) <= times) { currTimes = currTimes << 1; ++possibleShifts; } result = result + (num << possibleShifts); times = times - currTimes; } return result; } static void Main() { for(int n = 10; n <= 15; ++n) { Console.WriteLine(\"n = \" + n + \", n^2 = \" + square(n)); } }} // This code is contributed by divyeshrabadiy07",
"e": 36635,
"s": 35691,
"text": null
},
{
"code": "<script> // Simple solution to calculate square without// using * and pow() function square(num){ // handle negative input if (num < 0) num = -num; // Initialize result let result = 0, times = num; while (times > 0) { let possibleShifts = 0, currTimes = 1; while ((currTimes << 1) <= times) { currTimes = currTimes << 1; ++possibleShifts; } result = result + (num << possibleShifts); times = times - currTimes; } return result;} // Driver code // Function calls for (let n = 10; n <= 15; ++n) document.write(\"n = \" + n + \", n^2 = \" + square(n) + \"<br>\"); //This code is contributed by Mayank Tyagi </script>",
"e": 37350,
"s": 36635,
"text": null
},
{
"code": null,
"e": 37459,
"s": 37350,
"text": "n = 10, n^2 = 100\nn = 11, n^2 = 121\nn = 12, n^2 = 144\nn = 13, n^2 = 169\nn = 14, n^2 = 196\nn = 15, n^2 = 225\n"
},
{
"code": null,
"e": 37557,
"s": 37459,
"text": "The time complexity of the above solution is O(Log n). Thanks to Sanjay for approach 3 solution."
},
{
"code": null,
"e": 37726,
"s": 37557,
"text": "This article is contributed by Ujjwal Jain. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 37730,
"s": 37726,
"text": "C++"
},
{
"code": "// Simple solution to calculate square without// using * and pow()#include <iostream>using namespace std; int square(int num){ // handle negative input if (num < 0) num = -num; // Initialize power of 2 and result int power = 0, result = 0; int temp = num; while (temp) { if (temp & 1) { // result=result+(num*(2^power)) result += (num << power); } power++; // temp=temp/2 temp = temp >> 1; } return result;} // Driver codeint main(){ // Function calls for (int n = 10; n <= 15; ++n) cout << \"n = \" << n << \", n^2 = \" << square(n) << endl; return 0;} // This code is contributed by Aditya Verma",
"e": 38444,
"s": 37730,
"text": null
},
{
"code": null,
"e": 38553,
"s": 38444,
"text": "n = 10, n^2 = 100\nn = 11, n^2 = 121\nn = 12, n^2 = 144\nn = 13, n^2 = 169\nn = 14, n^2 = 196\nn = 15, n^2 = 225\n"
},
{
"code": null,
"e": 38560,
"s": 38553,
"text": "Sam007"
},
{
"code": null,
"e": 38566,
"s": 38560,
"text": "jit_t"
},
{
"code": null,
"e": 38577,
"s": 38566,
"text": "nidhi_biet"
},
{
"code": null,
"e": 38587,
"s": 38577,
"text": "sanjay035"
},
{
"code": null,
"e": 38599,
"s": 38587,
"text": "RohitOberoi"
},
{
"code": null,
"e": 38617,
"s": 38599,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 38631,
"s": 38617,
"text": "divyesh072019"
},
{
"code": null,
"e": 38643,
"s": 38631,
"text": "geeksvishal"
},
{
"code": null,
"e": 38659,
"s": 38643,
"text": "mayanktyagi1709"
},
{
"code": null,
"e": 38671,
"s": 38659,
"text": "123adiverma"
},
{
"code": null,
"e": 38681,
"s": 38671,
"text": "Bit Magic"
},
{
"code": null,
"e": 38691,
"s": 38681,
"text": "Bit Magic"
},
{
"code": null,
"e": 38789,
"s": 38691,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38798,
"s": 38789,
"text": "Comments"
},
{
"code": null,
"e": 38811,
"s": 38798,
"text": "Old Comments"
},
{
"code": null,
"e": 38862,
"s": 38811,
"text": "Set, Clear and Toggle a given bit of a number in C"
},
{
"code": null,
"e": 38885,
"s": 38862,
"text": "Program to find parity"
},
{
"code": null,
"e": 38949,
"s": 38885,
"text": "Write an Efficient Method to Check if a Number is Multiple of 3"
},
{
"code": null,
"e": 38986,
"s": 38949,
"text": "Hamming code Implementation in C/C++"
},
{
"code": null,
"e": 39023,
"s": 38986,
"text": "Check whether K-th bit is set or not"
},
{
"code": null,
"e": 39073,
"s": 39023,
"text": "Implementation of Bit Stuffing and Bit Destuffing"
},
{
"code": null,
"e": 39102,
"s": 39073,
"text": "Count total bits in a number"
},
{
"code": null,
"e": 39136,
"s": 39102,
"text": "Builtin functions of GCC compiler"
},
{
"code": null,
"e": 39163,
"s": 39136,
"text": "Check for Integer Overflow"
}
] |
JavaScript | clearTimeout() & clearInterval() Method - GeeksforGeeks
|
26 Jul, 2019
Prerequisite: setTimeout() and setInterval()
clearTimeout()The clearTimeout() function in javascript clears the timeout which has been set by setTimeout()function before that.
setTimeout() function takes two parameters. First a function to be executed and second after how much time (in ms).
setTimeout() executes the passed function after given time. The number id value returned by setTimeout() function is stored in a variable and it’s passed into the clearTimeout() function to clear the timer.
Example:
<!DOCTYPE html><html> <head> <title> HTML | DOM Windows clearTimeout() method </title></head> <body> <button id="btn" onclick="fun()" style="color: blue;"> GeeksForGeeks</button> <button id="btn" onclick="stop()">Stop</button> <script> var t; function color() { if (document.getElementById('btn').style.color == 'blue') { document.getElementById('btn').style.color = 'green'; } else { document.getElementById('btn').style.color = 'blue'; } } function fun() { t = setTimeout(color, 3000); } function stop() { clearTimeout(t); } </script></body> </html>
Explanation:The GeeksForGeeks button color changes after 3 seconds for just one time. Click on Stop before 3 seconds after clicking GeeksForGeeks button to clear Timeout.
clearInterval()The clearInterval() function in javascript clears the interval which has been set by setInterval() function before that.
setInterval() function takes two parameters. First a function to be executed and second after how much time (in ms).
setInterval() executes the passed function for the given time interval. The number id value returned by setInterval() function is stored in a variable and it’s passed into the clearInterval() function to clear the interval.
Example:
<!DOCTYPE html><html> <head> <title> HTML | DOM Windows clearInterval() method </title></head> <body> <button id="btn" onclick="fun()" style="color: blue;"> GeeksForGeeks</button> <button id="btn" onclick="stop()">Stop</button> <script> var t; function color() { if (document.getElementById('btn').style.color == 'blue') { document.getElementById('btn').style.color = 'green'; } else { document.getElementById('btn').style.color = 'blue'; } } function fun() { t = setInterval(color, 3000); } function stop() { clearInterval(t); } </script></body> </html>
Explanation:In this example, the GeeksForGeeks color changes and stays the same for every 3 seconds, after that it changes again. Click on Stop to clear the interval.
Supported Browser: The browser supported by clearTimeout() & clearInterval() Method are listed below:
Google Chrome 1.0
Internet Explorer 4.0
Firefox 1.0
Opera 4.0
Safari 1.0
ShivaPrakash7
javascript-date
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Difference Between PUT and PATCH Request
JavaScript | console.log() with Examples
How to read a local text file using JavaScript?
Node.js | fs.writeFileSync() Method
|
[
{
"code": null,
"e": 25621,
"s": 25593,
"text": "\n26 Jul, 2019"
},
{
"code": null,
"e": 25666,
"s": 25621,
"text": "Prerequisite: setTimeout() and setInterval()"
},
{
"code": null,
"e": 25797,
"s": 25666,
"text": "clearTimeout()The clearTimeout() function in javascript clears the timeout which has been set by setTimeout()function before that."
},
{
"code": null,
"e": 25913,
"s": 25797,
"text": "setTimeout() function takes two parameters. First a function to be executed and second after how much time (in ms)."
},
{
"code": null,
"e": 26120,
"s": 25913,
"text": "setTimeout() executes the passed function after given time. The number id value returned by setTimeout() function is stored in a variable and it’s passed into the clearTimeout() function to clear the timer."
},
{
"code": null,
"e": 26129,
"s": 26120,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> HTML | DOM Windows clearTimeout() method </title></head> <body> <button id=\"btn\" onclick=\"fun()\" style=\"color: blue;\"> GeeksForGeeks</button> <button id=\"btn\" onclick=\"stop()\">Stop</button> <script> var t; function color() { if (document.getElementById('btn').style.color == 'blue') { document.getElementById('btn').style.color = 'green'; } else { document.getElementById('btn').style.color = 'blue'; } } function fun() { t = setTimeout(color, 3000); } function stop() { clearTimeout(t); } </script></body> </html>",
"e": 26862,
"s": 26129,
"text": null
},
{
"code": null,
"e": 27033,
"s": 26862,
"text": "Explanation:The GeeksForGeeks button color changes after 3 seconds for just one time. Click on Stop before 3 seconds after clicking GeeksForGeeks button to clear Timeout."
},
{
"code": null,
"e": 27169,
"s": 27033,
"text": "clearInterval()The clearInterval() function in javascript clears the interval which has been set by setInterval() function before that."
},
{
"code": null,
"e": 27286,
"s": 27169,
"text": "setInterval() function takes two parameters. First a function to be executed and second after how much time (in ms)."
},
{
"code": null,
"e": 27510,
"s": 27286,
"text": "setInterval() executes the passed function for the given time interval. The number id value returned by setInterval() function is stored in a variable and it’s passed into the clearInterval() function to clear the interval."
},
{
"code": null,
"e": 27519,
"s": 27510,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> HTML | DOM Windows clearInterval() method </title></head> <body> <button id=\"btn\" onclick=\"fun()\" style=\"color: blue;\"> GeeksForGeeks</button> <button id=\"btn\" onclick=\"stop()\">Stop</button> <script> var t; function color() { if (document.getElementById('btn').style.color == 'blue') { document.getElementById('btn').style.color = 'green'; } else { document.getElementById('btn').style.color = 'blue'; } } function fun() { t = setInterval(color, 3000); } function stop() { clearInterval(t); } </script></body> </html>",
"e": 28253,
"s": 27519,
"text": null
},
{
"code": null,
"e": 28420,
"s": 28253,
"text": "Explanation:In this example, the GeeksForGeeks color changes and stays the same for every 3 seconds, after that it changes again. Click on Stop to clear the interval."
},
{
"code": null,
"e": 28522,
"s": 28420,
"text": "Supported Browser: The browser supported by clearTimeout() & clearInterval() Method are listed below:"
},
{
"code": null,
"e": 28540,
"s": 28522,
"text": "Google Chrome 1.0"
},
{
"code": null,
"e": 28562,
"s": 28540,
"text": "Internet Explorer 4.0"
},
{
"code": null,
"e": 28574,
"s": 28562,
"text": "Firefox 1.0"
},
{
"code": null,
"e": 28584,
"s": 28574,
"text": "Opera 4.0"
},
{
"code": null,
"e": 28595,
"s": 28584,
"text": "Safari 1.0"
},
{
"code": null,
"e": 28609,
"s": 28595,
"text": "ShivaPrakash7"
},
{
"code": null,
"e": 28625,
"s": 28609,
"text": "javascript-date"
},
{
"code": null,
"e": 28636,
"s": 28625,
"text": "JavaScript"
},
{
"code": null,
"e": 28734,
"s": 28636,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28774,
"s": 28734,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28819,
"s": 28774,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28880,
"s": 28819,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28952,
"s": 28880,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 29004,
"s": 28952,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 29050,
"s": 29004,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 29091,
"s": 29050,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 29132,
"s": 29091,
"text": "JavaScript | console.log() with Examples"
},
{
"code": null,
"e": 29180,
"s": 29132,
"text": "How to read a local text file using JavaScript?"
}
] |
How to Escape Square Brackets in a LIKE Clause in SQL Server?
|
15 Oct, 2021
Here we will see, how to escape square brackets in a LIKE clause. LIKE clause used for pattern matching in SQL using wildcard operators like %, ^, [], etc. If we try to filter the record using a LIKE clause with a string consisting of square brackets, we will not get the expected results.
For example:
For a string value Romy[R]kumari in a table. If we try to apply LIKE ‘Romy[R]%’ to the select statement, it will not return anything.
Explanation:
Square brackets[], is among the wildcard operators used in SQL with the LIKE clause. It is used to match any single character within the specified range like ([b-h]) or set ([ghijk]).
We can escape square brackets using two methods:
Escape using one more square bracket
Escape using Escape character
Step 1: Create a database
The database can be created using CREATE command.
Query:
CREATE DATABASE geeks;
Step 2: Using a database
Use the below SQL statement to switch the database context to geeks:
Query:
USE geeks;
Step 3: Table definition
We have the following demo_table in our geek’s database.
Query:
CREATE TABLE demo_table(
FIRSTNAME VARCHAR(20), LASTNAME VARCHAR(20),
EMPCODE VARCHAR(20));
Step 4: Inserting data into the table
Query:
INSERT INTO demo_table VALUES
('ROMY', 'Kumari', 'ROMY[78]KUM'),
('Rinkle', 'Arora', 'RINKLE[78}ARO'),
('Nikhil', 'Kalra','NIKHIL[90]Kal'),
('Pushkar', 'Jha', 'PUSHKAR[91]JHA'),
('Sujata', 'jha', 'SUJATA[98]JHA'),
('Roshini', 'Kumari','ROSHINI[78]');
Step 5: For a view a table data
Query:
SELECT * FROM demo_table;
Output:
Syntax:
For matching ‘ROMY[78]’
SELECT *
FROM table_name
WHERE column_name LIKE 'ROMY[[]78]%'
Query: To match EMPCODE having [78]
SELECT *
FROM demo_table
WHERE EMPCODE LIKE '%[[]78]%'
Output:
In this method, we have to specify the character with the ESCAPE keyword after the LIKE clause.
Syntax:
For matching ‘ROMY[78]’
SELECT *
FROM table_name
WHERE column_name LIKE 'ROMY\[78]%' ESCAPE '\';
Query:
SELECT *
FROM demo_table
WHERE EMPCODE LIKE '%\[78]%' ESCAPE '\';
Output:
Picked
SQL-Server
TrueGeek-2021
SQL
TrueGeek
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | Sub queries in From Clause
Window functions in SQL
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
How to redirect to another page in ReactJS ?
Basics of API Testing Using Postman
How to Convert Char to String in Java?
How to remove duplicate elements from JavaScript Array ?
Types of Internet Protocols
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Oct, 2021"
},
{
"code": null,
"e": 318,
"s": 28,
"text": "Here we will see, how to escape square brackets in a LIKE clause. LIKE clause used for pattern matching in SQL using wildcard operators like %, ^, [], etc. If we try to filter the record using a LIKE clause with a string consisting of square brackets, we will not get the expected results."
},
{
"code": null,
"e": 331,
"s": 318,
"text": "For example:"
},
{
"code": null,
"e": 465,
"s": 331,
"text": "For a string value Romy[R]kumari in a table. If we try to apply LIKE ‘Romy[R]%’ to the select statement, it will not return anything."
},
{
"code": null,
"e": 478,
"s": 465,
"text": "Explanation:"
},
{
"code": null,
"e": 662,
"s": 478,
"text": "Square brackets[], is among the wildcard operators used in SQL with the LIKE clause. It is used to match any single character within the specified range like ([b-h]) or set ([ghijk])."
},
{
"code": null,
"e": 711,
"s": 662,
"text": "We can escape square brackets using two methods:"
},
{
"code": null,
"e": 748,
"s": 711,
"text": "Escape using one more square bracket"
},
{
"code": null,
"e": 778,
"s": 748,
"text": "Escape using Escape character"
},
{
"code": null,
"e": 804,
"s": 778,
"text": "Step 1: Create a database"
},
{
"code": null,
"e": 854,
"s": 804,
"text": "The database can be created using CREATE command."
},
{
"code": null,
"e": 861,
"s": 854,
"text": "Query:"
},
{
"code": null,
"e": 884,
"s": 861,
"text": "CREATE DATABASE geeks;"
},
{
"code": null,
"e": 909,
"s": 884,
"text": "Step 2: Using a database"
},
{
"code": null,
"e": 978,
"s": 909,
"text": "Use the below SQL statement to switch the database context to geeks:"
},
{
"code": null,
"e": 985,
"s": 978,
"text": "Query:"
},
{
"code": null,
"e": 996,
"s": 985,
"text": "USE geeks;"
},
{
"code": null,
"e": 1022,
"s": 996,
"text": "Step 3: Table definition"
},
{
"code": null,
"e": 1079,
"s": 1022,
"text": "We have the following demo_table in our geek’s database."
},
{
"code": null,
"e": 1086,
"s": 1079,
"text": "Query:"
},
{
"code": null,
"e": 1178,
"s": 1086,
"text": "CREATE TABLE demo_table(\nFIRSTNAME VARCHAR(20), LASTNAME VARCHAR(20),\nEMPCODE VARCHAR(20));"
},
{
"code": null,
"e": 1216,
"s": 1178,
"text": "Step 4: Inserting data into the table"
},
{
"code": null,
"e": 1223,
"s": 1216,
"text": "Query:"
},
{
"code": null,
"e": 1474,
"s": 1223,
"text": "INSERT INTO demo_table VALUES\n('ROMY', 'Kumari', 'ROMY[78]KUM'),\n('Rinkle', 'Arora', 'RINKLE[78}ARO'),\n('Nikhil', 'Kalra','NIKHIL[90]Kal'),\n('Pushkar', 'Jha', 'PUSHKAR[91]JHA'),\n('Sujata', 'jha', 'SUJATA[98]JHA'),\n('Roshini', 'Kumari','ROSHINI[78]');"
},
{
"code": null,
"e": 1507,
"s": 1474,
"text": "Step 5: For a view a table data"
},
{
"code": null,
"e": 1514,
"s": 1507,
"text": "Query:"
},
{
"code": null,
"e": 1540,
"s": 1514,
"text": "SELECT * FROM demo_table;"
},
{
"code": null,
"e": 1548,
"s": 1540,
"text": "Output:"
},
{
"code": null,
"e": 1556,
"s": 1548,
"text": "Syntax:"
},
{
"code": null,
"e": 1581,
"s": 1556,
"text": "For matching ‘ROMY[78]’ "
},
{
"code": null,
"e": 1650,
"s": 1581,
"text": "SELECT * \n FROM table_name \n WHERE column_name LIKE 'ROMY[[]78]%'"
},
{
"code": null,
"e": 1687,
"s": 1650,
"text": "Query: To match EMPCODE having [78] "
},
{
"code": null,
"e": 1750,
"s": 1687,
"text": "SELECT * \n FROM demo_table \n WHERE EMPCODE LIKE '%[[]78]%'"
},
{
"code": null,
"e": 1758,
"s": 1750,
"text": "Output:"
},
{
"code": null,
"e": 1854,
"s": 1758,
"text": "In this method, we have to specify the character with the ESCAPE keyword after the LIKE clause."
},
{
"code": null,
"e": 1862,
"s": 1854,
"text": "Syntax:"
},
{
"code": null,
"e": 1887,
"s": 1862,
"text": "For matching ‘ROMY[78]’ "
},
{
"code": null,
"e": 1968,
"s": 1887,
"text": "SELECT * \n FROM table_name \n WHERE column_name LIKE 'ROMY\\[78]%' ESCAPE '\\';"
},
{
"code": null,
"e": 1975,
"s": 1968,
"text": "Query:"
},
{
"code": null,
"e": 2047,
"s": 1975,
"text": "SELECT * \n FROM demo_table\n WHERE EMPCODE LIKE '%\\[78]%' ESCAPE '\\';"
},
{
"code": null,
"e": 2055,
"s": 2047,
"text": "Output:"
},
{
"code": null,
"e": 2062,
"s": 2055,
"text": "Picked"
},
{
"code": null,
"e": 2073,
"s": 2062,
"text": "SQL-Server"
},
{
"code": null,
"e": 2087,
"s": 2073,
"text": "TrueGeek-2021"
},
{
"code": null,
"e": 2091,
"s": 2087,
"text": "SQL"
},
{
"code": null,
"e": 2100,
"s": 2091,
"text": "TrueGeek"
},
{
"code": null,
"e": 2104,
"s": 2100,
"text": "SQL"
},
{
"code": null,
"e": 2202,
"s": 2104,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2268,
"s": 2202,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 2301,
"s": 2268,
"text": "SQL | Sub queries in From Clause"
},
{
"code": null,
"e": 2325,
"s": 2301,
"text": "Window functions in SQL"
},
{
"code": null,
"e": 2357,
"s": 2325,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 2435,
"s": 2357,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 2480,
"s": 2435,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 2516,
"s": 2480,
"text": "Basics of API Testing Using Postman"
},
{
"code": null,
"e": 2555,
"s": 2516,
"text": "How to Convert Char to String in Java?"
},
{
"code": null,
"e": 2612,
"s": 2555,
"text": "How to remove duplicate elements from JavaScript Array ?"
}
] |
Python | Plotting charts in excel sheet using openpyxl module | Set – 1
|
04 Jul, 2022
Prerequisite: Reading & Writing to excel sheet using openpyxl Openpyxl is a Python library using which one can perform multiple operations on excel files like reading, writing, arithmetic operations and plotting graphs. Let’s see how to plot different charts using realtime data. Charts are composed of at least one series of one or more data points. Series themselves are comprised of references to cell ranges. For plotting the charts on an excel sheet, firstly, create chart object of specific chart class( i.e BarChart, LineChart etc.). After creating chart objects, insert data in it and lastly, add that chart object in the sheet object.
Code #1 : Plot the Bar Chart For plotting the bar chart on an excel sheet, use BarChart class from openpyxl.chart submodule.
Python3
# import openpyxl moduleimport openpyxl # import BarChart class from openpyxl.chart sub_modulefrom openpyxl.chart import BarChart,Reference # Call a Workbook() function of openpyxl# to create a new blank Workbook objectwb = openpyxl.Workbook() # Get workbook active sheet# from the active attribute.sheet = wb.active # write o to 9 in 1st column of the active sheetfor i in range(10): sheet.append([i]) # create data for plottingvalues = Reference(sheet, min_col = 1, min_row = 1, max_col = 1, max_row = 10) # Create object of BarChart classchart = BarChart() # adding data to the Bar chart objectchart.add_data(values) # set the title of the chartchart.title = " BAR-CHART " # set the title of the x-axischart.x_axis.title = " X_AXIS " # set the title of the y-axischart.y_axis.title = " Y_AXIS " # add chart to the sheet# the top-left corner of a chart# is anchored to cell E2 .sheet.add_chart(chart, "E2") # save the filewb.save("barChart.xlsx")
Output: Code #2 : Plot the 3D Bar Chart For plotting the 3D bar chart on an excel sheet, use BarChart3D class from openpyxl.chart submodule.
Python3
# import openpyxl moduleimport openpyxl # import BarChart3D class from openpyxl.chart sub_modulefrom openpyxl.chart import BarChart3D,Reference # write o to 9 in 1st column of the active sheetfor i in range(10): sheet.append([i]) values = Reference(sheet, min_col = 1, min_row = 1, max_col = 1, max_row = 10) # Create object of BarChart3D classchart = BarChart3D() chart.add_data(values) # set the title of the chartchart.title = " BAR-CHART3D " # set the title of the x-axischart.x_axis.title = " X AXIS " # set the title of the y-axischart.y_axis.title = " Y AXIS " # add chart to the sheet# the top-left corner of a chart# is anchored to cell E2.sheet.add_chart(chart, "E2") # save the filewb.save("BarChart3D.xlsx")
Output: Code #3 : Plot the Area Chart For plotting the Area chart on an excel sheet, use AreaChart class from openpyxl.chart submodule.
Python3
import openpyxl # import AreaChart class from openpyxl.chart sub_modulefrom openpyxl.chart import AreaChart,Reference wb = openpyxl.Workbook()sheet = wb.active # write o to 9 in 1st column of the active sheetfor i in range(10): sheet.append([i]) values = Reference(sheet, min_col = 1, min_row = 1, max_col = 1, max_row = 10) # create object of AreaChart classchart = AreaChart() chart.add_data(values) # set the title of the chartchart.title = " AREA-CHART " # set the title of the x-axischart.x_axis.title = " X-AXIS " # set the title of the y-axischart.y_axis.title = " Y-AXIS " # add chart to the sheet# the top-left corner of a chart# is anchored to cell E2 .sheet.add_chart(chart, "E2") # save the filewb.save("AreaChart.xlsx")
Output: Code #4 : Plot the 3D Area Chart For plotting the 3D Area chart on an excel sheet, use AreaChart3D class from openpyxl.chart submodule.
Python3
import openpyxl # import AreaChart3D class from openpyxl.chart sub_modulefrom openpyxl.chart import AreaChart3D,Reference wb = openpyxl.Workbook()sheet = wb.active # write o to 9 in 1st column of the active sheetfor i in range(10): sheet.append([i]) values = Reference(sheet, min_col = 1, min_row = 1, max_col = 1, max_row = 10) # Create object of AreaChart3D classchart = AreaChart3D() chart.add_data(values) # set the title of the chartchart.title = " AREA-CHART3D " # set the title of the x-axischart.x_axis.title = " X-AXIS " # set the title of the y-axischart.y_axis.title = " Y-AXIS " # add chart to the sheet# the top-left corner of a chart# is anchored to cell E2 .sheet.add_chart(chart, "E2") # save the filewb.save("AreaChart3D.xlsx")
Output: Code #5 : Plot a Line Chart. For plotting the Line chart on an excel sheet, use LineChart class from openpyxl.chart submodule.
Python3
# import openpyxl moduleimport openpyxl # import LineChart class from openpyxl.chart sub_modulefrom openpyxl.chart import LineChart,Reference wb = openpyxl.Workbook()sheet = wb.active # write o to 9 in 1st column of the active sheetfor i in range(10): sheet.append([i]) values = Reference(sheet, min_col = 1, min_row = 1, max_col = 1, max_row = 10) # Create object of LineChart classchart = LineChart() chart.add_data(values) # set the title of the chartchart.title = " LINE-CHART " # set the title of the x-axischart.x_axis.title = " X-AXIS " # set the title of the y-axischart.y_axis.title = " Y-AXIS " # add chart to the sheet# the top-left corner of a chart# is anchored to cell E2 .sheet.add_chart(chart, "E2") # save the filewb.save("LineChart.xlsx")
Output: Code #6 : Plot a 3D Line Chart. For plotting the 3D Line chart on an excel sheet we have to use LineChart3D class from openpyxl.chart submodule.
Python3
import openpyxl # import LineChart3D class from openpyxl.chart sub_modulefrom openpyxl.chart import LineChart3D,Reference wb = openpyxl.Workbook()sheet = wb.active # write o to 9 in 1st column of the active sheetfor i in range(10): sheet.append([i]) values = Reference(sheet, min_col = 1, min_row = 1, max_col = 1, max_row = 10) # Create object of LineChart3D classchart = LineChart3D() chart.add_data(values) # set the title of the chartchart.title = " LINE-CHART3D " # set the title of the x-axischart.x_axis.title = " X-AXIS " # set the title of the y-axischart.y_axis.title = " Y-AXIS " # add chart to the sheet# the top-left corner of a chart# is anchored to cell E2 .sheet.add_chart(chart, "E2") # save the filewb.save("LineChart3D.xlsx")
Output:
ankthon
sweetyty
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n04 Jul, 2022"
},
{
"code": null,
"e": 699,
"s": 54,
"text": "Prerequisite: Reading & Writing to excel sheet using openpyxl Openpyxl is a Python library using which one can perform multiple operations on excel files like reading, writing, arithmetic operations and plotting graphs. Let’s see how to plot different charts using realtime data. Charts are composed of at least one series of one or more data points. Series themselves are comprised of references to cell ranges. For plotting the charts on an excel sheet, firstly, create chart object of specific chart class( i.e BarChart, LineChart etc.). After creating chart objects, insert data in it and lastly, add that chart object in the sheet object. "
},
{
"code": null,
"e": 825,
"s": 699,
"text": "Code #1 : Plot the Bar Chart For plotting the bar chart on an excel sheet, use BarChart class from openpyxl.chart submodule. "
},
{
"code": null,
"e": 833,
"s": 825,
"text": "Python3"
},
{
"code": "# import openpyxl moduleimport openpyxl # import BarChart class from openpyxl.chart sub_modulefrom openpyxl.chart import BarChart,Reference # Call a Workbook() function of openpyxl# to create a new blank Workbook objectwb = openpyxl.Workbook() # Get workbook active sheet# from the active attribute.sheet = wb.active # write o to 9 in 1st column of the active sheetfor i in range(10): sheet.append([i]) # create data for plottingvalues = Reference(sheet, min_col = 1, min_row = 1, max_col = 1, max_row = 10) # Create object of BarChart classchart = BarChart() # adding data to the Bar chart objectchart.add_data(values) # set the title of the chartchart.title = \" BAR-CHART \" # set the title of the x-axischart.x_axis.title = \" X_AXIS \" # set the title of the y-axischart.y_axis.title = \" Y_AXIS \" # add chart to the sheet# the top-left corner of a chart# is anchored to cell E2 .sheet.add_chart(chart, \"E2\") # save the filewb.save(\"barChart.xlsx\")",
"e": 1809,
"s": 833,
"text": null
},
{
"code": null,
"e": 1954,
"s": 1809,
"text": "Output: Code #2 : Plot the 3D Bar Chart For plotting the 3D bar chart on an excel sheet, use BarChart3D class from openpyxl.chart submodule. "
},
{
"code": null,
"e": 1962,
"s": 1954,
"text": "Python3"
},
{
"code": "# import openpyxl moduleimport openpyxl # import BarChart3D class from openpyxl.chart sub_modulefrom openpyxl.chart import BarChart3D,Reference # write o to 9 in 1st column of the active sheetfor i in range(10): sheet.append([i]) values = Reference(sheet, min_col = 1, min_row = 1, max_col = 1, max_row = 10) # Create object of BarChart3D classchart = BarChart3D() chart.add_data(values) # set the title of the chartchart.title = \" BAR-CHART3D \" # set the title of the x-axischart.x_axis.title = \" X AXIS \" # set the title of the y-axischart.y_axis.title = \" Y AXIS \" # add chart to the sheet# the top-left corner of a chart# is anchored to cell E2.sheet.add_chart(chart, \"E2\") # save the filewb.save(\"BarChart3D.xlsx\")",
"e": 2709,
"s": 1962,
"text": null
},
{
"code": null,
"e": 2849,
"s": 2709,
"text": "Output: Code #3 : Plot the Area Chart For plotting the Area chart on an excel sheet, use AreaChart class from openpyxl.chart submodule. "
},
{
"code": null,
"e": 2857,
"s": 2849,
"text": "Python3"
},
{
"code": "import openpyxl # import AreaChart class from openpyxl.chart sub_modulefrom openpyxl.chart import AreaChart,Reference wb = openpyxl.Workbook()sheet = wb.active # write o to 9 in 1st column of the active sheetfor i in range(10): sheet.append([i]) values = Reference(sheet, min_col = 1, min_row = 1, max_col = 1, max_row = 10) # create object of AreaChart classchart = AreaChart() chart.add_data(values) # set the title of the chartchart.title = \" AREA-CHART \" # set the title of the x-axischart.x_axis.title = \" X-AXIS \" # set the title of the y-axischart.y_axis.title = \" Y-AXIS \" # add chart to the sheet# the top-left corner of a chart# is anchored to cell E2 .sheet.add_chart(chart, \"E2\") # save the filewb.save(\"AreaChart.xlsx\")",
"e": 3618,
"s": 2857,
"text": null
},
{
"code": null,
"e": 3766,
"s": 3618,
"text": "Output: Code #4 : Plot the 3D Area Chart For plotting the 3D Area chart on an excel sheet, use AreaChart3D class from openpyxl.chart submodule. "
},
{
"code": null,
"e": 3774,
"s": 3766,
"text": "Python3"
},
{
"code": "import openpyxl # import AreaChart3D class from openpyxl.chart sub_modulefrom openpyxl.chart import AreaChart3D,Reference wb = openpyxl.Workbook()sheet = wb.active # write o to 9 in 1st column of the active sheetfor i in range(10): sheet.append([i]) values = Reference(sheet, min_col = 1, min_row = 1, max_col = 1, max_row = 10) # Create object of AreaChart3D classchart = AreaChart3D() chart.add_data(values) # set the title of the chartchart.title = \" AREA-CHART3D \" # set the title of the x-axischart.x_axis.title = \" X-AXIS \" # set the title of the y-axischart.y_axis.title = \" Y-AXIS \" # add chart to the sheet# the top-left corner of a chart# is anchored to cell E2 .sheet.add_chart(chart, \"E2\") # save the filewb.save(\"AreaChart3D.xlsx\")",
"e": 4546,
"s": 3774,
"text": null
},
{
"code": null,
"e": 4685,
"s": 4546,
"text": "Output: Code #5 : Plot a Line Chart. For plotting the Line chart on an excel sheet, use LineChart class from openpyxl.chart submodule. "
},
{
"code": null,
"e": 4693,
"s": 4685,
"text": "Python3"
},
{
"code": "# import openpyxl moduleimport openpyxl # import LineChart class from openpyxl.chart sub_modulefrom openpyxl.chart import LineChart,Reference wb = openpyxl.Workbook()sheet = wb.active # write o to 9 in 1st column of the active sheetfor i in range(10): sheet.append([i]) values = Reference(sheet, min_col = 1, min_row = 1, max_col = 1, max_row = 10) # Create object of LineChart classchart = LineChart() chart.add_data(values) # set the title of the chartchart.title = \" LINE-CHART \" # set the title of the x-axischart.x_axis.title = \" X-AXIS \" # set the title of the y-axischart.y_axis.title = \" Y-AXIS \" # add chart to the sheet# the top-left corner of a chart# is anchored to cell E2 .sheet.add_chart(chart, \"E2\") # save the filewb.save(\"LineChart.xlsx\")",
"e": 5477,
"s": 4693,
"text": null
},
{
"code": null,
"e": 5634,
"s": 5477,
"text": "Output: Code #6 : Plot a 3D Line Chart. For plotting the 3D Line chart on an excel sheet we have to use LineChart3D class from openpyxl.chart submodule. "
},
{
"code": null,
"e": 5642,
"s": 5634,
"text": "Python3"
},
{
"code": "import openpyxl # import LineChart3D class from openpyxl.chart sub_modulefrom openpyxl.chart import LineChart3D,Reference wb = openpyxl.Workbook()sheet = wb.active # write o to 9 in 1st column of the active sheetfor i in range(10): sheet.append([i]) values = Reference(sheet, min_col = 1, min_row = 1, max_col = 1, max_row = 10) # Create object of LineChart3D classchart = LineChart3D() chart.add_data(values) # set the title of the chartchart.title = \" LINE-CHART3D \" # set the title of the x-axischart.x_axis.title = \" X-AXIS \" # set the title of the y-axischart.y_axis.title = \" Y-AXIS \" # add chart to the sheet# the top-left corner of a chart# is anchored to cell E2 .sheet.add_chart(chart, \"E2\") # save the filewb.save(\"LineChart3D.xlsx\")",
"e": 6415,
"s": 5642,
"text": null
},
{
"code": null,
"e": 6424,
"s": 6415,
"text": "Output: "
},
{
"code": null,
"e": 6432,
"s": 6424,
"text": "ankthon"
},
{
"code": null,
"e": 6441,
"s": 6432,
"text": "sweetyty"
},
{
"code": null,
"e": 6456,
"s": 6441,
"text": "python-modules"
},
{
"code": null,
"e": 6463,
"s": 6456,
"text": "Python"
}
] |
The Hidden Wiki
|
25 Jan, 2021
The Dark Web is that part of the internet where all the illegal works are done. You can access to the dark web through TOR(The Onion Router). The Hidden Wiki is the name used by censorship-resistant wikis operating as Tor hidden services that anyone can anonymously edit after registering on the site. The main page here serves as a directory of links to other .onion sites. So, the hidden wiki is also accessed from the TOR browser.
Early stage: The hidden wiki was first recorded in 2007 when it was located at 6sxoyfb3h2nvok2d.onion. But later in 2011, a full-fledged website with many of the links found. Prior to August 2013, the site was hosted on domain “Freedom Hosting”. In March 2014 the site and its kpvz7ki2v5agwt35.onion domain was hacked and redirected to a new domain “Doxbin”. Why it is used? Hidden wiki is operated and run at .onion domains which are only accessed by TOR or TOR gateway. Hidden wiki is a website that has a link to all the hidden and secret/ illegal works such as money laundering, contract killing, cyber-attacks for hire, contraband chemicals, and bomb-making. Fact: It is said that hidden wiki is a collection of links of websites, but many more thousands more websites are there on Darkweb which do not shows up on the hidden wiki. How to Access: You can access the hidden wiki for educational purposes using this link:
http://zqktlwiuavvvqqt4ybvgvi7tyo4hjl5xgfuvpdf6otjiycgwqbym2qad.onion/wiki/Main_Page
Is HiddenWiki Illegal? Hidden Wiki is not illegal to access in many countries. But doing Illegal work on Hidden wiki is illegal. How hidden wiki work?
On the hidden wiki, once you registered you can edit itSo people add more links to there services on Hidden Wiki.
On the hidden wiki, once you registered you can edit it
So people add more links to there services on Hidden Wiki.
lamar2
Web technologies
GBlog
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n25 Jan, 2021"
},
{
"code": null,
"e": 489,
"s": 54,
"text": "The Dark Web is that part of the internet where all the illegal works are done. You can access to the dark web through TOR(The Onion Router). The Hidden Wiki is the name used by censorship-resistant wikis operating as Tor hidden services that anyone can anonymously edit after registering on the site. The main page here serves as a directory of links to other .onion sites. So, the hidden wiki is also accessed from the TOR browser. "
},
{
"code": null,
"e": 1416,
"s": 489,
"text": "Early stage: The hidden wiki was first recorded in 2007 when it was located at 6sxoyfb3h2nvok2d.onion. But later in 2011, a full-fledged website with many of the links found. Prior to August 2013, the site was hosted on domain “Freedom Hosting”. In March 2014 the site and its kpvz7ki2v5agwt35.onion domain was hacked and redirected to a new domain “Doxbin”. Why it is used? Hidden wiki is operated and run at .onion domains which are only accessed by TOR or TOR gateway. Hidden wiki is a website that has a link to all the hidden and secret/ illegal works such as money laundering, contract killing, cyber-attacks for hire, contraband chemicals, and bomb-making. Fact: It is said that hidden wiki is a collection of links of websites, but many more thousands more websites are there on Darkweb which do not shows up on the hidden wiki. How to Access: You can access the hidden wiki for educational purposes using this link: "
},
{
"code": null,
"e": 1501,
"s": 1416,
"text": "http://zqktlwiuavvvqqt4ybvgvi7tyo4hjl5xgfuvpdf6otjiycgwqbym2qad.onion/wiki/Main_Page"
},
{
"code": null,
"e": 1654,
"s": 1501,
"text": "Is HiddenWiki Illegal? Hidden Wiki is not illegal to access in many countries. But doing Illegal work on Hidden wiki is illegal. How hidden wiki work? "
},
{
"code": null,
"e": 1769,
"s": 1654,
"text": "On the hidden wiki, once you registered you can edit itSo people add more links to there services on Hidden Wiki. "
},
{
"code": null,
"e": 1825,
"s": 1769,
"text": "On the hidden wiki, once you registered you can edit it"
},
{
"code": null,
"e": 1885,
"s": 1825,
"text": "So people add more links to there services on Hidden Wiki. "
},
{
"code": null,
"e": 1892,
"s": 1885,
"text": "lamar2"
},
{
"code": null,
"e": 1909,
"s": 1892,
"text": "Web technologies"
},
{
"code": null,
"e": 1915,
"s": 1909,
"text": "GBlog"
}
] |
Collections.UserString in Python
|
31 Aug, 2021
Strings are the arrays of bytes representing Unicode characters. However, Python does not support the character data type. A character is a string of length one. Example:
Python3
# Python program to demonstrate# string # Creating a String # with single QuotesString1 = 'Welcome to the Geeks World'print("String with the use of Single Quotes: ")print(String1) # Creating a String# with double QuotesString1 = "I'm a Geek"print("\nString with the use of Double Quotes: ")print(String1)
Output:
String with the use of Single Quotes:
Welcome to the Geeks World
String with the use of Double Quotes:
I'm a Geek
Note: For more information, refer to Python String
Python supports a String like a container called UserString present in the collections module. This class acts as a wrapper class around the string objects. This class is useful when one wants to create a string of their own with some modified functionality or with some new functionality. It can be considered as a way of adding new behaviors for the string. This class takes any argument that can be converted to string and simulates a string whose content is kept in a regular string. The string is accessible by the data attribute of this class.Syntax:
collections.UserString(seq)
Example 1:
Python3
# Python program to demonstrate# userstring from collections import UserString d = 12344 # Creating an UserDictuserS = UserString(d)print(userS.data) # Creating an empty UserDictuserS = UserString("")print(userS.data)
Output:
12344
Example 2:
Python3
# Python program to demonstrate# userstring from collections import UserString # Creating a Mutable Stringclass Mystring(UserString): # Function to append to # string def append(self, s): self.data += s # Function to remove from # string def remove(self, s): self.data = self.data.replace(s, "") # Driver's codes1 = Mystring("Geeks")print("Original String:", s1.data) # Appending to strings1.append("s")print("String After Appending:", s1.data) # Removing from strings1.remove("e")print("String after Removing:", s1.data)
Output:
Original String: Geeks
String After Appending: Geekss
String after Removing: Gkss
varshagumber28
Python collections-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n31 Aug, 2021"
},
{
"code": null,
"e": 223,
"s": 52,
"text": "Strings are the arrays of bytes representing Unicode characters. However, Python does not support the character data type. A character is a string of length one. Example:"
},
{
"code": null,
"e": 231,
"s": 223,
"text": "Python3"
},
{
"code": "# Python program to demonstrate# string # Creating a String # with single QuotesString1 = 'Welcome to the Geeks World'print(\"String with the use of Single Quotes: \")print(String1) # Creating a String# with double QuotesString1 = \"I'm a Geek\"print(\"\\nString with the use of Double Quotes: \")print(String1)",
"e": 538,
"s": 231,
"text": null
},
{
"code": null,
"e": 546,
"s": 538,
"text": "Output:"
},
{
"code": null,
"e": 663,
"s": 546,
"text": "String with the use of Single Quotes: \nWelcome to the Geeks World\n\nString with the use of Double Quotes: \nI'm a Geek"
},
{
"code": null,
"e": 715,
"s": 663,
"text": "Note: For more information, refer to Python String "
},
{
"code": null,
"e": 1273,
"s": 715,
"text": "Python supports a String like a container called UserString present in the collections module. This class acts as a wrapper class around the string objects. This class is useful when one wants to create a string of their own with some modified functionality or with some new functionality. It can be considered as a way of adding new behaviors for the string. This class takes any argument that can be converted to string and simulates a string whose content is kept in a regular string. The string is accessible by the data attribute of this class.Syntax: "
},
{
"code": null,
"e": 1301,
"s": 1273,
"text": "collections.UserString(seq)"
},
{
"code": null,
"e": 1312,
"s": 1301,
"text": "Example 1:"
},
{
"code": null,
"e": 1320,
"s": 1312,
"text": "Python3"
},
{
"code": "# Python program to demonstrate# userstring from collections import UserString d = 12344 # Creating an UserDictuserS = UserString(d)print(userS.data) # Creating an empty UserDictuserS = UserString(\"\")print(userS.data)",
"e": 1541,
"s": 1320,
"text": null
},
{
"code": null,
"e": 1550,
"s": 1541,
"text": "Output: "
},
{
"code": null,
"e": 1556,
"s": 1550,
"text": "12344"
},
{
"code": null,
"e": 1567,
"s": 1556,
"text": "Example 2:"
},
{
"code": null,
"e": 1575,
"s": 1567,
"text": "Python3"
},
{
"code": "# Python program to demonstrate# userstring from collections import UserString # Creating a Mutable Stringclass Mystring(UserString): # Function to append to # string def append(self, s): self.data += s # Function to remove from # string def remove(self, s): self.data = self.data.replace(s, \"\") # Driver's codes1 = Mystring(\"Geeks\")print(\"Original String:\", s1.data) # Appending to strings1.append(\"s\")print(\"String After Appending:\", s1.data) # Removing from strings1.remove(\"e\")print(\"String after Removing:\", s1.data)",
"e": 2151,
"s": 1575,
"text": null
},
{
"code": null,
"e": 2159,
"s": 2151,
"text": "Output:"
},
{
"code": null,
"e": 2241,
"s": 2159,
"text": "Original String: Geeks\nString After Appending: Geekss\nString after Removing: Gkss"
},
{
"code": null,
"e": 2256,
"s": 2241,
"text": "varshagumber28"
},
{
"code": null,
"e": 2282,
"s": 2256,
"text": "Python collections-module"
},
{
"code": null,
"e": 2289,
"s": 2282,
"text": "Python"
}
] |
HTTP headers | Access-Control-Expose-Headers
|
19 Nov, 2019
The HTTP Access-Control-Expose-Headers header is a response header that is used to expose the headers that have been mentioned in it. By default 6 response headers are already exposed which are known as CORS-safelisted response headers. They are namely- Cache-Control, Content-Language, Content-Type, Expires, Last-Modified, Pragma.
Syntax:
Access-Control-Expose-Headers: <header-name>
Access-Control-Expose-Headers: *
Note: Multiple headers can be used.
Directives:
<header-name>: It specifies the header that needs to be exposed other than the safe listed headers specified by CORS. If there are multiple headers in use we separate them using commas.
*(wildcard): It is used for requests without HTTP cookies or HTTP authentication information. It should be noted that the Authorization header cannot be wildcarded and needs explicit mentioning.
Examples:
In this example, the Accept-Language HTTP header is exposed. It can be noted that it is a non-CORS safe listed header.Access-Control-Expose-Headers: Accept-Language
Access-Control-Expose-Headers: Accept-Language
In this example, the Authorization HTTP header was needed to be mentioned explicitly as it can’t be wild-carded normally.Access-Control-Expose-Headers: *, Authorization
Access-Control-Expose-Headers: *, Authorization
Supported Browsers: The browsers are compatible with HTTP header Access-Control-Expose-Headers are listed below:
Google Chrome 4.0
Internet Explorer 12.0
Opera 12.0
Firefox 3.5
Safari 4.0
Note: *(wildcard) directive may not supported on Safari and Internet Explorer.
HTTP-headers
Picked
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Nov, 2019"
},
{
"code": null,
"e": 361,
"s": 28,
"text": "The HTTP Access-Control-Expose-Headers header is a response header that is used to expose the headers that have been mentioned in it. By default 6 response headers are already exposed which are known as CORS-safelisted response headers. They are namely- Cache-Control, Content-Language, Content-Type, Expires, Last-Modified, Pragma."
},
{
"code": null,
"e": 369,
"s": 361,
"text": "Syntax:"
},
{
"code": null,
"e": 414,
"s": 369,
"text": "Access-Control-Expose-Headers: <header-name>"
},
{
"code": null,
"e": 447,
"s": 414,
"text": "Access-Control-Expose-Headers: *"
},
{
"code": null,
"e": 483,
"s": 447,
"text": "Note: Multiple headers can be used."
},
{
"code": null,
"e": 495,
"s": 483,
"text": "Directives:"
},
{
"code": null,
"e": 681,
"s": 495,
"text": "<header-name>: It specifies the header that needs to be exposed other than the safe listed headers specified by CORS. If there are multiple headers in use we separate them using commas."
},
{
"code": null,
"e": 876,
"s": 681,
"text": "*(wildcard): It is used for requests without HTTP cookies or HTTP authentication information. It should be noted that the Authorization header cannot be wildcarded and needs explicit mentioning."
},
{
"code": null,
"e": 886,
"s": 876,
"text": "Examples:"
},
{
"code": null,
"e": 1051,
"s": 886,
"text": "In this example, the Accept-Language HTTP header is exposed. It can be noted that it is a non-CORS safe listed header.Access-Control-Expose-Headers: Accept-Language"
},
{
"code": null,
"e": 1098,
"s": 1051,
"text": "Access-Control-Expose-Headers: Accept-Language"
},
{
"code": null,
"e": 1267,
"s": 1098,
"text": "In this example, the Authorization HTTP header was needed to be mentioned explicitly as it can’t be wild-carded normally.Access-Control-Expose-Headers: *, Authorization"
},
{
"code": null,
"e": 1315,
"s": 1267,
"text": "Access-Control-Expose-Headers: *, Authorization"
},
{
"code": null,
"e": 1428,
"s": 1315,
"text": "Supported Browsers: The browsers are compatible with HTTP header Access-Control-Expose-Headers are listed below:"
},
{
"code": null,
"e": 1446,
"s": 1428,
"text": "Google Chrome 4.0"
},
{
"code": null,
"e": 1469,
"s": 1446,
"text": "Internet Explorer 12.0"
},
{
"code": null,
"e": 1480,
"s": 1469,
"text": "Opera 12.0"
},
{
"code": null,
"e": 1492,
"s": 1480,
"text": "Firefox 3.5"
},
{
"code": null,
"e": 1503,
"s": 1492,
"text": "Safari 4.0"
},
{
"code": null,
"e": 1582,
"s": 1503,
"text": "Note: *(wildcard) directive may not supported on Safari and Internet Explorer."
},
{
"code": null,
"e": 1595,
"s": 1582,
"text": "HTTP-headers"
},
{
"code": null,
"e": 1602,
"s": 1595,
"text": "Picked"
},
{
"code": null,
"e": 1619,
"s": 1602,
"text": "Web Technologies"
}
] |
LINQ | How to find minimum value of the given sequence?
|
21 May, 2019
In LINQ, you can find the minimum element of the given sequence by using Min() function. This method provides the minimum element of the given set of values. It does not support query syntax in C#, but it supports in VB.NET. It is available in both Enumerable and Queryable classes in C#. It returns null if all the elements present in the collection are null. It returns any type of data type means you can also use Min with the collection of a custom type(does not contain numeric value), but for this, you have to implement the IComparable interface. It can work with nullable, non-nullable decimal, double, floats, int, etc. values.
Example 1:
// C# program to find minimum// value from the given arrayusing System;using System.Linq; class GFG { // Main Method static public void Main() { // Data source int[] sequence = {20, 45, 50, 79, 90, 79, 89, 100, 567, 29}; // Display the sequence Console.WriteLine("The sequence is: "); foreach(int s in sequence) { Console.WriteLine(s); } // Finding the minimum element // from the given sequence // Using Min function int result = sequence.Min(); Console.WriteLine("Minimum Value: {0}", result); }}
The sequence is:
20
45
50
79
90
79
89
100
567
29
Minimum Value: 20
Example 2:
// C# program to find the Minimum// salary of the employeeusing System;using System.Linq;using System.Collections.Generic; // Employee detailsclass Employee { public int emp_id { get; set; } public string emp_name { get; set; } public string emp_gender { get; set; } public string emp_hire_date { get; set; } public int emp_salary { get; set; }} class GFG { // Main method static public void Main() { List<Employee> emp = new List<Employee>() { new Employee() { emp_id = 209, emp_name = "Anjita", emp_gender = "Female", emp_hire_date = "12/3/2017", emp_salary = 20000 }, new Employee() { emp_id = 210, emp_name = "Soniya", emp_gender = "Female", emp_hire_date = "22/4/2018", emp_salary = 30000 }, new Employee() { emp_id = 211, emp_name = "Rohit", emp_gender = "Male", emp_hire_date = "3/5/2016", emp_salary = 40000 }, new Employee() { emp_id = 212, emp_name = "Supriya", emp_gender = "Female", emp_hire_date = "4/8/2017", emp_salary = 40000 }, new Employee() { emp_id = 213, emp_name = "Anil", emp_gender = "Male", emp_hire_date = "12/1/2016", emp_salary = 40000 }, new Employee() { emp_id = 214, emp_name = "Anju", emp_gender = "Female", emp_hire_date = "17/6/2015", emp_salary = 50000 }, }; // Find the minimum salary // of the employee // Using Min () method var res = emp.Min(a => a.emp_salary); Console.WriteLine("Minimum salary of the employee: {0}", res); }}
Minimum salary of the employee: 20000
CSharp LINQ
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 May, 2019"
},
{
"code": null,
"e": 665,
"s": 28,
"text": "In LINQ, you can find the minimum element of the given sequence by using Min() function. This method provides the minimum element of the given set of values. It does not support query syntax in C#, but it supports in VB.NET. It is available in both Enumerable and Queryable classes in C#. It returns null if all the elements present in the collection are null. It returns any type of data type means you can also use Min with the collection of a custom type(does not contain numeric value), but for this, you have to implement the IComparable interface. It can work with nullable, non-nullable decimal, double, floats, int, etc. values."
},
{
"code": null,
"e": 676,
"s": 665,
"text": "Example 1:"
},
{
"code": "// C# program to find minimum// value from the given arrayusing System;using System.Linq; class GFG { // Main Method static public void Main() { // Data source int[] sequence = {20, 45, 50, 79, 90, 79, 89, 100, 567, 29}; // Display the sequence Console.WriteLine(\"The sequence is: \"); foreach(int s in sequence) { Console.WriteLine(s); } // Finding the minimum element // from the given sequence // Using Min function int result = sequence.Min(); Console.WriteLine(\"Minimum Value: {0}\", result); }}",
"e": 1315,
"s": 676,
"text": null
},
{
"code": null,
"e": 1384,
"s": 1315,
"text": "The sequence is: \n20\n45\n50\n79\n90\n79\n89\n100\n567\n29\nMinimum Value: 20\n"
},
{
"code": null,
"e": 1395,
"s": 1384,
"text": "Example 2:"
},
{
"code": "// C# program to find the Minimum// salary of the employeeusing System;using System.Linq;using System.Collections.Generic; // Employee detailsclass Employee { public int emp_id { get; set; } public string emp_name { get; set; } public string emp_gender { get; set; } public string emp_hire_date { get; set; } public int emp_salary { get; set; }} class GFG { // Main method static public void Main() { List<Employee> emp = new List<Employee>() { new Employee() { emp_id = 209, emp_name = \"Anjita\", emp_gender = \"Female\", emp_hire_date = \"12/3/2017\", emp_salary = 20000 }, new Employee() { emp_id = 210, emp_name = \"Soniya\", emp_gender = \"Female\", emp_hire_date = \"22/4/2018\", emp_salary = 30000 }, new Employee() { emp_id = 211, emp_name = \"Rohit\", emp_gender = \"Male\", emp_hire_date = \"3/5/2016\", emp_salary = 40000 }, new Employee() { emp_id = 212, emp_name = \"Supriya\", emp_gender = \"Female\", emp_hire_date = \"4/8/2017\", emp_salary = 40000 }, new Employee() { emp_id = 213, emp_name = \"Anil\", emp_gender = \"Male\", emp_hire_date = \"12/1/2016\", emp_salary = 40000 }, new Employee() { emp_id = 214, emp_name = \"Anju\", emp_gender = \"Female\", emp_hire_date = \"17/6/2015\", emp_salary = 50000 }, }; // Find the minimum salary // of the employee // Using Min () method var res = emp.Min(a => a.emp_salary); Console.WriteLine(\"Minimum salary of the employee: {0}\", res); }}",
"e": 3033,
"s": 1395,
"text": null
},
{
"code": null,
"e": 3072,
"s": 3033,
"text": "Minimum salary of the employee: 20000\n"
},
{
"code": null,
"e": 3084,
"s": 3072,
"text": "CSharp LINQ"
},
{
"code": null,
"e": 3087,
"s": 3084,
"text": "C#"
}
] |
Python | Integer count in Mixed List
|
07 Feb, 2022
The lists in python can handle different type of data types in it. The manipulation of such lists is complicated. Sometimes we have a problem in which we need to find the count of integer values in which the list can contain string as a data type i.e heterogeneous. Let’s discuss certain ways in which this can be performed.Method #1 : Using list comprehension + len() + isinstance() This particular problem can be solved by filtering our search of len using the isinstance method, we can filter out the integer value and then can use len function to get required length value.
Python3
# Python3 code to demonstrate# Integer count in Mixed List# using list comprehension + len() + isinstance() # initializing listtest_list = [3, 'computer', 5, 'geeks', 6, 7] # printing original listprint ("The original list is : " + str(test_list)) # using list comprehension + len() + isinstance()# Integer count in Mixed Listres = len(list(i for i in test_list if isinstance(i, int))) # printing resultprint ("The length of integers in list is : " + str(res))
The original list is : [3, 'computer', 5, 'geeks', 6, 7]
The length of integers in list is : 4
Method #2 : Using lambda + map() + len() + isinstance() The above problem can also be solved using the lambda function as a map() in the len() along with the isinstance method which performs the task of checking for integer values.
Python3
# Python3 code to demonstrate# Integer count in Mixed List# using lambda + map() + len() + isinstance() # initializing listtest_list = [3, 'computer', 5, 'geeks', 6, 7] # printing original listprint ("The original list is : " + str(test_list)) # using lambda + map() + len() + isinstance()# Integer count in Mixed Listtemp = list(map(lambda i: isinstance(i, int), test_list))res = len([ele for ele in temp if ele]) # printing resultprint ("The length of integers in list is : " + str(res))
The original list is : [3, 'computer', 5, 'geeks', 6, 7]
The length of integers in list is : 4
saurabh1990aror
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Feb, 2022"
},
{
"code": null,
"e": 607,
"s": 28,
"text": "The lists in python can handle different type of data types in it. The manipulation of such lists is complicated. Sometimes we have a problem in which we need to find the count of integer values in which the list can contain string as a data type i.e heterogeneous. Let’s discuss certain ways in which this can be performed.Method #1 : Using list comprehension + len() + isinstance() This particular problem can be solved by filtering our search of len using the isinstance method, we can filter out the integer value and then can use len function to get required length value. "
},
{
"code": null,
"e": 615,
"s": 607,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate# Integer count in Mixed List# using list comprehension + len() + isinstance() # initializing listtest_list = [3, 'computer', 5, 'geeks', 6, 7] # printing original listprint (\"The original list is : \" + str(test_list)) # using list comprehension + len() + isinstance()# Integer count in Mixed Listres = len(list(i for i in test_list if isinstance(i, int))) # printing resultprint (\"The length of integers in list is : \" + str(res))",
"e": 1076,
"s": 615,
"text": null
},
{
"code": null,
"e": 1171,
"s": 1076,
"text": "The original list is : [3, 'computer', 5, 'geeks', 6, 7]\nThe length of integers in list is : 4"
},
{
"code": null,
"e": 1407,
"s": 1173,
"text": " Method #2 : Using lambda + map() + len() + isinstance() The above problem can also be solved using the lambda function as a map() in the len() along with the isinstance method which performs the task of checking for integer values. "
},
{
"code": null,
"e": 1415,
"s": 1407,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate# Integer count in Mixed List# using lambda + map() + len() + isinstance() # initializing listtest_list = [3, 'computer', 5, 'geeks', 6, 7] # printing original listprint (\"The original list is : \" + str(test_list)) # using lambda + map() + len() + isinstance()# Integer count in Mixed Listtemp = list(map(lambda i: isinstance(i, int), test_list))res = len([ele for ele in temp if ele]) # printing resultprint (\"The length of integers in list is : \" + str(res))",
"e": 1905,
"s": 1415,
"text": null
},
{
"code": null,
"e": 2000,
"s": 1905,
"text": "The original list is : [3, 'computer', 5, 'geeks', 6, 7]\nThe length of integers in list is : 4"
},
{
"code": null,
"e": 2018,
"s": 2002,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 2039,
"s": 2018,
"text": "Python list-programs"
},
{
"code": null,
"e": 2046,
"s": 2039,
"text": "Python"
},
{
"code": null,
"e": 2062,
"s": 2046,
"text": "Python Programs"
},
{
"code": null,
"e": 2160,
"s": 2062,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2178,
"s": 2160,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2220,
"s": 2178,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2242,
"s": 2220,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2268,
"s": 2242,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2300,
"s": 2268,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2322,
"s": 2300,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2361,
"s": 2322,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2399,
"s": 2361,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2436,
"s": 2399,
"text": "Python Program for Fibonacci numbers"
}
] |
How to Get a Comma Separated String From an Array in C#?
|
17 Jan, 2022
Given an array, now our task is to get a comma-separated string from the given array. So we can do this task using String.Join() method. This method concatenates the items of an array with the help of a comma separator between each item of the array.
Syntax:
String.Join(",", array_name)
Where array_name is the input array.
Example:
Input: {"sireesha", "priyank", "ojaswi", "gnanesh"}
Output: sireesha,priyank,ojaswi,gnanesh
Input: {"sireesha", "priyank"}
Output: sireesha,priyank
Approach 1:
Declare an array of strings.
Use the string join() function to get the comma separated strings.
String.Join(",", names)
Display the final result.
Example:
C#
// C# program to display the comma separated// string from an arrayusing System; class GFG{ public static void Main(){ // Creating an array of string elements String[] names = { "sireesha", "priyank", "ojaswi", "gnanesh" }; // Join the elements separated by comma // Using Join() method var str1 = String.Join(",", names); // Display the final string Console.WriteLine(str1);}}
Output:
sireesha,priyank,ojaswi,gnanesh
Approach 2:
We can also find the command-separated string from the object array.
Create a class named MyEmployee with First_Name and Last_Name methods.
Declare object array of MyEmployee in the main method.
Use string join() function to get the comma separated strings.
String.Join(",", e.Select(m => m.First_Name));
Here, we only join the first name so we use the select method to select the First_Name of the employees.
Display the final result.
Example 2:
C#
// C# program to display the comma separated// string from an arrayusing System;using System.Linq; // MyEmployee classclass MyEmployee{ public string First_Name { get; set; } public string Last_Name { get; set; }} class GFG{ public static void Main(){ // Creating object array of MyEmployee MyEmployee[] e = { new MyEmployee(){ First_Name = "Sumi", Last_Name = "Goyal" }, new MyEmployee(){ First_Name = "Mohan", Last_Name = "Priya" }, new MyEmployee(){ First_Name = "Sumit", Last_Name = "Singh" } }; // Join the elements separated by comma // Using Join() method var res = String.Join(",", e.Select(m => m.First_Name)); // Display the final result Console.WriteLine("Final String:" + res);}}
Output:
Final String:Sumi,Mohan,Sumit
saurabh1990aror
CSharp-Arrays-Programs
CSharp-Strings-Programs
Picked
C#
C# Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Jan, 2022"
},
{
"code": null,
"e": 279,
"s": 28,
"text": "Given an array, now our task is to get a comma-separated string from the given array. So we can do this task using String.Join() method. This method concatenates the items of an array with the help of a comma separator between each item of the array."
},
{
"code": null,
"e": 287,
"s": 279,
"text": "Syntax:"
},
{
"code": null,
"e": 316,
"s": 287,
"text": "String.Join(\",\", array_name)"
},
{
"code": null,
"e": 353,
"s": 316,
"text": "Where array_name is the input array."
},
{
"code": null,
"e": 362,
"s": 353,
"text": "Example:"
},
{
"code": null,
"e": 511,
"s": 362,
"text": "Input: {\"sireesha\", \"priyank\", \"ojaswi\", \"gnanesh\"}\nOutput: sireesha,priyank,ojaswi,gnanesh\n\nInput: {\"sireesha\", \"priyank\"}\nOutput: sireesha,priyank"
},
{
"code": null,
"e": 523,
"s": 511,
"text": "Approach 1:"
},
{
"code": null,
"e": 552,
"s": 523,
"text": "Declare an array of strings."
},
{
"code": null,
"e": 619,
"s": 552,
"text": "Use the string join() function to get the comma separated strings."
},
{
"code": null,
"e": 643,
"s": 619,
"text": "String.Join(\",\", names)"
},
{
"code": null,
"e": 669,
"s": 643,
"text": "Display the final result."
},
{
"code": null,
"e": 678,
"s": 669,
"text": "Example:"
},
{
"code": null,
"e": 681,
"s": 678,
"text": "C#"
},
{
"code": "// C# program to display the comma separated// string from an arrayusing System; class GFG{ public static void Main(){ // Creating an array of string elements String[] names = { \"sireesha\", \"priyank\", \"ojaswi\", \"gnanesh\" }; // Join the elements separated by comma // Using Join() method var str1 = String.Join(\",\", names); // Display the final string Console.WriteLine(str1);}}",
"e": 1136,
"s": 681,
"text": null
},
{
"code": null,
"e": 1145,
"s": 1136,
"text": " Output:"
},
{
"code": null,
"e": 1177,
"s": 1145,
"text": "sireesha,priyank,ojaswi,gnanesh"
},
{
"code": null,
"e": 1189,
"s": 1177,
"text": "Approach 2:"
},
{
"code": null,
"e": 1258,
"s": 1189,
"text": "We can also find the command-separated string from the object array."
},
{
"code": null,
"e": 1329,
"s": 1258,
"text": "Create a class named MyEmployee with First_Name and Last_Name methods."
},
{
"code": null,
"e": 1384,
"s": 1329,
"text": "Declare object array of MyEmployee in the main method."
},
{
"code": null,
"e": 1447,
"s": 1384,
"text": "Use string join() function to get the comma separated strings."
},
{
"code": null,
"e": 1494,
"s": 1447,
"text": "String.Join(\",\", e.Select(m => m.First_Name));"
},
{
"code": null,
"e": 1599,
"s": 1494,
"text": "Here, we only join the first name so we use the select method to select the First_Name of the employees."
},
{
"code": null,
"e": 1625,
"s": 1599,
"text": "Display the final result."
},
{
"code": null,
"e": 1636,
"s": 1625,
"text": "Example 2:"
},
{
"code": null,
"e": 1639,
"s": 1636,
"text": "C#"
},
{
"code": "// C# program to display the comma separated// string from an arrayusing System;using System.Linq; // MyEmployee classclass MyEmployee{ public string First_Name { get; set; } public string Last_Name { get; set; }} class GFG{ public static void Main(){ // Creating object array of MyEmployee MyEmployee[] e = { new MyEmployee(){ First_Name = \"Sumi\", Last_Name = \"Goyal\" }, new MyEmployee(){ First_Name = \"Mohan\", Last_Name = \"Priya\" }, new MyEmployee(){ First_Name = \"Sumit\", Last_Name = \"Singh\" } }; // Join the elements separated by comma // Using Join() method var res = String.Join(\",\", e.Select(m => m.First_Name)); // Display the final result Console.WriteLine(\"Final String:\" + res);}}",
"e": 2397,
"s": 1639,
"text": null
},
{
"code": null,
"e": 2405,
"s": 2397,
"text": "Output:"
},
{
"code": null,
"e": 2435,
"s": 2405,
"text": "Final String:Sumi,Mohan,Sumit"
},
{
"code": null,
"e": 2451,
"s": 2435,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 2474,
"s": 2451,
"text": "CSharp-Arrays-Programs"
},
{
"code": null,
"e": 2498,
"s": 2474,
"text": "CSharp-Strings-Programs"
},
{
"code": null,
"e": 2505,
"s": 2498,
"text": "Picked"
},
{
"code": null,
"e": 2508,
"s": 2505,
"text": "C#"
},
{
"code": null,
"e": 2520,
"s": 2508,
"text": "C# Programs"
}
] |
Determining the Number of Clusters in Data Mining
|
13 Feb, 2022
In Clustering algorithms like K-Means clustering, we have to determine the right number of clusters for our dataset. This ensures that the data is properly and efficiently divided. An appropriate value of ‘k’ i.e. the number of clusters helps in ensuring proper granularity of clusters and helps in maintaining a good balance between compressibility and accuracy of clusters.
Let us consider two cases:
Case 1: Treat the entire dataset as one cluster
Case 2: Treat each data point as a cluster
This will give the most accurate clustering because of the zero distance between the data point and its corresponding cluster center. But, this will not help in predicting new inputs. It will not enable any kind of data summarization.
So, we can conclude that it is very important to determine the ‘right’ number of clusters for any dataset. This is a challenging task but very approachable if we depend on the shape and scaling of the data distribution. A simple method to calculate the number of clusters is to set the value to about √(n/2) for a dataset of ‘n’ points. In the rest of the article, two methods have been described and implemented in Python for determining the number of clusters in data mining.
This method is based on the observation that increasing the number of clusters can help in reducing the sum of the within-cluster variance of each cluster. Having more clusters allows one to extract finer groups of data objects that are more similar to each other. For choosing the ‘right’ number of clusters, the turning point of the curve of the sum of within-cluster variances with respect to the number of clusters is used. The first turning point of the curve suggests the right value of ‘k’ for any k > 0. Let us implement the elbow method in Python.
Step 1: Importing the libraries
Python3
# importing the librariesimport pandas as pdimport matplotlib.pyplot as pltfrom sklearn.cluster import KMeans
Step 2: Loading the dataset
We have used the Mall Customer dataset which can be found on this link.
Python3
# loading the datasetdataset = pd.read_csv('Mall_Customers.csv') # printing first five rows of the datasetprint(dataset.head(5))
Output:
First five rows of the dataset
Step 3: Checking for any null values
The dataset has 200 rows and 5 columns. It has no null values.
Python3
# printing the shape of datasetprint(dataset.shape) # checking for any# null values presentprint(dataset.isnull().sum())
Output:
Shape of the dataset along with count of null values
Step 4: Extracting 2 columns from the dataset for clustering
Let us extract two columns namely ‘Annual Income (k$)’ and ‘Spending Score (1-100)’ for further process.
Python3
# extracting values from two# columns for clusteringdataset_new = dataset[['Annual Income (k$)', 'Spending Score (1-100)']].values
Step 5: Determining the number of clusters using the elbow method and plotting the graph
Python3
# determining the maximum number of clusters# using the simple methodlimit = int((dataset_new.shape[0]//2)**0.5) # selecting optimal value of 'k'# using elbow method # wcss - within cluster sum of# squared distanceswcss = {} for k in range(2,limit+1): model = KMeans(n_clusters=k) model.fit(dataset_new) wcss[k] = model.inertia_ # plotting the wcss values# to find out the elbow valueplt.plot(wcss.keys(), wcss.values(), 'gs-')plt.xlabel('Values of "k"')plt.ylabel('WCSS')plt.show()
Output:
Plot of Elbow Method
Through the above plot, we can observe that the turning point of this curve is at the value of k = 5. Therefore, we can say that the ‘right’ number of clusters for this data is 5.
Silhouette score is used to evaluate the quality of clusters created using clustering algorithms such as K-Means in terms of how well data points are clustered with other data points that are similar to each other. This method can be used to find the optimal value of ‘k’. This score is within the range of [-1,1]. The value of ‘k’ having the silhouette score nearer to 1 can be considered as the ‘right’ number of clusters. sklearn.metrics.silhouette _score() is used to find the score in Python. Let us implement this for the same dataset used in elbow method.
Step 1: Importing libraries
Python3
# importing the librariesimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom sklearn.cluster import KMeansfrom sklearn.metrics import silhouette_score
Step 2: Loading the dataset
We have used the Mall Customer dataset.
Python3
# loading the datasetdataset = pd.read_csv('Mall_Customers.csv') # printing first five rows of the datasetprint(dataset.head(5))
Output:
First five rows of the dataset
Step 3: Checking for any null values
The dataset has 200 rows and 5 columns. It has no null values.
Python3
# printing the shape of datasetprint(dataset.shape) # checking for any# null values presentprint(dataset.isnull().sum())
Output:
Shape of the dataset along with count of null values
Step 4: Extracting 2 columns from the dataset for clustering
Let us extract two columns namely ‘Annual Income (k$)’ and ‘Spending Score (1-100)’ for further process.
Python3
# extracting values from two# columns for clusteringdataset_new = dataset[['Annual Income (k$)', 'Spending Score (1-100)']].values
Step 5: Determining the number of clusters using silhouette score
The minimum number of clusters required for calculating silhouette score is 2. So the loop starts from 2.
Python3
# determining the maximum number of clusters# using the simple methodlimit = int((dataset_new.shape[0]//2)**0.5) # determining number of clusters# using silhouette score methodfor k in range(2, limit+1): model = KMeans(n_clusters=k) model.fit(dataset_new) pred = model.predict(dataset_new) score = silhouette_score(dataset_new, pred) print('Silhouette Score for k = {}: {:<.3f}'.format(k, score))
Silhouette scores for k = [2,..,10]
As we can observe, the value of k = 5 has the highest value i.e. nearest to +1. So, we can say that the optimal value of ‘k’ is 5.
Now, we have rightly determined and validated the number of clusters for the Mall Customer Dataset using two methods – elbow method and silhouette score. In both the cases, k = 5. Let us now perform KMeans clustering on the dataset and plot the clusters.
Python3
# clustering the data using Kmeans# using k = 5model = KMeans(n_clusters=5) # predicting the clusterspred = model.fit_predict(dataset_new) # plotting all the clusterscolours = ['red', 'blue', 'green', 'yellow', 'orange'] for i in np.unique(model.labels_): plt.scatter(dataset_new[pred==i, 0], dataset_new[pred==i, 1], c = colours[i]) # plotting the cluster centroidsplt.scatter(model.cluster_centers_[:, 0], model.cluster_centers_[:, 1], s = 200, # marker size c = 'black') plt.title('K Means clustering')plt.xlabel('Annual Income (k$)')plt.ylabel('Spending Score (1-100)')plt.show()
Final Clusters so formed
From the above plot, we can see that five efficient clusters have been formed which are clearly separable from each other. The cluster centroids are also visible in black color.
simranarora5sos
Picked
Python-pandas
Data Mining
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Feb, 2022"
},
{
"code": null,
"e": 404,
"s": 28,
"text": "In Clustering algorithms like K-Means clustering, we have to determine the right number of clusters for our dataset. This ensures that the data is properly and efficiently divided. An appropriate value of ‘k’ i.e. the number of clusters helps in ensuring proper granularity of clusters and helps in maintaining a good balance between compressibility and accuracy of clusters."
},
{
"code": null,
"e": 431,
"s": 404,
"text": "Let us consider two cases:"
},
{
"code": null,
"e": 522,
"s": 431,
"text": "Case 1: Treat the entire dataset as one cluster\nCase 2: Treat each data point as a cluster"
},
{
"code": null,
"e": 757,
"s": 522,
"text": "This will give the most accurate clustering because of the zero distance between the data point and its corresponding cluster center. But, this will not help in predicting new inputs. It will not enable any kind of data summarization."
},
{
"code": null,
"e": 1235,
"s": 757,
"text": "So, we can conclude that it is very important to determine the ‘right’ number of clusters for any dataset. This is a challenging task but very approachable if we depend on the shape and scaling of the data distribution. A simple method to calculate the number of clusters is to set the value to about √(n/2) for a dataset of ‘n’ points. In the rest of the article, two methods have been described and implemented in Python for determining the number of clusters in data mining."
},
{
"code": null,
"e": 1792,
"s": 1235,
"text": "This method is based on the observation that increasing the number of clusters can help in reducing the sum of the within-cluster variance of each cluster. Having more clusters allows one to extract finer groups of data objects that are more similar to each other. For choosing the ‘right’ number of clusters, the turning point of the curve of the sum of within-cluster variances with respect to the number of clusters is used. The first turning point of the curve suggests the right value of ‘k’ for any k > 0. Let us implement the elbow method in Python."
},
{
"code": null,
"e": 1824,
"s": 1792,
"text": "Step 1: Importing the libraries"
},
{
"code": null,
"e": 1832,
"s": 1824,
"text": "Python3"
},
{
"code": "# importing the librariesimport pandas as pdimport matplotlib.pyplot as pltfrom sklearn.cluster import KMeans",
"e": 1942,
"s": 1832,
"text": null
},
{
"code": null,
"e": 1974,
"s": 1946,
"text": "Step 2: Loading the dataset"
},
{
"code": null,
"e": 2048,
"s": 1976,
"text": "We have used the Mall Customer dataset which can be found on this link."
},
{
"code": null,
"e": 2058,
"s": 2050,
"text": "Python3"
},
{
"code": "# loading the datasetdataset = pd.read_csv('Mall_Customers.csv') # printing first five rows of the datasetprint(dataset.head(5))",
"e": 2187,
"s": 2058,
"text": null
},
{
"code": null,
"e": 2199,
"s": 2191,
"text": "Output:"
},
{
"code": null,
"e": 2232,
"s": 2201,
"text": "First five rows of the dataset"
},
{
"code": null,
"e": 2271,
"s": 2234,
"text": "Step 3: Checking for any null values"
},
{
"code": null,
"e": 2336,
"s": 2273,
"text": "The dataset has 200 rows and 5 columns. It has no null values."
},
{
"code": null,
"e": 2346,
"s": 2338,
"text": "Python3"
},
{
"code": "# printing the shape of datasetprint(dataset.shape) # checking for any# null values presentprint(dataset.isnull().sum())",
"e": 2467,
"s": 2346,
"text": null
},
{
"code": null,
"e": 2479,
"s": 2471,
"text": "Output:"
},
{
"code": null,
"e": 2534,
"s": 2481,
"text": "Shape of the dataset along with count of null values"
},
{
"code": null,
"e": 2597,
"s": 2536,
"text": "Step 4: Extracting 2 columns from the dataset for clustering"
},
{
"code": null,
"e": 2704,
"s": 2599,
"text": "Let us extract two columns namely ‘Annual Income (k$)’ and ‘Spending Score (1-100)’ for further process."
},
{
"code": null,
"e": 2714,
"s": 2706,
"text": "Python3"
},
{
"code": "# extracting values from two# columns for clusteringdataset_new = dataset[['Annual Income (k$)', 'Spending Score (1-100)']].values",
"e": 2867,
"s": 2714,
"text": null
},
{
"code": null,
"e": 2960,
"s": 2871,
"text": "Step 5: Determining the number of clusters using the elbow method and plotting the graph"
},
{
"code": null,
"e": 2970,
"s": 2962,
"text": "Python3"
},
{
"code": "# determining the maximum number of clusters# using the simple methodlimit = int((dataset_new.shape[0]//2)**0.5) # selecting optimal value of 'k'# using elbow method # wcss - within cluster sum of# squared distanceswcss = {} for k in range(2,limit+1): model = KMeans(n_clusters=k) model.fit(dataset_new) wcss[k] = model.inertia_ # plotting the wcss values# to find out the elbow valueplt.plot(wcss.keys(), wcss.values(), 'gs-')plt.xlabel('Values of \"k\"')plt.ylabel('WCSS')plt.show()",
"e": 3466,
"s": 2970,
"text": null
},
{
"code": null,
"e": 3474,
"s": 3466,
"text": "Output:"
},
{
"code": null,
"e": 3495,
"s": 3474,
"text": "Plot of Elbow Method"
},
{
"code": null,
"e": 3675,
"s": 3495,
"text": "Through the above plot, we can observe that the turning point of this curve is at the value of k = 5. Therefore, we can say that the ‘right’ number of clusters for this data is 5."
},
{
"code": null,
"e": 4238,
"s": 3675,
"text": "Silhouette score is used to evaluate the quality of clusters created using clustering algorithms such as K-Means in terms of how well data points are clustered with other data points that are similar to each other. This method can be used to find the optimal value of ‘k’. This score is within the range of [-1,1]. The value of ‘k’ having the silhouette score nearer to 1 can be considered as the ‘right’ number of clusters. sklearn.metrics.silhouette _score() is used to find the score in Python. Let us implement this for the same dataset used in elbow method."
},
{
"code": null,
"e": 4266,
"s": 4238,
"text": "Step 1: Importing libraries"
},
{
"code": null,
"e": 4274,
"s": 4266,
"text": "Python3"
},
{
"code": "# importing the librariesimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom sklearn.cluster import KMeansfrom sklearn.metrics import silhouette_score",
"e": 4446,
"s": 4274,
"text": null
},
{
"code": null,
"e": 4478,
"s": 4450,
"text": "Step 2: Loading the dataset"
},
{
"code": null,
"e": 4520,
"s": 4480,
"text": "We have used the Mall Customer dataset."
},
{
"code": null,
"e": 4530,
"s": 4522,
"text": "Python3"
},
{
"code": "# loading the datasetdataset = pd.read_csv('Mall_Customers.csv') # printing first five rows of the datasetprint(dataset.head(5))",
"e": 4659,
"s": 4530,
"text": null
},
{
"code": null,
"e": 4671,
"s": 4663,
"text": "Output:"
},
{
"code": null,
"e": 4704,
"s": 4673,
"text": "First five rows of the dataset"
},
{
"code": null,
"e": 4743,
"s": 4706,
"text": "Step 3: Checking for any null values"
},
{
"code": null,
"e": 4808,
"s": 4745,
"text": "The dataset has 200 rows and 5 columns. It has no null values."
},
{
"code": null,
"e": 4818,
"s": 4810,
"text": "Python3"
},
{
"code": "# printing the shape of datasetprint(dataset.shape) # checking for any# null values presentprint(dataset.isnull().sum())",
"e": 4939,
"s": 4818,
"text": null
},
{
"code": null,
"e": 4951,
"s": 4943,
"text": "Output:"
},
{
"code": null,
"e": 5006,
"s": 4953,
"text": "Shape of the dataset along with count of null values"
},
{
"code": null,
"e": 5069,
"s": 5008,
"text": "Step 4: Extracting 2 columns from the dataset for clustering"
},
{
"code": null,
"e": 5176,
"s": 5071,
"text": "Let us extract two columns namely ‘Annual Income (k$)’ and ‘Spending Score (1-100)’ for further process."
},
{
"code": null,
"e": 5186,
"s": 5178,
"text": "Python3"
},
{
"code": "# extracting values from two# columns for clusteringdataset_new = dataset[['Annual Income (k$)', 'Spending Score (1-100)']].values",
"e": 5339,
"s": 5186,
"text": null
},
{
"code": null,
"e": 5409,
"s": 5343,
"text": "Step 5: Determining the number of clusters using silhouette score"
},
{
"code": null,
"e": 5517,
"s": 5411,
"text": "The minimum number of clusters required for calculating silhouette score is 2. So the loop starts from 2."
},
{
"code": null,
"e": 5527,
"s": 5519,
"text": "Python3"
},
{
"code": "# determining the maximum number of clusters# using the simple methodlimit = int((dataset_new.shape[0]//2)**0.5) # determining number of clusters# using silhouette score methodfor k in range(2, limit+1): model = KMeans(n_clusters=k) model.fit(dataset_new) pred = model.predict(dataset_new) score = silhouette_score(dataset_new, pred) print('Silhouette Score for k = {}: {:<.3f}'.format(k, score))",
"e": 5939,
"s": 5527,
"text": null
},
{
"code": null,
"e": 5978,
"s": 5942,
"text": "Silhouette scores for k = [2,..,10]"
},
{
"code": null,
"e": 6111,
"s": 5980,
"text": "As we can observe, the value of k = 5 has the highest value i.e. nearest to +1. So, we can say that the optimal value of ‘k’ is 5."
},
{
"code": null,
"e": 6368,
"s": 6113,
"text": "Now, we have rightly determined and validated the number of clusters for the Mall Customer Dataset using two methods – elbow method and silhouette score. In both the cases, k = 5. Let us now perform KMeans clustering on the dataset and plot the clusters."
},
{
"code": null,
"e": 6378,
"s": 6370,
"text": "Python3"
},
{
"code": "# clustering the data using Kmeans# using k = 5model = KMeans(n_clusters=5) # predicting the clusterspred = model.fit_predict(dataset_new) # plotting all the clusterscolours = ['red', 'blue', 'green', 'yellow', 'orange'] for i in np.unique(model.labels_): plt.scatter(dataset_new[pred==i, 0], dataset_new[pred==i, 1], c = colours[i]) # plotting the cluster centroidsplt.scatter(model.cluster_centers_[:, 0], model.cluster_centers_[:, 1], s = 200, # marker size c = 'black') plt.title('K Means clustering')plt.xlabel('Annual Income (k$)')plt.ylabel('Spending Score (1-100)')plt.show()",
"e": 7033,
"s": 6378,
"text": null
},
{
"code": null,
"e": 7061,
"s": 7036,
"text": "Final Clusters so formed"
},
{
"code": null,
"e": 7241,
"s": 7063,
"text": "From the above plot, we can see that five efficient clusters have been formed which are clearly separable from each other. The cluster centroids are also visible in black color."
},
{
"code": null,
"e": 7259,
"s": 7243,
"text": "simranarora5sos"
},
{
"code": null,
"e": 7266,
"s": 7259,
"text": "Picked"
},
{
"code": null,
"e": 7280,
"s": 7266,
"text": "Python-pandas"
},
{
"code": null,
"e": 7292,
"s": 7280,
"text": "Data Mining"
},
{
"code": null,
"e": 7299,
"s": 7292,
"text": "Python"
}
] |
Python | grid() method in Tkinter
|
21 Apr, 2022
The Grid geometry manager puts the widgets in a 2-dimensional table. The master widget is split into a number of rows and columns, and each “cell” in the resulting table can hold a widget. The grid manager is the most flexible of the geometry managers in Tkinter. If you don’t want to learn how and when to use all three managers, you should at least make sure to learn this one. Consider the following example –
Creating this layout using the pack manager is possible, but it takes a number of extra frame widgets, and a lot of work to make things look good. If you use the grid manager instead, you only need one call per widget to get everything laid out properly. Using the grid manager is easy. Just create the widgets, and use the grid method to tell the manager in which row and column to place them. You don’t have to specify the size of the grid beforehand; the manager automatically determines that from the widgets in it.
Code #1:
Python3
# import tkinter modulefrom tkinter import * from tkinter.ttk import * # creating main tkinter window/toplevelmaster = Tk() # this will create a label widgetl1 = Label(master, text = "First:")l2 = Label(master, text = "Second:") # grid method to arrange labels in respective# rows and columns as specifiedl1.grid(row = 0, column = 0, sticky = W, pady = 2)l2.grid(row = 1, column = 0, sticky = W, pady = 2) # entry widgets, used to take entry from usere1 = Entry(master)e2 = Entry(master) # this will arrange entry widgetse1.grid(row = 0, column = 1, pady = 2)e2.grid(row = 1, column = 1, pady = 2) # infinite loop which can be terminated by keyboard# or mouse interruptmainloop()
Output:
Code #2: Creating the layout which is shown above.
Python3
# import tkinter modulefrom tkinter import * from tkinter.ttk import * # creating main tkinter window/toplevelmaster = Tk() # this will create a label widgetl1 = Label(master, text = "Height")l2 = Label(master, text = "Width") # grid method to arrange labels in respective# rows and columns as specifiedl1.grid(row = 0, column = 0, sticky = W, pady = 2)l2.grid(row = 1, column = 0, sticky = W, pady = 2) # entry widgets, used to take entry from usere1 = Entry(master)e2 = Entry(master) # this will arrange entry widgetse1.grid(row = 0, column = 1, pady = 2)e2.grid(row = 1, column = 1, pady = 2) # checkbutton widgetc1 = Checkbutton(master, text = "Preserve")c1.grid(row = 2, column = 0, sticky = W, columnspan = 2) # adding image (remember image should be PNG and not JPG)img = PhotoImage(file = r"C:\Users\Admin\Pictures\capture1.png")img1 = img.subsample(2, 2) # setting image with the help of labelLabel(master, image = img1).grid(row = 0, column = 2, columnspan = 2, rowspan = 2, padx = 5, pady = 5) # button widgetb1 = Button(master, text = "Zoom in")b2 = Button(master, text = "Zoom out") # arranging button widgetsb1.grid(row = 2, column = 2, sticky = E)b2.grid(row = 2, column = 3, sticky = E) # infinite loop which can be terminated# by keyboard or mouse interruptmainloop()
Output:
Warning: Never mix grid() and pack() in the same master window.
simmytarika5
Python-gui
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n21 Apr, 2022"
},
{
"code": null,
"e": 468,
"s": 53,
"text": "The Grid geometry manager puts the widgets in a 2-dimensional table. The master widget is split into a number of rows and columns, and each “cell” in the resulting table can hold a widget. The grid manager is the most flexible of the geometry managers in Tkinter. If you don’t want to learn how and when to use all three managers, you should at least make sure to learn this one. Consider the following example – "
},
{
"code": null,
"e": 989,
"s": 468,
"text": "Creating this layout using the pack manager is possible, but it takes a number of extra frame widgets, and a lot of work to make things look good. If you use the grid manager instead, you only need one call per widget to get everything laid out properly. Using the grid manager is easy. Just create the widgets, and use the grid method to tell the manager in which row and column to place them. You don’t have to specify the size of the grid beforehand; the manager automatically determines that from the widgets in it. "
},
{
"code": null,
"e": 999,
"s": 989,
"text": "Code #1: "
},
{
"code": null,
"e": 1007,
"s": 999,
"text": "Python3"
},
{
"code": "# import tkinter modulefrom tkinter import * from tkinter.ttk import * # creating main tkinter window/toplevelmaster = Tk() # this will create a label widgetl1 = Label(master, text = \"First:\")l2 = Label(master, text = \"Second:\") # grid method to arrange labels in respective# rows and columns as specifiedl1.grid(row = 0, column = 0, sticky = W, pady = 2)l2.grid(row = 1, column = 0, sticky = W, pady = 2) # entry widgets, used to take entry from usere1 = Entry(master)e2 = Entry(master) # this will arrange entry widgetse1.grid(row = 0, column = 1, pady = 2)e2.grid(row = 1, column = 1, pady = 2) # infinite loop which can be terminated by keyboard# or mouse interruptmainloop()",
"e": 1687,
"s": 1007,
"text": null
},
{
"code": null,
"e": 1695,
"s": 1687,
"text": "Output:"
},
{
"code": null,
"e": 1752,
"s": 1700,
"text": "Code #2: Creating the layout which is shown above. "
},
{
"code": null,
"e": 1760,
"s": 1752,
"text": "Python3"
},
{
"code": "# import tkinter modulefrom tkinter import * from tkinter.ttk import * # creating main tkinter window/toplevelmaster = Tk() # this will create a label widgetl1 = Label(master, text = \"Height\")l2 = Label(master, text = \"Width\") # grid method to arrange labels in respective# rows and columns as specifiedl1.grid(row = 0, column = 0, sticky = W, pady = 2)l2.grid(row = 1, column = 0, sticky = W, pady = 2) # entry widgets, used to take entry from usere1 = Entry(master)e2 = Entry(master) # this will arrange entry widgetse1.grid(row = 0, column = 1, pady = 2)e2.grid(row = 1, column = 1, pady = 2) # checkbutton widgetc1 = Checkbutton(master, text = \"Preserve\")c1.grid(row = 2, column = 0, sticky = W, columnspan = 2) # adding image (remember image should be PNG and not JPG)img = PhotoImage(file = r\"C:\\Users\\Admin\\Pictures\\capture1.png\")img1 = img.subsample(2, 2) # setting image with the help of labelLabel(master, image = img1).grid(row = 0, column = 2, columnspan = 2, rowspan = 2, padx = 5, pady = 5) # button widgetb1 = Button(master, text = \"Zoom in\")b2 = Button(master, text = \"Zoom out\") # arranging button widgetsb1.grid(row = 2, column = 2, sticky = E)b2.grid(row = 2, column = 3, sticky = E) # infinite loop which can be terminated# by keyboard or mouse interruptmainloop()",
"e": 3051,
"s": 1760,
"text": null
},
{
"code": null,
"e": 3059,
"s": 3051,
"text": "Output:"
},
{
"code": null,
"e": 3126,
"s": 3062,
"text": "Warning: Never mix grid() and pack() in the same master window."
},
{
"code": null,
"e": 3139,
"s": 3126,
"text": "simmytarika5"
},
{
"code": null,
"e": 3150,
"s": 3139,
"text": "Python-gui"
},
{
"code": null,
"e": 3165,
"s": 3150,
"text": "Python-tkinter"
},
{
"code": null,
"e": 3172,
"s": 3165,
"text": "Python"
}
] |
How to Create Image Accordion using HTML and CSS ?
|
16 Dec, 2021
In this article, we will see how to create an image accordion using HTML & CSS that is basically used for advertising purposes on e-commerce websites. An Accordion is often used to open the multiple sections with full width & also content pushes the page content downward.
Approach:
Create an HTML file in which will contain the different types of images for advertisement.
Create a CSS style that will provide some animation effects to the web page elements.
HTML Code:
Create an HTML file, named index.html, that contains a title to our webpage using the <title> tag. It should be placed inside the <head> tag.
Link the CSS file that provides all the animation’s effects to our HTML. This is also placed inside the <head> tag.
In the body section, create a class main_box that has the corresponding div classes containing the different advertisements images.
HTML
<!DOCTYPE html><html lang="en"> <head> <link rel="stylesheet" href="style.css"> </head> <body> <div class="main_box"> <div class="img img1"> <p>gfg 1</p> </div> <div class="img img2"> <p>gfg 2</p> </div> <div class="img img3"> <p>gfg 3</p> </div> <div class="img img4"> <p>gfg 4</p> </div> </div></body> </html>
CSS Code: CSS is used to provide the different types of animations and effects to our HTML page so that it looks interactive to all users. In CSS, we will note the following points:
Restore all the browser effects.
Use classes and ids to give effects to HTML elements.
Use of :hover to use hover effects.
CSS
/* Restoring browser properties */*{ margin: 0; padding: 0; box-sizing: border-box; color: white;} body { background-color: rgb(0, 0, 0); height: 100vh; display: flex; justify-content: center; align-items: center;} .main_box { width: 90%; height: 80vh; display: flex;} .img { flex: 1; height: 100%; transform: skew(10deg); cursor: pointer; margin: 0 0.125em; transition: all .3s; background-repeat: no-repeat; background-size: cover; background-position: center; border: 1px solid pink; position: relative;} p { position: absolute; bottom: 0; left: 0; padding: .75em; background-color: rgba(0,0,0,0.6); transform: rotate(-90deg); transform-origin: 0% 0%; transition: all 0.3s; text-transform: uppercase; white-space: nowrap;} .img1 { background-image: url(https://media.geeksforgeeks.org/wp-content/uploads/20211216100749/GFG1.jpg);} .img2 { background-image: url(https://media.geeksforgeeks.org/wp-content/uploads/20211216100751/GFG2.png);} .img3 { background-image: url(https://media.geeksforgeeks.org/wp-content/uploads/20211216100753/GFG3.jpg);} .img4 { background-image: url(https://media.geeksforgeeks.org/wp-content/uploads/20211216100754/GFG4.jpg);} .main_box:hover .img { transform: skew(0);} .img:hover { flex: 5;} .img:hover p { background-color: transparent; border: .125em solid blue; color: rgb(255, 38, 0); transform: rotate(0deg);}
Output: In this way, you can create your own advertisement section!.
Image Accordion
bhaskargeeksforgeeks
CSS-Questions
HTML-Questions
CSS
HTML
Technical Scripter
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n16 Dec, 2021"
},
{
"code": null,
"e": 327,
"s": 54,
"text": "In this article, we will see how to create an image accordion using HTML & CSS that is basically used for advertising purposes on e-commerce websites. An Accordion is often used to open the multiple sections with full width & also content pushes the page content downward."
},
{
"code": null,
"e": 337,
"s": 327,
"text": "Approach:"
},
{
"code": null,
"e": 428,
"s": 337,
"text": "Create an HTML file in which will contain the different types of images for advertisement."
},
{
"code": null,
"e": 514,
"s": 428,
"text": "Create a CSS style that will provide some animation effects to the web page elements."
},
{
"code": null,
"e": 525,
"s": 514,
"text": "HTML Code:"
},
{
"code": null,
"e": 667,
"s": 525,
"text": "Create an HTML file, named index.html, that contains a title to our webpage using the <title> tag. It should be placed inside the <head> tag."
},
{
"code": null,
"e": 783,
"s": 667,
"text": "Link the CSS file that provides all the animation’s effects to our HTML. This is also placed inside the <head> tag."
},
{
"code": null,
"e": 915,
"s": 783,
"text": "In the body section, create a class main_box that has the corresponding div classes containing the different advertisements images."
},
{
"code": null,
"e": 920,
"s": 915,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <link rel=\"stylesheet\" href=\"style.css\"> </head> <body> <div class=\"main_box\"> <div class=\"img img1\"> <p>gfg 1</p> </div> <div class=\"img img2\"> <p>gfg 2</p> </div> <div class=\"img img3\"> <p>gfg 3</p> </div> <div class=\"img img4\"> <p>gfg 4</p> </div> </div></body> </html>",
"e": 1349,
"s": 920,
"text": null
},
{
"code": null,
"e": 1531,
"s": 1349,
"text": "CSS Code: CSS is used to provide the different types of animations and effects to our HTML page so that it looks interactive to all users. In CSS, we will note the following points:"
},
{
"code": null,
"e": 1564,
"s": 1531,
"text": "Restore all the browser effects."
},
{
"code": null,
"e": 1618,
"s": 1564,
"text": "Use classes and ids to give effects to HTML elements."
},
{
"code": null,
"e": 1654,
"s": 1618,
"text": "Use of :hover to use hover effects."
},
{
"code": null,
"e": 1658,
"s": 1654,
"text": "CSS"
},
{
"code": "/* Restoring browser properties */*{ margin: 0; padding: 0; box-sizing: border-box; color: white;} body { background-color: rgb(0, 0, 0); height: 100vh; display: flex; justify-content: center; align-items: center;} .main_box { width: 90%; height: 80vh; display: flex;} .img { flex: 1; height: 100%; transform: skew(10deg); cursor: pointer; margin: 0 0.125em; transition: all .3s; background-repeat: no-repeat; background-size: cover; background-position: center; border: 1px solid pink; position: relative;} p { position: absolute; bottom: 0; left: 0; padding: .75em; background-color: rgba(0,0,0,0.6); transform: rotate(-90deg); transform-origin: 0% 0%; transition: all 0.3s; text-transform: uppercase; white-space: nowrap;} .img1 { background-image: url(https://media.geeksforgeeks.org/wp-content/uploads/20211216100749/GFG1.jpg);} .img2 { background-image: url(https://media.geeksforgeeks.org/wp-content/uploads/20211216100751/GFG2.png);} .img3 { background-image: url(https://media.geeksforgeeks.org/wp-content/uploads/20211216100753/GFG3.jpg);} .img4 { background-image: url(https://media.geeksforgeeks.org/wp-content/uploads/20211216100754/GFG4.jpg);} .main_box:hover .img { transform: skew(0);} .img:hover { flex: 5;} .img:hover p { background-color: transparent; border: .125em solid blue; color: rgb(255, 38, 0); transform: rotate(0deg);}",
"e": 3135,
"s": 1658,
"text": null
},
{
"code": null,
"e": 3205,
"s": 3135,
"text": " Output: In this way, you can create your own advertisement section!."
},
{
"code": null,
"e": 3222,
"s": 3205,
"text": "Image Accordion "
},
{
"code": null,
"e": 3243,
"s": 3222,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 3257,
"s": 3243,
"text": "CSS-Questions"
},
{
"code": null,
"e": 3272,
"s": 3257,
"text": "HTML-Questions"
},
{
"code": null,
"e": 3276,
"s": 3272,
"text": "CSS"
},
{
"code": null,
"e": 3281,
"s": 3276,
"text": "HTML"
},
{
"code": null,
"e": 3300,
"s": 3281,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3317,
"s": 3300,
"text": "Web Technologies"
},
{
"code": null,
"e": 3322,
"s": 3317,
"text": "HTML"
}
] |
Python | Printing list vertically
|
22 Jan, 2019
Printing the list has been dealt many times. But sometimes we need a different format to get the output of list. This also has application in getting a transpose of matrix. Printing list vertically also has application in web development. Lets discuss certain ways in which this task can be achieved.
Method #1 : Using Naive MethodThe naive method can be used to print the list vertically vis. using the loops and printing each index element of each list successively will help us achieve this task.
# Python3 code to demonstrate # Vertical list print # using naive method # initializing list test_list = [[1, 4, 5], [4, 6, 8], [8, 3, 10]] # printing original listprint ("The original list is : " + str(test_list)) # using naive method # to print list verticallyfor i in range(len(test_list)): for x in test_list: print(x[i], end =' ') print()
Output :
The original list is : [[1, 4, 5], [4, 6, 8], [8, 3, 10]]
1 4 8
4 6 3
5 8 10
Method #2 : Using zip()Using zip function, we map the elements at respective index to one other and after that print each of them. This performs the task of vertical printing.
# Python3 code to demonstrate # Vertical list print # using zip() # initializing list test_list = [[1, 4, 5], [4, 6, 8], [8, 3, 10]] # printing original listprint ("The original list is : " + str(test_list)) # using zip() # to print list verticallyfor x, y, z in zip(*test_list): print(x, y, z)
Output :
The original list is : [[1, 4, 5], [4, 6, 8], [8, 3, 10]]
1 4 8
4 6 3
5 8 10
Python list-programs
python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Jan, 2019"
},
{
"code": null,
"e": 329,
"s": 28,
"text": "Printing the list has been dealt many times. But sometimes we need a different format to get the output of list. This also has application in getting a transpose of matrix. Printing list vertically also has application in web development. Lets discuss certain ways in which this task can be achieved."
},
{
"code": null,
"e": 528,
"s": 329,
"text": "Method #1 : Using Naive MethodThe naive method can be used to print the list vertically vis. using the loops and printing each index element of each list successively will help us achieve this task."
},
{
"code": "# Python3 code to demonstrate # Vertical list print # using naive method # initializing list test_list = [[1, 4, 5], [4, 6, 8], [8, 3, 10]] # printing original listprint (\"The original list is : \" + str(test_list)) # using naive method # to print list verticallyfor i in range(len(test_list)): for x in test_list: print(x[i], end =' ') print()",
"e": 891,
"s": 528,
"text": null
},
{
"code": null,
"e": 900,
"s": 891,
"text": "Output :"
},
{
"code": null,
"e": 981,
"s": 900,
"text": "The original list is : [[1, 4, 5], [4, 6, 8], [8, 3, 10]]\n1 4 8 \n4 6 3 \n5 8 10 \n"
},
{
"code": null,
"e": 1157,
"s": 981,
"text": "Method #2 : Using zip()Using zip function, we map the elements at respective index to one other and after that print each of them. This performs the task of vertical printing."
},
{
"code": "# Python3 code to demonstrate # Vertical list print # using zip() # initializing list test_list = [[1, 4, 5], [4, 6, 8], [8, 3, 10]] # printing original listprint (\"The original list is : \" + str(test_list)) # using zip() # to print list verticallyfor x, y, z in zip(*test_list): print(x, y, z)",
"e": 1459,
"s": 1157,
"text": null
},
{
"code": null,
"e": 1468,
"s": 1459,
"text": "Output :"
},
{
"code": null,
"e": 1546,
"s": 1468,
"text": "The original list is : [[1, 4, 5], [4, 6, 8], [8, 3, 10]]\n1 4 8\n4 6 3\n5 8 10\n"
},
{
"code": null,
"e": 1567,
"s": 1546,
"text": "Python list-programs"
},
{
"code": null,
"e": 1579,
"s": 1567,
"text": "python-list"
},
{
"code": null,
"e": 1586,
"s": 1579,
"text": "Python"
},
{
"code": null,
"e": 1598,
"s": 1586,
"text": "python-list"
}
] |
Check whether Arithmetic Progression can be formed from the given array
|
22 Jun, 2022
Given an array of n integers. The task is to check whether an arithmetic progression can be formed using all the given elements. If possible print “Yes”, else print “No”.
Examples:
Input : arr[] = {0, 12, 4, 8}
Output : Yes
Rearrange given array as {0, 4, 8, 12}
which forms an arithmetic progression.
Input : arr[] = {12, 40, 11, 20}
Output : No
Method 1 (Simple) A simple solution is to first find the smallest element, then find second smallest element and find the difference between these two. Let this difference be d. After finding the difference, find third smallest, fourth smallest and so on. After finding every i-th smallest (from third onward), find the difference between value of current element and value of previous element. If difference is not same as d, return false. If all elements have same difference, return true. Time complexity of this solution is O(n2)
Method 2(Use Sorting) The idea is to sort the given array. After sorting, check if differences between consecutive elements are same or not. If all differences are same, Arithmetic Progression is possible.
Below is the implementation of this approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to check if a given array// can form arithmetic progression#include<bits/stdc++.h>using namespace std; // Returns true if a permutation of arr[0..n-1]// can form arithmetic progressionbool checkIsAP(int arr[], int n){ if (n == 1) return true; // Sort array sort(arr, arr + n); // After sorting, difference between // consecutive elements must be same. int d = arr[1] - arr[0]; for (int i=2; i<n; i++) if (arr[i] - arr[i-1] != d) return false; return true;} // Driven Programint main(){ int arr[] = { 20, 15, 5, 0, 10 }; int n = sizeof(arr)/sizeof(arr[0]); (checkIsAP(arr, n))? (cout << "Yes" << endl) : (cout << "No" << endl); return 0;}
// Java program to check if a given array// can form arithmetic progressionimport java.util.Arrays; class GFG { // Returns true if a permutation of // arr[0..n-1] can form arithmetic // progression static boolean checkIsAP(int arr[], int n) { if (n == 1) return true; // Sort array Arrays.sort(arr); // After sorting, difference between // consecutive elements must be same. int d = arr[1] - arr[0]; for (int i = 2; i < n; i++) if (arr[i] - arr[i-1] != d) return false; return true; } //driver code public static void main (String[] args) { int arr[] = { 20, 15, 5, 0, 10 }; int n = arr.length; if(checkIsAP(arr, n)) System.out.println("Yes"); else System.out.println("No"); }} // This code is contributed by Anant Agarwal.
# Python3 program to check if a given# array can form arithmetic progression # Returns true if a permutation of arr[0..n-1]# can form arithmetic progressiondef checkIsAP(arr, n): if (n == 1): return True # Sort array arr.sort() # After sorting, difference between # consecutive elements must be same. d = arr[1] - arr[0] for i in range(2, n): if (arr[i] - arr[i-1] != d): return False return True # Driver codearr = [ 20, 15, 5, 0, 10 ]n = len(arr)print("Yes") if(checkIsAP(arr, n)) else print("No") # This code is contributed by Anant Agarwal.
// C# program to check if a given array// can form arithmetic progressionusing System; class GFG { // Returns true if a permutation of // arr[0..n-1] can form arithmetic // progression static bool checkIsAP(int []arr, int n) { if (n == 1) return true; // Sort array Array.Sort(arr); // After sorting, difference between // consecutive elements must be same. int d = arr[1] - arr[0]; for (int i = 2; i < n; i++) if (arr[i] - arr[i - 1] != d) return false; return true; } //Driver Code public static void Main () { int []arr = {20, 15, 5, 0, 10}; int n = arr.Length; if(checkIsAP(arr, n)) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed by vt_m.
<?php// PHP program to check if// a given array can form// arithmetic progression // Returns true if a permutation// of arr[0..n-1] can form// arithmetic progressionfunction checkIsAP($arr, $n){ if ($n == 1) return true; // Sort array sort($arr); // After sorting, difference // between consecutive elements // must be same. $d = $arr[1] - $arr[0]; for ($i = 2; $i < $n; $i++) if ($arr[$i] - $arr[$i - 1] != $d) return false; return true;} // Driver Code$arr = array(20, 15, 5, 0, 10);$n = count($arr); if(checkIsAP($arr, $n))echo "Yes";elseecho "No"; // This code is contributed// by Sam007?>
<script> // Javascript program to check if a given array// can form arithmetic progression // Returns true if a permutation of arr[0..n-1]// can form arithmetic progressionfunction checkIsAP(arr, n){ if (n == 1) return true; // Sort array arr.sort((a, b) => a - b); // After sorting, difference between // consecutive elements must be same. let d = arr[1] - arr[0]; for (let i=2; i<n; i++) if (arr[i] - arr[i-1] != d) return false; return true;} // Driven Program let arr = [ 20, 15, 5, 0, 10 ]; let n = arr.length; (checkIsAP(arr, n))? (document.write("Yes" + "<br>")) : (document.write("No" + "<br>")); // This code is contributed by Mayank Tyagi </script>
Yes
Time Complexity: O(n Log n).
Auxiliary Space: O(1)
Method 3(Use Hashing)
Find out the smallest and second smallest elementsFind different between the two elements. d = second_smallest – smallestStore all elements in a hashmap and return “NO” if duplicate element found (can be done together with step 1).Now start from “second smallest element + d” and one by one check n-2 terms of Arithmetic Progression in hashmap. If any value of progression is missing, return false.Return “YES” after end of the loop.
Find out the smallest and second smallest elements
Find different between the two elements. d = second_smallest – smallest
Store all elements in a hashmap and return “NO” if duplicate element found (can be done together with step 1).
Now start from “second smallest element + d” and one by one check n-2 terms of Arithmetic Progression in hashmap. If any value of progression is missing, return false.
Return “YES” after end of the loop.
Below is the implementation of this method.
C++
Java
Python3
C#
Javascript
// C++ program to check if a given array// can form arithmetic progression#include <bits/stdc++.h>using namespace std; // Returns true if a permutation of arr[0..n-1]// can form arithmetic progressionbool checkIsAP(int arr[], int n){ unordered_map<int, int> hm; int smallest = INT_MAX, second_smallest = INT_MAX; for (int i = 0; i < n; i++) { // Find the smallest and and // update second smallest if (arr[i] < smallest) { second_smallest = smallest; smallest = arr[i]; } // Find second smallest else if (arr[i] != smallest && arr[i] < second_smallest) second_smallest = arr[i]; // Check if the duplicate element found or not if (hm.find(arr[i]) == hm.end()) hm[arr[i]]++; // If duplicate found then return false else return false; } // Find the difference between smallest and second // smallest int diff = second_smallest - smallest; // As we have used smallest and // second smallest,so we // should now only check for n-2 elements for (int i = 0; i < n - 1; i++) { if (hm.find(second_smallest) == hm.end()) return false; second_smallest += diff; } return true;} // Driven Programint main(){ int arr[] = { 20, 15, 5, 0, 10 }; int n = sizeof(arr) / sizeof(arr[0]); (checkIsAP(arr, n)) ? (cout << "Yes" << endl) : (cout << "No" << endl); return 0; // This code is contributed by Raman Jha}
// Java program to check if a given array// can form arithmetic progressionimport java.util.HashMap; class GFG { // Returns true if a permutation of arr[0..n-1] // can form arithmetic progression static boolean checkIsAP(int arr[], int n) { HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>(); int smallest = Integer.MAX_VALUE, second_smallest = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { // Find the smallest and and // update second smallest if (arr[i] < smallest) { second_smallest = smallest; smallest = arr[i]; } // Find second smallest else if (arr[i] != smallest && arr[i] < second_smallest) second_smallest = arr[i]; // Check if the duplicate element found or not if (!hm.containsKey(arr[i])) { hm.put(arr[i], 1); } // If duplicate found then return false else return false; } // Find the difference between smallest and second // smallest int diff = second_smallest - smallest; // As we have used smallest and // second smallest,so we // should now only check for n-2 elements for (int i = 0; i < n - 1; i++) { if (!hm.containsKey(second_smallest)) return false; second_smallest += diff; } return true; } // Driven Program public static void main(String args[]) { int arr[] = { 20, 15, 5, 0, 10 }; int n = arr.length; if (checkIsAP(arr, n)) { System.out.println("Yes"); } else { System.out.println("No"); } ; }} // This code is contributed by gfgking
# Python3 program to check if a given array# can form arithmetic progression # Returns true if a permutation of arr[0..n-1]# can form arithmetic progressiondef checkIsAP(arr, n): hm = {} smallest = float('inf') second_smallest = float('inf') for i in range(n): # Find the smallest and and # update second smallest if (arr[i] < smallest): second_smallest = smallest smallest = arr[i] # Find second smallest else if (arr[i] != smallest and arr[i] < second_smallest): second_smallest = arr[i] # Check if the duplicate element found or not if arr[i] not in hm: hm[arr[i]] = 1 # If duplicate found then return false else: return False # Find the difference between smallest # and second smallest diff = second_smallest - smallest # As we have used smallest and # second smallest,so we # should now only check for n-2 elements for i in range(n-1): if (second_smallest) not in hm: return False second_smallest += diff return True # Driver codearr = [ 20, 15, 5, 0, 10 ]n = len(arr) if (checkIsAP(arr, n)): print("Yes")else: print("No") # This code is contributed by rohitsingh07052
// C# program to check if a given array// can form arithmetic progressionusing System;using System.Collections.Generic; class GFG{ // Returns true if a permutation of arr[0..n-1] // can form arithmetic progression public static bool checkIsAP(int[] arr, int n) { Dictionary<int, int> hm = new Dictionary<int, int>(); int smallest = Int32.MaxValue, second_smallest = Int32.MaxValue; for (int i = 0; i < n; i++) { // Find the smallest and and // update second smallest if (arr[i] < smallest) { second_smallest = smallest; smallest = arr[i]; } // Find second smallest else if (arr[i] != smallest && arr[i] < second_smallest) second_smallest = arr[i]; // Check if the duplicate element found or not if (!hm.ContainsKey(arr[i])) { hm[arr[i]]= 1; } // If duplicate found then return false else return false; } // Find the difference between smallest and second // smallest int diff = second_smallest - smallest; // As we have used smallest and // second smallest,so we // should now only check for n-2 elements for (int i = 0; i < n - 1; i++) { if (!hm.ContainsKey(second_smallest)) return false; second_smallest += diff; } return true; } // Driven Program public static void Main(string[] args) { int[] arr = { 20, 15, 5, 0, 10 }; int n = arr.Length; if (checkIsAP(arr, n)) { Console.WriteLine("Yes"); } else { Console.WriteLine("No"); } }} // This code is contributed by Pushpesh raj
<script>// Javascript program to check if a given array// can form arithmetic progression // Returns true if a permutation of arr[0..n-1]// can form arithmetic progressionfunction checkIsAP(arr, n){ var hm = new Map(); var smallest = 1000000000, second_smallest = 1000000000; for (var i = 0; i < n; i++) { // Find the smallest and and // update second smallest if (arr[i] < smallest) { second_smallest = smallest; smallest = arr[i]; } // Find second smallest else if (arr[i] != smallest && arr[i] < second_smallest) second_smallest = arr[i]; // Check if the duplicate element found or not if (!hm.has(arr[i])) { hm.set(arr[i], 1); } // If duplicate found then return false else return false; } // Find the difference between smallest and second // smallest var diff = second_smallest - smallest; // As we have used smallest and // second smallest,so we // should now only check for n-2 elements for (var i = 0; i < n - 1; i++) { if (!hm.has(second_smallest)) return false; second_smallest += diff; } return true;} // Driven Programvar arr = [20, 15, 5, 0, 10 ];var n = arr.length;(checkIsAP(arr, n)) ? (document.write( "Yes")) : (document.write( "No" )); // This code is contributed by famously.</script>
Yes
Time Complexity: O(n) Auxiliary Space: O(n)Thanks to Chenna Rao for suggesting this method,
Method 4(Using counting sort) We can reduce space required in method 3 if given array can be modified.
Find smallest and second smallest elements.Find d = second_smallest – smallestSubtract smallest element from all elements.Now if given array represent AP, all elements should be of form i*d where i varies from 0 to n-1.One by one divide all reduced elements with d. If any element is not divisible by d, return false.Now if array represents AP, it must be a permutation of numbers from 0 to n-1. We can easily check this using counting sort.
Find smallest and second smallest elements.
Find d = second_smallest – smallest
Subtract smallest element from all elements.
Now if given array represent AP, all elements should be of form i*d where i varies from 0 to n-1.
One by one divide all reduced elements with d. If any element is not divisible by d, return false.
Now if array represents AP, it must be a permutation of numbers from 0 to n-1. We can easily check this using counting sort.
Method 5( Hashing with Single Pass)
The basic idea is to find the common difference of the AP by finding out the maximum and the minimum element of the array. After that start from the maximum value and keep on decreasing the value by the common difference alongside checking that whether this new value is present in the hashmap or not . If at any point the value isn’t present in the hashset , break the loop . The ideal situation after the loop breaking is that all n elements have been covered and if yes , then return true else return false.
C++
Java
Python3
C#
Javascript
// C++ program for above approach#include <bits/stdc++.h>using namespace std; bool checkIsAP(int arr[], int n){ unordered_set<int> st; int maxi = INT_MIN; int mini = INT_MAX; for (int i=0;i<n;i++) { maxi = max(arr[i], maxi); mini = min(arr[i], mini); st.insert(arr[i]); } // FINDING THE COMMON DIFFERENCE int diff = (maxi - mini) / (n - 1); int count = 0; // CHECK IF PRESENT IN THE HASHSET OR NOT while (st.find(maxi)!=st.end()) { count++; maxi = maxi - diff; } if (count == n) return true; return false;} // Driver Codeint main(){ int arr[] = { 0, 12, 4, 8 }; int n = 4; cout << boolalpha << checkIsAP(arr, n); return 0;} // This code is contributed by Rohit Pradhan
/*package whatever //do not write package name here */ import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { int[] arr = { 0, 12, 4, 8 }; int n = arr.length; System.out.println(checkIsAP(arr, n)); } static boolean checkIsAP(int arr[], int n) { HashSet<Integer> set = new HashSet<Integer>(); int max = Integer.MIN_VALUE; int min = Integer.MAX_VALUE; for (int i : arr) { max = Math.max(i, max); min = Math.min(i, min); set.add(i); } // FINDING THE COMMON DIFFERENCE int diff = (max - min) / (n - 1); int count = 0; // CHECK IF PRESENT IN THE HASHSET OR NOT while (set.contains(max)) { count++; max = max - diff; } if (count == arr.length) return true; return false; }}
import sys def checkIsAP(arr, n): Set = set() Max = -sys.maxsize - 1 Min = sys.maxsize for i in arr: Max = max(i, Max) Min = min(i, Min) Set.add(i) # FINDING THE COMMON DIFFERENCE diff = (Max - Min) // (n - 1) count = 0 # CHECK IF PRESENT IN THE HASHSET OR NOT while (Max in Set): count += 1 Max = Max - diff if (count == len(arr)): return True return False # driver codearr = [ 0, 12, 4, 8 ]n = len(arr)print(checkIsAP(arr, n)) # This code is contributed by shinjanpatra
using System;using System.Collections.Generic; public class GFG{ // C# program for above approach static bool checkIsAP(int[] arr, int n) { HashSet<int> st = new HashSet<int>(); int maxi = int.MinValue; int mini = int.MaxValue; for (int i = 0; i < n; i++) { maxi = Math.Max(arr[i], maxi); mini = Math.Min(arr[i], mini); st.Add(arr[i]); } // FINDING THE COMMON DIFFERENCE int diff = (maxi - mini) / (n - 1); int count = 0; // CHECK IF PRESENT IN THE HASHSET OR NOT while (st.Contains(maxi)) { count++; maxi = maxi - diff; } if (count == n) { return true; } return false; } // Driver Code internal static void Main() { int[] arr = { 0, 12, 4, 8 }; int n = 4; Console.Write(checkIsAP(arr, n)); } // This code is contributed by Aarti_Rathi}
<script> function checkIsAP(arr, n){ set = new Set() let Max = Number.MIN_VALUE let Min = Number.MAX_VALUE for(let i of arr){ Max = Math.max(i, Max) Min = Math.min(i, Min) set.add(i) } // FINDING THE COMMON DIFFERENCE let diff = Math.floor((Max - Min) / (n - 1)) let count = 0 // CHECK IF PRESENT IN THE HASHSET OR NOT while (set.has(Max)){ count += 1 Max = Max - diff } if (count == arr.length) return true return false} // driver codelet arr = [ 0, 12, 4, 8 ]let n = arr.lengthdocument.write(checkIsAP(arr, n)) // This code is contributed by shinjanpatra </script>
true
Time Complexity – O(n) Auxiliary Space – O(n)
This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
vt_m
Sam007
mayanktyagi1709
thestranger7
rohitsingh07052
famously
Tanisha_Rastogi
simmytarika5
shinjanpatra
sagartomar9927
rohit768
gfgking
pushpeshrajdx01
codewithrathi
adi1212
arithmetic progression
Arrays
Hash
Sorting
Arrays
Hash
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n22 Jun, 2022"
},
{
"code": null,
"e": 225,
"s": 54,
"text": "Given an array of n integers. The task is to check whether an arithmetic progression can be formed using all the given elements. If possible print “Yes”, else print “No”."
},
{
"code": null,
"e": 236,
"s": 225,
"text": "Examples: "
},
{
"code": null,
"e": 404,
"s": 236,
"text": "Input : arr[] = {0, 12, 4, 8}\nOutput : Yes\nRearrange given array as {0, 4, 8, 12} \nwhich forms an arithmetic progression.\n\nInput : arr[] = {12, 40, 11, 20}\nOutput : No"
},
{
"code": null,
"e": 939,
"s": 404,
"text": "Method 1 (Simple) A simple solution is to first find the smallest element, then find second smallest element and find the difference between these two. Let this difference be d. After finding the difference, find third smallest, fourth smallest and so on. After finding every i-th smallest (from third onward), find the difference between value of current element and value of previous element. If difference is not same as d, return false. If all elements have same difference, return true. Time complexity of this solution is O(n2)"
},
{
"code": null,
"e": 1146,
"s": 939,
"text": "Method 2(Use Sorting) The idea is to sort the given array. After sorting, check if differences between consecutive elements are same or not. If all differences are same, Arithmetic Progression is possible. "
},
{
"code": null,
"e": 1193,
"s": 1146,
"text": "Below is the implementation of this approach: "
},
{
"code": null,
"e": 1197,
"s": 1193,
"text": "C++"
},
{
"code": null,
"e": 1202,
"s": 1197,
"text": "Java"
},
{
"code": null,
"e": 1210,
"s": 1202,
"text": "Python3"
},
{
"code": null,
"e": 1213,
"s": 1210,
"text": "C#"
},
{
"code": null,
"e": 1217,
"s": 1213,
"text": "PHP"
},
{
"code": null,
"e": 1228,
"s": 1217,
"text": "Javascript"
},
{
"code": "// C++ program to check if a given array// can form arithmetic progression#include<bits/stdc++.h>using namespace std; // Returns true if a permutation of arr[0..n-1]// can form arithmetic progressionbool checkIsAP(int arr[], int n){ if (n == 1) return true; // Sort array sort(arr, arr + n); // After sorting, difference between // consecutive elements must be same. int d = arr[1] - arr[0]; for (int i=2; i<n; i++) if (arr[i] - arr[i-1] != d) return false; return true;} // Driven Programint main(){ int arr[] = { 20, 15, 5, 0, 10 }; int n = sizeof(arr)/sizeof(arr[0]); (checkIsAP(arr, n))? (cout << \"Yes\" << endl) : (cout << \"No\" << endl); return 0;}",
"e": 1931,
"s": 1228,
"text": null
},
{
"code": "// Java program to check if a given array// can form arithmetic progressionimport java.util.Arrays; class GFG { // Returns true if a permutation of // arr[0..n-1] can form arithmetic // progression static boolean checkIsAP(int arr[], int n) { if (n == 1) return true; // Sort array Arrays.sort(arr); // After sorting, difference between // consecutive elements must be same. int d = arr[1] - arr[0]; for (int i = 2; i < n; i++) if (arr[i] - arr[i-1] != d) return false; return true; } //driver code public static void main (String[] args) { int arr[] = { 20, 15, 5, 0, 10 }; int n = arr.length; if(checkIsAP(arr, n)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // This code is contributed by Anant Agarwal.",
"e": 2874,
"s": 1931,
"text": null
},
{
"code": "# Python3 program to check if a given# array can form arithmetic progression # Returns true if a permutation of arr[0..n-1]# can form arithmetic progressiondef checkIsAP(arr, n): if (n == 1): return True # Sort array arr.sort() # After sorting, difference between # consecutive elements must be same. d = arr[1] - arr[0] for i in range(2, n): if (arr[i] - arr[i-1] != d): return False return True # Driver codearr = [ 20, 15, 5, 0, 10 ]n = len(arr)print(\"Yes\") if(checkIsAP(arr, n)) else print(\"No\") # This code is contributed by Anant Agarwal.",
"e": 3464,
"s": 2874,
"text": null
},
{
"code": "// C# program to check if a given array// can form arithmetic progressionusing System; class GFG { // Returns true if a permutation of // arr[0..n-1] can form arithmetic // progression static bool checkIsAP(int []arr, int n) { if (n == 1) return true; // Sort array Array.Sort(arr); // After sorting, difference between // consecutive elements must be same. int d = arr[1] - arr[0]; for (int i = 2; i < n; i++) if (arr[i] - arr[i - 1] != d) return false; return true; } //Driver Code public static void Main () { int []arr = {20, 15, 5, 0, 10}; int n = arr.Length; if(checkIsAP(arr, n)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code is contributed by vt_m.",
"e": 4366,
"s": 3464,
"text": null
},
{
"code": "<?php// PHP program to check if// a given array can form// arithmetic progression // Returns true if a permutation// of arr[0..n-1] can form// arithmetic progressionfunction checkIsAP($arr, $n){ if ($n == 1) return true; // Sort array sort($arr); // After sorting, difference // between consecutive elements // must be same. $d = $arr[1] - $arr[0]; for ($i = 2; $i < $n; $i++) if ($arr[$i] - $arr[$i - 1] != $d) return false; return true;} // Driver Code$arr = array(20, 15, 5, 0, 10);$n = count($arr); if(checkIsAP($arr, $n))echo \"Yes\";elseecho \"No\"; // This code is contributed// by Sam007?>",
"e": 5058,
"s": 4366,
"text": null
},
{
"code": "<script> // Javascript program to check if a given array// can form arithmetic progression // Returns true if a permutation of arr[0..n-1]// can form arithmetic progressionfunction checkIsAP(arr, n){ if (n == 1) return true; // Sort array arr.sort((a, b) => a - b); // After sorting, difference between // consecutive elements must be same. let d = arr[1] - arr[0]; for (let i=2; i<n; i++) if (arr[i] - arr[i-1] != d) return false; return true;} // Driven Program let arr = [ 20, 15, 5, 0, 10 ]; let n = arr.length; (checkIsAP(arr, n))? (document.write(\"Yes\" + \"<br>\")) : (document.write(\"No\" + \"<br>\")); // This code is contributed by Mayank Tyagi </script>",
"e": 5768,
"s": 5058,
"text": null
},
{
"code": null,
"e": 5772,
"s": 5768,
"text": "Yes"
},
{
"code": null,
"e": 5801,
"s": 5772,
"text": "Time Complexity: O(n Log n)."
},
{
"code": null,
"e": 5823,
"s": 5801,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 5846,
"s": 5823,
"text": "Method 3(Use Hashing) "
},
{
"code": null,
"e": 6280,
"s": 5846,
"text": "Find out the smallest and second smallest elementsFind different between the two elements. d = second_smallest – smallestStore all elements in a hashmap and return “NO” if duplicate element found (can be done together with step 1).Now start from “second smallest element + d” and one by one check n-2 terms of Arithmetic Progression in hashmap. If any value of progression is missing, return false.Return “YES” after end of the loop."
},
{
"code": null,
"e": 6331,
"s": 6280,
"text": "Find out the smallest and second smallest elements"
},
{
"code": null,
"e": 6403,
"s": 6331,
"text": "Find different between the two elements. d = second_smallest – smallest"
},
{
"code": null,
"e": 6514,
"s": 6403,
"text": "Store all elements in a hashmap and return “NO” if duplicate element found (can be done together with step 1)."
},
{
"code": null,
"e": 6682,
"s": 6514,
"text": "Now start from “second smallest element + d” and one by one check n-2 terms of Arithmetic Progression in hashmap. If any value of progression is missing, return false."
},
{
"code": null,
"e": 6718,
"s": 6682,
"text": "Return “YES” after end of the loop."
},
{
"code": null,
"e": 6762,
"s": 6718,
"text": "Below is the implementation of this method."
},
{
"code": null,
"e": 6766,
"s": 6762,
"text": "C++"
},
{
"code": null,
"e": 6771,
"s": 6766,
"text": "Java"
},
{
"code": null,
"e": 6779,
"s": 6771,
"text": "Python3"
},
{
"code": null,
"e": 6782,
"s": 6779,
"text": "C#"
},
{
"code": null,
"e": 6793,
"s": 6782,
"text": "Javascript"
},
{
"code": "// C++ program to check if a given array// can form arithmetic progression#include <bits/stdc++.h>using namespace std; // Returns true if a permutation of arr[0..n-1]// can form arithmetic progressionbool checkIsAP(int arr[], int n){ unordered_map<int, int> hm; int smallest = INT_MAX, second_smallest = INT_MAX; for (int i = 0; i < n; i++) { // Find the smallest and and // update second smallest if (arr[i] < smallest) { second_smallest = smallest; smallest = arr[i]; } // Find second smallest else if (arr[i] != smallest && arr[i] < second_smallest) second_smallest = arr[i]; // Check if the duplicate element found or not if (hm.find(arr[i]) == hm.end()) hm[arr[i]]++; // If duplicate found then return false else return false; } // Find the difference between smallest and second // smallest int diff = second_smallest - smallest; // As we have used smallest and // second smallest,so we // should now only check for n-2 elements for (int i = 0; i < n - 1; i++) { if (hm.find(second_smallest) == hm.end()) return false; second_smallest += diff; } return true;} // Driven Programint main(){ int arr[] = { 20, 15, 5, 0, 10 }; int n = sizeof(arr) / sizeof(arr[0]); (checkIsAP(arr, n)) ? (cout << \"Yes\" << endl) : (cout << \"No\" << endl); return 0; // This code is contributed by Raman Jha}",
"e": 8367,
"s": 6793,
"text": null
},
{
"code": "// Java program to check if a given array// can form arithmetic progressionimport java.util.HashMap; class GFG { // Returns true if a permutation of arr[0..n-1] // can form arithmetic progression static boolean checkIsAP(int arr[], int n) { HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>(); int smallest = Integer.MAX_VALUE, second_smallest = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { // Find the smallest and and // update second smallest if (arr[i] < smallest) { second_smallest = smallest; smallest = arr[i]; } // Find second smallest else if (arr[i] != smallest && arr[i] < second_smallest) second_smallest = arr[i]; // Check if the duplicate element found or not if (!hm.containsKey(arr[i])) { hm.put(arr[i], 1); } // If duplicate found then return false else return false; } // Find the difference between smallest and second // smallest int diff = second_smallest - smallest; // As we have used smallest and // second smallest,so we // should now only check for n-2 elements for (int i = 0; i < n - 1; i++) { if (!hm.containsKey(second_smallest)) return false; second_smallest += diff; } return true; } // Driven Program public static void main(String args[]) { int arr[] = { 20, 15, 5, 0, 10 }; int n = arr.length; if (checkIsAP(arr, n)) { System.out.println(\"Yes\"); } else { System.out.println(\"No\"); } ; }} // This code is contributed by gfgking",
"e": 9949,
"s": 8367,
"text": null
},
{
"code": "# Python3 program to check if a given array# can form arithmetic progression # Returns true if a permutation of arr[0..n-1]# can form arithmetic progressiondef checkIsAP(arr, n): hm = {} smallest = float('inf') second_smallest = float('inf') for i in range(n): # Find the smallest and and # update second smallest if (arr[i] < smallest): second_smallest = smallest smallest = arr[i] # Find second smallest else if (arr[i] != smallest and arr[i] < second_smallest): second_smallest = arr[i] # Check if the duplicate element found or not if arr[i] not in hm: hm[arr[i]] = 1 # If duplicate found then return false else: return False # Find the difference between smallest # and second smallest diff = second_smallest - smallest # As we have used smallest and # second smallest,so we # should now only check for n-2 elements for i in range(n-1): if (second_smallest) not in hm: return False second_smallest += diff return True # Driver codearr = [ 20, 15, 5, 0, 10 ]n = len(arr) if (checkIsAP(arr, n)): print(\"Yes\")else: print(\"No\") # This code is contributed by rohitsingh07052",
"e": 11296,
"s": 9949,
"text": null
},
{
"code": "// C# program to check if a given array// can form arithmetic progressionusing System;using System.Collections.Generic; class GFG{ // Returns true if a permutation of arr[0..n-1] // can form arithmetic progression public static bool checkIsAP(int[] arr, int n) { Dictionary<int, int> hm = new Dictionary<int, int>(); int smallest = Int32.MaxValue, second_smallest = Int32.MaxValue; for (int i = 0; i < n; i++) { // Find the smallest and and // update second smallest if (arr[i] < smallest) { second_smallest = smallest; smallest = arr[i]; } // Find second smallest else if (arr[i] != smallest && arr[i] < second_smallest) second_smallest = arr[i]; // Check if the duplicate element found or not if (!hm.ContainsKey(arr[i])) { hm[arr[i]]= 1; } // If duplicate found then return false else return false; } // Find the difference between smallest and second // smallest int diff = second_smallest - smallest; // As we have used smallest and // second smallest,so we // should now only check for n-2 elements for (int i = 0; i < n - 1; i++) { if (!hm.ContainsKey(second_smallest)) return false; second_smallest += diff; } return true; } // Driven Program public static void Main(string[] args) { int[] arr = { 20, 15, 5, 0, 10 }; int n = arr.Length; if (checkIsAP(arr, n)) { Console.WriteLine(\"Yes\"); } else { Console.WriteLine(\"No\"); } }} // This code is contributed by Pushpesh raj",
"e": 12877,
"s": 11296,
"text": null
},
{
"code": "<script>// Javascript program to check if a given array// can form arithmetic progression // Returns true if a permutation of arr[0..n-1]// can form arithmetic progressionfunction checkIsAP(arr, n){ var hm = new Map(); var smallest = 1000000000, second_smallest = 1000000000; for (var i = 0; i < n; i++) { // Find the smallest and and // update second smallest if (arr[i] < smallest) { second_smallest = smallest; smallest = arr[i]; } // Find second smallest else if (arr[i] != smallest && arr[i] < second_smallest) second_smallest = arr[i]; // Check if the duplicate element found or not if (!hm.has(arr[i])) { hm.set(arr[i], 1); } // If duplicate found then return false else return false; } // Find the difference between smallest and second // smallest var diff = second_smallest - smallest; // As we have used smallest and // second smallest,so we // should now only check for n-2 elements for (var i = 0; i < n - 1; i++) { if (!hm.has(second_smallest)) return false; second_smallest += diff; } return true;} // Driven Programvar arr = [20, 15, 5, 0, 10 ];var n = arr.length;(checkIsAP(arr, n)) ? (document.write( \"Yes\")) : (document.write( \"No\" )); // This code is contributed by famously.</script>",
"e": 14357,
"s": 12877,
"text": null
},
{
"code": null,
"e": 14361,
"s": 14357,
"text": "Yes"
},
{
"code": null,
"e": 14453,
"s": 14361,
"text": "Time Complexity: O(n) Auxiliary Space: O(n)Thanks to Chenna Rao for suggesting this method,"
},
{
"code": null,
"e": 14557,
"s": 14453,
"text": "Method 4(Using counting sort) We can reduce space required in method 3 if given array can be modified. "
},
{
"code": null,
"e": 14999,
"s": 14557,
"text": "Find smallest and second smallest elements.Find d = second_smallest – smallestSubtract smallest element from all elements.Now if given array represent AP, all elements should be of form i*d where i varies from 0 to n-1.One by one divide all reduced elements with d. If any element is not divisible by d, return false.Now if array represents AP, it must be a permutation of numbers from 0 to n-1. We can easily check this using counting sort."
},
{
"code": null,
"e": 15043,
"s": 14999,
"text": "Find smallest and second smallest elements."
},
{
"code": null,
"e": 15079,
"s": 15043,
"text": "Find d = second_smallest – smallest"
},
{
"code": null,
"e": 15124,
"s": 15079,
"text": "Subtract smallest element from all elements."
},
{
"code": null,
"e": 15222,
"s": 15124,
"text": "Now if given array represent AP, all elements should be of form i*d where i varies from 0 to n-1."
},
{
"code": null,
"e": 15321,
"s": 15222,
"text": "One by one divide all reduced elements with d. If any element is not divisible by d, return false."
},
{
"code": null,
"e": 15446,
"s": 15321,
"text": "Now if array represents AP, it must be a permutation of numbers from 0 to n-1. We can easily check this using counting sort."
},
{
"code": null,
"e": 15482,
"s": 15446,
"text": "Method 5( Hashing with Single Pass)"
},
{
"code": null,
"e": 15994,
"s": 15482,
"text": "The basic idea is to find the common difference of the AP by finding out the maximum and the minimum element of the array. After that start from the maximum value and keep on decreasing the value by the common difference alongside checking that whether this new value is present in the hashmap or not . If at any point the value isn’t present in the hashset , break the loop . The ideal situation after the loop breaking is that all n elements have been covered and if yes , then return true else return false. "
},
{
"code": null,
"e": 15998,
"s": 15994,
"text": "C++"
},
{
"code": null,
"e": 16003,
"s": 15998,
"text": "Java"
},
{
"code": null,
"e": 16011,
"s": 16003,
"text": "Python3"
},
{
"code": null,
"e": 16014,
"s": 16011,
"text": "C#"
},
{
"code": null,
"e": 16025,
"s": 16014,
"text": "Javascript"
},
{
"code": "// C++ program for above approach#include <bits/stdc++.h>using namespace std; bool checkIsAP(int arr[], int n){ unordered_set<int> st; int maxi = INT_MIN; int mini = INT_MAX; for (int i=0;i<n;i++) { maxi = max(arr[i], maxi); mini = min(arr[i], mini); st.insert(arr[i]); } // FINDING THE COMMON DIFFERENCE int diff = (maxi - mini) / (n - 1); int count = 0; // CHECK IF PRESENT IN THE HASHSET OR NOT while (st.find(maxi)!=st.end()) { count++; maxi = maxi - diff; } if (count == n) return true; return false;} // Driver Codeint main(){ int arr[] = { 0, 12, 4, 8 }; int n = 4; cout << boolalpha << checkIsAP(arr, n); return 0;} // This code is contributed by Rohit Pradhan",
"e": 16789,
"s": 16025,
"text": null
},
{
"code": "/*package whatever //do not write package name here */ import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { int[] arr = { 0, 12, 4, 8 }; int n = arr.length; System.out.println(checkIsAP(arr, n)); } static boolean checkIsAP(int arr[], int n) { HashSet<Integer> set = new HashSet<Integer>(); int max = Integer.MIN_VALUE; int min = Integer.MAX_VALUE; for (int i : arr) { max = Math.max(i, max); min = Math.min(i, min); set.add(i); } // FINDING THE COMMON DIFFERENCE int diff = (max - min) / (n - 1); int count = 0; // CHECK IF PRESENT IN THE HASHSET OR NOT while (set.contains(max)) { count++; max = max - diff; } if (count == arr.length) return true; return false; }}",
"e": 17691,
"s": 16789,
"text": null
},
{
"code": "import sys def checkIsAP(arr, n): Set = set() Max = -sys.maxsize - 1 Min = sys.maxsize for i in arr: Max = max(i, Max) Min = min(i, Min) Set.add(i) # FINDING THE COMMON DIFFERENCE diff = (Max - Min) // (n - 1) count = 0 # CHECK IF PRESENT IN THE HASHSET OR NOT while (Max in Set): count += 1 Max = Max - diff if (count == len(arr)): return True return False # driver codearr = [ 0, 12, 4, 8 ]n = len(arr)print(checkIsAP(arr, n)) # This code is contributed by shinjanpatra",
"e": 18247,
"s": 17691,
"text": null
},
{
"code": "using System;using System.Collections.Generic; public class GFG{ // C# program for above approach static bool checkIsAP(int[] arr, int n) { HashSet<int> st = new HashSet<int>(); int maxi = int.MinValue; int mini = int.MaxValue; for (int i = 0; i < n; i++) { maxi = Math.Max(arr[i], maxi); mini = Math.Min(arr[i], mini); st.Add(arr[i]); } // FINDING THE COMMON DIFFERENCE int diff = (maxi - mini) / (n - 1); int count = 0; // CHECK IF PRESENT IN THE HASHSET OR NOT while (st.Contains(maxi)) { count++; maxi = maxi - diff; } if (count == n) { return true; } return false; } // Driver Code internal static void Main() { int[] arr = { 0, 12, 4, 8 }; int n = 4; Console.Write(checkIsAP(arr, n)); } // This code is contributed by Aarti_Rathi}",
"e": 19079,
"s": 18247,
"text": null
},
{
"code": "<script> function checkIsAP(arr, n){ set = new Set() let Max = Number.MIN_VALUE let Min = Number.MAX_VALUE for(let i of arr){ Max = Math.max(i, Max) Min = Math.min(i, Min) set.add(i) } // FINDING THE COMMON DIFFERENCE let diff = Math.floor((Max - Min) / (n - 1)) let count = 0 // CHECK IF PRESENT IN THE HASHSET OR NOT while (set.has(Max)){ count += 1 Max = Max - diff } if (count == arr.length) return true return false} // driver codelet arr = [ 0, 12, 4, 8 ]let n = arr.lengthdocument.write(checkIsAP(arr, n)) // This code is contributed by shinjanpatra </script>",
"e": 19736,
"s": 19079,
"text": null
},
{
"code": null,
"e": 19741,
"s": 19736,
"text": "true"
},
{
"code": null,
"e": 19787,
"s": 19741,
"text": "Time Complexity – O(n) Auxiliary Space – O(n)"
},
{
"code": null,
"e": 20207,
"s": 19787,
"text": "This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 20212,
"s": 20207,
"text": "vt_m"
},
{
"code": null,
"e": 20219,
"s": 20212,
"text": "Sam007"
},
{
"code": null,
"e": 20235,
"s": 20219,
"text": "mayanktyagi1709"
},
{
"code": null,
"e": 20248,
"s": 20235,
"text": "thestranger7"
},
{
"code": null,
"e": 20264,
"s": 20248,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 20273,
"s": 20264,
"text": "famously"
},
{
"code": null,
"e": 20289,
"s": 20273,
"text": "Tanisha_Rastogi"
},
{
"code": null,
"e": 20302,
"s": 20289,
"text": "simmytarika5"
},
{
"code": null,
"e": 20315,
"s": 20302,
"text": "shinjanpatra"
},
{
"code": null,
"e": 20330,
"s": 20315,
"text": "sagartomar9927"
},
{
"code": null,
"e": 20339,
"s": 20330,
"text": "rohit768"
},
{
"code": null,
"e": 20347,
"s": 20339,
"text": "gfgking"
},
{
"code": null,
"e": 20363,
"s": 20347,
"text": "pushpeshrajdx01"
},
{
"code": null,
"e": 20377,
"s": 20363,
"text": "codewithrathi"
},
{
"code": null,
"e": 20385,
"s": 20377,
"text": "adi1212"
},
{
"code": null,
"e": 20408,
"s": 20385,
"text": "arithmetic progression"
},
{
"code": null,
"e": 20415,
"s": 20408,
"text": "Arrays"
},
{
"code": null,
"e": 20420,
"s": 20415,
"text": "Hash"
},
{
"code": null,
"e": 20428,
"s": 20420,
"text": "Sorting"
},
{
"code": null,
"e": 20435,
"s": 20428,
"text": "Arrays"
},
{
"code": null,
"e": 20440,
"s": 20435,
"text": "Hash"
},
{
"code": null,
"e": 20448,
"s": 20440,
"text": "Sorting"
}
] |
Printing longest Increasing consecutive subsequence
|
08 Jun, 2022
Given n elements, write a program that prints the longest increasing subsequence whose adjacent element difference is one. Examples:
Input : a[] = {3, 10, 3, 11, 4, 5, 6, 7, 8, 12} Output : 3 4 5 6 7 8 Explanation: 3, 4, 5, 6, 7, 8 is the longest increasing subsequence whose adjacent element differs by one. Input : a[] = {6, 7, 8, 3, 4, 5, 9, 10} Output : 6 7 8 9 10 Explanation: 6, 7, 8, 9, 10 is the longest increasing subsequence
We have discussed how to find length of Longest Increasing consecutive subsequence. To print the subsequence, we store index of last element. Then we print consecutive elements ending with last element.Given below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// CPP program to find length of the// longest increasing subsequence// whose adjacent element differ by 1#include <bits/stdc++.h>using namespace std; // function that returns the length of the// longest increasing subsequence// whose adjacent element differ by 1void longestSubsequence(int a[], int n){ // stores the index of elements unordered_map<int, int> mp; // stores the length of the longest // subsequence that ends with a[i] int dp[n]; memset(dp, 0, sizeof(dp)); int maximum = INT_MIN; // iterate for all element int index = -1; for (int i = 0; i < n; i++) { // if a[i]-1 is present before i-th index if (mp.find(a[i] - 1) != mp.end()) { // last index of a[i]-1 int lastIndex = mp[a[i] - 1] - 1; // relation dp[i] = 1 + dp[lastIndex]; } else dp[i] = 1; // stores the index as 1-index as we need to // check for occurrence, hence 0-th index // will not be possible to check mp[a[i]] = i + 1; // stores the longest length if (maximum < dp[i]) { maximum = dp[i]; index = i; } } // We know last element of sequence is // a[index]. We also know that length // of subsequence is "maximum". So We // print these many consecutive elements // starting from "a[index] - maximum + 1" // to a[index]. for (int curr = a[index] - maximum + 1; curr <= a[index]; curr++) cout << curr << " ";} // Driver Codeint main(){ int a[] = { 3, 10, 3, 11, 4, 5, 6, 7, 8, 12 }; int n = sizeof(a) / sizeof(a[0]); longestSubsequence(a, n); return 0;}
// Java program to find length of the// longest increasing subsequence// whose adjacent element differ byimport java.util.HashMap; class GFG{ // function that returns the length of the // longest increasing subsequence // whose adjacent element differ by 1 public static void longestSubsequence(int[] a, int n) { // stores the index of elements HashMap<Integer, Integer> mp = new HashMap<>(); // stores the length of the longest // subsequence that ends with a[i] int[] dp = new int[n]; int maximum = Integer.MIN_VALUE; // iterate for all element int index = -1; for(int i = 0; i < n; i++) { // if a[i]-1 is present before i-th index if (mp.get(a[i] - 1) != null) { // last index of a[i]-1 int lastIndex = mp.get(a[i] - 1) - 1; // relation dp[i] = 1 + dp[lastIndex]; } else dp[i] = 1; // stores the index as 1-index as we need to // check for occurrence, hence 0-th index // will not be possible to check mp.put(a[i], i + 1); // stores the longest length if (maximum < dp[i]) { maximum = dp[i]; index = i; } } // We know last element of sequence is // a[index]. We also know that length // of subsequence is "maximum". So We // print these many consecutive elements // starting from "a[index] - maximum + 1" // to a[index]. for (int curr = a[index] - maximum + 1; curr <= a[index]; curr++) System.out.print(curr + " "); } // Driver Code public static void main(String[] args) { int[] a = { 3, 10, 3, 11, 4, 5, 6, 7, 8, 12 }; int n = a.length; longestSubsequence(a, n); }} // This code is contributed by sanjeev2552
# Python 3 program to find length of# the longest increasing subsequence# whose adjacent element differ by 1import sys # function that returns the length# of the longest increasing subsequence# whose adjacent element differ by 1def longestSubsequence(a, n): # stores the index of elements mp = {i:0 for i in range(13)} # stores the length of the longest # subsequence that ends with a[i] dp = [0 for i in range(n)] maximum = -sys.maxsize - 1 # iterate for all element index = -1 for i in range(n): # if a[i]-1 is present before # i-th index if ((a[i] - 1 ) in mp): # last index of a[i]-1 lastIndex = mp[a[i] - 1] - 1 # relation dp[i] = 1 + dp[lastIndex] else: dp[i] = 1 # stores the index as 1-index as we # need to check for occurrence, hence # 0-th index will not be possible to check mp[a[i]] = i + 1 # stores the longest length if (maximum < dp[i]): maximum = dp[i] index = i # We know last element of sequence is # a[index]. We also know that length # of subsequence is "maximum". So We # print these many consecutive elements # starting from "a[index] - maximum + 1" # to a[index]. for curr in range(a[index] - maximum + 1, a[index] + 1, 1): print(curr, end = " ") # Driver Codeif __name__ == '__main__': a = [3, 10, 3, 11, 4, 5, 6, 7, 8, 12] n = len(a) longestSubsequence(a, n) # This code is contributed by# Surendra_Gangwar
// C# program to find length of the// longest increasing subsequence// whose adjacent element differ byusing System;using System.Collections.Generic; class GFG{ // function that returns the length of the // longest increasing subsequence // whose adjacent element differ by 1 static void longestSubsequence(int[] a, int n) { // stores the index of elements Dictionary<int, int> mp = new Dictionary<int, int>(); // stores the length of the longest // subsequence that ends with a[i] int[] dp = new int[n]; int maximum = -100000000; // iterate for all element int index = -1; for(int i = 0; i < n; i++) { // if a[i]-1 is present before i-th index if (mp.ContainsKey(a[i] - 1) == true) { // last index of a[i]-1 int lastIndex = mp[a[i] - 1] - 1; // relation dp[i] = 1 + dp[lastIndex]; } else dp[i] = 1; // stores the index as 1-index as we need to // check for occurrence, hence 0-th index // will not be possible to check mp[a[i]] = i + 1; // stores the longest length if (maximum < dp[i]) { maximum = dp[i]; index = i; } } // We know last element of sequence is // a[index]. We also know that length // of subsequence is "maximum". So We // print these many consecutive elements // starting from "a[index] - maximum + 1" // to a[index]. for (int curr = a[index] - maximum + 1; curr <= a[index]; curr++) Console.Write(curr + " "); } // Driver Code static void Main() { int[] a = { 3, 10, 3, 11, 4, 5, 6, 7, 8, 12 }; int n = a.Length; longestSubsequence(a, n); }} // This code is contributed by mohit kumar
<script>// Javascript program to find length of the// longest increasing subsequence// whose adjacent element differ by // function that returns the length of the // longest increasing subsequence // whose adjacent element differ by 1 function longestSubsequence(a, n) { // stores the index of elements let mp = new Map(); // stores the length of the longest // subsequence that ends with a[i] let dp = new Array(n); let maximum = Number.MIN_VALUE; // iterate for all element let index = -1; for(let i = 0; i < n; i++) { // if a[i]-1 is present before i-th index if (mp.get(a[i] - 1) != null) { // last index of a[i]-1 let lastIndex = mp.get(a[i] - 1) - 1; // relation dp[i] = 1 + dp[lastIndex]; } else dp[i] = 1; // stores the index as 1-index as we need to // check for occurrence, hence 0-th index // will not be possible to check mp.set(a[i], i + 1); // stores the longest length if (maximum < dp[i]) { maximum = dp[i]; index = i; } } // We know last element of sequence is // a[index]. We also know that length // of subsequence is "maximum". So We // print these many consecutive elements // starting from "a[index] - maximum + 1" // to a[index]. for (let curr = a[index] - maximum + 1; curr <= a[index]; curr++) document.write(curr + " "); } // Driver Code let a=[3, 10, 3, 11, 4, 5, 6, 7, 8, 12 ]; let n = a.length; longestSubsequence(a, n); // This code is contributed by patel2127</script>
Output:
3 4 5 6 7 8
Time Complexity: O(n), as we are using a loop to traverse n times and in each traversal.
Auxiliary Space: O(n), as we are using extra space for dp and mp.
SURENDRA_GANGWAR
sanjeev2552
mohit kumar 29
patel2127
akshatagrawalmat18
rohitsingh07052
cpp-unordered_map
Arrays
Dynamic Programming
Hash
Arrays
Hash
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n08 Jun, 2022"
},
{
"code": null,
"e": 189,
"s": 54,
"text": "Given n elements, write a program that prints the longest increasing subsequence whose adjacent element difference is one. Examples: "
},
{
"code": null,
"e": 492,
"s": 189,
"text": "Input : a[] = {3, 10, 3, 11, 4, 5, 6, 7, 8, 12} Output : 3 4 5 6 7 8 Explanation: 3, 4, 5, 6, 7, 8 is the longest increasing subsequence whose adjacent element differs by one. Input : a[] = {6, 7, 8, 3, 4, 5, 9, 10} Output : 6 7 8 9 10 Explanation: 6, 7, 8, 9, 10 is the longest increasing subsequence "
},
{
"code": null,
"e": 755,
"s": 494,
"text": "We have discussed how to find length of Longest Increasing consecutive subsequence. To print the subsequence, we store index of last element. Then we print consecutive elements ending with last element.Given below is the implementation of the above approach: "
},
{
"code": null,
"e": 759,
"s": 755,
"text": "C++"
},
{
"code": null,
"e": 764,
"s": 759,
"text": "Java"
},
{
"code": null,
"e": 772,
"s": 764,
"text": "Python3"
},
{
"code": null,
"e": 775,
"s": 772,
"text": "C#"
},
{
"code": null,
"e": 786,
"s": 775,
"text": "Javascript"
},
{
"code": "// CPP program to find length of the// longest increasing subsequence// whose adjacent element differ by 1#include <bits/stdc++.h>using namespace std; // function that returns the length of the// longest increasing subsequence// whose adjacent element differ by 1void longestSubsequence(int a[], int n){ // stores the index of elements unordered_map<int, int> mp; // stores the length of the longest // subsequence that ends with a[i] int dp[n]; memset(dp, 0, sizeof(dp)); int maximum = INT_MIN; // iterate for all element int index = -1; for (int i = 0; i < n; i++) { // if a[i]-1 is present before i-th index if (mp.find(a[i] - 1) != mp.end()) { // last index of a[i]-1 int lastIndex = mp[a[i] - 1] - 1; // relation dp[i] = 1 + dp[lastIndex]; } else dp[i] = 1; // stores the index as 1-index as we need to // check for occurrence, hence 0-th index // will not be possible to check mp[a[i]] = i + 1; // stores the longest length if (maximum < dp[i]) { maximum = dp[i]; index = i; } } // We know last element of sequence is // a[index]. We also know that length // of subsequence is \"maximum\". So We // print these many consecutive elements // starting from \"a[index] - maximum + 1\" // to a[index]. for (int curr = a[index] - maximum + 1; curr <= a[index]; curr++) cout << curr << \" \";} // Driver Codeint main(){ int a[] = { 3, 10, 3, 11, 4, 5, 6, 7, 8, 12 }; int n = sizeof(a) / sizeof(a[0]); longestSubsequence(a, n); return 0;}",
"e": 2461,
"s": 786,
"text": null
},
{
"code": "// Java program to find length of the// longest increasing subsequence// whose adjacent element differ byimport java.util.HashMap; class GFG{ // function that returns the length of the // longest increasing subsequence // whose adjacent element differ by 1 public static void longestSubsequence(int[] a, int n) { // stores the index of elements HashMap<Integer, Integer> mp = new HashMap<>(); // stores the length of the longest // subsequence that ends with a[i] int[] dp = new int[n]; int maximum = Integer.MIN_VALUE; // iterate for all element int index = -1; for(int i = 0; i < n; i++) { // if a[i]-1 is present before i-th index if (mp.get(a[i] - 1) != null) { // last index of a[i]-1 int lastIndex = mp.get(a[i] - 1) - 1; // relation dp[i] = 1 + dp[lastIndex]; } else dp[i] = 1; // stores the index as 1-index as we need to // check for occurrence, hence 0-th index // will not be possible to check mp.put(a[i], i + 1); // stores the longest length if (maximum < dp[i]) { maximum = dp[i]; index = i; } } // We know last element of sequence is // a[index]. We also know that length // of subsequence is \"maximum\". So We // print these many consecutive elements // starting from \"a[index] - maximum + 1\" // to a[index]. for (int curr = a[index] - maximum + 1; curr <= a[index]; curr++) System.out.print(curr + \" \"); } // Driver Code public static void main(String[] args) { int[] a = { 3, 10, 3, 11, 4, 5, 6, 7, 8, 12 }; int n = a.length; longestSubsequence(a, n); }} // This code is contributed by sanjeev2552",
"e": 4523,
"s": 2461,
"text": null
},
{
"code": "# Python 3 program to find length of# the longest increasing subsequence# whose adjacent element differ by 1import sys # function that returns the length# of the longest increasing subsequence# whose adjacent element differ by 1def longestSubsequence(a, n): # stores the index of elements mp = {i:0 for i in range(13)} # stores the length of the longest # subsequence that ends with a[i] dp = [0 for i in range(n)] maximum = -sys.maxsize - 1 # iterate for all element index = -1 for i in range(n): # if a[i]-1 is present before # i-th index if ((a[i] - 1 ) in mp): # last index of a[i]-1 lastIndex = mp[a[i] - 1] - 1 # relation dp[i] = 1 + dp[lastIndex] else: dp[i] = 1 # stores the index as 1-index as we # need to check for occurrence, hence # 0-th index will not be possible to check mp[a[i]] = i + 1 # stores the longest length if (maximum < dp[i]): maximum = dp[i] index = i # We know last element of sequence is # a[index]. We also know that length # of subsequence is \"maximum\". So We # print these many consecutive elements # starting from \"a[index] - maximum + 1\" # to a[index]. for curr in range(a[index] - maximum + 1, a[index] + 1, 1): print(curr, end = \" \") # Driver Codeif __name__ == '__main__': a = [3, 10, 3, 11, 4, 5, 6, 7, 8, 12] n = len(a) longestSubsequence(a, n) # This code is contributed by# Surendra_Gangwar",
"e": 6137,
"s": 4523,
"text": null
},
{
"code": "// C# program to find length of the// longest increasing subsequence// whose adjacent element differ byusing System;using System.Collections.Generic; class GFG{ // function that returns the length of the // longest increasing subsequence // whose adjacent element differ by 1 static void longestSubsequence(int[] a, int n) { // stores the index of elements Dictionary<int, int> mp = new Dictionary<int, int>(); // stores the length of the longest // subsequence that ends with a[i] int[] dp = new int[n]; int maximum = -100000000; // iterate for all element int index = -1; for(int i = 0; i < n; i++) { // if a[i]-1 is present before i-th index if (mp.ContainsKey(a[i] - 1) == true) { // last index of a[i]-1 int lastIndex = mp[a[i] - 1] - 1; // relation dp[i] = 1 + dp[lastIndex]; } else dp[i] = 1; // stores the index as 1-index as we need to // check for occurrence, hence 0-th index // will not be possible to check mp[a[i]] = i + 1; // stores the longest length if (maximum < dp[i]) { maximum = dp[i]; index = i; } } // We know last element of sequence is // a[index]. We also know that length // of subsequence is \"maximum\". So We // print these many consecutive elements // starting from \"a[index] - maximum + 1\" // to a[index]. for (int curr = a[index] - maximum + 1; curr <= a[index]; curr++) Console.Write(curr + \" \"); } // Driver Code static void Main() { int[] a = { 3, 10, 3, 11, 4, 5, 6, 7, 8, 12 }; int n = a.Length; longestSubsequence(a, n); }} // This code is contributed by mohit kumar",
"e": 8192,
"s": 6137,
"text": null
},
{
"code": "<script>// Javascript program to find length of the// longest increasing subsequence// whose adjacent element differ by // function that returns the length of the // longest increasing subsequence // whose adjacent element differ by 1 function longestSubsequence(a, n) { // stores the index of elements let mp = new Map(); // stores the length of the longest // subsequence that ends with a[i] let dp = new Array(n); let maximum = Number.MIN_VALUE; // iterate for all element let index = -1; for(let i = 0; i < n; i++) { // if a[i]-1 is present before i-th index if (mp.get(a[i] - 1) != null) { // last index of a[i]-1 let lastIndex = mp.get(a[i] - 1) - 1; // relation dp[i] = 1 + dp[lastIndex]; } else dp[i] = 1; // stores the index as 1-index as we need to // check for occurrence, hence 0-th index // will not be possible to check mp.set(a[i], i + 1); // stores the longest length if (maximum < dp[i]) { maximum = dp[i]; index = i; } } // We know last element of sequence is // a[index]. We also know that length // of subsequence is \"maximum\". So We // print these many consecutive elements // starting from \"a[index] - maximum + 1\" // to a[index]. for (let curr = a[index] - maximum + 1; curr <= a[index]; curr++) document.write(curr + \" \"); } // Driver Code let a=[3, 10, 3, 11, 4, 5, 6, 7, 8, 12 ]; let n = a.length; longestSubsequence(a, n); // This code is contributed by patel2127</script>",
"e": 10117,
"s": 8192,
"text": null
},
{
"code": null,
"e": 10127,
"s": 10117,
"text": "Output: "
},
{
"code": null,
"e": 10140,
"s": 10127,
"text": "3 4 5 6 7 8 "
},
{
"code": null,
"e": 10229,
"s": 10140,
"text": "Time Complexity: O(n), as we are using a loop to traverse n times and in each traversal."
},
{
"code": null,
"e": 10296,
"s": 10229,
"text": "Auxiliary Space: O(n), as we are using extra space for dp and mp. "
},
{
"code": null,
"e": 10313,
"s": 10296,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 10325,
"s": 10313,
"text": "sanjeev2552"
},
{
"code": null,
"e": 10340,
"s": 10325,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 10350,
"s": 10340,
"text": "patel2127"
},
{
"code": null,
"e": 10369,
"s": 10350,
"text": "akshatagrawalmat18"
},
{
"code": null,
"e": 10385,
"s": 10369,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 10403,
"s": 10385,
"text": "cpp-unordered_map"
},
{
"code": null,
"e": 10410,
"s": 10403,
"text": "Arrays"
},
{
"code": null,
"e": 10430,
"s": 10410,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 10435,
"s": 10430,
"text": "Hash"
},
{
"code": null,
"e": 10442,
"s": 10435,
"text": "Arrays"
},
{
"code": null,
"e": 10447,
"s": 10442,
"text": "Hash"
},
{
"code": null,
"e": 10467,
"s": 10447,
"text": "Dynamic Programming"
}
] |
HTML | Class Attribute
|
10 Aug, 2021
Class in html:
The class is an attribute which specifies one or more class names for an HTML element.
The class attribute can be used on any HTML element.
The class name can be used by CSS and JavaScript to perform certain tasks for elements with the specified class name.
Supported Tags: It supports all HTML elements.
Example :
html
<!DOCTYPE html><html> <head> <style> .country { background-color: black; color: white; padding: 8px; } </style></head> <body> <h2 class="country">CHINA</h2> <p>China has the largest population in the world.</p> <h2 class="country">INDIA</h2> <p>India has the second largest population in the world.</p> <h2 class="country">UNITED STATES</h2> <p>United States has the third largest population in the world.</p> </body> </html>
Output:
Explanation: In the above example CSS styles all elements with the class name “country”.Using the class attribute in JavaScript: JavaScript can access elements with a specified class name by using the getElementsByClassName() method.Example:
html
<!DOCTYPE html><html> <head> <script> function myFunction() { var x = document.getElementsByClassName("country"); for (var i = 0; i < x.length; i++) { x[i].style.display = "none"; } } </script></head> <body> <p>Click the button, and a JavaScript hides all elements with the class name "country":</p> <button onclick="myFunction()">Hide elements</button> <h2 class="country">CHINA</h2> <p>China has the largest population in the world.</p> <h2 class="country">INDIA</h2> <p>India has the second largest population in the world.</p> <h2 class="country">UNITED STATES</h2> <p>United States has the third largest population in the world.</p> </body> </html>
Output :
Before Clicking the hide elements button:
After clicking on the hide elements button :
Using multiple classes: HTML elements can have more than one class name, where each class name must be separated by a space.Example:
html
<!DOCTYPE html><html><style> .country { background-color: black; color: white; padding: 10px; } .middle { text-align: center; }</style> <body> <h2 class="country middle">CHINA</h2> <h2 class="country">INDIA</h2> <h2 class="country">UNITED STATES</h2> </body> </html>
Output :
Explanation: All three headers have the class name “country”, but in addition to that, CHINA also has the class name “middle”, which makes the text center-aligned.Using same class in different tags: Different tags, like <h2> and <p>, can have the same class name and thereby share the same style.Example:
html
<!DOCTYPE html><html><style> .country { background-color: black; color: white; padding: 10px; }</style> <body> <h2 class="country">CHINA</h2> <p class="country">China has the largest population in the world.</p> </body> </html>
Output :
Explanation: Even if the two elements do not have the same tag name, they can have the same class name, and get the same styling.Supported Browser: The browser supported by Class attribute are listed below :
Google Chrome
Internet Explorer
Firefox
Opera
Safari
anmol_mittal26
nidhi_biet
ManasChhabra2
HTML-Attributes
HTML
Technical Scripter
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n10 Aug, 2021"
},
{
"code": null,
"e": 69,
"s": 52,
"text": "Class in html: "
},
{
"code": null,
"e": 156,
"s": 69,
"text": "The class is an attribute which specifies one or more class names for an HTML element."
},
{
"code": null,
"e": 209,
"s": 156,
"text": "The class attribute can be used on any HTML element."
},
{
"code": null,
"e": 327,
"s": 209,
"text": "The class name can be used by CSS and JavaScript to perform certain tasks for elements with the specified class name."
},
{
"code": null,
"e": 375,
"s": 327,
"text": "Supported Tags: It supports all HTML elements. "
},
{
"code": null,
"e": 386,
"s": 375,
"text": "Example : "
},
{
"code": null,
"e": 391,
"s": 386,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <style> .country { background-color: black; color: white; padding: 8px; } </style></head> <body> <h2 class=\"country\">CHINA</h2> <p>China has the largest population in the world.</p> <h2 class=\"country\">INDIA</h2> <p>India has the second largest population in the world.</p> <h2 class=\"country\">UNITED STATES</h2> <p>United States has the third largest population in the world.</p> </body> </html>",
"e": 915,
"s": 391,
"text": null
},
{
"code": null,
"e": 925,
"s": 915,
"text": "Output: "
},
{
"code": null,
"e": 1169,
"s": 925,
"text": "Explanation: In the above example CSS styles all elements with the class name “country”.Using the class attribute in JavaScript: JavaScript can access elements with a specified class name by using the getElementsByClassName() method.Example: "
},
{
"code": null,
"e": 1174,
"s": 1169,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <script> function myFunction() { var x = document.getElementsByClassName(\"country\"); for (var i = 0; i < x.length; i++) { x[i].style.display = \"none\"; } } </script></head> <body> <p>Click the button, and a JavaScript hides all elements with the class name \"country\":</p> <button onclick=\"myFunction()\">Hide elements</button> <h2 class=\"country\">CHINA</h2> <p>China has the largest population in the world.</p> <h2 class=\"country\">INDIA</h2> <p>India has the second largest population in the world.</p> <h2 class=\"country\">UNITED STATES</h2> <p>United States has the third largest population in the world.</p> </body> </html>",
"e": 1945,
"s": 1174,
"text": null
},
{
"code": null,
"e": 1956,
"s": 1945,
"text": "Output : "
},
{
"code": null,
"e": 2000,
"s": 1956,
"text": "Before Clicking the hide elements button: "
},
{
"code": null,
"e": 2047,
"s": 2000,
"text": "After clicking on the hide elements button : "
},
{
"code": null,
"e": 2182,
"s": 2047,
"text": "Using multiple classes: HTML elements can have more than one class name, where each class name must be separated by a space.Example: "
},
{
"code": null,
"e": 2187,
"s": 2182,
"text": "html"
},
{
"code": "<!DOCTYPE html><html><style> .country { background-color: black; color: white; padding: 10px; } .middle { text-align: center; }</style> <body> <h2 class=\"country middle\">CHINA</h2> <h2 class=\"country\">INDIA</h2> <h2 class=\"country\">UNITED STATES</h2> </body> </html>",
"e": 2509,
"s": 2187,
"text": null
},
{
"code": null,
"e": 2520,
"s": 2509,
"text": "Output : "
},
{
"code": null,
"e": 2827,
"s": 2520,
"text": "Explanation: All three headers have the class name “country”, but in addition to that, CHINA also has the class name “middle”, which makes the text center-aligned.Using same class in different tags: Different tags, like <h2> and <p>, can have the same class name and thereby share the same style.Example: "
},
{
"code": null,
"e": 2832,
"s": 2827,
"text": "html"
},
{
"code": "<!DOCTYPE html><html><style> .country { background-color: black; color: white; padding: 10px; }</style> <body> <h2 class=\"country\">CHINA</h2> <p class=\"country\">China has the largest population in the world.</p> </body> </html>",
"e": 3110,
"s": 2832,
"text": null
},
{
"code": null,
"e": 3120,
"s": 3110,
"text": "Output : "
},
{
"code": null,
"e": 3330,
"s": 3120,
"text": "Explanation: Even if the two elements do not have the same tag name, they can have the same class name, and get the same styling.Supported Browser: The browser supported by Class attribute are listed below : "
},
{
"code": null,
"e": 3344,
"s": 3330,
"text": "Google Chrome"
},
{
"code": null,
"e": 3362,
"s": 3344,
"text": "Internet Explorer"
},
{
"code": null,
"e": 3370,
"s": 3362,
"text": "Firefox"
},
{
"code": null,
"e": 3376,
"s": 3370,
"text": "Opera"
},
{
"code": null,
"e": 3383,
"s": 3376,
"text": "Safari"
},
{
"code": null,
"e": 3400,
"s": 3385,
"text": "anmol_mittal26"
},
{
"code": null,
"e": 3411,
"s": 3400,
"text": "nidhi_biet"
},
{
"code": null,
"e": 3425,
"s": 3411,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 3441,
"s": 3425,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 3446,
"s": 3441,
"text": "HTML"
},
{
"code": null,
"e": 3465,
"s": 3446,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3482,
"s": 3465,
"text": "Web Technologies"
},
{
"code": null,
"e": 3487,
"s": 3482,
"text": "HTML"
}
] |
ReactJS useParams Hook
|
17 Mar, 2021
In our React app sometimes we want to access the parameters of the current route in this case useParams hook comes into action. The react-router-dom package has useParams hooks that let you access the parameters of the current route.
Syntax:
useParams();
Creating React Application and Installing required modules:
Step 1: Create a React application using the following command.npx create-react-app useparams_react
Step 1: Create a React application using the following command.
npx create-react-app useparams_react
Step 2: After creating your project folder i.e. useparams_react, move to it using the following command.cd useparams_react
Step 2: After creating your project folder i.e. useparams_react, move to it using the following command.
cd useparams_react
Step 3: After creating the ReactJS application, Install the react-router-dom and react-dom packages using the following command.npm install --save react-router-dom react-dom
Step 3: After creating the ReactJS application, Install the react-router-dom and react-dom packages using the following command.
npm install --save react-router-dom react-dom
Project structure:
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from "react"; import { BrowserRouter as Router, Switch, Route, useParams,} from "react-router-dom"; function BlogPost() { let { id } = useParams(); return <div style={{ fontSize: "50px" }}> Now showing post {id} </div>;} function Home() { return <h3>home page </h3>;} function App() { return ( <Router> <Switch> <Route path="/page/:id"> <BlogPost /> </Route> <Route path="/"> <Home /> </Route> </Switch> </Router> );} export default App;
Step to Run Application: Run the application using the following command from the root directory of the project.
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output. You can see what you have passed in the URL as “: id” is displayed on the screen. In this way, you can access the parameters of the current route’s URL.
React-Hooks
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Axios in React: A Guide for Beginners
How to pass data from one component to other component in ReactJS ?
ReactJS setState()
Re-rendering Components in ReactJS
ReactJS defaultProps
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Remove elements from a JavaScript Array
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n17 Mar, 2021"
},
{
"code": null,
"e": 288,
"s": 54,
"text": "In our React app sometimes we want to access the parameters of the current route in this case useParams hook comes into action. The react-router-dom package has useParams hooks that let you access the parameters of the current route."
},
{
"code": null,
"e": 296,
"s": 288,
"text": "Syntax:"
},
{
"code": null,
"e": 309,
"s": 296,
"text": "useParams();"
},
{
"code": null,
"e": 369,
"s": 309,
"text": "Creating React Application and Installing required modules:"
},
{
"code": null,
"e": 469,
"s": 369,
"text": "Step 1: Create a React application using the following command.npx create-react-app useparams_react"
},
{
"code": null,
"e": 533,
"s": 469,
"text": "Step 1: Create a React application using the following command."
},
{
"code": null,
"e": 570,
"s": 533,
"text": "npx create-react-app useparams_react"
},
{
"code": null,
"e": 693,
"s": 570,
"text": "Step 2: After creating your project folder i.e. useparams_react, move to it using the following command.cd useparams_react"
},
{
"code": null,
"e": 798,
"s": 693,
"text": "Step 2: After creating your project folder i.e. useparams_react, move to it using the following command."
},
{
"code": null,
"e": 817,
"s": 798,
"text": "cd useparams_react"
},
{
"code": null,
"e": 991,
"s": 817,
"text": "Step 3: After creating the ReactJS application, Install the react-router-dom and react-dom packages using the following command.npm install --save react-router-dom react-dom"
},
{
"code": null,
"e": 1120,
"s": 991,
"text": "Step 3: After creating the ReactJS application, Install the react-router-dom and react-dom packages using the following command."
},
{
"code": null,
"e": 1166,
"s": 1120,
"text": "npm install --save react-router-dom react-dom"
},
{
"code": null,
"e": 1185,
"s": 1166,
"text": "Project structure:"
},
{
"code": null,
"e": 1315,
"s": 1185,
"text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code."
},
{
"code": null,
"e": 1322,
"s": 1315,
"text": "App.js"
},
{
"code": "import React from \"react\"; import { BrowserRouter as Router, Switch, Route, useParams,} from \"react-router-dom\"; function BlogPost() { let { id } = useParams(); return <div style={{ fontSize: \"50px\" }}> Now showing post {id} </div>;} function Home() { return <h3>home page </h3>;} function App() { return ( <Router> <Switch> <Route path=\"/page/:id\"> <BlogPost /> </Route> <Route path=\"/\"> <Home /> </Route> </Switch> </Router> );} export default App;",
"e": 1867,
"s": 1322,
"text": null
},
{
"code": null,
"e": 1980,
"s": 1867,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project."
},
{
"code": null,
"e": 1990,
"s": 1980,
"text": "npm start"
},
{
"code": null,
"e": 2242,
"s": 1990,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output. You can see what you have passed in the URL as “: id” is displayed on the screen. In this way, you can access the parameters of the current route’s URL."
},
{
"code": null,
"e": 2254,
"s": 2242,
"text": "React-Hooks"
},
{
"code": null,
"e": 2262,
"s": 2254,
"text": "ReactJS"
},
{
"code": null,
"e": 2279,
"s": 2262,
"text": "Web Technologies"
},
{
"code": null,
"e": 2377,
"s": 2279,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2415,
"s": 2377,
"text": "Axios in React: A Guide for Beginners"
},
{
"code": null,
"e": 2483,
"s": 2415,
"text": "How to pass data from one component to other component in ReactJS ?"
},
{
"code": null,
"e": 2502,
"s": 2483,
"text": "ReactJS setState()"
},
{
"code": null,
"e": 2537,
"s": 2502,
"text": "Re-rendering Components in ReactJS"
},
{
"code": null,
"e": 2558,
"s": 2537,
"text": "ReactJS defaultProps"
},
{
"code": null,
"e": 2591,
"s": 2558,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2653,
"s": 2591,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2714,
"s": 2653,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2764,
"s": 2714,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Implement Email Validator in Android - GeeksforGeeks
|
14 Dec, 2020
Prerequisite: EditText widget in Android using Java with Examples
Email validation is required to inform the user that the Email entered by the user is not in a valid format. If the user has not entered the Email in the wrong format then the error filed is to be given for the EditText. In this article, it’s been discussed how to implement the Email validator in Android step by step. Have a look at the following image to get an idea of what’s been discussed in this article. Note that we are going to implement this project using the Java language.
Step 1: Create an empty activity project
Create an empty activity Android Studio project. Select Java as a programming language.
To know how to create an empty activity Android Studio project refer to Android | How to Create/Start a New Project in Android Studio?.
Step 2: Working with the activity_main.xml file
In the main layout of the application, only two of the widgets are implemented. One is the Email EditText field and one Button which when clicked the entered email is to be checked.
Invoke the following code in the activity_main.xml file to implement the UI layout.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" tools:ignore="HardcodedText"> <!--EditText which takes input as Email from the user--> <EditText android:id="@+id/emailField" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="64dp" android:layout_marginEnd="16dp" android:drawableStart="@drawable/ic_email_black_24dp" android:drawablePadding="12dp" android:hint="Email" /> <!--Button which when clicked validates the entered email is valid or not--> <Button android:id="@+id/validateButton" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/emailField" android:layout_marginStart="16dp" android:layout_marginTop="16dp" android:layout_marginEnd="16dp" android:backgroundTint="@color/colorPrimary" android:text="VALIDATE" android:textColor="@android:color/white" /> </RelativeLayout>
Output UI:
Step 3: Working with the MainActivity.java file
In this case, the pattern EMAIL_ADDRESS is used for demonstration purposes.
However, there are 5 more patterns to get validate the input from the user. Those are:
DOMAIN_NAME, IP_ADDRESS, PHONE, TOP_LEVEL_DOMAIN, WEB_URL.
Refer to the Patterns for more information about the predefined patterns in Android.
Invoke the following code inside the MainActivity.java file to implement the Email Validator in this case. Comments are added for a better understanding.
Java
import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.util.Patterns;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast; public class MainActivity extends AppCompatActivity { // EditText filed for Email EditText etMail; // Button to validate the Email address Button bValidate; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // register all the UI elements // with their appropriate IDs etMail = findViewById(R.id.emailField); bValidate = findViewById(R.id.validateButton); // handle the VALIDATE button to show the toast // message whether the entered email is valid or not bValidate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { emailValidator(etMail); } }); } // the function which triggered when the VALIDATE button is clicked // which validates the email address entered by the user public void emailValidator(EditText etMail) { // extract the entered data from the EditText String emailToText = etMail.getText().toString(); // Android offers the inbuilt patterns which the entered // data from the EditText field needs to be compared with // In this case the the entered data needs to compared with // the EMAIL_ADDRESS, which is implemented same below if (!emailToText.isEmpty() && Patterns.EMAIL_ADDRESS.matcher(emailToText).matches()) { Toast.makeText(this, "Email Verified !", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, "Enter valid Email address !", Toast.LENGTH_SHORT).show(); } }}
android
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create and Add Data to SQLite Database in Android?
Broadcast Receiver in Android With Example
Resource Raw Folder in Android Studio
Android RecyclerView in Kotlin
Content Providers in Android with Example
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
Arrays.sort() in Java with examples
|
[
{
"code": null,
"e": 26065,
"s": 26037,
"text": "\n14 Dec, 2020"
},
{
"code": null,
"e": 26131,
"s": 26065,
"text": "Prerequisite: EditText widget in Android using Java with Examples"
},
{
"code": null,
"e": 26618,
"s": 26131,
"text": "Email validation is required to inform the user that the Email entered by the user is not in a valid format. If the user has not entered the Email in the wrong format then the error filed is to be given for the EditText. In this article, it’s been discussed how to implement the Email validator in Android step by step. Have a look at the following image to get an idea of what’s been discussed in this article. Note that we are going to implement this project using the Java language. "
},
{
"code": null,
"e": 26659,
"s": 26618,
"text": "Step 1: Create an empty activity project"
},
{
"code": null,
"e": 26747,
"s": 26659,
"text": "Create an empty activity Android Studio project. Select Java as a programming language."
},
{
"code": null,
"e": 26883,
"s": 26747,
"text": "To know how to create an empty activity Android Studio project refer to Android | How to Create/Start a New Project in Android Studio?."
},
{
"code": null,
"e": 26931,
"s": 26883,
"text": "Step 2: Working with the activity_main.xml file"
},
{
"code": null,
"e": 27113,
"s": 26931,
"text": "In the main layout of the application, only two of the widgets are implemented. One is the Email EditText field and one Button which when clicked the entered email is to be checked."
},
{
"code": null,
"e": 27197,
"s": 27113,
"text": "Invoke the following code in the activity_main.xml file to implement the UI layout."
},
{
"code": null,
"e": 27201,
"s": 27197,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\" tools:ignore=\"HardcodedText\"> <!--EditText which takes input as Email from the user--> <EditText android:id=\"@+id/emailField\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"64dp\" android:layout_marginEnd=\"16dp\" android:drawableStart=\"@drawable/ic_email_black_24dp\" android:drawablePadding=\"12dp\" android:hint=\"Email\" /> <!--Button which when clicked validates the entered email is valid or not--> <Button android:id=\"@+id/validateButton\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@+id/emailField\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"16dp\" android:layout_marginEnd=\"16dp\" android:backgroundTint=\"@color/colorPrimary\" android:text=\"VALIDATE\" android:textColor=\"@android:color/white\" /> </RelativeLayout>",
"e": 28514,
"s": 27201,
"text": null
},
{
"code": null,
"e": 28525,
"s": 28514,
"text": "Output UI:"
},
{
"code": null,
"e": 28573,
"s": 28525,
"text": "Step 3: Working with the MainActivity.java file"
},
{
"code": null,
"e": 28649,
"s": 28573,
"text": "In this case, the pattern EMAIL_ADDRESS is used for demonstration purposes."
},
{
"code": null,
"e": 28736,
"s": 28649,
"text": "However, there are 5 more patterns to get validate the input from the user. Those are:"
},
{
"code": null,
"e": 28795,
"s": 28736,
"text": "DOMAIN_NAME, IP_ADDRESS, PHONE, TOP_LEVEL_DOMAIN, WEB_URL."
},
{
"code": null,
"e": 28880,
"s": 28795,
"text": "Refer to the Patterns for more information about the predefined patterns in Android."
},
{
"code": null,
"e": 29034,
"s": 28880,
"text": "Invoke the following code inside the MainActivity.java file to implement the Email Validator in this case. Comments are added for a better understanding."
},
{
"code": null,
"e": 29039,
"s": 29034,
"text": "Java"
},
{
"code": "import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.util.Patterns;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast; public class MainActivity extends AppCompatActivity { // EditText filed for Email EditText etMail; // Button to validate the Email address Button bValidate; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // register all the UI elements // with their appropriate IDs etMail = findViewById(R.id.emailField); bValidate = findViewById(R.id.validateButton); // handle the VALIDATE button to show the toast // message whether the entered email is valid or not bValidate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { emailValidator(etMail); } }); } // the function which triggered when the VALIDATE button is clicked // which validates the email address entered by the user public void emailValidator(EditText etMail) { // extract the entered data from the EditText String emailToText = etMail.getText().toString(); // Android offers the inbuilt patterns which the entered // data from the EditText field needs to be compared with // In this case the the entered data needs to compared with // the EMAIL_ADDRESS, which is implemented same below if (!emailToText.isEmpty() && Patterns.EMAIL_ADDRESS.matcher(emailToText).matches()) { Toast.makeText(this, \"Email Verified !\", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, \"Enter valid Email address !\", Toast.LENGTH_SHORT).show(); } }}",
"e": 30940,
"s": 29039,
"text": null
},
{
"code": null,
"e": 30948,
"s": 30940,
"text": "android"
},
{
"code": null,
"e": 30972,
"s": 30948,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 30980,
"s": 30972,
"text": "Android"
},
{
"code": null,
"e": 30985,
"s": 30980,
"text": "Java"
},
{
"code": null,
"e": 31004,
"s": 30985,
"text": "Technical Scripter"
},
{
"code": null,
"e": 31009,
"s": 31004,
"text": "Java"
},
{
"code": null,
"e": 31017,
"s": 31009,
"text": "Android"
},
{
"code": null,
"e": 31115,
"s": 31017,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31173,
"s": 31115,
"text": "How to Create and Add Data to SQLite Database in Android?"
},
{
"code": null,
"e": 31216,
"s": 31173,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 31254,
"s": 31216,
"text": "Resource Raw Folder in Android Studio"
},
{
"code": null,
"e": 31285,
"s": 31254,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 31327,
"s": 31285,
"text": "Content Providers in Android with Example"
},
{
"code": null,
"e": 31342,
"s": 31327,
"text": "Arrays in Java"
},
{
"code": null,
"e": 31386,
"s": 31342,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 31408,
"s": 31386,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 31459,
"s": 31408,
"text": "Object Oriented Programming (OOPs) Concept in Java"
}
] |
Find an element in Bitonic array - GeeksforGeeks
|
04 Mar, 2022
Given a bitonic sequence of n distinct elements, and an integer x, the task is to write a program to find given element x in the bitonic sequence in O(log n) time.
A Bitonic Sequence is a sequence of numbers that is first strictly increasing then after a point decreasing.
Examples:
Input : arr[] = {-3, 9, 18, 20, 17, 5, 1}, key = 20Output : Found at index 3
Input : arr[] = {5, 6, 7, 8, 9, 10, 3, 2, 1}, key = 30Output : Not Found
Naive Approach: A simple solution is to do a linear search. The time complexity of this solution would be O(n).
Efficient Approach: An efficient solution is based on Binary Search.
The idea is to find the bitonic point ‘k’ which is the index of the maximum element of a given sequence.
If the element to be searched is greater than the maximum element return -1,
else search the element in both halves.
Below is the step by step algorithm on how to do this.
Find the bitonic point in the given array, i.e the maximum element in the given bitonic array. This can be done in log(n) time by modifying the binary search algorithm. You can refer to this post on how to do this.If the element to be searched is equal to the element at the bitonic point then print the index of the bitonic point.If the element to be searched is greater than the element at a bitonic point then the element does not exist in the array.If the element to be searched is less than the element at a bitonic point then search for the element in both halves of the array using binary search.
Find the bitonic point in the given array, i.e the maximum element in the given bitonic array. This can be done in log(n) time by modifying the binary search algorithm. You can refer to this post on how to do this.
If the element to be searched is equal to the element at the bitonic point then print the index of the bitonic point.
If the element to be searched is greater than the element at a bitonic point then the element does not exist in the array.
If the element to be searched is less than the element at a bitonic point then search for the element in both halves of the array using binary search.
Below is the implementation of the above idea:
C++
Java
Python3
C#
Javascript
// C++ code to search key in bitonic array#include <iostream> using namespace std; // Function for binary search in ascending partint ascendingBinarySearch(int arr[], int low, int high, int key){ while (low <= high) { int mid = low + (high - low) / 2; if (arr[mid] == key) return mid; if (arr[mid] > key) high = mid - 1; else low = mid + 1; } return -1;} // Function for binary search in// descending part of arrayint descendingBinarySearch(int arr[], int low, int high, int key){ while (low <= high) { int mid = low + (high - low) / 2; if (arr[mid] == key) return mid; if (arr[mid] < key) high = mid - 1; else low = mid + 1; } return -1;} // finding bitonic pointint findBitonicPoint(int arr[], int n, int l, int r){ int mid; int bitonicPoint = 0; mid = (r + l) / 2; if (arr[mid] > arr[mid - 1] && arr[mid] > arr[mid + 1]) { return mid; } else if (arr[mid] > arr[mid - 1] && arr[mid] < arr[mid + 1]) { bitonicPoint = findBitonicPoint(arr, n, mid, r); } else if (arr[mid] < arr[mid - 1] && arr[mid] > arr[mid + 1]) { bitonicPoint = findBitonicPoint(arr, n, l, mid); } return bitonicPoint;} // Function to search key in// bitonic arrayint searchBitonic(int arr[], int n, int key, int index){ if (key > arr[index]) return -1; else if (key == arr[index]) return index; else { int temp = ascendingBinarySearch(arr, 0, index - 1, key); if (temp != -1) { return temp; } // Search in right of k return descendingBinarySearch(arr, index + 1, n - 1, key); }} // Driver codeint main(){ int arr[] = { -8, 1, 2, 3, 4, 5, -2, -3 }; int key = 1; int n, l, r; n = sizeof(arr) / sizeof(arr[0]); l = 0; r = n - 1; int index; // Function call index = findBitonicPoint(arr, n, l, r); int x = searchBitonic(arr, n, key, index); if (x == -1) cout << "Element Not Found" << endl; else cout << "Element Found at index " << x << endl; return 0;}
// Java code to search key in bitonic arraypublic class GFG { // Function for binary search // in ascending part static int ascendingBinarySearch(int arr[], int low, int high, int key) { while (low <= high) { int mid = low + (high - low) / 2; if (arr[mid] == key) { return mid; } if (arr[mid] > key) { high = mid - 1; } else { low = mid + 1; } } return -1; } // Function for binary search in // descending part of array static int descendingBinarySearch(int arr[], int low, int high, int key) { while (low <= high) { int mid = low + (high - low) / 2; if (arr[mid] == key) { return mid; } if (arr[mid] < key) { high = mid - 1; } else { low = mid + 1; } } return -1; } // finding bitonic point static int findBitonicPoint(int arr[], int n, int l, int r) { int mid; int bitonicPoint = 0; mid = (r + l) / 2; if (arr[mid] > arr[mid - 1] && arr[mid] > arr[mid + 1]) { return mid; } else { if (arr[mid] > arr[mid - 1] && arr[mid] < arr[mid + 1]) { bitonicPoint = findBitonicPoint(arr, n, mid, r); } else { if (arr[mid] < arr[mid - 1] && arr[mid] > arr[mid + 1]) { bitonicPoint = findBitonicPoint(arr, n, l, mid); } } } return bitonicPoint; } // Function to search key in bitonic array static int searchBitonic(int arr[], int n, int key, int index) { if (key > arr[index]) { return -1; } else if (key == arr[index]) { return index; } else { int temp = ascendingBinarySearch( arr, 0, index - 1, key); if (temp != -1) { return temp; } // Search in right of k return descendingBinarySearch(arr, index + 1, n - 1, key); } } // Driver code public static void main(String args[]) { int arr[] = { -8, 1, 2, 3, 4, 5, -2, -3 }; int key = 5; int n, l, r; n = arr.length; l = 0; r = n - 1; int index; index = findBitonicPoint(arr, n, l, r); int x = searchBitonic(arr, n, key, index); if (x == -1) { System.out.println("Element Not Found"); } else { System.out.println("Element Found at index " + x); } }} /*This code is contributed by 29AjayKumar*/
# Python code to search key in bitonic array # Function for binary search in ascending partdef ascendingBinarySearch(arr, low, high, key): while low <= high: mid = low + (high - low) // 2 if arr[mid] == key: return mid if arr[mid] > key: high = mid - 1 else: low = mid + 1 return -1 # Function for binary search in descending part of arraydef descendingBinarySearch(arr, low, high, key): while low <= high: mid = low + (high - low) // 2 if arr[mid] == key: return mid if arr[mid] < key: high = mid - 1 else: low = mid + 1 return -1 # Find bitonic pointdef findBitonicPoint(arr, n, l, r): bitonicPoint = 0 mid = (r + l) // 2 if arr[mid] > arr[mid-1] and arr[mid] > arr[mid+1]: return mid elif arr[mid] > arr[mid-1] and arr[mid] < arr[mid+1]: bitonicPoint = findBitonicPoint(arr, n, mid, r) else: bitonicPoint = finsBitonicPoint(arr, n, l, mid) return bitonicPoint # Function to search key in bitonic arraydef searchBitonic(arr, n, key, index): if key > arr[index]: return -1 elif key == arr[index]: return index else: temp = ascendingBinarySearch(arr, 0, index-1, key) if temp != -1: return temp # search in right of k return descendingBinarySearch(arr, index+1, n-1, key) # Driver codedef main(): arr = [-8, 1, 2, 3, 4, 5, -2, -3] key = 1 n = len(arr) l = 0 r = n - 1 # Function call index = findBitonicPoint(arr, n, l, r) x = searchBitonic(arr, n, key, index) if x == -1: print("Element Not Found") else: print("Element Found at index", x) main() # This code is contributed by stutipathak31jan
// C# code to search key in bitonic arrayusing System; class GFG { // Function for binary search in ascending part static int ascendingBinarySearch(int[] arr, int low, int high, int key) { while (low <= high) { int mid = low + (high - low) / 2; if (arr[mid] == key) { return mid; } if (arr[mid] > key) { high = mid - 1; } else { low = mid + 1; } } return -1; } // Function for binary search in descending part of // array static int descendingBinarySearch(int[] arr, int low, int high, int key) { while (low <= high) { int mid = low + (high - low) / 2; if (arr[mid] == key) { return mid; } if (arr[mid] < key) { high = mid - 1; } else { low = mid + 1; } } return -1; } // finding bitonic point static int findBitonicPoint(int[] arr, int n, int l, int r) { int mid; int bitonicPoint = 0; mid = (r + l) / 2; if (arr[mid] > arr[mid - 1] && arr[mid] > arr[mid + 1]) { return mid; } else { if (arr[mid] > arr[mid - 1] && arr[mid] < arr[mid + 1]) { bitonicPoint = findBitonicPoint(arr, n, mid, r); } else { if (arr[mid] < arr[mid - 1] && arr[mid] > arr[mid + 1]) { bitonicPoint = findBitonicPoint(arr, n, l, mid); } } } return bitonicPoint; } // Function to search key in bitonic array static int searchBitonic(int[] arr, int n, int key, int index) { if (key > arr[index]) { return -1; } else if (key == arr[index]) { return index; } else { int temp = ascendingBinarySearch( arr, 0, index - 1, key); if (temp != -1) { return temp; } // Search in right of k return descendingBinarySearch(arr, index + 1, n - 1, key); } } // Driver Code static public void Main() { int[] arr = { -8, 1, 2, 3, 4, 5, -2, -3 }; int key = 1; int n, l, r; n = arr.Length; l = 0; r = n - 1; int index; index = findBitonicPoint(arr, n, l, r); int x = searchBitonic(arr, n, key, index); if (x == -1) { Console.WriteLine("Element Not Found"); } else { Console.WriteLine("Element Found at index " + x); } }} // This code is contributed by ajit
<script> // JavaScript code to search key in bitonic array // Function for binary search in ascending partfunction ascendingBinarySearch(arr, low, high, key) { while (low <= high) { let mid = Math.floor(low + (high - low) / 2); if (arr[mid] == key) return mid; if (arr[mid] > key) high = mid - 1; else low = mid + 1; } return -1;} // Function for binary search in// descending part of arrayfunction descendingBinarySearch(arr, low, high, key) { while (low <= high) { let mid = Math.floor(low + (high - low) / 2); if (arr[mid] == key) return mid; if (arr[mid] < key) high = mid - 1; else low = mid + 1; } return -1;} // finding bitonic pointfunction findBitonicPoint(arr, n, l, r) { let mid; let bitonicPoint = 0; mid = Math.floor((r + l) / 2); if (arr[mid] > arr[mid - 1] && arr[mid] > arr[mid + 1]) { return mid; } else if (arr[mid] > arr[mid - 1] && arr[mid] < arr[mid + 1]) { bitonicPoint = findBitonicPoint(arr, n, mid, r); } else if (arr[mid] < arr[mid - 1] && arr[mid] > arr[mid + 1]) { bitonicPoint = findBitonicPoint(arr, n, l, mid); } return bitonicPoint;} // Function to search key in// bitonic arrayfunction searchBitonic(arr, n, key, index) { if (key > arr[index]) return -1; else if (key == arr[index]) return index; else { let temp = ascendingBinarySearch(arr, 0, index - 1, key); if (temp != -1) { return temp; } // Search in right of k return descendingBinarySearch(arr, index + 1, n - 1, key); }} // Driver code let arr = [-8, 1, 2, 3, 4, 5, -2, -3];let key = 1;let n, l, r;n = arr.length;l = 0;r = n - 1;let index; // Function callindex = findBitonicPoint(arr, n, l, r); let x = searchBitonic(arr, n, key, index); if (x == -1) document.write("Element Not Found" + "<br>");else document.write("Element Found at index " + x + "<br>"); </script>
Element Found at index 1
Time complexity: O(log n) Auxiliary Space: O(1)
This article is contributed by Vaishali Goyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
29AjayKumar
jit_t
shresth_mehta
guptarashi2001
prajjwal21
stutipathak31jan
_saurabh_jaiswal
ankit1210
nehakumariintern
Binary Search
Arrays
Arrays
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Stack Data Structure (Introduction and Program)
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Linked List vs Array
Python | Using 2D arrays/lists the right way
Search an element in a sorted and rotated array
Array of Strings in C++ (5 Different Ways to Create)
|
[
{
"code": null,
"e": 26455,
"s": 26427,
"text": "\n04 Mar, 2022"
},
{
"code": null,
"e": 26620,
"s": 26455,
"text": "Given a bitonic sequence of n distinct elements, and an integer x, the task is to write a program to find given element x in the bitonic sequence in O(log n) time. "
},
{
"code": null,
"e": 26729,
"s": 26620,
"text": "A Bitonic Sequence is a sequence of numbers that is first strictly increasing then after a point decreasing."
},
{
"code": null,
"e": 26740,
"s": 26729,
"text": "Examples: "
},
{
"code": null,
"e": 26818,
"s": 26740,
"text": "Input : arr[] = {-3, 9, 18, 20, 17, 5, 1}, key = 20Output : Found at index 3"
},
{
"code": null,
"e": 26892,
"s": 26818,
"text": "Input : arr[] = {5, 6, 7, 8, 9, 10, 3, 2, 1}, key = 30Output : Not Found"
},
{
"code": null,
"e": 27004,
"s": 26892,
"text": "Naive Approach: A simple solution is to do a linear search. The time complexity of this solution would be O(n)."
},
{
"code": null,
"e": 27074,
"s": 27004,
"text": "Efficient Approach: An efficient solution is based on Binary Search. "
},
{
"code": null,
"e": 27180,
"s": 27074,
"text": "The idea is to find the bitonic point ‘k’ which is the index of the maximum element of a given sequence. "
},
{
"code": null,
"e": 27258,
"s": 27180,
"text": "If the element to be searched is greater than the maximum element return -1, "
},
{
"code": null,
"e": 27299,
"s": 27258,
"text": "else search the element in both halves. "
},
{
"code": null,
"e": 27354,
"s": 27299,
"text": "Below is the step by step algorithm on how to do this."
},
{
"code": null,
"e": 27958,
"s": 27354,
"text": "Find the bitonic point in the given array, i.e the maximum element in the given bitonic array. This can be done in log(n) time by modifying the binary search algorithm. You can refer to this post on how to do this.If the element to be searched is equal to the element at the bitonic point then print the index of the bitonic point.If the element to be searched is greater than the element at a bitonic point then the element does not exist in the array.If the element to be searched is less than the element at a bitonic point then search for the element in both halves of the array using binary search."
},
{
"code": null,
"e": 28173,
"s": 27958,
"text": "Find the bitonic point in the given array, i.e the maximum element in the given bitonic array. This can be done in log(n) time by modifying the binary search algorithm. You can refer to this post on how to do this."
},
{
"code": null,
"e": 28291,
"s": 28173,
"text": "If the element to be searched is equal to the element at the bitonic point then print the index of the bitonic point."
},
{
"code": null,
"e": 28414,
"s": 28291,
"text": "If the element to be searched is greater than the element at a bitonic point then the element does not exist in the array."
},
{
"code": null,
"e": 28565,
"s": 28414,
"text": "If the element to be searched is less than the element at a bitonic point then search for the element in both halves of the array using binary search."
},
{
"code": null,
"e": 28613,
"s": 28565,
"text": "Below is the implementation of the above idea: "
},
{
"code": null,
"e": 28617,
"s": 28613,
"text": "C++"
},
{
"code": null,
"e": 28622,
"s": 28617,
"text": "Java"
},
{
"code": null,
"e": 28630,
"s": 28622,
"text": "Python3"
},
{
"code": null,
"e": 28633,
"s": 28630,
"text": "C#"
},
{
"code": null,
"e": 28644,
"s": 28633,
"text": "Javascript"
},
{
"code": "// C++ code to search key in bitonic array#include <iostream> using namespace std; // Function for binary search in ascending partint ascendingBinarySearch(int arr[], int low, int high, int key){ while (low <= high) { int mid = low + (high - low) / 2; if (arr[mid] == key) return mid; if (arr[mid] > key) high = mid - 1; else low = mid + 1; } return -1;} // Function for binary search in// descending part of arrayint descendingBinarySearch(int arr[], int low, int high, int key){ while (low <= high) { int mid = low + (high - low) / 2; if (arr[mid] == key) return mid; if (arr[mid] < key) high = mid - 1; else low = mid + 1; } return -1;} // finding bitonic pointint findBitonicPoint(int arr[], int n, int l, int r){ int mid; int bitonicPoint = 0; mid = (r + l) / 2; if (arr[mid] > arr[mid - 1] && arr[mid] > arr[mid + 1]) { return mid; } else if (arr[mid] > arr[mid - 1] && arr[mid] < arr[mid + 1]) { bitonicPoint = findBitonicPoint(arr, n, mid, r); } else if (arr[mid] < arr[mid - 1] && arr[mid] > arr[mid + 1]) { bitonicPoint = findBitonicPoint(arr, n, l, mid); } return bitonicPoint;} // Function to search key in// bitonic arrayint searchBitonic(int arr[], int n, int key, int index){ if (key > arr[index]) return -1; else if (key == arr[index]) return index; else { int temp = ascendingBinarySearch(arr, 0, index - 1, key); if (temp != -1) { return temp; } // Search in right of k return descendingBinarySearch(arr, index + 1, n - 1, key); }} // Driver codeint main(){ int arr[] = { -8, 1, 2, 3, 4, 5, -2, -3 }; int key = 1; int n, l, r; n = sizeof(arr) / sizeof(arr[0]); l = 0; r = n - 1; int index; // Function call index = findBitonicPoint(arr, n, l, r); int x = searchBitonic(arr, n, key, index); if (x == -1) cout << \"Element Not Found\" << endl; else cout << \"Element Found at index \" << x << endl; return 0;}",
"e": 31101,
"s": 28644,
"text": null
},
{
"code": "// Java code to search key in bitonic arraypublic class GFG { // Function for binary search // in ascending part static int ascendingBinarySearch(int arr[], int low, int high, int key) { while (low <= high) { int mid = low + (high - low) / 2; if (arr[mid] == key) { return mid; } if (arr[mid] > key) { high = mid - 1; } else { low = mid + 1; } } return -1; } // Function for binary search in // descending part of array static int descendingBinarySearch(int arr[], int low, int high, int key) { while (low <= high) { int mid = low + (high - low) / 2; if (arr[mid] == key) { return mid; } if (arr[mid] < key) { high = mid - 1; } else { low = mid + 1; } } return -1; } // finding bitonic point static int findBitonicPoint(int arr[], int n, int l, int r) { int mid; int bitonicPoint = 0; mid = (r + l) / 2; if (arr[mid] > arr[mid - 1] && arr[mid] > arr[mid + 1]) { return mid; } else { if (arr[mid] > arr[mid - 1] && arr[mid] < arr[mid + 1]) { bitonicPoint = findBitonicPoint(arr, n, mid, r); } else { if (arr[mid] < arr[mid - 1] && arr[mid] > arr[mid + 1]) { bitonicPoint = findBitonicPoint(arr, n, l, mid); } } } return bitonicPoint; } // Function to search key in bitonic array static int searchBitonic(int arr[], int n, int key, int index) { if (key > arr[index]) { return -1; } else if (key == arr[index]) { return index; } else { int temp = ascendingBinarySearch( arr, 0, index - 1, key); if (temp != -1) { return temp; } // Search in right of k return descendingBinarySearch(arr, index + 1, n - 1, key); } } // Driver code public static void main(String args[]) { int arr[] = { -8, 1, 2, 3, 4, 5, -2, -3 }; int key = 5; int n, l, r; n = arr.length; l = 0; r = n - 1; int index; index = findBitonicPoint(arr, n, l, r); int x = searchBitonic(arr, n, key, index); if (x == -1) { System.out.println(\"Element Not Found\"); } else { System.out.println(\"Element Found at index \" + x); } }} /*This code is contributed by 29AjayKumar*/",
"e": 34407,
"s": 31101,
"text": null
},
{
"code": "# Python code to search key in bitonic array # Function for binary search in ascending partdef ascendingBinarySearch(arr, low, high, key): while low <= high: mid = low + (high - low) // 2 if arr[mid] == key: return mid if arr[mid] > key: high = mid - 1 else: low = mid + 1 return -1 # Function for binary search in descending part of arraydef descendingBinarySearch(arr, low, high, key): while low <= high: mid = low + (high - low) // 2 if arr[mid] == key: return mid if arr[mid] < key: high = mid - 1 else: low = mid + 1 return -1 # Find bitonic pointdef findBitonicPoint(arr, n, l, r): bitonicPoint = 0 mid = (r + l) // 2 if arr[mid] > arr[mid-1] and arr[mid] > arr[mid+1]: return mid elif arr[mid] > arr[mid-1] and arr[mid] < arr[mid+1]: bitonicPoint = findBitonicPoint(arr, n, mid, r) else: bitonicPoint = finsBitonicPoint(arr, n, l, mid) return bitonicPoint # Function to search key in bitonic arraydef searchBitonic(arr, n, key, index): if key > arr[index]: return -1 elif key == arr[index]: return index else: temp = ascendingBinarySearch(arr, 0, index-1, key) if temp != -1: return temp # search in right of k return descendingBinarySearch(arr, index+1, n-1, key) # Driver codedef main(): arr = [-8, 1, 2, 3, 4, 5, -2, -3] key = 1 n = len(arr) l = 0 r = n - 1 # Function call index = findBitonicPoint(arr, n, l, r) x = searchBitonic(arr, n, key, index) if x == -1: print(\"Element Not Found\") else: print(\"Element Found at index\", x) main() # This code is contributed by stutipathak31jan",
"e": 36318,
"s": 34407,
"text": null
},
{
"code": "// C# code to search key in bitonic arrayusing System; class GFG { // Function for binary search in ascending part static int ascendingBinarySearch(int[] arr, int low, int high, int key) { while (low <= high) { int mid = low + (high - low) / 2; if (arr[mid] == key) { return mid; } if (arr[mid] > key) { high = mid - 1; } else { low = mid + 1; } } return -1; } // Function for binary search in descending part of // array static int descendingBinarySearch(int[] arr, int low, int high, int key) { while (low <= high) { int mid = low + (high - low) / 2; if (arr[mid] == key) { return mid; } if (arr[mid] < key) { high = mid - 1; } else { low = mid + 1; } } return -1; } // finding bitonic point static int findBitonicPoint(int[] arr, int n, int l, int r) { int mid; int bitonicPoint = 0; mid = (r + l) / 2; if (arr[mid] > arr[mid - 1] && arr[mid] > arr[mid + 1]) { return mid; } else { if (arr[mid] > arr[mid - 1] && arr[mid] < arr[mid + 1]) { bitonicPoint = findBitonicPoint(arr, n, mid, r); } else { if (arr[mid] < arr[mid - 1] && arr[mid] > arr[mid + 1]) { bitonicPoint = findBitonicPoint(arr, n, l, mid); } } } return bitonicPoint; } // Function to search key in bitonic array static int searchBitonic(int[] arr, int n, int key, int index) { if (key > arr[index]) { return -1; } else if (key == arr[index]) { return index; } else { int temp = ascendingBinarySearch( arr, 0, index - 1, key); if (temp != -1) { return temp; } // Search in right of k return descendingBinarySearch(arr, index + 1, n - 1, key); } } // Driver Code static public void Main() { int[] arr = { -8, 1, 2, 3, 4, 5, -2, -3 }; int key = 1; int n, l, r; n = arr.Length; l = 0; r = n - 1; int index; index = findBitonicPoint(arr, n, l, r); int x = searchBitonic(arr, n, key, index); if (x == -1) { Console.WriteLine(\"Element Not Found\"); } else { Console.WriteLine(\"Element Found at index \" + x); } }} // This code is contributed by ajit",
"e": 39367,
"s": 36318,
"text": null
},
{
"code": "<script> // JavaScript code to search key in bitonic array // Function for binary search in ascending partfunction ascendingBinarySearch(arr, low, high, key) { while (low <= high) { let mid = Math.floor(low + (high - low) / 2); if (arr[mid] == key) return mid; if (arr[mid] > key) high = mid - 1; else low = mid + 1; } return -1;} // Function for binary search in// descending part of arrayfunction descendingBinarySearch(arr, low, high, key) { while (low <= high) { let mid = Math.floor(low + (high - low) / 2); if (arr[mid] == key) return mid; if (arr[mid] < key) high = mid - 1; else low = mid + 1; } return -1;} // finding bitonic pointfunction findBitonicPoint(arr, n, l, r) { let mid; let bitonicPoint = 0; mid = Math.floor((r + l) / 2); if (arr[mid] > arr[mid - 1] && arr[mid] > arr[mid + 1]) { return mid; } else if (arr[mid] > arr[mid - 1] && arr[mid] < arr[mid + 1]) { bitonicPoint = findBitonicPoint(arr, n, mid, r); } else if (arr[mid] < arr[mid - 1] && arr[mid] > arr[mid + 1]) { bitonicPoint = findBitonicPoint(arr, n, l, mid); } return bitonicPoint;} // Function to search key in// bitonic arrayfunction searchBitonic(arr, n, key, index) { if (key > arr[index]) return -1; else if (key == arr[index]) return index; else { let temp = ascendingBinarySearch(arr, 0, index - 1, key); if (temp != -1) { return temp; } // Search in right of k return descendingBinarySearch(arr, index + 1, n - 1, key); }} // Driver code let arr = [-8, 1, 2, 3, 4, 5, -2, -3];let key = 1;let n, l, r;n = arr.length;l = 0;r = n - 1;let index; // Function callindex = findBitonicPoint(arr, n, l, r); let x = searchBitonic(arr, n, key, index); if (x == -1) document.write(\"Element Not Found\" + \"<br>\");else document.write(\"Element Found at index \" + x + \"<br>\"); </script>",
"e": 41502,
"s": 39367,
"text": null
},
{
"code": null,
"e": 41527,
"s": 41502,
"text": "Element Found at index 1"
},
{
"code": null,
"e": 41575,
"s": 41527,
"text": "Time complexity: O(log n) Auxiliary Space: O(1)"
},
{
"code": null,
"e": 41998,
"s": 41575,
"text": "This article is contributed by Vaishali Goyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 42010,
"s": 41998,
"text": "29AjayKumar"
},
{
"code": null,
"e": 42016,
"s": 42010,
"text": "jit_t"
},
{
"code": null,
"e": 42030,
"s": 42016,
"text": "shresth_mehta"
},
{
"code": null,
"e": 42045,
"s": 42030,
"text": "guptarashi2001"
},
{
"code": null,
"e": 42056,
"s": 42045,
"text": "prajjwal21"
},
{
"code": null,
"e": 42073,
"s": 42056,
"text": "stutipathak31jan"
},
{
"code": null,
"e": 42090,
"s": 42073,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 42100,
"s": 42090,
"text": "ankit1210"
},
{
"code": null,
"e": 42117,
"s": 42100,
"text": "nehakumariintern"
},
{
"code": null,
"e": 42131,
"s": 42117,
"text": "Binary Search"
},
{
"code": null,
"e": 42138,
"s": 42131,
"text": "Arrays"
},
{
"code": null,
"e": 42145,
"s": 42138,
"text": "Arrays"
},
{
"code": null,
"e": 42159,
"s": 42145,
"text": "Binary Search"
},
{
"code": null,
"e": 42257,
"s": 42159,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 42325,
"s": 42257,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 42369,
"s": 42325,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 42417,
"s": 42369,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 42440,
"s": 42417,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 42472,
"s": 42440,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 42486,
"s": 42472,
"text": "Linear Search"
},
{
"code": null,
"e": 42507,
"s": 42486,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 42552,
"s": 42507,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 42600,
"s": 42552,
"text": "Search an element in a sorted and rotated array"
}
] |
Optimizers in Tensorflow - GeeksforGeeks
|
27 Jan, 2022
Optimizers are techniques or algorithms used to decrease loss (an error) by tuning various parameters and weights, hence minimizing the loss function, providing better accuracy of model faster.
Optimizer is the extended class in Tensorflow, that is initialized with parameters of the model but no tensor is given to it. The basic optimizer provided by Tensorflow is:
tf.train.Optimizer - Tensorflow version 1.x
tf.compat.v1.train.Optimizer - Tensorflow version 2.x
This class is never used directly but its sub-classes are instantiated.
Before explaining let’s first learn about the algorithm on top of which others are made .i.e. gradient descent. Gradient descent links weights and loss functions, as gradient means a measure of change, gradient descent algorithm determines what should be done to minimize loss functions using partial derivative – like add 0.7, subtract 0.27 etc. But obstacle arises when it gets stuck at local minima instead of global minima in the case of large multi-dimensional datasets.
Syntax: tf.compat.v1.train.GradientDescentOptimizer(learning_rate,
use_locking,
name = 'GradientDescent)
Parameters:
learning_rate: rate at which algorithm updates the parameter.
Tensor or float type of value.
use_locking: Use locks for update operations if True
name: Optional name for the operation
Tensorflow predominantly supports 9 optimizer classes including its base class (Optimizer).
Gradient Descent
SGD
AdaGrad
RMSprop
Adadelta
Adam
AdaMax
NAdam
FTRL
The stochastic Gradient Descent (SGD) optimization method executes a parameter update for every training example. In the case of huge datasets, SGD performs redundant calculations resulting in frequent updates having high variance causing the objective function to vary heavily.
Syntax: tf.kears.optimizers.SGD(learning_rate = 0.01,
momentum=0.0,
nesterov=False,
name='SGD',
**kwargs)
Parameters:
learning_rate: rate at which algorithm updates the parameter.
Tensor or float type of value.Default value is 0.01
momentum: accelerates gradient descent in appropriate
direction. Float type of value. Default value is 0.0
nesterov: Whether or not to apply Nesterov Momentum.
Boolean type of value. Default value is False.
name: Optional name for the operation
**kwargs: Keyworded variable length argument length.
Advantages:
Requires Less Memory.Frequent alteration of model parameters.If Momentum is used then helps to reduce noise.
Requires Less Memory.
Frequent alteration of model parameters.
If Momentum is used then helps to reduce noise.
Disadvantages:
High VarianceComputationally Expensive
High Variance
Computationally Expensive
AdaGrad stands for Adaptive Gradient Algorithm. AdaGrad optimizer modifies the learning rate particularly with individual features .i.e. some weights in the dataset may have separate learning rates than others.
Syntax: tf.keras.optimizers.Adagrad(learning_rate=0.001,
initial_accumulator_value=0.1,
epsilon=1e-07,
name="Adagrad",
**kwargs)
Parameters:
learning_rate: rate at which algorithm updates the parameter.
Tensor or float type of value.Default value is 0.001
initial_accumulator_value: Starting value for the per parameter
momentum. Floating point type of value.
Must be non-negative.Default value is 0.1
epsilon: Small value used to sustain numerical stability.
Floating point type of value. Default value is 1e-07.
name: Optional name for the operation
**kwargs: Keyworded variable length argument length
Advantages:
Best suited for Sparse DatasetLearning Rate updates with iterations
Best suited for Sparse Dataset
Learning Rate updates with iterations
Disadvantages:
Learning rate becomes small with an increase in depth of neural networkMay result in dead neuron problem
Learning rate becomes small with an increase in depth of neural network
May result in dead neuron problem
RMSprop stands for Root Mean Square Propagation. RMSprop optimizer doesn’t let gradients accumulate for momentum instead only accumulates gradients in a particular fixed window. It can be considered as an updated version of AdaGrad with few improvements. RMSprop uses simple momentum instead of Nesterov momentum.
Syntax: tf.keras.optimizers.RMSprop(learning_rate=0.001,
rho=0.9,
momentum=0.0,
epsilon=1e-07,
centered=False,
name='RMSprop',
**kwargs)
Parameters:
learning_rate: rate at which algorithm updates the parameter.
Tensor or float type of value.Default value is 0.001
rho: Discounting factor for gradients. Default value is 0.9
momentum: accelerates rmsprop in appropriate direction.
Float type of value. Default value is 0.0
epsilon: Small value used to sustain numerical stability.
Floating point type of value. Default value is 1e-07
centered: By this gradients are normalised by the variance of
gradient. Boolean type of value. Setting value to True may
help with training model however it is computationally
more expensive. Default value if False.
name: Optional name for the operation
**kwargs: Keyworded variable length argument length.
Advantages:
The learning rate is automatically adjusted.The discrete Learning rate for every parameter
The learning rate is automatically adjusted.
The discrete Learning rate for every parameter
Disadvantage: Slow learning
Adaptive Delta (Adadelta) optimizer is an extension of AdaGrad (similar to RMSprop optimizer), however, Adadelta discarded the use of learning rate by replacing it with an exponential moving mean of squared delta (difference between current and updated weights). It also tries to eliminate the decaying learning rate problem.
Syntax: tf.keras.optimizers.Adadelta(learning_rate=0.001,
rho=0.95,
epsilon=1e-07,
name='Adadelta',
**kwargs)
Parameters:
learning_rate: rate at which algorithm updates the parameter.
Tensor or float type of value.Default value is 0.001
rho: Decay rate. Tensor or Floating point type of value.
Default value is 0.95
epsilon: Small value used to sustain numerical stability.
Floating point type of value. Default value is 1e-07
name: Optional name for the operation
**kwargs: Keyworded variable length argument length
Advantage: Setting of default learning rate is not required.
Disadvantage: Computationally expensive
Adaptive Moment Estimation (Adam) is among the top-most optimization techniques used today. In this method, the adaptive learning rate for each parameter is calculated. This method combines advantages of both RMSprop and momentum .i.e. stores decaying average of previous gradients and previously squared gradients.
Syntax: tf.keras.optimizers.Adam(leaarning_rate=0.001,
beta_1=0.9,
beta_2=0.999,
epsilon=1e-07,
amsgrad=False,
name='Adam',
**kwargs)
Parameters:
learning_rate: rate at which algorithm updates the parameter.
Tensor or float type of value.Default value is 0.001
beta_1: Exponential decay rate for 1st moment. Constant Float
tensor or float type of value. Default value is 0.9
beta_2: Exponential decay rate for 2nd moment. Constant Float
tensor or float type of value. Default value is 0.999
epsilon: Small value used to sustain numerical stability.
Floating point type of value. Default value is 1e-07
amsgrad: Whether to use AMSGrad variant or not.
Default value is False.
name: Optional name for the operation
**kwargs: Keyworded variable length argument length
Advantages:
Easy ImplementationRequires less memoryComputationally efficient
Easy Implementation
Requires less memory
Computationally efficient
Disadvantages:
Can have weight decay problemSometimes may not converge to an optimal solution
Can have weight decay problem
Sometimes may not converge to an optimal solution
AdaMax is an alteration of the Adam optimizer. It is built on the adaptive approximation of low-order moments (based off on infinity norm). Sometimes in the case of embeddings, AdaMax is considered better than Adam.
Syntax: tf.keras.optimizers.Adamax(learning_rate=0.001,
beta_1=0.9,
beta_2=0.999,
epsilon=1e-07,
name='Adamax',
**kwargs)
Parameters:
learning_rate: rate at which algorithm updates the parameter.
Tensor or float type of value.Default value is 0.001
beta_1: Exponential decay rate for 1st moment. Constant Float
tensor or float type of value. Default value is 0.9
beta_2: Exponential decay rate for weighted infinity norm.
Constant Float tensor or float type of value.
Default value is 0.999
epsilon: Small value used to sustain numerical stability.
Floating point type of value. Default value is 1e-07
name: Optional name for the operation
**kwargs: Keyworded variable length argument length
Advantages:
Infinite order makes the algorithm stable.Requires less tuning on hyperparameters
Infinite order makes the algorithm stable.
Requires less tuning on hyperparameters
Disadvantage: Generalization Issue
NAdam is a short form for Nesterov and Adam optimizer. NAdam uses Nesterov momentum to update gradient than vanilla momentum used by Adam.
Syntax: tf.keras.optimizers.Nadam(learning_rate=0.001,
beta_1=0.9,
beta_2=0.999,
epsilon=1e-07,
name='Nadam',
**kwargs)
Parameters:
learning_rate: rate at which algorithm updates the parameter.
Tensor or float type of value.Default value is 0.001
beta_1: Exponential decay rate for 1st moment. Constant Float
tensor or float type of value. Default value is 0.9
beta_2: Exponential decay rate for weighted infinity norm.
Constant Float tensor or float type of value.
Default value is 0.999
epsilon: Small value used to sustain numerical stability.
Floating point type of value. Default value is 1e-07
name: Optional name for the operation
**kwargs: Keyworded variable length argument length
Advantages:
Gives better results for gradients with high curvature or noisy gradients.Learns faster
Gives better results for gradients with high curvature or noisy gradients.
Learns faster
Disadvantage: Sometimes may not converge to an optimal solution
Follow The Regularized Leader (FTRL) is an optimization algorithm best suited for shallow models having sparse and large feature spaces. This version supports both shrinkage-type L2 regularization (summation of L2 penalty and loss function) and online L2 regularization.
Syntax: tf.keras.optimizers.Ftrl(learning_rate=0.001,
learning_rate_power=-0.5,
initial_accumulator_value=0.1,
l1_regularization_strength=0.0,
l2_regularization_strength=0.0,
name='Ftrl',
l2_shrinkage_regularization_strength=0.0,
beta=0.0,
**kwargs)
Parameters:
learning_rate: rate at which algorithm updates the parameter.
Tensor or float type of value.Default value is 0.001
learning_rate_power: Controls the drop in learning rate during
training. Float type of value. Should be less
than or equal to 0. Default value is -0.5.
initial_accumulator_value: Initial value for accumulator. Value
should be greater than or equal to zero.
Default value is 0.1.
l1_regularization_strength:Stabilization penalty.
Only positive values or 0 is allowed.
Float type of value.Default value is 0.0
l2_regularization_strength: Stabiliztion Penalty.
Only positive values or 0 is allowed.
Float type of value.Default value is 0.0
name: Optional name for the operation
l2_shrinkage_regularization_strength: Magnitude Penalty.
Only positive values or 0 is allowed.
Float type of value.Default value is 0.0
beta: Default float value is 0.0
**kwargs: Keyworded variable length argument length
Advantage: Can minimize loss function better.
Disadvantages:
Cannot achieve adequate stability if the range of the regularizer is insufficient.If the range of the regularizer is huge, then it’s far away from the optimal decision.
Cannot achieve adequate stability if the range of the regularizer is insufficient.
If the range of the regularizer is huge, then it’s far away from the optimal decision.
adnanirshad158
Picked
Python-Tensorflow
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n27 Jan, 2022"
},
{
"code": null,
"e": 25732,
"s": 25537,
"text": "Optimizers are techniques or algorithms used to decrease loss (an error) by tuning various parameters and weights, hence minimizing the loss function, providing better accuracy of model faster. "
},
{
"code": null,
"e": 25906,
"s": 25732,
"text": "Optimizer is the extended class in Tensorflow, that is initialized with parameters of the model but no tensor is given to it. The basic optimizer provided by Tensorflow is: "
},
{
"code": null,
"e": 26004,
"s": 25906,
"text": "tf.train.Optimizer - Tensorflow version 1.x\ntf.compat.v1.train.Optimizer - Tensorflow version 2.x"
},
{
"code": null,
"e": 26076,
"s": 26004,
"text": "This class is never used directly but its sub-classes are instantiated."
},
{
"code": null,
"e": 26553,
"s": 26076,
"text": "Before explaining let’s first learn about the algorithm on top of which others are made .i.e. gradient descent. Gradient descent links weights and loss functions, as gradient means a measure of change, gradient descent algorithm determines what should be done to minimize loss functions using partial derivative – like add 0.7, subtract 0.27 etc. But obstacle arises when it gets stuck at local minima instead of global minima in the case of large multi-dimensional datasets. "
},
{
"code": null,
"e": 26977,
"s": 26553,
"text": "Syntax: tf.compat.v1.train.GradientDescentOptimizer(learning_rate, \n use_locking,\n name = 'GradientDescent)\nParameters: \nlearning_rate: rate at which algorithm updates the parameter. \n Tensor or float type of value. \nuse_locking: Use locks for update operations if True\nname: Optional name for the operation"
},
{
"code": null,
"e": 27069,
"s": 26977,
"text": "Tensorflow predominantly supports 9 optimizer classes including its base class (Optimizer)."
},
{
"code": null,
"e": 27086,
"s": 27069,
"text": "Gradient Descent"
},
{
"code": null,
"e": 27090,
"s": 27086,
"text": "SGD"
},
{
"code": null,
"e": 27098,
"s": 27090,
"text": "AdaGrad"
},
{
"code": null,
"e": 27106,
"s": 27098,
"text": "RMSprop"
},
{
"code": null,
"e": 27115,
"s": 27106,
"text": "Adadelta"
},
{
"code": null,
"e": 27120,
"s": 27115,
"text": "Adam"
},
{
"code": null,
"e": 27127,
"s": 27120,
"text": "AdaMax"
},
{
"code": null,
"e": 27133,
"s": 27127,
"text": "NAdam"
},
{
"code": null,
"e": 27138,
"s": 27133,
"text": "FTRL"
},
{
"code": null,
"e": 27419,
"s": 27138,
"text": "The stochastic Gradient Descent (SGD) optimization method executes a parameter update for every training example. In the case of huge datasets, SGD performs redundant calculations resulting in frequent updates having high variance causing the objective function to vary heavily. "
},
{
"code": null,
"e": 28117,
"s": 27419,
"text": "Syntax: tf.kears.optimizers.SGD(learning_rate = 0.01,\n momentum=0.0, \n nesterov=False, \n name='SGD', \n **kwargs)\nParameters: \nlearning_rate: rate at which algorithm updates the parameter. \n Tensor or float type of value.Default value is 0.01\nmomentum: accelerates gradient descent in appropriate\n direction. Float type of value. Default value is 0.0\nnesterov: Whether or not to apply Nesterov Momentum.\n Boolean type of value. Default value is False.\nname: Optional name for the operation\n**kwargs: Keyworded variable length argument length."
},
{
"code": null,
"e": 28130,
"s": 28117,
"text": "Advantages: "
},
{
"code": null,
"e": 28239,
"s": 28130,
"text": "Requires Less Memory.Frequent alteration of model parameters.If Momentum is used then helps to reduce noise."
},
{
"code": null,
"e": 28261,
"s": 28239,
"text": "Requires Less Memory."
},
{
"code": null,
"e": 28302,
"s": 28261,
"text": "Frequent alteration of model parameters."
},
{
"code": null,
"e": 28350,
"s": 28302,
"text": "If Momentum is used then helps to reduce noise."
},
{
"code": null,
"e": 28366,
"s": 28350,
"text": "Disadvantages: "
},
{
"code": null,
"e": 28405,
"s": 28366,
"text": "High VarianceComputationally Expensive"
},
{
"code": null,
"e": 28419,
"s": 28405,
"text": "High Variance"
},
{
"code": null,
"e": 28445,
"s": 28419,
"text": "Computationally Expensive"
},
{
"code": null,
"e": 28657,
"s": 28445,
"text": "AdaGrad stands for Adaptive Gradient Algorithm. AdaGrad optimizer modifies the learning rate particularly with individual features .i.e. some weights in the dataset may have separate learning rates than others. "
},
{
"code": null,
"e": 29491,
"s": 28657,
"text": "Syntax: tf.keras.optimizers.Adagrad(learning_rate=0.001,\n initial_accumulator_value=0.1,\n epsilon=1e-07,\n name=\"Adagrad\",\n **kwargs)\nParameters: \nlearning_rate: rate at which algorithm updates the parameter. \n Tensor or float type of value.Default value is 0.001\ninitial_accumulator_value: Starting value for the per parameter \n momentum. Floating point type of value.\n Must be non-negative.Default value is 0.1\nepsilon: Small value used to sustain numerical stability. \n Floating point type of value. Default value is 1e-07.\nname: Optional name for the operation\n**kwargs: Keyworded variable length argument length"
},
{
"code": null,
"e": 29503,
"s": 29491,
"text": "Advantages:"
},
{
"code": null,
"e": 29571,
"s": 29503,
"text": "Best suited for Sparse DatasetLearning Rate updates with iterations"
},
{
"code": null,
"e": 29602,
"s": 29571,
"text": "Best suited for Sparse Dataset"
},
{
"code": null,
"e": 29640,
"s": 29602,
"text": "Learning Rate updates with iterations"
},
{
"code": null,
"e": 29655,
"s": 29640,
"text": "Disadvantages:"
},
{
"code": null,
"e": 29760,
"s": 29655,
"text": "Learning rate becomes small with an increase in depth of neural networkMay result in dead neuron problem"
},
{
"code": null,
"e": 29832,
"s": 29760,
"text": "Learning rate becomes small with an increase in depth of neural network"
},
{
"code": null,
"e": 29866,
"s": 29832,
"text": "May result in dead neuron problem"
},
{
"code": null,
"e": 30180,
"s": 29866,
"text": "RMSprop stands for Root Mean Square Propagation. RMSprop optimizer doesn’t let gradients accumulate for momentum instead only accumulates gradients in a particular fixed window. It can be considered as an updated version of AdaGrad with few improvements. RMSprop uses simple momentum instead of Nesterov momentum."
},
{
"code": null,
"e": 31310,
"s": 30180,
"text": "Syntax: tf.keras.optimizers.RMSprop(learning_rate=0.001, \n rho=0.9, \n momentum=0.0, \n epsilon=1e-07, \n centered=False,\n name='RMSprop', \n **kwargs)\nParameters:\nlearning_rate: rate at which algorithm updates the parameter. \n Tensor or float type of value.Default value is 0.001\nrho: Discounting factor for gradients. Default value is 0.9\nmomentum: accelerates rmsprop in appropriate direction. \n Float type of value. Default value is 0.0\nepsilon: Small value used to sustain numerical stability. \n Floating point type of value. Default value is 1e-07\ncentered: By this gradients are normalised by the variance of \n gradient. Boolean type of value. Setting value to True may\n help with training model however it is computationally \n more expensive. Default value if False.\nname: Optional name for the operation\n**kwargs: Keyworded variable length argument length."
},
{
"code": null,
"e": 31322,
"s": 31310,
"text": "Advantages:"
},
{
"code": null,
"e": 31413,
"s": 31322,
"text": "The learning rate is automatically adjusted.The discrete Learning rate for every parameter"
},
{
"code": null,
"e": 31458,
"s": 31413,
"text": "The learning rate is automatically adjusted."
},
{
"code": null,
"e": 31505,
"s": 31458,
"text": "The discrete Learning rate for every parameter"
},
{
"code": null,
"e": 31533,
"s": 31505,
"text": "Disadvantage: Slow learning"
},
{
"code": null,
"e": 31859,
"s": 31533,
"text": "Adaptive Delta (Adadelta) optimizer is an extension of AdaGrad (similar to RMSprop optimizer), however, Adadelta discarded the use of learning rate by replacing it with an exponential moving mean of squared delta (difference between current and updated weights). It also tries to eliminate the decaying learning rate problem."
},
{
"code": null,
"e": 32558,
"s": 31859,
"text": "Syntax: tf.keras.optimizers.Adadelta(learning_rate=0.001, \n rho=0.95, \n epsilon=1e-07, \n name='Adadelta',\n **kwargs)\nParameters:\nlearning_rate: rate at which algorithm updates the parameter. \n Tensor or float type of value.Default value is 0.001\nrho: Decay rate. Tensor or Floating point type of value.\n Default value is 0.95\nepsilon: Small value used to sustain numerical stability. \n Floating point type of value. Default value is 1e-07\nname: Optional name for the operation\n**kwargs: Keyworded variable length argument length"
},
{
"code": null,
"e": 32619,
"s": 32558,
"text": "Advantage: Setting of default learning rate is not required."
},
{
"code": null,
"e": 32659,
"s": 32619,
"text": "Disadvantage: Computationally expensive"
},
{
"code": null,
"e": 32976,
"s": 32659,
"text": "Adaptive Moment Estimation (Adam) is among the top-most optimization techniques used today. In this method, the adaptive learning rate for each parameter is calculated. This method combines advantages of both RMSprop and momentum .i.e. stores decaying average of previous gradients and previously squared gradients. "
},
{
"code": null,
"e": 33997,
"s": 32976,
"text": "Syntax: tf.keras.optimizers.Adam(leaarning_rate=0.001, \n beta_1=0.9, \n beta_2=0.999, \n epsilon=1e-07, \n amsgrad=False,\n name='Adam', \n **kwargs)\nParameters:\nlearning_rate: rate at which algorithm updates the parameter. \n Tensor or float type of value.Default value is 0.001\nbeta_1: Exponential decay rate for 1st moment. Constant Float \n tensor or float type of value. Default value is 0.9\nbeta_2: Exponential decay rate for 2nd moment. Constant Float \n tensor or float type of value. Default value is 0.999\nepsilon: Small value used to sustain numerical stability. \n Floating point type of value. Default value is 1e-07\namsgrad: Whether to use AMSGrad variant or not. \n Default value is False.\nname: Optional name for the operation\n**kwargs: Keyworded variable length argument length"
},
{
"code": null,
"e": 34009,
"s": 33997,
"text": "Advantages:"
},
{
"code": null,
"e": 34074,
"s": 34009,
"text": "Easy ImplementationRequires less memoryComputationally efficient"
},
{
"code": null,
"e": 34094,
"s": 34074,
"text": "Easy Implementation"
},
{
"code": null,
"e": 34115,
"s": 34094,
"text": "Requires less memory"
},
{
"code": null,
"e": 34141,
"s": 34115,
"text": "Computationally efficient"
},
{
"code": null,
"e": 34156,
"s": 34141,
"text": "Disadvantages:"
},
{
"code": null,
"e": 34235,
"s": 34156,
"text": "Can have weight decay problemSometimes may not converge to an optimal solution"
},
{
"code": null,
"e": 34265,
"s": 34235,
"text": "Can have weight decay problem"
},
{
"code": null,
"e": 34315,
"s": 34265,
"text": "Sometimes may not converge to an optimal solution"
},
{
"code": null,
"e": 34532,
"s": 34315,
"text": "AdaMax is an alteration of the Adam optimizer. It is built on the adaptive approximation of low-order moments (based off on infinity norm). Sometimes in the case of embeddings, AdaMax is considered better than Adam. "
},
{
"code": null,
"e": 35456,
"s": 34532,
"text": "Syntax: tf.keras.optimizers.Adamax(learning_rate=0.001, \n beta_1=0.9, \n beta_2=0.999, \n epsilon=1e-07,\n name='Adamax', \n **kwargs)\nParameters:\nlearning_rate: rate at which algorithm updates the parameter. \n Tensor or float type of value.Default value is 0.001\nbeta_1: Exponential decay rate for 1st moment. Constant Float \n tensor or float type of value. Default value is 0.9\nbeta_2: Exponential decay rate for weighted infinity norm. \n Constant Float tensor or float type of value. \n Default value is 0.999\nepsilon: Small value used to sustain numerical stability. \n Floating point type of value. Default value is 1e-07\nname: Optional name for the operation\n**kwargs: Keyworded variable length argument length"
},
{
"code": null,
"e": 35469,
"s": 35456,
"text": "Advantages: "
},
{
"code": null,
"e": 35551,
"s": 35469,
"text": "Infinite order makes the algorithm stable.Requires less tuning on hyperparameters"
},
{
"code": null,
"e": 35594,
"s": 35551,
"text": "Infinite order makes the algorithm stable."
},
{
"code": null,
"e": 35634,
"s": 35594,
"text": "Requires less tuning on hyperparameters"
},
{
"code": null,
"e": 35669,
"s": 35634,
"text": "Disadvantage: Generalization Issue"
},
{
"code": null,
"e": 35809,
"s": 35669,
"text": "NAdam is a short form for Nesterov and Adam optimizer. NAdam uses Nesterov momentum to update gradient than vanilla momentum used by Adam. "
},
{
"code": null,
"e": 36726,
"s": 35809,
"text": "Syntax: tf.keras.optimizers.Nadam(learning_rate=0.001, \n beta_1=0.9, \n beta_2=0.999, \n epsilon=1e-07,\n name='Nadam', \n **kwargs)\nParameters:\nlearning_rate: rate at which algorithm updates the parameter. \n Tensor or float type of value.Default value is 0.001\nbeta_1: Exponential decay rate for 1st moment. Constant Float \n tensor or float type of value. Default value is 0.9\nbeta_2: Exponential decay rate for weighted infinity norm. \n Constant Float tensor or float type of value. \n Default value is 0.999\nepsilon: Small value used to sustain numerical stability. \n Floating point type of value. Default value is 1e-07\nname: Optional name for the operation\n**kwargs: Keyworded variable length argument length"
},
{
"code": null,
"e": 36739,
"s": 36726,
"text": "Advantages: "
},
{
"code": null,
"e": 36827,
"s": 36739,
"text": "Gives better results for gradients with high curvature or noisy gradients.Learns faster"
},
{
"code": null,
"e": 36902,
"s": 36827,
"text": "Gives better results for gradients with high curvature or noisy gradients."
},
{
"code": null,
"e": 36916,
"s": 36902,
"text": "Learns faster"
},
{
"code": null,
"e": 36981,
"s": 36916,
"text": "Disadvantage: Sometimes may not converge to an optimal solution "
},
{
"code": null,
"e": 37254,
"s": 36981,
"text": "Follow The Regularized Leader (FTRL) is an optimization algorithm best suited for shallow models having sparse and large feature spaces. This version supports both shrinkage-type L2 regularization (summation of L2 penalty and loss function) and online L2 regularization. "
},
{
"code": null,
"e": 38971,
"s": 37254,
"text": "Syntax: tf.keras.optimizers.Ftrl(learning_rate=0.001, \n learning_rate_power=-0.5, \n initial_accumulator_value=0.1,\n l1_regularization_strength=0.0, \n l2_regularization_strength=0.0,\n name='Ftrl', \n l2_shrinkage_regularization_strength=0.0, \n beta=0.0,\n **kwargs)\nParameters:\nlearning_rate: rate at which algorithm updates the parameter. \n Tensor or float type of value.Default value is 0.001\nlearning_rate_power: Controls the drop in learning rate during \n training. Float type of value. Should be less\n than or equal to 0. Default value is -0.5.\ninitial_accumulator_value: Initial value for accumulator. Value\n should be greater than or equal to zero.\n Default value is 0.1.\nl1_regularization_strength:Stabilization penalty.\n Only positive values or 0 is allowed.\n Float type of value.Default value is 0.0 \nl2_regularization_strength: Stabiliztion Penalty.\n Only positive values or 0 is allowed.\n Float type of value.Default value is 0.0\nname: Optional name for the operation\nl2_shrinkage_regularization_strength: Magnitude Penalty.\n Only positive values or 0 is allowed.\n Float type of value.Default value is 0.0 \nbeta: Default float value is 0.0\n**kwargs: Keyworded variable length argument length"
},
{
"code": null,
"e": 39017,
"s": 38971,
"text": "Advantage: Can minimize loss function better."
},
{
"code": null,
"e": 39032,
"s": 39017,
"text": "Disadvantages:"
},
{
"code": null,
"e": 39201,
"s": 39032,
"text": "Cannot achieve adequate stability if the range of the regularizer is insufficient.If the range of the regularizer is huge, then it’s far away from the optimal decision."
},
{
"code": null,
"e": 39284,
"s": 39201,
"text": "Cannot achieve adequate stability if the range of the regularizer is insufficient."
},
{
"code": null,
"e": 39371,
"s": 39284,
"text": "If the range of the regularizer is huge, then it’s far away from the optimal decision."
},
{
"code": null,
"e": 39386,
"s": 39371,
"text": "adnanirshad158"
},
{
"code": null,
"e": 39393,
"s": 39386,
"text": "Picked"
},
{
"code": null,
"e": 39411,
"s": 39393,
"text": "Python-Tensorflow"
},
{
"code": null,
"e": 39418,
"s": 39411,
"text": "Python"
},
{
"code": null,
"e": 39516,
"s": 39418,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39548,
"s": 39516,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 39590,
"s": 39548,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 39632,
"s": 39590,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 39659,
"s": 39632,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 39715,
"s": 39659,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 39737,
"s": 39715,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 39776,
"s": 39737,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 39807,
"s": 39776,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 39836,
"s": 39807,
"text": "Create a directory in Python"
}
] |
C Quiz - 113 - GeeksforGeeks
|
16 Feb, 2016
int A[100][100];
int main()
{
for(int i=1; i < 100 ; i++)
for(int j=1; j < 100;j++)
A[i][j] = (i/j)*(j/i);
return 0;
}
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Product Based Companies
Find size of largest subset with bitwise AND greater than their bitwise XOR
How to Replace Values in Column Based on Condition in Pandas?
C Program to read contents of Whole File
Insert Image in a Jupyter Notebook
How to Replace Values in a List in Python?
How to Read Text Files with Pandas?
How to Compare Two Columns in Pandas?
Python Data Structures and Algorithms
Data Science With Python Tutorial
|
[
{
"code": null,
"e": 28855,
"s": 28827,
"text": "\n16 Feb, 2016"
},
{
"code": null,
"e": 29007,
"s": 28855,
"text": " int A[100][100];\n int main()\n {\n for(int i=1; i < 100 ; i++)\n for(int j=1; j < 100;j++)\n A[i][j] = (i/j)*(j/i);\n return 0;\n }\n\n"
},
{
"code": null,
"e": 29105,
"s": 29007,
"text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here."
},
{
"code": null,
"e": 29158,
"s": 29105,
"text": "Must Do Coding Questions for Product Based Companies"
},
{
"code": null,
"e": 29234,
"s": 29158,
"text": "Find size of largest subset with bitwise AND greater than their bitwise XOR"
},
{
"code": null,
"e": 29296,
"s": 29234,
"text": "How to Replace Values in Column Based on Condition in Pandas?"
},
{
"code": null,
"e": 29337,
"s": 29296,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 29372,
"s": 29337,
"text": "Insert Image in a Jupyter Notebook"
},
{
"code": null,
"e": 29415,
"s": 29372,
"text": "How to Replace Values in a List in Python?"
},
{
"code": null,
"e": 29451,
"s": 29415,
"text": "How to Read Text Files with Pandas?"
},
{
"code": null,
"e": 29489,
"s": 29451,
"text": "How to Compare Two Columns in Pandas?"
},
{
"code": null,
"e": 29527,
"s": 29489,
"text": "Python Data Structures and Algorithms"
}
] |
C++ Inheritance Quiz - GeeksQuiz
|
01 Jun, 2021
Base1's destructor
Base2's destructor
Derived's destructor
Derived's destructor
Base2's destructor
Base1's destructor
Derived's destructor
#include<iostream>
using namespace std;
class base {
int arr[10];
};
class b1: virtual public base { };
class b2: virtual public base { };
class derived: public b1, public b2 {};
int main(void)
{
cout << sizeof(derived);
return 0;
}
This is Derived class
This is Base class
This is Base class
This is Derived class
This is Base class
This is Base class
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Product Based Companies
How to Replace Values in Column Based on Condition in Pandas?
C Program to read contents of Whole File
How to Replace Values in a List in Python?
Spring - REST Controller
Epam Interview Experience for Junior Software Engineer
EPAM Interview Experience | On-Campus 2022
How to Read Text Files with Pandas?
Construct a DFA that Start With aa or bb
Python Data Structures and Algorithms
|
[
{
"code": null,
"e": 28855,
"s": 28827,
"text": "\n01 Jun, 2021"
},
{
"code": null,
"e": 28914,
"s": 28855,
"text": "Base1's destructor\nBase2's destructor\nDerived's destructor"
},
{
"code": null,
"e": 28974,
"s": 28914,
"text": "Derived's destructor\nBase2's destructor\nBase1's destructor\n"
},
{
"code": null,
"e": 28995,
"s": 28974,
"text": "Derived's destructor"
},
{
"code": null,
"e": 29251,
"s": 28995,
"text": "#include<iostream>\nusing namespace std;\n \nclass base {\n int arr[10]; \n};\n \nclass b1: virtual public base { };\n \nclass b2: virtual public base { };\n \nclass derived: public b1, public b2 {};\n \nint main(void)\n{ \n cout << sizeof(derived);\n return 0;\n} "
},
{
"code": null,
"e": 29292,
"s": 29251,
"text": "This is Derived class\nThis is Base class"
},
{
"code": null,
"e": 29333,
"s": 29292,
"text": "This is Base class\nThis is Derived class"
},
{
"code": null,
"e": 29371,
"s": 29333,
"text": "This is Base class\nThis is Base class"
},
{
"code": null,
"e": 29469,
"s": 29371,
"text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here."
},
{
"code": null,
"e": 29522,
"s": 29469,
"text": "Must Do Coding Questions for Product Based Companies"
},
{
"code": null,
"e": 29584,
"s": 29522,
"text": "How to Replace Values in Column Based on Condition in Pandas?"
},
{
"code": null,
"e": 29625,
"s": 29584,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 29668,
"s": 29625,
"text": "How to Replace Values in a List in Python?"
},
{
"code": null,
"e": 29693,
"s": 29668,
"text": "Spring - REST Controller"
},
{
"code": null,
"e": 29748,
"s": 29693,
"text": "Epam Interview Experience for Junior Software Engineer"
},
{
"code": null,
"e": 29791,
"s": 29748,
"text": "EPAM Interview Experience | On-Campus 2022"
},
{
"code": null,
"e": 29827,
"s": 29791,
"text": "How to Read Text Files with Pandas?"
},
{
"code": null,
"e": 29868,
"s": 29827,
"text": "Construct a DFA that Start With aa or bb"
}
] |
C# Dictionary with examples - GeeksforGeeks
|
28 Feb, 2019
In C#, Dictionary is a generic collection which is generally used to store key/value pairs. The working of Dictionary is quite similar to the non-generic hashtable. The advantage of Dictionary is, it is generic type. Dictionary is defined under System.Collection.Generic namespace. It is dynamic in nature means the size of the dictionary is grows according to the need.
Important Points:
The Dictionary class implements theIDictionary<TKey,TValue> InterfaceIReadOnlyCollection<KeyValuePair<TKey,TValue>> InterfaceIReadOnlyDictionary<TKey,TValue> InterfaceIDictionary Interface
IDictionary<TKey,TValue> Interface
IReadOnlyCollection<KeyValuePair<TKey,TValue>> Interface
IReadOnlyDictionary<TKey,TValue> Interface
IDictionary Interface
In Dictionary, the key cannot be null, but value can be.
In Dictionary, key must be unique. Duplicate keys are not allowed if you try to use duplicate key then compiler will throw an exception.
In Dictionary, you can only store same types of elements.
The capacity of a Dictionary is the number of elements that Dictionary can hold.
Dictionary class has 7 constructors which are used to create the Dictionary, here we only use Dictionary<TKey, TValue>() constructor and if you want to learn more about constructors then refer C# | Dictionary Class.
Dictionary<TKey, TValue>(): This constructor is used to create an instance of the Dictionary<TKey, TValue> class that is empty, has the default initial capacity, and uses the default equality comparer for the key type as follows:
Step 1: IncludeSystem.Collection.Generics namespace in your program with the help of using keyword.
Syntax:
using System.Collection.Generics;
Step 2: Create a Dictionary using Dictionary<TKey, TValue> class as shown below:
Dictionary dictionary_name = new Dictionary();
Step 3: If you want to add elements in your Dictionary then use Add() method to add key/value pairs in your Dictionary. And you can also add key/value pair in the dictionary without using Add method. As shown in the below example.
Step 4: The key/value pair of the Dictionary is accessed using three different ways:
for loop: You can use for loop to access the key/value pairs of the Dictionary.Example:for(int x=0; i< My_dict1.Count; x++){ Console.WriteLine("{0} and {1}", My_dict1.Keys.ElementAt(x), My_dict1[ My_dict1.Keys.ElementAt(x)]);}
Example:
for(int x=0; i< My_dict1.Count; x++){ Console.WriteLine("{0} and {1}", My_dict1.Keys.ElementAt(x), My_dict1[ My_dict1.Keys.ElementAt(x)]);}
Using Index: You can access individual key/value pair of the Dictionary by using its index value. Here, you just specify the key in the index to get the value from the given dictionary, no need to specify the index. Indexer always takes the key as a parameter, if the given key is not available in the dictionary, then it gives KeyNotFoundException.Example:Console.WriteLine("Value is:{0}", My_dicti[1123]);Console.WriteLine("Value is:{0}", My_dicti[1125]);
Example:
Console.WriteLine("Value is:{0}", My_dicti[1123]);Console.WriteLine("Value is:{0}", My_dicti[1125]);
foreach loop: You can use foreach loop to access the key/value pairs of the dictionary.As shown in the below example we access the Dictionary using a foreach loop.
Example:
// C# program to illustrate how // to create a dictionaryusing System;using System.Collections.Generic; class GFG { // Main Method static public void Main () { // Creating a dictionary // using Dictionary<TKey,TValue> class Dictionary<int, string> My_dict1 = new Dictionary<int, string>(); // Adding key/value pairs // in the Dictionary // Using Add() method My_dict1.Add(1123, "Welcome"); My_dict1.Add(1124, "to"); My_dict1.Add(1125, "GeeksforGeeks"); foreach(KeyValuePair<int, string> ele1 in My_dict1) { Console.WriteLine("{0} and {1}", ele1.Key, ele1.Value); } Console.WriteLine(); // Creating another dictionary // using Dictionary<TKey,TValue> class // adding key/value pairs without // using Add method Dictionary<string, string> My_dict2 = new Dictionary<string, string>(){ {"a.1", "Dog"}, {"a.2", "Cat"}, {"a.3", "Pig"} }; foreach(KeyValuePair<string, string> ele2 in My_dict2) { Console.WriteLine("{0} and {1}", ele2.Key, ele2.Value); } }}
1123 and Welcome
1124 and to
1125 and GeeksforGeeks
a.1 and Dog
a.2 and Cat
a.3 and Pig
In Dictionary, you are allowed to remove elements from the Dictionary. Dictionary<TKey, TValue> class provides two different methods to remove elements and the methods are:
Clear: This method removes all keys and values from the Dictionary<TKey,TValue>.
Remove: This method removes the value with the specified key from the Dictionary<TKey,TValue>.
Example:
// C# program to illustrate how // remove key/value pairs from // the dictionaryusing System;using System.Collections.Generic; class GFG { // Main Method static public void Main() { // Creating a dictionary // using Dictionary<TKey,TValue> class Dictionary<int, string> My_dict = new Dictionary<int, string>(); // Adding key/value pairs in the // Dictionary Using Add() method My_dict.Add(1123, "Welcome"); My_dict.Add(1124, "to"); My_dict.Add(1125, "GeeksforGeeks"); // Before Remove() method foreach(KeyValuePair<int, string> ele in My_dict) { Console.WriteLine("{0} and {1}", ele.Key, ele.Value); } Console.WriteLine(); // Using Remove() method My_dict.Remove(1123); // After Remove() method foreach(KeyValuePair<int, string> ele in My_dict) { Console.WriteLine("{0} and {1}", ele.Key, ele.Value); } Console.WriteLine(); // Using Clear() method My_dict.Clear(); Console.WriteLine("Total number of key/value "+ "pairs present in My_dict:{0}", My_dict.Count); }}
1123 and Welcome
1124 and to
1125 and GeeksforGeeks
1124 and to
1125 and GeeksforGeeks
Total number of key/value pairs present in My_dict:0
In Dictionary, you can check whether the given key or value present in the specified dictionary or not. The Dictionary<TKey, TValue> class provides two different methods for checking and the methods are:
ContainsKey: This method is used to check whether the Dictionary<TKey,TValue> contains the specified key.
ContainsValue: This method is used to check whether the Dictionary<TKey,TValue> contains a specific value.
Example:
// C# program to illustrate how// to check the given key or // value present in the dictionary// or notusing System;using System.Collections.Generic; class GFG { // Main Method static public void Main () { // Creating a dictionary // using Dictionary<TKey,TValue> class Dictionary<int, string> My_dict = new Dictionary<int, string>(); // Adding key/value pairs in the // Dictionary Using Add() method My_dict.Add(1123, "Welcome"); My_dict.Add(1124, "to"); My_dict.Add(1125, "GeeksforGeeks"); // Using ContainsKey() method to check // the specified key is present or not if (My_dict.ContainsKey(1122)==true) { Console.WriteLine("Key is found...!!"); } else { Console.WriteLine("Key is not found...!!"); } // Using ContainsValue() method to check // the specified value is present or not if (My_dict.ContainsValue("GeeksforGeeks")==true) { Console.WriteLine("Value is found...!!"); } else { Console.WriteLine("Value is not found...!!"); } }}
Key is not found...!!
Value is found...!!
CSharp Dictionary Class
CSharp-Generic-Namespace
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Abstract Class and Interface in C#
String.Split() Method in C# with Examples
C# | How to check whether a List contains a specified element
C# | IsNullOrEmpty() Method
C# | Delegates
C# | Arrays of Strings
C# | Abstract Classes
Difference between Ref and Out keywords in C#
Extension Method in C#
C# | String.IndexOf( ) Method | Set - 1
|
[
{
"code": null,
"e": 26549,
"s": 26521,
"text": "\n28 Feb, 2019"
},
{
"code": null,
"e": 26920,
"s": 26549,
"text": "In C#, Dictionary is a generic collection which is generally used to store key/value pairs. The working of Dictionary is quite similar to the non-generic hashtable. The advantage of Dictionary is, it is generic type. Dictionary is defined under System.Collection.Generic namespace. It is dynamic in nature means the size of the dictionary is grows according to the need."
},
{
"code": null,
"e": 26938,
"s": 26920,
"text": "Important Points:"
},
{
"code": null,
"e": 27127,
"s": 26938,
"text": "The Dictionary class implements theIDictionary<TKey,TValue> InterfaceIReadOnlyCollection<KeyValuePair<TKey,TValue>> InterfaceIReadOnlyDictionary<TKey,TValue> InterfaceIDictionary Interface"
},
{
"code": null,
"e": 27162,
"s": 27127,
"text": "IDictionary<TKey,TValue> Interface"
},
{
"code": null,
"e": 27219,
"s": 27162,
"text": "IReadOnlyCollection<KeyValuePair<TKey,TValue>> Interface"
},
{
"code": null,
"e": 27262,
"s": 27219,
"text": "IReadOnlyDictionary<TKey,TValue> Interface"
},
{
"code": null,
"e": 27284,
"s": 27262,
"text": "IDictionary Interface"
},
{
"code": null,
"e": 27341,
"s": 27284,
"text": "In Dictionary, the key cannot be null, but value can be."
},
{
"code": null,
"e": 27478,
"s": 27341,
"text": "In Dictionary, key must be unique. Duplicate keys are not allowed if you try to use duplicate key then compiler will throw an exception."
},
{
"code": null,
"e": 27536,
"s": 27478,
"text": "In Dictionary, you can only store same types of elements."
},
{
"code": null,
"e": 27617,
"s": 27536,
"text": "The capacity of a Dictionary is the number of elements that Dictionary can hold."
},
{
"code": null,
"e": 27833,
"s": 27617,
"text": "Dictionary class has 7 constructors which are used to create the Dictionary, here we only use Dictionary<TKey, TValue>() constructor and if you want to learn more about constructors then refer C# | Dictionary Class."
},
{
"code": null,
"e": 28063,
"s": 27833,
"text": "Dictionary<TKey, TValue>(): This constructor is used to create an instance of the Dictionary<TKey, TValue> class that is empty, has the default initial capacity, and uses the default equality comparer for the key type as follows:"
},
{
"code": null,
"e": 28163,
"s": 28063,
"text": "Step 1: IncludeSystem.Collection.Generics namespace in your program with the help of using keyword."
},
{
"code": null,
"e": 28171,
"s": 28163,
"text": "Syntax:"
},
{
"code": null,
"e": 28206,
"s": 28171,
"text": "using System.Collection.Generics; "
},
{
"code": null,
"e": 28287,
"s": 28206,
"text": "Step 2: Create a Dictionary using Dictionary<TKey, TValue> class as shown below:"
},
{
"code": null,
"e": 28334,
"s": 28287,
"text": "Dictionary dictionary_name = new Dictionary();"
},
{
"code": null,
"e": 28565,
"s": 28334,
"text": "Step 3: If you want to add elements in your Dictionary then use Add() method to add key/value pairs in your Dictionary. And you can also add key/value pair in the dictionary without using Add method. As shown in the below example."
},
{
"code": null,
"e": 28650,
"s": 28565,
"text": "Step 4: The key/value pair of the Dictionary is accessed using three different ways:"
},
{
"code": null,
"e": 28905,
"s": 28650,
"text": "for loop: You can use for loop to access the key/value pairs of the Dictionary.Example:for(int x=0; i< My_dict1.Count; x++){ Console.WriteLine(\"{0} and {1}\", My_dict1.Keys.ElementAt(x), My_dict1[ My_dict1.Keys.ElementAt(x)]);}"
},
{
"code": null,
"e": 28914,
"s": 28905,
"text": "Example:"
},
{
"code": "for(int x=0; i< My_dict1.Count; x++){ Console.WriteLine(\"{0} and {1}\", My_dict1.Keys.ElementAt(x), My_dict1[ My_dict1.Keys.ElementAt(x)]);}",
"e": 29082,
"s": 28914,
"text": null
},
{
"code": null,
"e": 29540,
"s": 29082,
"text": "Using Index: You can access individual key/value pair of the Dictionary by using its index value. Here, you just specify the key in the index to get the value from the given dictionary, no need to specify the index. Indexer always takes the key as a parameter, if the given key is not available in the dictionary, then it gives KeyNotFoundException.Example:Console.WriteLine(\"Value is:{0}\", My_dicti[1123]);Console.WriteLine(\"Value is:{0}\", My_dicti[1125]);"
},
{
"code": null,
"e": 29549,
"s": 29540,
"text": "Example:"
},
{
"code": "Console.WriteLine(\"Value is:{0}\", My_dicti[1123]);Console.WriteLine(\"Value is:{0}\", My_dicti[1125]);",
"e": 29650,
"s": 29549,
"text": null
},
{
"code": null,
"e": 29814,
"s": 29650,
"text": "foreach loop: You can use foreach loop to access the key/value pairs of the dictionary.As shown in the below example we access the Dictionary using a foreach loop."
},
{
"code": null,
"e": 29823,
"s": 29814,
"text": "Example:"
},
{
"code": "// C# program to illustrate how // to create a dictionaryusing System;using System.Collections.Generic; class GFG { // Main Method static public void Main () { // Creating a dictionary // using Dictionary<TKey,TValue> class Dictionary<int, string> My_dict1 = new Dictionary<int, string>(); // Adding key/value pairs // in the Dictionary // Using Add() method My_dict1.Add(1123, \"Welcome\"); My_dict1.Add(1124, \"to\"); My_dict1.Add(1125, \"GeeksforGeeks\"); foreach(KeyValuePair<int, string> ele1 in My_dict1) { Console.WriteLine(\"{0} and {1}\", ele1.Key, ele1.Value); } Console.WriteLine(); // Creating another dictionary // using Dictionary<TKey,TValue> class // adding key/value pairs without // using Add method Dictionary<string, string> My_dict2 = new Dictionary<string, string>(){ {\"a.1\", \"Dog\"}, {\"a.2\", \"Cat\"}, {\"a.3\", \"Pig\"} }; foreach(KeyValuePair<string, string> ele2 in My_dict2) { Console.WriteLine(\"{0} and {1}\", ele2.Key, ele2.Value); } }}",
"e": 31212,
"s": 29823,
"text": null
},
{
"code": null,
"e": 31302,
"s": 31212,
"text": "1123 and Welcome\n1124 and to\n1125 and GeeksforGeeks\n\na.1 and Dog\na.2 and Cat\na.3 and Pig\n"
},
{
"code": null,
"e": 31475,
"s": 31302,
"text": "In Dictionary, you are allowed to remove elements from the Dictionary. Dictionary<TKey, TValue> class provides two different methods to remove elements and the methods are:"
},
{
"code": null,
"e": 31556,
"s": 31475,
"text": "Clear: This method removes all keys and values from the Dictionary<TKey,TValue>."
},
{
"code": null,
"e": 31651,
"s": 31556,
"text": "Remove: This method removes the value with the specified key from the Dictionary<TKey,TValue>."
},
{
"code": null,
"e": 31660,
"s": 31651,
"text": "Example:"
},
{
"code": "// C# program to illustrate how // remove key/value pairs from // the dictionaryusing System;using System.Collections.Generic; class GFG { // Main Method static public void Main() { // Creating a dictionary // using Dictionary<TKey,TValue> class Dictionary<int, string> My_dict = new Dictionary<int, string>(); // Adding key/value pairs in the // Dictionary Using Add() method My_dict.Add(1123, \"Welcome\"); My_dict.Add(1124, \"to\"); My_dict.Add(1125, \"GeeksforGeeks\"); // Before Remove() method foreach(KeyValuePair<int, string> ele in My_dict) { Console.WriteLine(\"{0} and {1}\", ele.Key, ele.Value); } Console.WriteLine(); // Using Remove() method My_dict.Remove(1123); // After Remove() method foreach(KeyValuePair<int, string> ele in My_dict) { Console.WriteLine(\"{0} and {1}\", ele.Key, ele.Value); } Console.WriteLine(); // Using Clear() method My_dict.Clear(); Console.WriteLine(\"Total number of key/value \"+ \"pairs present in My_dict:{0}\", My_dict.Count); }}",
"e": 33059,
"s": 31660,
"text": null
},
{
"code": null,
"e": 33202,
"s": 33059,
"text": "1123 and Welcome\n1124 and to\n1125 and GeeksforGeeks\n\n1124 and to\n1125 and GeeksforGeeks\n\nTotal number of key/value pairs present in My_dict:0\n"
},
{
"code": null,
"e": 33406,
"s": 33202,
"text": "In Dictionary, you can check whether the given key or value present in the specified dictionary or not. The Dictionary<TKey, TValue> class provides two different methods for checking and the methods are:"
},
{
"code": null,
"e": 33512,
"s": 33406,
"text": "ContainsKey: This method is used to check whether the Dictionary<TKey,TValue> contains the specified key."
},
{
"code": null,
"e": 33619,
"s": 33512,
"text": "ContainsValue: This method is used to check whether the Dictionary<TKey,TValue> contains a specific value."
},
{
"code": null,
"e": 33628,
"s": 33619,
"text": "Example:"
},
{
"code": "// C# program to illustrate how// to check the given key or // value present in the dictionary// or notusing System;using System.Collections.Generic; class GFG { // Main Method static public void Main () { // Creating a dictionary // using Dictionary<TKey,TValue> class Dictionary<int, string> My_dict = new Dictionary<int, string>(); // Adding key/value pairs in the // Dictionary Using Add() method My_dict.Add(1123, \"Welcome\"); My_dict.Add(1124, \"to\"); My_dict.Add(1125, \"GeeksforGeeks\"); // Using ContainsKey() method to check // the specified key is present or not if (My_dict.ContainsKey(1122)==true) { Console.WriteLine(\"Key is found...!!\"); } else { Console.WriteLine(\"Key is not found...!!\"); } // Using ContainsValue() method to check // the specified value is present or not if (My_dict.ContainsValue(\"GeeksforGeeks\")==true) { Console.WriteLine(\"Value is found...!!\"); } else { Console.WriteLine(\"Value is not found...!!\"); } }}",
"e": 34935,
"s": 33628,
"text": null
},
{
"code": null,
"e": 34978,
"s": 34935,
"text": "Key is not found...!!\nValue is found...!!\n"
},
{
"code": null,
"e": 35002,
"s": 34978,
"text": "CSharp Dictionary Class"
},
{
"code": null,
"e": 35027,
"s": 35002,
"text": "CSharp-Generic-Namespace"
},
{
"code": null,
"e": 35030,
"s": 35027,
"text": "C#"
},
{
"code": null,
"e": 35128,
"s": 35030,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35182,
"s": 35128,
"text": "Difference between Abstract Class and Interface in C#"
},
{
"code": null,
"e": 35224,
"s": 35182,
"text": "String.Split() Method in C# with Examples"
},
{
"code": null,
"e": 35286,
"s": 35224,
"text": "C# | How to check whether a List contains a specified element"
},
{
"code": null,
"e": 35314,
"s": 35286,
"text": "C# | IsNullOrEmpty() Method"
},
{
"code": null,
"e": 35329,
"s": 35314,
"text": "C# | Delegates"
},
{
"code": null,
"e": 35352,
"s": 35329,
"text": "C# | Arrays of Strings"
},
{
"code": null,
"e": 35374,
"s": 35352,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 35420,
"s": 35374,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 35443,
"s": 35420,
"text": "Extension Method in C#"
}
] |
Python - Maximum Consecutive Substring Occurrence - GeeksforGeeks
|
10 May, 2020
Sometimes, while working with python, we can have a problem in which we need to check for substrings occurring in consecutive repetition. This can have application in data domains. Lets discuss a way in which this task can be performed.
Method : Using max() + re.findall()The combination of above methods can be used to perform this task. In this, we extract the substrings repetitions using using findall() and extract the maximum of them using max().
# Python3 code to demonstrate working of # Maximum Consecutive Substring Occurrence# Using max() + re.findall()import re # initializing stringtest_str = 'geeksgeeks are geeks for all geeksgeeksgeeks' # printing original stringprint("The original string is : " + str(test_str)) # initializing subs sub_str = 'geeks' # Maximum Consecutive Substring Occurrence# Using max() + re.findall()res = max(re.findall('((?:' + re.escape(sub_str) + ')*)', test_str), key = len) # printing result print("The maximum run of Substring : " + res)
The original string is : geeksgeeks are geeks for all geeksgeeksgeeks
The maximum run of Substring : geeksgeeksgeeks
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
|
[
{
"code": null,
"e": 26307,
"s": 26279,
"text": "\n10 May, 2020"
},
{
"code": null,
"e": 26544,
"s": 26307,
"text": "Sometimes, while working with python, we can have a problem in which we need to check for substrings occurring in consecutive repetition. This can have application in data domains. Lets discuss a way in which this task can be performed."
},
{
"code": null,
"e": 26760,
"s": 26544,
"text": "Method : Using max() + re.findall()The combination of above methods can be used to perform this task. In this, we extract the substrings repetitions using using findall() and extract the maximum of them using max()."
},
{
"code": "# Python3 code to demonstrate working of # Maximum Consecutive Substring Occurrence# Using max() + re.findall()import re # initializing stringtest_str = 'geeksgeeks are geeks for all geeksgeeksgeeks' # printing original stringprint(\"The original string is : \" + str(test_str)) # initializing subs sub_str = 'geeks' # Maximum Consecutive Substring Occurrence# Using max() + re.findall()res = max(re.findall('((?:' + re.escape(sub_str) + ')*)', test_str), key = len) # printing result print(\"The maximum run of Substring : \" + res) ",
"e": 27298,
"s": 26760,
"text": null
},
{
"code": null,
"e": 27416,
"s": 27298,
"text": "The original string is : geeksgeeks are geeks for all geeksgeeksgeeks\nThe maximum run of Substring : geeksgeeksgeeks\n"
},
{
"code": null,
"e": 27441,
"s": 27418,
"text": "Python string-programs"
},
{
"code": null,
"e": 27448,
"s": 27441,
"text": "Python"
},
{
"code": null,
"e": 27464,
"s": 27448,
"text": "Python Programs"
},
{
"code": null,
"e": 27562,
"s": 27464,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27580,
"s": 27562,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27615,
"s": 27580,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27647,
"s": 27615,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27669,
"s": 27647,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27711,
"s": 27669,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27754,
"s": 27711,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 27776,
"s": 27754,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27815,
"s": 27776,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27861,
"s": 27815,
"text": "Python | Split string into list of characters"
}
] |
What is Wallet Smart Contract? - GeeksforGeeks
|
09 Jul, 2020
Wallets are just like your bank account, through which we can receive money, send money, and can check the balance.
uint- unsigned integer.address- It is a unique set of the string provided for the transaction.msg.sender- Address of the current user.msg.value- Cost put by the current user.public- Visibility of the function.view- This keyword is used when the function is read-only.modifier- modifier is just like a function, which is used at, the initial point of function so that it can check the required condition and prevent wastage of ether before function execution.
uint- unsigned integer.
address- It is a unique set of the string provided for the transaction.
msg.sender- Address of the current user.
msg.value- Cost put by the current user.
public- Visibility of the function.
view- This keyword is used when the function is read-only.
modifier- modifier is just like a function, which is used at, the initial point of function so that it can check the required condition and prevent wastage of ether before function execution.
Solidity
// pragma is the directive through// which we write the smart contract pragma solidity 0.6.0; // Creating a contractcontract wallet{ // Specify the owner's address // which is publicly visible address payable public Owner; // mapping is created for mapping // address=>uint for transaction mapping(address=>uint) Amount; // Defining a constructor // constructor is payable, which means // it cost ether during the deployment constructor() public payable{ // msg.sender is the address of the // person who has currently deployed contract Owner = msg.sender // msg.value is the value of the ether we are // giving during the deploying of contract Amount[Owner] = msg.value; } // modifier(onlyOwner) it will check // the required condition, here condition // is the only owner can call this function modifier onlyOwner(){ // require is used whether the // owner is the person who has // deployed the contract or not require(Owner == msg.sender); _; } // Defining a function which is // used to send money function sendMoney( address payable receiver, uint amount) public payable onlyOwner { // receiver account balance should be>0 require( receiver.balance>0); // amount should not be negative, // otherwise it will throw error require(amount>0); Amount[Owner] -= amount; Amount[receiver] += amount; } // Defining function for Receiving money // to our smart contract account // not to an owners account function ReceiveMoney() public payable{ } // This function will return the current // balance of the contract account owned // by the owner function CheckBalance_contractAccount() public view onlyOwner returns(uint){ return address(this).balance; } // Defining a function that will return // the current balance of the owner's account function CheckBalance() public view onlyOwner returns(uint){ return Amount[Owner]; } }
In the above code, money is deposited in the contract account, not in the owner’s account. Let us discuss a code in which we will see how to send ether directly into the owner’s account.
Solidity
// pragma is the directive through which// we write the smart contractpragma solidity 0.6.0; // Creating a contractcontract wallet{ // Specify the owner's address // which is publicly visible address payable public Owner; // Mapping is done from // address=>uint for transaction mapping(address => uint) Amount; // Constructor 'payable' is created, // which means it cost ether during the // deployment constructor() public payable{ // msg.sender is the address of the person // who has currently deployed contract Owner = msg.sender // msg.value is the value of the ether we // are giving during the deploying of contract Amount[Owner] = msg.value; } // Modifier is created modifier onlyOwner(){ // require is used whether the owner is the // person who has deployed the contract or not require(Owner == msg.sender); _; } // Defining a function to send money, // we have used modifier(onlyOwner) // it will check the required condition, // here condition is the only owner can // call this function function sendMoney( address payable receiver, uint amount) public payable onlyOwner { // receiver account balance should be > 0 require( receiver.balance>0); // amount should not be negative , // otherwise it throw error require(amount >0); Amount[Owner] -= amount; Amount[receiver] += amount; } // Defining a function to receive money function ReceiveMoney() public payable{ // Receiving money in owners // account directly Amount[Owner] += msg.value; } // Defining a function to return // the balance of the contract // account owned by the owner function CheckBalance_contractAccount() public view onlyOwwner returns(uint){ // return the balance of contract // account owned by owner return address(this).balance; } // Defining a function to check the // current balance of the owner account function CheckBalance() public view onlyOwner returns(uint){ // return the current balance // of the owner's account return Amount[Owner]; }}
Solidity
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Solidity - Constructors
Solidity - Operators
Solidity - Inheritance
Mathematical Operations in Solidity
Solidity - Fall Back Function
Solidity - While, Do-While, and For Loop
Introduction to Solidity
Dynamic Arrays and its Operations in Solidity
Solidity - Types
Solidity - View and Pure Functions
|
[
{
"code": null,
"e": 26183,
"s": 26155,
"text": "\n09 Jul, 2020"
},
{
"code": null,
"e": 26299,
"s": 26183,
"text": "Wallets are just like your bank account, through which we can receive money, send money, and can check the balance."
},
{
"code": null,
"e": 26758,
"s": 26299,
"text": "uint- unsigned integer.address- It is a unique set of the string provided for the transaction.msg.sender- Address of the current user.msg.value- Cost put by the current user.public- Visibility of the function.view- This keyword is used when the function is read-only.modifier- modifier is just like a function, which is used at, the initial point of function so that it can check the required condition and prevent wastage of ether before function execution."
},
{
"code": null,
"e": 26782,
"s": 26758,
"text": "uint- unsigned integer."
},
{
"code": null,
"e": 26854,
"s": 26782,
"text": "address- It is a unique set of the string provided for the transaction."
},
{
"code": null,
"e": 26895,
"s": 26854,
"text": "msg.sender- Address of the current user."
},
{
"code": null,
"e": 26936,
"s": 26895,
"text": "msg.value- Cost put by the current user."
},
{
"code": null,
"e": 26972,
"s": 26936,
"text": "public- Visibility of the function."
},
{
"code": null,
"e": 27031,
"s": 26972,
"text": "view- This keyword is used when the function is read-only."
},
{
"code": null,
"e": 27223,
"s": 27031,
"text": "modifier- modifier is just like a function, which is used at, the initial point of function so that it can check the required condition and prevent wastage of ether before function execution."
},
{
"code": null,
"e": 27232,
"s": 27223,
"text": "Solidity"
},
{
"code": "// pragma is the directive through// which we write the smart contract pragma solidity 0.6.0; // Creating a contractcontract wallet{ // Specify the owner's address // which is publicly visible address payable public Owner; // mapping is created for mapping // address=>uint for transaction mapping(address=>uint) Amount; // Defining a constructor // constructor is payable, which means // it cost ether during the deployment constructor() public payable{ // msg.sender is the address of the // person who has currently deployed contract Owner = msg.sender // msg.value is the value of the ether we are // giving during the deploying of contract Amount[Owner] = msg.value; } // modifier(onlyOwner) it will check // the required condition, here condition // is the only owner can call this function modifier onlyOwner(){ // require is used whether the // owner is the person who has // deployed the contract or not require(Owner == msg.sender); _; } // Defining a function which is // used to send money function sendMoney( address payable receiver, uint amount) public payable onlyOwner { // receiver account balance should be>0 require( receiver.balance>0); // amount should not be negative, // otherwise it will throw error require(amount>0); Amount[Owner] -= amount; Amount[receiver] += amount; } // Defining function for Receiving money // to our smart contract account // not to an owners account function ReceiveMoney() public payable{ } // This function will return the current // balance of the contract account owned // by the owner function CheckBalance_contractAccount() public view onlyOwner returns(uint){ return address(this).balance; } // Defining a function that will return // the current balance of the owner's account function CheckBalance() public view onlyOwner returns(uint){ return Amount[Owner]; } }",
"e": 29467,
"s": 27232,
"text": null
},
{
"code": null,
"e": 29654,
"s": 29467,
"text": "In the above code, money is deposited in the contract account, not in the owner’s account. Let us discuss a code in which we will see how to send ether directly into the owner’s account."
},
{
"code": null,
"e": 29663,
"s": 29654,
"text": "Solidity"
},
{
"code": "// pragma is the directive through which// we write the smart contractpragma solidity 0.6.0; // Creating a contractcontract wallet{ // Specify the owner's address // which is publicly visible address payable public Owner; // Mapping is done from // address=>uint for transaction mapping(address => uint) Amount; // Constructor 'payable' is created, // which means it cost ether during the // deployment constructor() public payable{ // msg.sender is the address of the person // who has currently deployed contract Owner = msg.sender // msg.value is the value of the ether we // are giving during the deploying of contract Amount[Owner] = msg.value; } // Modifier is created modifier onlyOwner(){ // require is used whether the owner is the // person who has deployed the contract or not require(Owner == msg.sender); _; } // Defining a function to send money, // we have used modifier(onlyOwner) // it will check the required condition, // here condition is the only owner can // call this function function sendMoney( address payable receiver, uint amount) public payable onlyOwner { // receiver account balance should be > 0 require( receiver.balance>0); // amount should not be negative , // otherwise it throw error require(amount >0); Amount[Owner] -= amount; Amount[receiver] += amount; } // Defining a function to receive money function ReceiveMoney() public payable{ // Receiving money in owners // account directly Amount[Owner] += msg.value; } // Defining a function to return // the balance of the contract // account owned by the owner function CheckBalance_contractAccount() public view onlyOwwner returns(uint){ // return the balance of contract // account owned by owner return address(this).balance; } // Defining a function to check the // current balance of the owner account function CheckBalance() public view onlyOwner returns(uint){ // return the current balance // of the owner's account return Amount[Owner]; }}",
"e": 32190,
"s": 29663,
"text": null
},
{
"code": null,
"e": 32199,
"s": 32190,
"text": "Solidity"
},
{
"code": null,
"e": 32297,
"s": 32199,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32321,
"s": 32297,
"text": "Solidity - Constructors"
},
{
"code": null,
"e": 32342,
"s": 32321,
"text": "Solidity - Operators"
},
{
"code": null,
"e": 32365,
"s": 32342,
"text": "Solidity - Inheritance"
},
{
"code": null,
"e": 32401,
"s": 32365,
"text": "Mathematical Operations in Solidity"
},
{
"code": null,
"e": 32431,
"s": 32401,
"text": "Solidity - Fall Back Function"
},
{
"code": null,
"e": 32472,
"s": 32431,
"text": "Solidity - While, Do-While, and For Loop"
},
{
"code": null,
"e": 32497,
"s": 32472,
"text": "Introduction to Solidity"
},
{
"code": null,
"e": 32543,
"s": 32497,
"text": "Dynamic Arrays and its Operations in Solidity"
},
{
"code": null,
"e": 32560,
"s": 32543,
"text": "Solidity - Types"
}
] |
Program to Encrypt a String using ! and @ - GeeksforGeeks
|
03 Jun, 2021
Given a string, the task is to encrypt this string using ! and @ symbols, alternatively. While encrypting the message the encrypted format must repeat the symbol as many times as the letter position in Alphabetical order.Examples:
Input: string = "Ab"
Output: !@@
Explanation:
Position of 'A' in alphabetical order is 1
and in String is odd position
so encrypted message will have 1 '!'
Position of 'b' in alphabetical order is 2
and in String is even position
so encrypted message will have 2 '@'
Therefore, the output "!@@"
Input: string = "CDE"
Output: !!!@@@@!!!!!
Approach: This is a very basic and simple type of Encryption technique and can be done as follows:
Get the character one by one from the String
For each character, get the difference between the ASCII value of that character and ‘A'(if the character is a capital letter) or ‘a’ (if the letter is a small letter). This will be the number of times the encryption character is to be repeated.
For the ith character of the string, if i is odd, the encryption character will be ‘!’ and if i is even, the encryption character will be ‘@’.
Below is the implementation of the above code:
C++
C
Java
Python3
C#
Javascript
// C++ program to Encrypt the String// using ! and @#include <bits/stdc++.h>using namespace std; // Function to encrypt the stringvoid encrypt(char input[100]){ // evenPos is for storing encrypting // char at evenPosition // oddPos is for storing encrypting // char at oddPosition char evenPos = '@', oddPos = '!'; int repeat, ascii; for (int i = 0; i <= strlen(input); i++) { // Get the number of times the character // is to be repeated ascii = input[i]; repeat = ascii >= 97 ? ascii - 96 : ascii - 64; for (int j = 0; j < repeat; j++) { // if i is odd, print '!' // else print '@' if (i % 2 == 0) cout << oddPos; else cout << evenPos; } }} // Driver codeint main(){ char input[100] = { 'A', 'b', 'C', 'd' }; // Encrypt the String encrypt(input); return 0;} // This code is contributed by// shubhamsingh10
// C program to Encrypt the String// using ! and @ #include <stdio.h>#include <string.h> // Function to encrypt the stringvoid encrypt(char input[100]){ // evenPos is for storing encrypting // char at evenPosition // oddPos is for storing encrypting // char at oddPosition char evenPos = '@', oddPos = '!'; int repeat, ascii; for (int i = 0; i <= strlen(input); i++) { // Get the number of times the character // is to be repeated ascii = input[i]; repeat = ascii >= 97 ? ascii - 96 : ascii - 64; for (int j = 0; j < repeat; j++) { // if i is odd, print '!' // else print '@' if (i % 2 == 0) printf("%c", oddPos); else printf("%c", evenPos); } }} // Driver codevoid main(){ char input[100] = { 'A', 'b', 'C', 'd' }; // Encrypt the String encrypt(input);}
// Java program to Encrypt the String// using ! and @class GFG{ // Function to encrypt the stringstatic void encrypt(char input[]){ // evenPos is for storing encrypting // char at evenPosition // oddPos is for storing encrypting // char at oddPosition char evenPos = '@', oddPos = '!'; int repeat, ascii; for (int i = 0; i < input.length; i++) { // Get the number of times the character // is to be repeated ascii = input[i]; repeat = ascii >= 97 ? ascii - 96 : ascii - 64; for (int j = 0; j < repeat; j++) { // if i is odd, print '!' // else print '@' if (i % 2 == 0) System.out.printf("%c", oddPos); else System.out.printf("%c", evenPos); } }} // Driver codepublic static void main(String[] args){ char input[] = { 'A', 'b', 'C', 'd' }; // Encrypt the String encrypt(input);}} // This code is contributed by PrinciRaj1992
# Python3 program to Encrypt the String# using ! and @ # Function to encrypt the stringdef encrypt(input_arr) : # evenPos is for storing encrypting # char at evenPosition # oddPos is for storing encrypting # char at oddPosition evenPos = '@'; oddPos = '!'; for i in range(len(input_arr)) : # Get the number of times the character # is to be repeated ascii = ord(input_arr[i]); repeat = (ascii - 96 ) if ascii >= 97 \ else (ascii - 64); for j in range(repeat) : # if i is odd, print '!' # else print '@' if (i % 2 == 0) : print(oddPos, end = ""); else : print(evenPos, end = ""); # Driver codeif __name__ == "__main__" : input_arr = [ 'A', 'b', 'C', 'd' ]; # Encrypt the String encrypt(input_arr); # This code is contributed by AnkitRai01
// C# program to Encrypt the String// using ! and @using System;using System.Collections.Generic; class GFG{ // Function to encrypt the stringstatic void encrypt(char []input){ // evenPos is for storing encrypting // char at evenPosition // oddPos is for storing encrypting // char at oddPosition char evenPos = '@', oddPos = '!'; int repeat, ascii; for (int i = 0; i < input.Length; i++) { // Get the number of times the character // is to be repeated ascii = input[i]; repeat = ascii >= 97 ? ascii - 96 : ascii - 64; for (int j = 0; j < repeat; j++) { // if i is odd, print '!' // else print '@' if (i % 2 == 0) Console.Write("{0}", oddPos); else Console.Write("{0}", evenPos); } }} // Driver codepublic static void Main(String[] args){ char []input = { 'A', 'b', 'C', 'd' }; // Encrypt the String encrypt(input);}} // This code is contributed by 29AjayKumar
<script> // JavaScript program to Encrypt the // String using ! and @ // Function to encrypt the string function encrypt(input) { // evenPos is for storing encrypting // char at evenPosition // oddPos is for storing encrypting // char at oddPosition let evenPos = '@', oddPos = '!'; let repeat, ascii; for (let i = 0; i < input.length; i++) { // Get the number of times the character // is to be repeated ascii = input[i].charCodeAt(); repeat = ascii >= 97 ? ascii - 96 : ascii - 64; for (let j = 0; j < repeat; j++) { // if i is odd, print '!' // else print '@' if (i % 2 == 0) document.write(oddPos); else document.write(evenPos); } } } let input = [ 'A', 'b', 'C', 'd' ]; // Encrypt the String encrypt(input); </script>
!@@!!!@@@@
princiraj1992
29AjayKumar
ankthon
gp6
SHUBHAMSINGH10
divyeshrabadiya07
encoding-decoding
School Programming
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
Constructors in C++
Operator Overloading in C++
Copy Constructor in C++
Polymorphism in C++
Write a program to reverse an array or string
Write a program to print all permutations of a given string
Longest Common Subsequence | DP-4
Check for Balanced Brackets in an expression (well-formedness) using Stack
Python program to check if a string is palindrome or not
|
[
{
"code": null,
"e": 25752,
"s": 25724,
"text": "\n03 Jun, 2021"
},
{
"code": null,
"e": 25985,
"s": 25752,
"text": "Given a string, the task is to encrypt this string using ! and @ symbols, alternatively. While encrypting the message the encrypted format must repeat the symbol as many times as the letter position in Alphabetical order.Examples: "
},
{
"code": null,
"e": 26329,
"s": 25985,
"text": "Input: string = \"Ab\" \nOutput: !@@\nExplanation:\nPosition of 'A' in alphabetical order is 1\nand in String is odd position \nso encrypted message will have 1 '!'\n\nPosition of 'b' in alphabetical order is 2\nand in String is even position \nso encrypted message will have 2 '@'\n\nTherefore, the output \"!@@\"\n\nInput: string = \"CDE\"\nOutput: !!!@@@@!!!!!"
},
{
"code": null,
"e": 26432,
"s": 26331,
"text": "Approach: This is a very basic and simple type of Encryption technique and can be done as follows: "
},
{
"code": null,
"e": 26477,
"s": 26432,
"text": "Get the character one by one from the String"
},
{
"code": null,
"e": 26723,
"s": 26477,
"text": "For each character, get the difference between the ASCII value of that character and ‘A'(if the character is a capital letter) or ‘a’ (if the letter is a small letter). This will be the number of times the encryption character is to be repeated."
},
{
"code": null,
"e": 26866,
"s": 26723,
"text": "For the ith character of the string, if i is odd, the encryption character will be ‘!’ and if i is even, the encryption character will be ‘@’."
},
{
"code": null,
"e": 26915,
"s": 26866,
"text": "Below is the implementation of the above code: "
},
{
"code": null,
"e": 26919,
"s": 26915,
"text": "C++"
},
{
"code": null,
"e": 26921,
"s": 26919,
"text": "C"
},
{
"code": null,
"e": 26926,
"s": 26921,
"text": "Java"
},
{
"code": null,
"e": 26934,
"s": 26926,
"text": "Python3"
},
{
"code": null,
"e": 26937,
"s": 26934,
"text": "C#"
},
{
"code": null,
"e": 26948,
"s": 26937,
"text": "Javascript"
},
{
"code": "// C++ program to Encrypt the String// using ! and @#include <bits/stdc++.h>using namespace std; // Function to encrypt the stringvoid encrypt(char input[100]){ // evenPos is for storing encrypting // char at evenPosition // oddPos is for storing encrypting // char at oddPosition char evenPos = '@', oddPos = '!'; int repeat, ascii; for (int i = 0; i <= strlen(input); i++) { // Get the number of times the character // is to be repeated ascii = input[i]; repeat = ascii >= 97 ? ascii - 96 : ascii - 64; for (int j = 0; j < repeat; j++) { // if i is odd, print '!' // else print '@' if (i % 2 == 0) cout << oddPos; else cout << evenPos; } }} // Driver codeint main(){ char input[100] = { 'A', 'b', 'C', 'd' }; // Encrypt the String encrypt(input); return 0;} // This code is contributed by// shubhamsingh10",
"e": 27937,
"s": 26948,
"text": null
},
{
"code": "// C program to Encrypt the String// using ! and @ #include <stdio.h>#include <string.h> // Function to encrypt the stringvoid encrypt(char input[100]){ // evenPos is for storing encrypting // char at evenPosition // oddPos is for storing encrypting // char at oddPosition char evenPos = '@', oddPos = '!'; int repeat, ascii; for (int i = 0; i <= strlen(input); i++) { // Get the number of times the character // is to be repeated ascii = input[i]; repeat = ascii >= 97 ? ascii - 96 : ascii - 64; for (int j = 0; j < repeat; j++) { // if i is odd, print '!' // else print '@' if (i % 2 == 0) printf(\"%c\", oddPos); else printf(\"%c\", evenPos); } }} // Driver codevoid main(){ char input[100] = { 'A', 'b', 'C', 'd' }; // Encrypt the String encrypt(input);}",
"e": 28847,
"s": 27937,
"text": null
},
{
"code": "// Java program to Encrypt the String// using ! and @class GFG{ // Function to encrypt the stringstatic void encrypt(char input[]){ // evenPos is for storing encrypting // char at evenPosition // oddPos is for storing encrypting // char at oddPosition char evenPos = '@', oddPos = '!'; int repeat, ascii; for (int i = 0; i < input.length; i++) { // Get the number of times the character // is to be repeated ascii = input[i]; repeat = ascii >= 97 ? ascii - 96 : ascii - 64; for (int j = 0; j < repeat; j++) { // if i is odd, print '!' // else print '@' if (i % 2 == 0) System.out.printf(\"%c\", oddPos); else System.out.printf(\"%c\", evenPos); } }} // Driver codepublic static void main(String[] args){ char input[] = { 'A', 'b', 'C', 'd' }; // Encrypt the String encrypt(input);}} // This code is contributed by PrinciRaj1992",
"e": 29853,
"s": 28847,
"text": null
},
{
"code": "# Python3 program to Encrypt the String# using ! and @ # Function to encrypt the stringdef encrypt(input_arr) : # evenPos is for storing encrypting # char at evenPosition # oddPos is for storing encrypting # char at oddPosition evenPos = '@'; oddPos = '!'; for i in range(len(input_arr)) : # Get the number of times the character # is to be repeated ascii = ord(input_arr[i]); repeat = (ascii - 96 ) if ascii >= 97 \\ else (ascii - 64); for j in range(repeat) : # if i is odd, print '!' # else print '@' if (i % 2 == 0) : print(oddPos, end = \"\"); else : print(evenPos, end = \"\"); # Driver codeif __name__ == \"__main__\" : input_arr = [ 'A', 'b', 'C', 'd' ]; # Encrypt the String encrypt(input_arr); # This code is contributed by AnkitRai01",
"e": 30780,
"s": 29853,
"text": null
},
{
"code": "// C# program to Encrypt the String// using ! and @using System;using System.Collections.Generic; class GFG{ // Function to encrypt the stringstatic void encrypt(char []input){ // evenPos is for storing encrypting // char at evenPosition // oddPos is for storing encrypting // char at oddPosition char evenPos = '@', oddPos = '!'; int repeat, ascii; for (int i = 0; i < input.Length; i++) { // Get the number of times the character // is to be repeated ascii = input[i]; repeat = ascii >= 97 ? ascii - 96 : ascii - 64; for (int j = 0; j < repeat; j++) { // if i is odd, print '!' // else print '@' if (i % 2 == 0) Console.Write(\"{0}\", oddPos); else Console.Write(\"{0}\", evenPos); } }} // Driver codepublic static void Main(String[] args){ char []input = { 'A', 'b', 'C', 'd' }; // Encrypt the String encrypt(input);}} // This code is contributed by 29AjayKumar",
"e": 31821,
"s": 30780,
"text": null
},
{
"code": "<script> // JavaScript program to Encrypt the // String using ! and @ // Function to encrypt the string function encrypt(input) { // evenPos is for storing encrypting // char at evenPosition // oddPos is for storing encrypting // char at oddPosition let evenPos = '@', oddPos = '!'; let repeat, ascii; for (let i = 0; i < input.length; i++) { // Get the number of times the character // is to be repeated ascii = input[i].charCodeAt(); repeat = ascii >= 97 ? ascii - 96 : ascii - 64; for (let j = 0; j < repeat; j++) { // if i is odd, print '!' // else print '@' if (i % 2 == 0) document.write(oddPos); else document.write(evenPos); } } } let input = [ 'A', 'b', 'C', 'd' ]; // Encrypt the String encrypt(input); </script>",
"e": 32847,
"s": 31821,
"text": null
},
{
"code": null,
"e": 32858,
"s": 32847,
"text": "!@@!!!@@@@"
},
{
"code": null,
"e": 32874,
"s": 32860,
"text": "princiraj1992"
},
{
"code": null,
"e": 32886,
"s": 32874,
"text": "29AjayKumar"
},
{
"code": null,
"e": 32894,
"s": 32886,
"text": "ankthon"
},
{
"code": null,
"e": 32898,
"s": 32894,
"text": "gp6"
},
{
"code": null,
"e": 32913,
"s": 32898,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 32931,
"s": 32913,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 32949,
"s": 32931,
"text": "encoding-decoding"
},
{
"code": null,
"e": 32968,
"s": 32949,
"text": "School Programming"
},
{
"code": null,
"e": 32976,
"s": 32968,
"text": "Strings"
},
{
"code": null,
"e": 32984,
"s": 32976,
"text": "Strings"
},
{
"code": null,
"e": 33082,
"s": 32984,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33101,
"s": 33082,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 33121,
"s": 33101,
"text": "Constructors in C++"
},
{
"code": null,
"e": 33149,
"s": 33121,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 33173,
"s": 33149,
"text": "Copy Constructor in C++"
},
{
"code": null,
"e": 33193,
"s": 33173,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 33239,
"s": 33193,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 33299,
"s": 33239,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 33333,
"s": 33299,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 33408,
"s": 33333,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
}
] |
How to Transfer Files using SFTP? - GeeksforGeeks
|
18 Oct, 2021
SFTP (Secure File Transfer Protocol) or SSH (Secure Shell) File Transfer Protocol) is a file transfer protocol used to transfer files between client and server. It uses SSH(Secure Socket Shell) and is also known as Secure Socket Shell File Transfer Protocol. It provides secure access to a remote server for the secure transfer of files.
Secure FTP arose to meet the necessities for enhanced security with tunneling. It uses Secure Shell 2 (SSH2) to create a secure tunnel and emulate an FTP connection to provide a firewall-friendly and encrypted channel to transfer files using the popular TCP port 22. SSH offers enhanced security by having the entire file transfer session, including all session control commands, entirely encrypted at all times while only needing a single port to be opened on your firewall instead of the two ports that need to be opened for FTP and SSL connections.
SFTP uses the SSH protocol to transfer files. You’ll need to configure SSH first. To check if you have SSH configured. Do the following on your server
$ ssh geeksforgeeks@your_server_ip_or_remote_hostname.
Replace “geeksforgeeks” with your username and “your_server_ip_or_remote_hostname” with your server IP or hostname.
If that works and you’re logged in. You’re good to go. If not you’ll need to set up SSH access first.
Then exit from the prompt.
$ exit
Establishing SFTP Session :We can connect to the SFTP session by using the following command.
$ sftp geeksforgeeks@your_server_ip_or_remote_hostname
This command will connect you to the remote session and the prompt will change to SFTP prompt.
If you’re using a custom SSH port (not the default port 22), then you can use the following command to connect to SFTP.
$ sftp -oPort=customport geeksforgeeks@your_server_ip_or_remote_hostname.
Here, change “customport” to the port number that you are using. This command will connect you to the SFTP with the port you specified.
Transferring Files with SFTP :
1. Transferring Remote Files to Local System –If we want to transfer files from our remote host, we can do so by using the following command.
sftp> get remote-file
Output
Fetching home/geeksforgeeks/remote-file to remote-file
/home/geeksforgeeks/remote-file 100% 40KB 39.8KB/s 00:05
Here, the remote file will be the name of the files that you want to transfer. The get command will download the “remotefile” on your local system with the same name as on the server.
We can download the remotefile with a different remote host to our machine by specifying the name after the remote file name.
sftp> get remote-file local-file
The get command can also take some flags as options. For example, if we want to copy a directory with all of its content we can use the “-r” recursive flag.
sftp> get -r some-directory
2. Transferring Local Files to the Remote System –Transferring files from the Local System to Remote System can be achieved easily by using the put command.
sftp> put localFile
Output
Uploading local-file to /home/geeksforgeeks/local-file
local-file 100% 7607 7.4KB/s 00:00
Put can use the same options flags that get can use. So, to copy an entire directory will all of its files you can use.
sftp> put -r local-directory
Conclusion :SFTP is a better way to use the strength of FTP or SCP to perform transfers between local and remote files and folders.
Picked
TrueGeek-2021
Computer Networks
TrueGeek
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Advanced Encryption Standard (AES)
Introduction and IPv4 Datagram Header
Intrusion Detection System (IDS)
Secure Socket Layer (SSL)
Cryptography and its Types
How to redirect to another page in ReactJS ?
How to remove duplicate elements from JavaScript Array ?
Basics of API Testing Using Postman
SQL Statement to Remove Part of a String
Types of Internet Protocols
|
[
{
"code": null,
"e": 25755,
"s": 25727,
"text": "\n18 Oct, 2021"
},
{
"code": null,
"e": 26093,
"s": 25755,
"text": "SFTP (Secure File Transfer Protocol) or SSH (Secure Shell) File Transfer Protocol) is a file transfer protocol used to transfer files between client and server. It uses SSH(Secure Socket Shell) and is also known as Secure Socket Shell File Transfer Protocol. It provides secure access to a remote server for the secure transfer of files."
},
{
"code": null,
"e": 26646,
"s": 26093,
"text": "Secure FTP arose to meet the necessities for enhanced security with tunneling. It uses Secure Shell 2 (SSH2) to create a secure tunnel and emulate an FTP connection to provide a firewall-friendly and encrypted channel to transfer files using the popular TCP port 22. SSH offers enhanced security by having the entire file transfer session, including all session control commands, entirely encrypted at all times while only needing a single port to be opened on your firewall instead of the two ports that need to be opened for FTP and SSL connections."
},
{
"code": null,
"e": 26797,
"s": 26646,
"text": "SFTP uses the SSH protocol to transfer files. You’ll need to configure SSH first. To check if you have SSH configured. Do the following on your server"
},
{
"code": null,
"e": 26852,
"s": 26797,
"text": "$ ssh geeksforgeeks@your_server_ip_or_remote_hostname."
},
{
"code": null,
"e": 26968,
"s": 26852,
"text": "Replace “geeksforgeeks” with your username and “your_server_ip_or_remote_hostname” with your server IP or hostname."
},
{
"code": null,
"e": 27070,
"s": 26968,
"text": "If that works and you’re logged in. You’re good to go. If not you’ll need to set up SSH access first."
},
{
"code": null,
"e": 27097,
"s": 27070,
"text": "Then exit from the prompt."
},
{
"code": null,
"e": 27104,
"s": 27097,
"text": "$ exit"
},
{
"code": null,
"e": 27198,
"s": 27104,
"text": "Establishing SFTP Session :We can connect to the SFTP session by using the following command."
},
{
"code": null,
"e": 27253,
"s": 27198,
"text": "$ sftp geeksforgeeks@your_server_ip_or_remote_hostname"
},
{
"code": null,
"e": 27348,
"s": 27253,
"text": "This command will connect you to the remote session and the prompt will change to SFTP prompt."
},
{
"code": null,
"e": 27468,
"s": 27348,
"text": "If you’re using a custom SSH port (not the default port 22), then you can use the following command to connect to SFTP."
},
{
"code": null,
"e": 27542,
"s": 27468,
"text": "$ sftp -oPort=customport geeksforgeeks@your_server_ip_or_remote_hostname."
},
{
"code": null,
"e": 27678,
"s": 27542,
"text": "Here, change “customport” to the port number that you are using. This command will connect you to the SFTP with the port you specified."
},
{
"code": null,
"e": 27709,
"s": 27678,
"text": "Transferring Files with SFTP :"
},
{
"code": null,
"e": 27851,
"s": 27709,
"text": "1. Transferring Remote Files to Local System –If we want to transfer files from our remote host, we can do so by using the following command."
},
{
"code": null,
"e": 27873,
"s": 27851,
"text": "sftp> get remote-file"
},
{
"code": null,
"e": 28019,
"s": 27873,
"text": "Output\nFetching home/geeksforgeeks/remote-file to remote-file\n/home/geeksforgeeks/remote-file 100% 40KB 39.8KB/s 00:05"
},
{
"code": null,
"e": 28204,
"s": 28019,
"text": " Here, the remote file will be the name of the files that you want to transfer. The get command will download the “remotefile” on your local system with the same name as on the server."
},
{
"code": null,
"e": 28330,
"s": 28204,
"text": "We can download the remotefile with a different remote host to our machine by specifying the name after the remote file name."
},
{
"code": null,
"e": 28363,
"s": 28330,
"text": "sftp> get remote-file local-file"
},
{
"code": null,
"e": 28520,
"s": 28363,
"text": "The get command can also take some flags as options. For example, if we want to copy a directory with all of its content we can use the “-r” recursive flag."
},
{
"code": null,
"e": 28548,
"s": 28520,
"text": "sftp> get -r some-directory"
},
{
"code": null,
"e": 28705,
"s": 28548,
"text": "2. Transferring Local Files to the Remote System –Transferring files from the Local System to Remote System can be achieved easily by using the put command."
},
{
"code": null,
"e": 28725,
"s": 28705,
"text": "sftp> put localFile"
},
{
"code": null,
"e": 28864,
"s": 28725,
"text": "Output\nUploading local-file to /home/geeksforgeeks/local-file\nlocal-file 100% 7607 7.4KB/s 00:00"
},
{
"code": null,
"e": 28984,
"s": 28864,
"text": "Put can use the same options flags that get can use. So, to copy an entire directory will all of its files you can use."
},
{
"code": null,
"e": 29013,
"s": 28984,
"text": "sftp> put -r local-directory"
},
{
"code": null,
"e": 29145,
"s": 29013,
"text": "Conclusion :SFTP is a better way to use the strength of FTP or SCP to perform transfers between local and remote files and folders."
},
{
"code": null,
"e": 29152,
"s": 29145,
"text": "Picked"
},
{
"code": null,
"e": 29166,
"s": 29152,
"text": "TrueGeek-2021"
},
{
"code": null,
"e": 29184,
"s": 29166,
"text": "Computer Networks"
},
{
"code": null,
"e": 29193,
"s": 29184,
"text": "TrueGeek"
},
{
"code": null,
"e": 29211,
"s": 29193,
"text": "Computer Networks"
},
{
"code": null,
"e": 29309,
"s": 29211,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29344,
"s": 29309,
"text": "Advanced Encryption Standard (AES)"
},
{
"code": null,
"e": 29382,
"s": 29344,
"text": "Introduction and IPv4 Datagram Header"
},
{
"code": null,
"e": 29415,
"s": 29382,
"text": "Intrusion Detection System (IDS)"
},
{
"code": null,
"e": 29441,
"s": 29415,
"text": "Secure Socket Layer (SSL)"
},
{
"code": null,
"e": 29468,
"s": 29441,
"text": "Cryptography and its Types"
},
{
"code": null,
"e": 29513,
"s": 29468,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 29570,
"s": 29513,
"text": "How to remove duplicate elements from JavaScript Array ?"
},
{
"code": null,
"e": 29606,
"s": 29570,
"text": "Basics of API Testing Using Postman"
},
{
"code": null,
"e": 29647,
"s": 29606,
"text": "SQL Statement to Remove Part of a String"
}
] |
Scrapy - Settings - GeeksforGeeks
|
03 Mar, 2021
Scrapy is an open-source tool built with Python Framework. It presents us with a strong and robust web crawling framework that can easily extract the info from the online page with the assistance of selectors supported by XPath.
We can define the behavior of Scrapy components with the help of Scrapy settings. Pipelines and setting files are very important for scrapy. It is the core of automating the task. These rules help with inserting data into the database. These files are includes when we start with the base template. The Scrapy settings allow you to customize the behavior of all Scrapy components, including the core, extensions, pipelines, and spiders themselves.
We are often presented with the situation where we need to define multiple crapper projects in that case we can define which individual project with the help of scrapy settings. For this, the environment variable SCRAPY_SETTINGS_MODULE should be used and its value should be in Python path syntax. Hence, with the help of the Scrapy settings, the mechanism for choosing the currently active Scrapy project could be specified.
The infrastructure of the settings provides a worldwide namespace of key-value mappings that the code can use to tug configuration values from. The settings are often populated through different mechanisms, which are described below.
Use these commands to start the scrapy template folder.
scrapy startproject <project_name>
This is the base outline of the scrapy project.
With this article, we would be focusing on the settings.py file.
The settings.py file looks something like this. We are provided with this as our default settings.
Most commonly used settings and their description is given below:
BOT_NAME
It is the name of the project. The bot symbolizes the automation that we are doing with the help of the scrapper. It defaults to ‘scrapybot’. Also as seen in the screenshot it is automatically available with your project name when you start the project.
USER_AGENT
User-Agent helps us with the identification. It basically tells “who you are” to the servers and network peers. It helps with the identification of the application, OS, vendor, and/or version of the requesting user agent. It defaults to “Scrapy/VERSION (+https://scrapy.org)” while crawling unless explicitly specified.
The common format for browsers:
User-Agent: <browser>/<version> (<system-info>) <platform> (<platform-details>) <extensions>
For Example:
# Crawl responsibly by identifying yourself (and your website) on the user-agent
USER_AGENT = 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'
ROBOTSTXT_OBEY
A robots.txt file basically tells the crawlers from search engines which pages it could request from the site. ROBOTSTXT_OBEY defaults to “False”. It is mostly kept enabled, so our scrapy will respect the robots.txt policies by the website.
The image shows the content of the file robots.txt, the policies are written here are managed by the ROBOTSTXT_OBEY setting.
CONCURRENT_REQUESTS
It is basically asking the website to open up. It defaults to 16. So basically it is the maximum number of the request that the crawler will perform.
More request increases a load to the server so keeping it as low as 16 or 32 is a good value.
CONCURRENT_ITEMS
It means while scrapping the data what a maximum number of concurrent items the scrapy will process in parallel per response. It defaults to 100, which is again a good value.
custom_settings = {
'CONCURRENT_REQUESTS' = 30,
'CONCURRENT_ITEMS' = 80,
}
CONCURRENT_REQUESTS_PER_DOMAIN
It means while scrapping the data what is the maximum number of existing requests that can be performed concurrently for any single domain value. It defaults to value ‘8’.
CONCURRENT_REQUESTS_PER_IP
It means while scrapping the data what is the maximum number of existing requests that can be performed concurrently for any single IP address. It defaults to the value ‘0’.
custom_settings = {
'CONCURRENT_REQUESTS_PER_DOMAIN' = 8,
'CONCURRENT_REQUESTS_PER_IP' = 2
}
DOWNLOAD_DELAY
It is the delay in the amount of time that the downloader would before again downloading the pages from the website. This again is used to limit the load on the server where the website is hosted. It defaults to 0.
For Example:
DOWNLOAD_DELAY = 0.25 # 250 ms of delay
DOWNLOAD_TIMEOUT
It is the time-out time. Tells scrapy to wait for the given amount of time to wait before the downloader times out. It defaults to 180.
LOG_ENABLED
It is used to enable or disable the logging for the scrapper. It defaults to “True”.
FTP_PASSWORD
Used to set a password for the FTP connections. The value is used only when there is no “ftp_password” in Request meta. It defaults to “guest”.
FTP_USER
Used to set a username for the FTP connections. The value is used only when there is no “ftp_user” in Request meta. It defaults to “anonymous”.
DEFAULT_ITEM_CLASS
This setting is used to represent items within a scrapy, the values are stored in this class format specified by DEFAULT_ITEM_CLASS. The default format is given by ‘scrapy.item.Item’.
DEFAULT_REQUEST_HEADERS
The given setting lists the default header used for HTTP requests made by Scrapy. It is populated within the DefaultHeadersMiddleware.
The default header value is given by:
{
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'en',
}
REACTOR_THREADPOOL_MAXSIZE
The reactor thread pool could also be set within the scrapy. It binds the max size for the reactor thread pool of the spider. Its default size is 10.
For example, the settings could be applied within the code like the following Python code:
class exampleSpider(scrapy.Spider):
name = 'example'
custom_settings = {
'CONCURRENT_REQUESTS': 25,
'CONCURRENT_REQUESTS_PER_DOMAIN': 100,
'DOWNLOAD_DELAY': 0
}
f = open("example")
start_urls = [url.strip() for url in f.readlines()]
f.close()
def parse(self, response):
for itemin response.xpath("//div[@class=<class_component>]"):
urlgem = item.xpath(".//div[@class=<class_component>]/a/@href").extract()
AWS_ACCESS_KEY_ID
With this you can set AWS ID within your scrapy, it is used to access Amazon Web Services. It defaults to the “None” value.
AWS_SECRET_ACCESS_KEY
With this you can set AWS Access Key (Password or ID credential) within your scrapy, it is used to access Amazon Web Services. It defaults to the “None” value.
DEPTH_LIMIT
The limiting depth for the spider to crawl a target site. It defaults to 0.
DEPTH_PRIORITY
It further manages the priority of the depth to crawl a target site. It also defaults to 0.
This is a basic layout of the selector graph inside the Scrapy. The components could be built inside this Selector Graph. Each component is responsible for scrapping individual items from the site.
DEPTH_STATS
With this setting, we can also collect the Depth Stats within the logs of the level crawled. If the setting is enabled then the value of each individual request for each depth is collected in the stats. Its default is “True”.
DEPTH_STATS_VERBOSE
Further improves the DEPTH_STATS by enabling the number of requests which are collected in stats for each verbose depth.
By default, it is “False”.
Selector levels can extend up to infinite depth as structured by the webmaster. With the various depth settings, it’s our duty to limit the Selector Graph within our crawler.
DNSCACHE_ENABLED
With this setting, we could enable DNS inside a memory cache. By default, it is “True”.
DNSCACHE_SIZE
With this setting, we could define the size of the DNS in-memory cache. Its default value is 10000.
DNS_TIMEOUT
It is the time-out time for the DNS to process the scrapy query. It defaults to 60.
DOWNLOADER
The actual downloader used by the crawler. The default format is given by ‘scrapy.core.downloader.Downloader’.
DOWNLOADER_MIDDLEWARES
The dictionary holds downloading middleware and its orders. It is by default empty.
EXTENSIONS_BASE
The dictionary with a built-in extension value. It is defaulted by value: { ‘scrapy.extensions.corestats.CoreStats’: 0, }
FEED_TEMPDIR
This is a directory that is used to set the custom folder which stores the crawler temporary files.
ITEM_PIPELINES
We can define the scrapy dictionary as having pipelines, this represents the pipelines joining each item class. It defaults to the value null.
LOG_STDOUT
With this setting, if set to true, all the concurrent process output will appear in the log file. Its default value is False.
Setting up the values
It is advisable to put these values manually inside the settings.py file. Still, there is also an option to modify these values using the command line.
For Example:
If you want to generate a scrapy log file use the following command.
scrapy crawl myspider -s LOG_FILE=scrapy.log
Conclusion: This is the most important file of the scrapy. Only with this file, you may be able to customize the behaviour of all Scrapy components.
Picked
Python-Scrapy
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n03 Mar, 2021"
},
{
"code": null,
"e": 25766,
"s": 25537,
"text": "Scrapy is an open-source tool built with Python Framework. It presents us with a strong and robust web crawling framework that can easily extract the info from the online page with the assistance of selectors supported by XPath."
},
{
"code": null,
"e": 26214,
"s": 25766,
"text": "We can define the behavior of Scrapy components with the help of Scrapy settings. Pipelines and setting files are very important for scrapy. It is the core of automating the task. These rules help with inserting data into the database. These files are includes when we start with the base template. The Scrapy settings allow you to customize the behavior of all Scrapy components, including the core, extensions, pipelines, and spiders themselves."
},
{
"code": null,
"e": 26640,
"s": 26214,
"text": "We are often presented with the situation where we need to define multiple crapper projects in that case we can define which individual project with the help of scrapy settings. For this, the environment variable SCRAPY_SETTINGS_MODULE should be used and its value should be in Python path syntax. Hence, with the help of the Scrapy settings, the mechanism for choosing the currently active Scrapy project could be specified."
},
{
"code": null,
"e": 26874,
"s": 26640,
"text": "The infrastructure of the settings provides a worldwide namespace of key-value mappings that the code can use to tug configuration values from. The settings are often populated through different mechanisms, which are described below."
},
{
"code": null,
"e": 26930,
"s": 26874,
"text": "Use these commands to start the scrapy template folder."
},
{
"code": null,
"e": 26965,
"s": 26930,
"text": "scrapy startproject <project_name>"
},
{
"code": null,
"e": 27013,
"s": 26965,
"text": "This is the base outline of the scrapy project."
},
{
"code": null,
"e": 27079,
"s": 27013,
"text": "With this article, we would be focusing on the settings.py file. "
},
{
"code": null,
"e": 27178,
"s": 27079,
"text": "The settings.py file looks something like this. We are provided with this as our default settings."
},
{
"code": null,
"e": 27244,
"s": 27178,
"text": "Most commonly used settings and their description is given below:"
},
{
"code": null,
"e": 27253,
"s": 27244,
"text": "BOT_NAME"
},
{
"code": null,
"e": 27507,
"s": 27253,
"text": "It is the name of the project. The bot symbolizes the automation that we are doing with the help of the scrapper. It defaults to ‘scrapybot’. Also as seen in the screenshot it is automatically available with your project name when you start the project."
},
{
"code": null,
"e": 27518,
"s": 27507,
"text": "USER_AGENT"
},
{
"code": null,
"e": 27839,
"s": 27518,
"text": "User-Agent helps us with the identification. It basically tells “who you are” to the servers and network peers. It helps with the identification of the application, OS, vendor, and/or version of the requesting user agent. It defaults to “Scrapy/VERSION (+https://scrapy.org)” while crawling unless explicitly specified. "
},
{
"code": null,
"e": 27871,
"s": 27839,
"text": "The common format for browsers:"
},
{
"code": null,
"e": 27964,
"s": 27871,
"text": "User-Agent: <browser>/<version> (<system-info>) <platform> (<platform-details>) <extensions>"
},
{
"code": null,
"e": 27977,
"s": 27964,
"text": "For Example:"
},
{
"code": null,
"e": 28146,
"s": 27977,
"text": "# Crawl responsibly by identifying yourself (and your website) on the user-agent\nUSER_AGENT = 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'"
},
{
"code": null,
"e": 28161,
"s": 28146,
"text": "ROBOTSTXT_OBEY"
},
{
"code": null,
"e": 28403,
"s": 28161,
"text": "A robots.txt file basically tells the crawlers from search engines which pages it could request from the site. ROBOTSTXT_OBEY defaults to “False”. It is mostly kept enabled, so our scrapy will respect the robots.txt policies by the website. "
},
{
"code": null,
"e": 28528,
"s": 28403,
"text": "The image shows the content of the file robots.txt, the policies are written here are managed by the ROBOTSTXT_OBEY setting."
},
{
"code": null,
"e": 28548,
"s": 28528,
"text": "CONCURRENT_REQUESTS"
},
{
"code": null,
"e": 28698,
"s": 28548,
"text": "It is basically asking the website to open up. It defaults to 16. So basically it is the maximum number of the request that the crawler will perform."
},
{
"code": null,
"e": 28792,
"s": 28698,
"text": "More request increases a load to the server so keeping it as low as 16 or 32 is a good value."
},
{
"code": null,
"e": 28809,
"s": 28792,
"text": "CONCURRENT_ITEMS"
},
{
"code": null,
"e": 28984,
"s": 28809,
"text": "It means while scrapping the data what a maximum number of concurrent items the scrapy will process in parallel per response. It defaults to 100, which is again a good value."
},
{
"code": null,
"e": 29065,
"s": 28984,
"text": "custom_settings = {\n 'CONCURRENT_REQUESTS' = 30,\n 'CONCURRENT_ITEMS' = 80,\n}"
},
{
"code": null,
"e": 29096,
"s": 29065,
"text": "CONCURRENT_REQUESTS_PER_DOMAIN"
},
{
"code": null,
"e": 29268,
"s": 29096,
"text": "It means while scrapping the data what is the maximum number of existing requests that can be performed concurrently for any single domain value. It defaults to value ‘8’."
},
{
"code": null,
"e": 29295,
"s": 29268,
"text": "CONCURRENT_REQUESTS_PER_IP"
},
{
"code": null,
"e": 29469,
"s": 29295,
"text": "It means while scrapping the data what is the maximum number of existing requests that can be performed concurrently for any single IP address. It defaults to the value ‘0’."
},
{
"code": null,
"e": 29570,
"s": 29469,
"text": "custom_settings = {\n 'CONCURRENT_REQUESTS_PER_DOMAIN' = 8,\n 'CONCURRENT_REQUESTS_PER_IP' = 2\n}"
},
{
"code": null,
"e": 29585,
"s": 29570,
"text": "DOWNLOAD_DELAY"
},
{
"code": null,
"e": 29800,
"s": 29585,
"text": "It is the delay in the amount of time that the downloader would before again downloading the pages from the website. This again is used to limit the load on the server where the website is hosted. It defaults to 0."
},
{
"code": null,
"e": 29813,
"s": 29800,
"text": "For Example:"
},
{
"code": null,
"e": 29856,
"s": 29813,
"text": "DOWNLOAD_DELAY = 0.25 # 250 ms of delay"
},
{
"code": null,
"e": 29873,
"s": 29856,
"text": "DOWNLOAD_TIMEOUT"
},
{
"code": null,
"e": 30009,
"s": 29873,
"text": "It is the time-out time. Tells scrapy to wait for the given amount of time to wait before the downloader times out. It defaults to 180."
},
{
"code": null,
"e": 30021,
"s": 30009,
"text": "LOG_ENABLED"
},
{
"code": null,
"e": 30106,
"s": 30021,
"text": "It is used to enable or disable the logging for the scrapper. It defaults to “True”."
},
{
"code": null,
"e": 30119,
"s": 30106,
"text": "FTP_PASSWORD"
},
{
"code": null,
"e": 30263,
"s": 30119,
"text": "Used to set a password for the FTP connections. The value is used only when there is no “ftp_password” in Request meta. It defaults to “guest”."
},
{
"code": null,
"e": 30272,
"s": 30263,
"text": "FTP_USER"
},
{
"code": null,
"e": 30416,
"s": 30272,
"text": "Used to set a username for the FTP connections. The value is used only when there is no “ftp_user” in Request meta. It defaults to “anonymous”."
},
{
"code": null,
"e": 30435,
"s": 30416,
"text": "DEFAULT_ITEM_CLASS"
},
{
"code": null,
"e": 30619,
"s": 30435,
"text": "This setting is used to represent items within a scrapy, the values are stored in this class format specified by DEFAULT_ITEM_CLASS. The default format is given by ‘scrapy.item.Item’."
},
{
"code": null,
"e": 30643,
"s": 30619,
"text": "DEFAULT_REQUEST_HEADERS"
},
{
"code": null,
"e": 30778,
"s": 30643,
"text": "The given setting lists the default header used for HTTP requests made by Scrapy. It is populated within the DefaultHeadersMiddleware."
},
{
"code": null,
"e": 30816,
"s": 30778,
"text": "The default header value is given by:"
},
{
"code": null,
"e": 30930,
"s": 30816,
"text": "{\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n 'Accept-Language': 'en',\n}"
},
{
"code": null,
"e": 30957,
"s": 30930,
"text": "REACTOR_THREADPOOL_MAXSIZE"
},
{
"code": null,
"e": 31107,
"s": 30957,
"text": "The reactor thread pool could also be set within the scrapy. It binds the max size for the reactor thread pool of the spider. Its default size is 10."
},
{
"code": null,
"e": 31198,
"s": 31107,
"text": "For example, the settings could be applied within the code like the following Python code:"
},
{
"code": null,
"e": 31655,
"s": 31198,
"text": "class exampleSpider(scrapy.Spider):\n name = 'example'\n custom_settings = {\n 'CONCURRENT_REQUESTS': 25,\n 'CONCURRENT_REQUESTS_PER_DOMAIN': 100,\n 'DOWNLOAD_DELAY': 0\n }\n \n f = open(\"example\")\n start_urls = [url.strip() for url in f.readlines()]\n f.close()\n\n def parse(self, response):\n for itemin response.xpath(\"//div[@class=<class_component>]\"):\n urlgem = item.xpath(\".//div[@class=<class_component>]/a/@href\").extract()"
},
{
"code": null,
"e": 31673,
"s": 31655,
"text": "AWS_ACCESS_KEY_ID"
},
{
"code": null,
"e": 31798,
"s": 31673,
"text": "With this you can set AWS ID within your scrapy, it is used to access Amazon Web Services. It defaults to the “None” value. "
},
{
"code": null,
"e": 31820,
"s": 31798,
"text": "AWS_SECRET_ACCESS_KEY"
},
{
"code": null,
"e": 31981,
"s": 31820,
"text": "With this you can set AWS Access Key (Password or ID credential) within your scrapy, it is used to access Amazon Web Services. It defaults to the “None” value. "
},
{
"code": null,
"e": 31993,
"s": 31981,
"text": "DEPTH_LIMIT"
},
{
"code": null,
"e": 32069,
"s": 31993,
"text": "The limiting depth for the spider to crawl a target site. It defaults to 0."
},
{
"code": null,
"e": 32084,
"s": 32069,
"text": "DEPTH_PRIORITY"
},
{
"code": null,
"e": 32176,
"s": 32084,
"text": "It further manages the priority of the depth to crawl a target site. It also defaults to 0."
},
{
"code": null,
"e": 32374,
"s": 32176,
"text": "This is a basic layout of the selector graph inside the Scrapy. The components could be built inside this Selector Graph. Each component is responsible for scrapping individual items from the site."
},
{
"code": null,
"e": 32386,
"s": 32374,
"text": "DEPTH_STATS"
},
{
"code": null,
"e": 32612,
"s": 32386,
"text": "With this setting, we can also collect the Depth Stats within the logs of the level crawled. If the setting is enabled then the value of each individual request for each depth is collected in the stats. Its default is “True”."
},
{
"code": null,
"e": 32632,
"s": 32612,
"text": "DEPTH_STATS_VERBOSE"
},
{
"code": null,
"e": 32753,
"s": 32632,
"text": "Further improves the DEPTH_STATS by enabling the number of requests which are collected in stats for each verbose depth."
},
{
"code": null,
"e": 32780,
"s": 32753,
"text": "By default, it is “False”."
},
{
"code": null,
"e": 32955,
"s": 32780,
"text": "Selector levels can extend up to infinite depth as structured by the webmaster. With the various depth settings, it’s our duty to limit the Selector Graph within our crawler."
},
{
"code": null,
"e": 32972,
"s": 32955,
"text": "DNSCACHE_ENABLED"
},
{
"code": null,
"e": 33060,
"s": 32972,
"text": "With this setting, we could enable DNS inside a memory cache. By default, it is “True”."
},
{
"code": null,
"e": 33074,
"s": 33060,
"text": "DNSCACHE_SIZE"
},
{
"code": null,
"e": 33174,
"s": 33074,
"text": "With this setting, we could define the size of the DNS in-memory cache. Its default value is 10000."
},
{
"code": null,
"e": 33186,
"s": 33174,
"text": "DNS_TIMEOUT"
},
{
"code": null,
"e": 33270,
"s": 33186,
"text": "It is the time-out time for the DNS to process the scrapy query. It defaults to 60."
},
{
"code": null,
"e": 33281,
"s": 33270,
"text": "DOWNLOADER"
},
{
"code": null,
"e": 33392,
"s": 33281,
"text": "The actual downloader used by the crawler. The default format is given by ‘scrapy.core.downloader.Downloader’."
},
{
"code": null,
"e": 33415,
"s": 33392,
"text": "DOWNLOADER_MIDDLEWARES"
},
{
"code": null,
"e": 33499,
"s": 33415,
"text": "The dictionary holds downloading middleware and its orders. It is by default empty."
},
{
"code": null,
"e": 33515,
"s": 33499,
"text": "EXTENSIONS_BASE"
},
{
"code": null,
"e": 33637,
"s": 33515,
"text": "The dictionary with a built-in extension value. It is defaulted by value: { ‘scrapy.extensions.corestats.CoreStats’: 0, }"
},
{
"code": null,
"e": 33650,
"s": 33637,
"text": "FEED_TEMPDIR"
},
{
"code": null,
"e": 33750,
"s": 33650,
"text": "This is a directory that is used to set the custom folder which stores the crawler temporary files."
},
{
"code": null,
"e": 33765,
"s": 33750,
"text": "ITEM_PIPELINES"
},
{
"code": null,
"e": 33908,
"s": 33765,
"text": "We can define the scrapy dictionary as having pipelines, this represents the pipelines joining each item class. It defaults to the value null."
},
{
"code": null,
"e": 33919,
"s": 33908,
"text": "LOG_STDOUT"
},
{
"code": null,
"e": 34045,
"s": 33919,
"text": "With this setting, if set to true, all the concurrent process output will appear in the log file. Its default value is False."
},
{
"code": null,
"e": 34067,
"s": 34045,
"text": "Setting up the values"
},
{
"code": null,
"e": 34219,
"s": 34067,
"text": "It is advisable to put these values manually inside the settings.py file. Still, there is also an option to modify these values using the command line."
},
{
"code": null,
"e": 34233,
"s": 34219,
"text": "For Example: "
},
{
"code": null,
"e": 34302,
"s": 34233,
"text": "If you want to generate a scrapy log file use the following command."
},
{
"code": null,
"e": 34347,
"s": 34302,
"text": "scrapy crawl myspider -s LOG_FILE=scrapy.log"
},
{
"code": null,
"e": 34496,
"s": 34347,
"text": "Conclusion: This is the most important file of the scrapy. Only with this file, you may be able to customize the behaviour of all Scrapy components."
},
{
"code": null,
"e": 34503,
"s": 34496,
"text": "Picked"
},
{
"code": null,
"e": 34517,
"s": 34503,
"text": "Python-Scrapy"
},
{
"code": null,
"e": 34541,
"s": 34517,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 34548,
"s": 34541,
"text": "Python"
},
{
"code": null,
"e": 34567,
"s": 34548,
"text": "Technical Scripter"
},
{
"code": null,
"e": 34665,
"s": 34567,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34697,
"s": 34665,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 34739,
"s": 34697,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 34781,
"s": 34739,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 34808,
"s": 34781,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 34864,
"s": 34808,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 34886,
"s": 34864,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 34925,
"s": 34886,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 34956,
"s": 34925,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 34985,
"s": 34956,
"text": "Create a directory in Python"
}
] |
Split the binary string into substrings with equal number of 0s and 1s - GeeksforGeeks
|
26 Nov, 2021
Given a binary string str of length N, the task is to find the maximum count of consecutive substrings str can be divided into such that all the substrings are balanced i.e. they have equal number of 0s and 1s. If it is not possible to split str satisfying the conditions then print -1.Example:
Input: str = “0100110101” Output: 4 The required substrings are “01”, “0011”, “01” and “01”.Input: str = “0111100010” Output: 3
Input: str = “0000000000”
Output: -1
Approach: Initialize count = 0 and traverse the string character by character and keep track of the number of 0s and 1s so far, whenever the count of 0s and 1s become equal increment the count. As in the given question, if it is not possible to split string then on that time count of 0s must not be equal to count of 1s then return -1 else print the value of count after the traversal of the complete string.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count// of maximum substrings str// can be divided intoint maxSubStr(string str, int n){ // To store the count of 0s and 1s int count0 = 0, count1 = 0; // To store the count of maximum // substrings str can be divided into int cnt = 0; for (int i = 0; i < n; i++) { if (str[i] == '0') { count0++; } else { count1++; } if (count0 == count1) { cnt++; } } // It is not possible to // split the string if (count0!=count1) { return -1; } return cnt;} // Driver codeint main(){ string str = "0100110101"; int n = str.length(); cout << maxSubStr(str, n); return 0;}
// Java implementation of the above approachclass GFG{ // Function to return the count// of maximum substrings str// can be divided intostatic int maxSubStr(String str, int n){ // To store the count of 0s and 1s int count0 = 0, count1 = 0; // To store the count of maximum // substrings str can be divided into int cnt = 0; for (int i = 0; i < n; i++) { if (str.charAt(i) == '0') { count0++; } else { count1++; } if (count0 == count1) { cnt++; } } // It is not possible to // split the string if (count0 != count1) { return -1; } return cnt;} // Driver codepublic static void main(String []args){ String str = "0100110101"; int n = str.length(); System.out.println(maxSubStr(str, n));}} // This code is contributed by PrinciRaj1992
# Python3 implementation of the approach # Function to return the count# of maximum substrings str# can be divided intodef maxSubStr(str, n): # To store the count of 0s and 1s count0 = 0 count1 = 0 # To store the count of maximum # substrings str can be divided into cnt = 0 for i in range(n): if str[i] == '0': count0 += 1 else: count1 += 1 if count0 == count1: cnt += 1 # It is not possible to # split the string if count0 != count1: return -1 return cnt # Driver codestr = "0100110101"n = len(str)print(maxSubStr(str, n))
// C# implementation of the above approachusing System; class GFG{ // Function to return the count// of maximum substrings str// can be divided intostatic int maxSubStr(String str, int n){ // To store the count of 0s and 1s int count0 = 0, count1 = 0; // To store the count of maximum // substrings str can be divided into int cnt = 0; for (int i = 0; i < n; i++) { if (str[i] == '0') { count0++; } else { count1++; } if (count0 == count1) { cnt++; } } // It is not possible to // split the string if (count0 != count1) { return -1; } return cnt;} // Driver codepublic static void Main(String []args){ String str = "0100110101"; int n = str.Length; Console.WriteLine(maxSubStr(str, n));}} // This code is contributed by PrinciRaj1992
<script> // JavaScript implementation of the approach // Function to return the count// of maximum substrings str// can be divided intofunction maxSubStr(str, n){ // To store the count of 0s and 1s var count0 = 0, count1 = 0; // To store the count of maximum // substrings str can be divided into var cnt = 0; for (var i = 0; i < n; i++) { if (str[i] == '0') { count0++; } else { count1++; } if (count0 == count1) { cnt++; } } // It is not possible to // split the string if (count0 != count1) { return -1; } return cnt;} // Driver codevar str = "0100110101";var n = str.length;document.write( maxSubStr(str, n)); </script>
4
Time complexity: O(N) where N is the length of string Space Complexity: O(1)
princiraj1992
famously
yashwant94308
yadavsoumya1010
ashutoshsinghgeeksforgeeks
binary-string
substring
Algorithms
Pattern Searching
Strings
Strings
Pattern Searching
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
How to write a Pseudo Code?
Understanding Time Complexity with Simple Examples
How to Start Learning DSA?
KMP Algorithm for Pattern Searching
Rabin-Karp Algorithm for Pattern Searching
Naive algorithm for Pattern Searching
Check if a string is substring of another
Boyer Moore Algorithm for Pattern Searching
|
[
{
"code": null,
"e": 26129,
"s": 26101,
"text": "\n26 Nov, 2021"
},
{
"code": null,
"e": 26426,
"s": 26129,
"text": "Given a binary string str of length N, the task is to find the maximum count of consecutive substrings str can be divided into such that all the substrings are balanced i.e. they have equal number of 0s and 1s. If it is not possible to split str satisfying the conditions then print -1.Example: "
},
{
"code": null,
"e": 26555,
"s": 26426,
"text": "Input: str = “0100110101” Output: 4 The required substrings are “01”, “0011”, “01” and “01”.Input: str = “0111100010” Output: 3 "
},
{
"code": null,
"e": 26582,
"s": 26555,
"text": "Input: str = “0000000000” "
},
{
"code": null,
"e": 26594,
"s": 26582,
"text": "Output: -1 "
},
{
"code": null,
"e": 27057,
"s": 26596,
"text": "Approach: Initialize count = 0 and traverse the string character by character and keep track of the number of 0s and 1s so far, whenever the count of 0s and 1s become equal increment the count. As in the given question, if it is not possible to split string then on that time count of 0s must not be equal to count of 1s then return -1 else print the value of count after the traversal of the complete string.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27061,
"s": 27057,
"text": "C++"
},
{
"code": null,
"e": 27066,
"s": 27061,
"text": "Java"
},
{
"code": null,
"e": 27074,
"s": 27066,
"text": "Python3"
},
{
"code": null,
"e": 27077,
"s": 27074,
"text": "C#"
},
{
"code": null,
"e": 27088,
"s": 27077,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count// of maximum substrings str// can be divided intoint maxSubStr(string str, int n){ // To store the count of 0s and 1s int count0 = 0, count1 = 0; // To store the count of maximum // substrings str can be divided into int cnt = 0; for (int i = 0; i < n; i++) { if (str[i] == '0') { count0++; } else { count1++; } if (count0 == count1) { cnt++; } } // It is not possible to // split the string if (count0!=count1) { return -1; } return cnt;} // Driver codeint main(){ string str = \"0100110101\"; int n = str.length(); cout << maxSubStr(str, n); return 0;}",
"e": 27891,
"s": 27088,
"text": null
},
{
"code": "// Java implementation of the above approachclass GFG{ // Function to return the count// of maximum substrings str// can be divided intostatic int maxSubStr(String str, int n){ // To store the count of 0s and 1s int count0 = 0, count1 = 0; // To store the count of maximum // substrings str can be divided into int cnt = 0; for (int i = 0; i < n; i++) { if (str.charAt(i) == '0') { count0++; } else { count1++; } if (count0 == count1) { cnt++; } } // It is not possible to // split the string if (count0 != count1) { return -1; } return cnt;} // Driver codepublic static void main(String []args){ String str = \"0100110101\"; int n = str.length(); System.out.println(maxSubStr(str, n));}} // This code is contributed by PrinciRaj1992",
"e": 28781,
"s": 27891,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to return the count# of maximum substrings str# can be divided intodef maxSubStr(str, n): # To store the count of 0s and 1s count0 = 0 count1 = 0 # To store the count of maximum # substrings str can be divided into cnt = 0 for i in range(n): if str[i] == '0': count0 += 1 else: count1 += 1 if count0 == count1: cnt += 1 # It is not possible to # split the string if count0 != count1: return -1 return cnt # Driver codestr = \"0100110101\"n = len(str)print(maxSubStr(str, n))",
"e": 29438,
"s": 28781,
"text": null
},
{
"code": "// C# implementation of the above approachusing System; class GFG{ // Function to return the count// of maximum substrings str// can be divided intostatic int maxSubStr(String str, int n){ // To store the count of 0s and 1s int count0 = 0, count1 = 0; // To store the count of maximum // substrings str can be divided into int cnt = 0; for (int i = 0; i < n; i++) { if (str[i] == '0') { count0++; } else { count1++; } if (count0 == count1) { cnt++; } } // It is not possible to // split the string if (count0 != count1) { return -1; } return cnt;} // Driver codepublic static void Main(String []args){ String str = \"0100110101\"; int n = str.Length; Console.WriteLine(maxSubStr(str, n));}} // This code is contributed by PrinciRaj1992",
"e": 30330,
"s": 29438,
"text": null
},
{
"code": "<script> // JavaScript implementation of the approach // Function to return the count// of maximum substrings str// can be divided intofunction maxSubStr(str, n){ // To store the count of 0s and 1s var count0 = 0, count1 = 0; // To store the count of maximum // substrings str can be divided into var cnt = 0; for (var i = 0; i < n; i++) { if (str[i] == '0') { count0++; } else { count1++; } if (count0 == count1) { cnt++; } } // It is not possible to // split the string if (count0 != count1) { return -1; } return cnt;} // Driver codevar str = \"0100110101\";var n = str.length;document.write( maxSubStr(str, n)); </script>",
"e": 31076,
"s": 30330,
"text": null
},
{
"code": null,
"e": 31078,
"s": 31076,
"text": "4"
},
{
"code": null,
"e": 31158,
"s": 31080,
"text": "Time complexity: O(N) where N is the length of string Space Complexity: O(1) "
},
{
"code": null,
"e": 31172,
"s": 31158,
"text": "princiraj1992"
},
{
"code": null,
"e": 31181,
"s": 31172,
"text": "famously"
},
{
"code": null,
"e": 31195,
"s": 31181,
"text": "yashwant94308"
},
{
"code": null,
"e": 31211,
"s": 31195,
"text": "yadavsoumya1010"
},
{
"code": null,
"e": 31238,
"s": 31211,
"text": "ashutoshsinghgeeksforgeeks"
},
{
"code": null,
"e": 31252,
"s": 31238,
"text": "binary-string"
},
{
"code": null,
"e": 31262,
"s": 31252,
"text": "substring"
},
{
"code": null,
"e": 31273,
"s": 31262,
"text": "Algorithms"
},
{
"code": null,
"e": 31291,
"s": 31273,
"text": "Pattern Searching"
},
{
"code": null,
"e": 31299,
"s": 31291,
"text": "Strings"
},
{
"code": null,
"e": 31307,
"s": 31299,
"text": "Strings"
},
{
"code": null,
"e": 31325,
"s": 31307,
"text": "Pattern Searching"
},
{
"code": null,
"e": 31336,
"s": 31325,
"text": "Algorithms"
},
{
"code": null,
"e": 31434,
"s": 31336,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31483,
"s": 31434,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 31508,
"s": 31483,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 31536,
"s": 31508,
"text": "How to write a Pseudo Code?"
},
{
"code": null,
"e": 31587,
"s": 31536,
"text": "Understanding Time Complexity with Simple Examples"
},
{
"code": null,
"e": 31614,
"s": 31587,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 31650,
"s": 31614,
"text": "KMP Algorithm for Pattern Searching"
},
{
"code": null,
"e": 31693,
"s": 31650,
"text": "Rabin-Karp Algorithm for Pattern Searching"
},
{
"code": null,
"e": 31731,
"s": 31693,
"text": "Naive algorithm for Pattern Searching"
},
{
"code": null,
"e": 31773,
"s": 31731,
"text": "Check if a string is substring of another"
}
] |
Plotting cross-spectral density in Python using Matplotlib - GeeksforGeeks
|
24 Jan, 2022
Matplotlib is a comprehensive library consisting of modules that are used for Data Visualization just like MATLAB. Pyplot is a further module which makes functions and methods executable.
The cross-spectral density compares two signals, each from different source taking into account both amplitude and phase difference of the two signals. In Python, this function is carried out using the Pyplot module’s method matplotlib.pyplot.csd()Syntax:
matplotlib.pyplot.csd(x, y)
Here, x and y are 1-D arrays or a sequence having the data.Let us take two signals and plot their CSD:
Signal 1 has time period from 0 to 1 second and 0.1 radian phase angle with frequency being calculated using sin() function.Similarly, Signal 2 has time period from 5 to 10 seconds and 0.25 radians phase angle.Taking these two signals, we plot their cross spectral density.
Signal 1 has time period from 0 to 1 second and 0.1 radian phase angle with frequency being calculated using sin() function.
Similarly, Signal 2 has time period from 5 to 10 seconds and 0.25 radians phase angle.
Taking these two signals, we plot their cross spectral density.
Example 1: Plotting Signal 1
python3
import numpy as npimport matplotlib.pyplot as plt time = np.arange(0, 1, 0.1)amp = np.sin(time) plt.plot(time, amp)plt.title("Signal 1") plt.show()
Output:
Example 2: Plotting Signal 2
Python3
import numpy as npimport matplotlib.pyplot as plt t = np.arange(5, 10, 0.25)ampl = np.sin(t) plt.plot(t, ampl)plt.title("Signal 2") plt.show()
Output:
Example 3: Plotting the cross-spectral density
Python3
import numpy as npimport matplotlib.pyplot as plt # Signal 1time = np.arange(0, 1, 0.1)amp = np.sin(time) # Signal 2t = np.arange(5, 10, 0.25)ampl = np.sin(t) # Cross-spectral densityplt.csd(amp, ampl) plt.show()
Output:
Example 4: Using discrete lists or arrays
Python3
import numpy as npimport matplotlib.pyplot as plt a = np.arange(5)b = np.arange(10, 30) plt.csd(a, b)plt.show()
Output:
varshagumber28
Python-matplotlib
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Convert string to integer in Python
Python infinity
How to set input type date in dd-mm-yyyy format using HTML ?
Matplotlib.pyplot.title() in Python
Factory method design pattern in Java
|
[
{
"code": null,
"e": 25563,
"s": 25535,
"text": "\n24 Jan, 2022"
},
{
"code": null,
"e": 25752,
"s": 25563,
"text": "Matplotlib is a comprehensive library consisting of modules that are used for Data Visualization just like MATLAB. Pyplot is a further module which makes functions and methods executable. "
},
{
"code": null,
"e": 26009,
"s": 25752,
"text": "The cross-spectral density compares two signals, each from different source taking into account both amplitude and phase difference of the two signals. In Python, this function is carried out using the Pyplot module’s method matplotlib.pyplot.csd()Syntax: "
},
{
"code": null,
"e": 26037,
"s": 26009,
"text": "matplotlib.pyplot.csd(x, y)"
},
{
"code": null,
"e": 26141,
"s": 26037,
"text": "Here, x and y are 1-D arrays or a sequence having the data.Let us take two signals and plot their CSD: "
},
{
"code": null,
"e": 26415,
"s": 26141,
"text": "Signal 1 has time period from 0 to 1 second and 0.1 radian phase angle with frequency being calculated using sin() function.Similarly, Signal 2 has time period from 5 to 10 seconds and 0.25 radians phase angle.Taking these two signals, we plot their cross spectral density."
},
{
"code": null,
"e": 26540,
"s": 26415,
"text": "Signal 1 has time period from 0 to 1 second and 0.1 radian phase angle with frequency being calculated using sin() function."
},
{
"code": null,
"e": 26627,
"s": 26540,
"text": "Similarly, Signal 2 has time period from 5 to 10 seconds and 0.25 radians phase angle."
},
{
"code": null,
"e": 26691,
"s": 26627,
"text": "Taking these two signals, we plot their cross spectral density."
},
{
"code": null,
"e": 26722,
"s": 26691,
"text": "Example 1: Plotting Signal 1 "
},
{
"code": null,
"e": 26730,
"s": 26722,
"text": "python3"
},
{
"code": "import numpy as npimport matplotlib.pyplot as plt time = np.arange(0, 1, 0.1)amp = np.sin(time) plt.plot(time, amp)plt.title(\"Signal 1\") plt.show()",
"e": 26879,
"s": 26730,
"text": null
},
{
"code": null,
"e": 26888,
"s": 26879,
"text": "Output: "
},
{
"code": null,
"e": 26918,
"s": 26888,
"text": "Example 2: Plotting Signal 2 "
},
{
"code": null,
"e": 26926,
"s": 26918,
"text": "Python3"
},
{
"code": "import numpy as npimport matplotlib.pyplot as plt t = np.arange(5, 10, 0.25)ampl = np.sin(t) plt.plot(t, ampl)plt.title(\"Signal 2\") plt.show()",
"e": 27070,
"s": 26926,
"text": null
},
{
"code": null,
"e": 27079,
"s": 27070,
"text": "Output: "
},
{
"code": null,
"e": 27127,
"s": 27079,
"text": "Example 3: Plotting the cross-spectral density "
},
{
"code": null,
"e": 27135,
"s": 27127,
"text": "Python3"
},
{
"code": "import numpy as npimport matplotlib.pyplot as plt # Signal 1time = np.arange(0, 1, 0.1)amp = np.sin(time) # Signal 2t = np.arange(5, 10, 0.25)ampl = np.sin(t) # Cross-spectral densityplt.csd(amp, ampl) plt.show()",
"e": 27349,
"s": 27135,
"text": null
},
{
"code": null,
"e": 27358,
"s": 27349,
"text": "Output: "
},
{
"code": null,
"e": 27402,
"s": 27358,
"text": "Example 4: Using discrete lists or arrays "
},
{
"code": null,
"e": 27410,
"s": 27402,
"text": "Python3"
},
{
"code": "import numpy as npimport matplotlib.pyplot as plt a = np.arange(5)b = np.arange(10, 30) plt.csd(a, b)plt.show()",
"e": 27523,
"s": 27410,
"text": null
},
{
"code": null,
"e": 27532,
"s": 27523,
"text": "Output: "
},
{
"code": null,
"e": 27549,
"s": 27534,
"text": "varshagumber28"
},
{
"code": null,
"e": 27567,
"s": 27549,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 27574,
"s": 27567,
"text": "Python"
},
{
"code": null,
"e": 27590,
"s": 27574,
"text": "Write From Home"
},
{
"code": null,
"e": 27688,
"s": 27590,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27720,
"s": 27688,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27762,
"s": 27720,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27804,
"s": 27762,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27831,
"s": 27804,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27887,
"s": 27831,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27923,
"s": 27887,
"text": "Convert string to integer in Python"
},
{
"code": null,
"e": 27939,
"s": 27923,
"text": "Python infinity"
},
{
"code": null,
"e": 28000,
"s": 27939,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 28036,
"s": 28000,
"text": "Matplotlib.pyplot.title() in Python"
}
] |
How to combine Groupby and Multiple Aggregate Functions in Pandas? - GeeksforGeeks
|
10 May, 2020
Pandas is a Python package that offers various data structures and operations for manipulating numerical data and time series. It is mainly popular for importing and analyzing data much easier. It is an open-source library that is built on top of NumPy library.
Pandas dataframe.groupby() function is used to split the data in dataframe into groups based on a given condition.
Example 1:
# import libraryimport pandas as pd # import csv filedf = pd.read_csv("https://bit.ly/drinksbycountry") df.head()
Output:
Example 2:
# Find the average of each continent# by grouping the data # based on the "continent".df.groupby(["continent"]).mean()
Output:
Pandas dataframe.agg() function is used to do one or more operations on data based on specified axis
Example:
# here sum, minimum and maximum of column # beer_servings is calculataddf.beer_servings.agg(["sum", "min", "max"])
Output:
Using These two functions together: We can find multiple aggregation functions of a particular column grouped by another column.
Example:
# find an aggregation of column "beer_servings"# by grouping the "continent" column.df.groupby(df["continent"]).beer_servings.agg(["min", "max", "sum", "count", "mean"])
Output:
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Convert integer to string in Python
Convert string to integer in Python
How to set input type date in dd-mm-yyyy format using HTML ?
Python infinity
Matplotlib.pyplot.title() in Python
|
[
{
"code": null,
"e": 26197,
"s": 26169,
"text": "\n10 May, 2020"
},
{
"code": null,
"e": 26459,
"s": 26197,
"text": "Pandas is a Python package that offers various data structures and operations for manipulating numerical data and time series. It is mainly popular for importing and analyzing data much easier. It is an open-source library that is built on top of NumPy library."
},
{
"code": null,
"e": 26574,
"s": 26459,
"text": "Pandas dataframe.groupby() function is used to split the data in dataframe into groups based on a given condition."
},
{
"code": null,
"e": 26585,
"s": 26574,
"text": "Example 1:"
},
{
"code": "# import libraryimport pandas as pd # import csv filedf = pd.read_csv(\"https://bit.ly/drinksbycountry\") df.head()",
"e": 26701,
"s": 26585,
"text": null
},
{
"code": null,
"e": 26709,
"s": 26701,
"text": "Output:"
},
{
"code": null,
"e": 26720,
"s": 26709,
"text": "Example 2:"
},
{
"code": "# Find the average of each continent# by grouping the data # based on the \"continent\".df.groupby([\"continent\"]).mean()",
"e": 26840,
"s": 26720,
"text": null
},
{
"code": null,
"e": 26848,
"s": 26840,
"text": "Output:"
},
{
"code": null,
"e": 26949,
"s": 26848,
"text": "Pandas dataframe.agg() function is used to do one or more operations on data based on specified axis"
},
{
"code": null,
"e": 26958,
"s": 26949,
"text": "Example:"
},
{
"code": "# here sum, minimum and maximum of column # beer_servings is calculataddf.beer_servings.agg([\"sum\", \"min\", \"max\"])",
"e": 27073,
"s": 26958,
"text": null
},
{
"code": null,
"e": 27081,
"s": 27073,
"text": "Output:"
},
{
"code": null,
"e": 27210,
"s": 27081,
"text": "Using These two functions together: We can find multiple aggregation functions of a particular column grouped by another column."
},
{
"code": null,
"e": 27219,
"s": 27210,
"text": "Example:"
},
{
"code": "# find an aggregation of column \"beer_servings\"# by grouping the \"continent\" column.df.groupby(df[\"continent\"]).beer_servings.agg([\"min\", \"max\", \"sum\", \"count\", \"mean\"])",
"e": 27573,
"s": 27219,
"text": null
},
{
"code": null,
"e": 27581,
"s": 27573,
"text": "Output:"
},
{
"code": null,
"e": 27605,
"s": 27581,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 27637,
"s": 27605,
"text": "Python pandas-dataFrame-methods"
},
{
"code": null,
"e": 27651,
"s": 27637,
"text": "Python-pandas"
},
{
"code": null,
"e": 27658,
"s": 27651,
"text": "Python"
},
{
"code": null,
"e": 27674,
"s": 27658,
"text": "Write From Home"
},
{
"code": null,
"e": 27772,
"s": 27674,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27790,
"s": 27772,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27822,
"s": 27790,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27844,
"s": 27822,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27886,
"s": 27844,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27916,
"s": 27886,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27952,
"s": 27916,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 27988,
"s": 27952,
"text": "Convert string to integer in Python"
},
{
"code": null,
"e": 28049,
"s": 27988,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 28065,
"s": 28049,
"text": "Python infinity"
}
] |
Remove the whitespaces from a string using replace() in JavaScript?
|
Let’s say the following is our string with whitespace −
var fullName=" John Smith ";
Use replace() and set Regex in it to remove whitespaces.
function removeSpacesAtTheBeginningAndTheEnd(name) {
return name.toString().replace(/^\s+|\s+$/g,'');
}
var fullName=" John Smith ";
var
valueAfterRemovingSpace=removeSpacesAtTheBeginningAndTheEnd(fullName)
console.log(valueAfterRemovingSpace);
To run the above program, you need to use the following command −
node fileName.js.
Here my file name is demo208.js.
This will produce the following output −
PS C:\Users\Amit\javascript-code> node demo208.js
John Smith
|
[
{
"code": null,
"e": 1118,
"s": 1062,
"text": "Let’s say the following is our string with whitespace −"
},
{
"code": null,
"e": 1147,
"s": 1118,
"text": "var fullName=\" John Smith \";"
},
{
"code": null,
"e": 1204,
"s": 1147,
"text": "Use replace() and set Regex in it to remove whitespaces."
},
{
"code": null,
"e": 1452,
"s": 1204,
"text": "function removeSpacesAtTheBeginningAndTheEnd(name) {\n return name.toString().replace(/^\\s+|\\s+$/g,'');\n}\nvar fullName=\" John Smith \";\nvar\nvalueAfterRemovingSpace=removeSpacesAtTheBeginningAndTheEnd(fullName)\nconsole.log(valueAfterRemovingSpace);"
},
{
"code": null,
"e": 1518,
"s": 1452,
"text": "To run the above program, you need to use the following command −"
},
{
"code": null,
"e": 1536,
"s": 1518,
"text": "node fileName.js."
},
{
"code": null,
"e": 1569,
"s": 1536,
"text": "Here my file name is demo208.js."
},
{
"code": null,
"e": 1610,
"s": 1569,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1671,
"s": 1610,
"text": "PS C:\\Users\\Amit\\javascript-code> node demo208.js\nJohn Smith"
}
] |
Encrypt and Decrypt Image using Python - GeeksforGeeks
|
05 Aug, 2021
In this article, we will encrypt/decrypt an image using a simple mathematical logic. It requires two things, data and key and when XOR operation is applied on both the operands i.e data and key, the data gets encrypted but when the same process is done again with same key value data gets decrypted.
It is nothing but a simple process in which we convert our data or information into secrete code to prevent it from unauthorized access and keep it private and secure.
First, we will select an image, and then we will convert that image into a byte array due to which the image data will be totally converted into numeric form, and then we can easily apply the XOR operation on it. Now, whenever we will apply the XOR function on each value of the byte array then the data will be changed due to which we will be unable to access it. But we should remember one thing that here our encryption key plays a very important role without that key we can not decrypt our image. It acts as a password to decrypt it.
Below program depicts the basic approach of encryption:
Python3
# Assign valuesdata = 1281key = 27 # Display valuesprint('Original Data:', data)print('Key:', key) # Encryptiondata = data ^ keyprint('After Encryption:', data) # Decryptiondata = data ^ keyprint('After Decryption:', data)
Output:
Original Data: 1281
Key: 27
After Encryption: 1306
After Decryption: 1281
Here in above program, as we can see that how XOR operation works, it takes two variables data and key, whenever we perform XOR operation on them for the first time we get encrypted data. Then when we perform XOR operation between our data and key again, we get same value as our input variable data (decrypted data). Same logic will be applicable on byte array of Image during encryption and decryption.
Executable code for Encryption:
Python3
# try block to handle exceptiontry: # take path of image as a input path = input(r'Enter path of Image : ') # taking encryption key as input key = int(input('Enter Key for encryption of Image : ')) # print path of image file and encryption key that # we are using print('The path of file : ', path) print('Key for encryption : ', key) # open file for reading purpose fin = open(path, 'rb') # storing image data in variable "image" image = fin.read() fin.close() # converting image into byte array to # perform encryption easily on numeric data image = bytearray(image) # performing XOR operation on each value of bytearray for index, values in enumerate(image): image[index] = values ^ key # opening file for writing purpose fin = open(path, 'wb') # writing encrypted data in image fin.write(image) fin.close() print('Encryption Done...') except Exception: print('Error caught : ', Exception.__name__)
Output:
Enter path of Image : C:\Users\lenovo\Pictures\Instagram\enc.png
Enter Key for encryption of Image : 22
The path of file : C:\Users\lenovo\Pictures\Instagram\enc.png
Key for encryption : 22
Encryption done...
Here in the above code first we take the path of image and encryption key as input from the user then we use the file handling concept to handle the binary file and open that file for reading purpose then read binary data of image and store it in image variable. Now we convert that binary form of data into a byte array, then we apply the XOR operation on each value of byte array which changes the data due to which we will be unable to open the image.
It is nothing but a process of converting our encrypted data into a readable form. Here we will again apply the same XOR operation on an encrypted image to decrypt it. But always remember that our encryption key and decryption key must be the same.
Executable Code for Decryption:
Python3
# try block to handle the exceptiontry: # take path of image as a input path = input(r'Enter path of Image : ') # taking decryption key as input key = int(input('Enter Key for encryption of Image : ')) # print path of image file and decryption key that we are using print('The path of file : ', path) print('Note : Encryption key and Decryption key must be same.') print('Key for Decryption : ', key) # open file for reading purpose fin = open(path, 'rb') # storing image data in variable "image" image = fin.read() fin.close() # converting image into byte array to perform decryption easily on numeric data image = bytearray(image) # performing XOR operation on each value of bytearray for index, values in enumerate(image): image[index] = values ^ key # opening file for writing purpose fin = open(path, 'wb') # writing decryption data in image fin.write(image) fin.close() print('Decryption Done...') except Exception: print('Error caught : ', Exception.__name__)
Output:
Enter path of Image : C:\Users\lenovo\Pictures\Instagram\enc.png
Enter Key for Decryption of Image : 22
The path of file : C:\Users\lenovo\Pictures\Instagram\enc.png
Note : Encryption key and Decryption key must be same.
Key for Decryption : 22
Decryption done...
Here in the above Decryption program we use same procedure that we use during Encryption of image.’
Below is the video which depicts the functionality of the above programs using a given image and a key.
arorakashish0911
cryptography
python-utility
Python
cryptography
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
Selecting rows in pandas DataFrame based on conditions
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python Classes and Objects
|
[
{
"code": null,
"e": 24212,
"s": 24184,
"text": "\n05 Aug, 2021"
},
{
"code": null,
"e": 24512,
"s": 24212,
"text": "In this article, we will encrypt/decrypt an image using a simple mathematical logic. It requires two things, data and key and when XOR operation is applied on both the operands i.e data and key, the data gets encrypted but when the same process is done again with same key value data gets decrypted."
},
{
"code": null,
"e": 24680,
"s": 24512,
"text": "It is nothing but a simple process in which we convert our data or information into secrete code to prevent it from unauthorized access and keep it private and secure."
},
{
"code": null,
"e": 25219,
"s": 24680,
"text": "First, we will select an image, and then we will convert that image into a byte array due to which the image data will be totally converted into numeric form, and then we can easily apply the XOR operation on it. Now, whenever we will apply the XOR function on each value of the byte array then the data will be changed due to which we will be unable to access it. But we should remember one thing that here our encryption key plays a very important role without that key we can not decrypt our image. It acts as a password to decrypt it."
},
{
"code": null,
"e": 25275,
"s": 25219,
"text": "Below program depicts the basic approach of encryption:"
},
{
"code": null,
"e": 25283,
"s": 25275,
"text": "Python3"
},
{
"code": "# Assign valuesdata = 1281key = 27 # Display valuesprint('Original Data:', data)print('Key:', key) # Encryptiondata = data ^ keyprint('After Encryption:', data) # Decryptiondata = data ^ keyprint('After Decryption:', data)",
"e": 25506,
"s": 25283,
"text": null
},
{
"code": null,
"e": 25514,
"s": 25506,
"text": "Output:"
},
{
"code": null,
"e": 25588,
"s": 25514,
"text": "Original Data: 1281\nKey: 27\nAfter Encryption: 1306\nAfter Decryption: 1281"
},
{
"code": null,
"e": 25993,
"s": 25588,
"text": "Here in above program, as we can see that how XOR operation works, it takes two variables data and key, whenever we perform XOR operation on them for the first time we get encrypted data. Then when we perform XOR operation between our data and key again, we get same value as our input variable data (decrypted data). Same logic will be applicable on byte array of Image during encryption and decryption."
},
{
"code": null,
"e": 26026,
"s": 25993,
"text": "Executable code for Encryption: "
},
{
"code": null,
"e": 26034,
"s": 26026,
"text": "Python3"
},
{
"code": "# try block to handle exceptiontry: # take path of image as a input path = input(r'Enter path of Image : ') # taking encryption key as input key = int(input('Enter Key for encryption of Image : ')) # print path of image file and encryption key that # we are using print('The path of file : ', path) print('Key for encryption : ', key) # open file for reading purpose fin = open(path, 'rb') # storing image data in variable \"image\" image = fin.read() fin.close() # converting image into byte array to # perform encryption easily on numeric data image = bytearray(image) # performing XOR operation on each value of bytearray for index, values in enumerate(image): image[index] = values ^ key # opening file for writing purpose fin = open(path, 'wb') # writing encrypted data in image fin.write(image) fin.close() print('Encryption Done...') except Exception: print('Error caught : ', Exception.__name__)",
"e": 27055,
"s": 26034,
"text": null
},
{
"code": null,
"e": 27083,
"s": 27055,
"text": " Output: "
},
{
"code": null,
"e": 27294,
"s": 27083,
"text": "Enter path of Image : C:\\Users\\lenovo\\Pictures\\Instagram\\enc.png\nEnter Key for encryption of Image : 22\nThe path of file : C:\\Users\\lenovo\\Pictures\\Instagram\\enc.png\nKey for encryption : 22\nEncryption done..."
},
{
"code": null,
"e": 27750,
"s": 27294,
"text": "Here in the above code first we take the path of image and encryption key as input from the user then we use the file handling concept to handle the binary file and open that file for reading purpose then read binary data of image and store it in image variable. Now we convert that binary form of data into a byte array, then we apply the XOR operation on each value of byte array which changes the data due to which we will be unable to open the image. "
},
{
"code": null,
"e": 27999,
"s": 27750,
"text": "It is nothing but a process of converting our encrypted data into a readable form. Here we will again apply the same XOR operation on an encrypted image to decrypt it. But always remember that our encryption key and decryption key must be the same."
},
{
"code": null,
"e": 28032,
"s": 27999,
"text": "Executable Code for Decryption: "
},
{
"code": null,
"e": 28040,
"s": 28032,
"text": "Python3"
},
{
"code": "# try block to handle the exceptiontry: # take path of image as a input path = input(r'Enter path of Image : ') # taking decryption key as input key = int(input('Enter Key for encryption of Image : ')) # print path of image file and decryption key that we are using print('The path of file : ', path) print('Note : Encryption key and Decryption key must be same.') print('Key for Decryption : ', key) # open file for reading purpose fin = open(path, 'rb') # storing image data in variable \"image\" image = fin.read() fin.close() # converting image into byte array to perform decryption easily on numeric data image = bytearray(image) # performing XOR operation on each value of bytearray for index, values in enumerate(image): image[index] = values ^ key # opening file for writing purpose fin = open(path, 'wb') # writing decryption data in image fin.write(image) fin.close() print('Decryption Done...') except Exception: print('Error caught : ', Exception.__name__)",
"e": 29119,
"s": 28040,
"text": null
},
{
"code": null,
"e": 29127,
"s": 29119,
"text": "Output:"
},
{
"code": null,
"e": 29393,
"s": 29127,
"text": "Enter path of Image : C:\\Users\\lenovo\\Pictures\\Instagram\\enc.png\nEnter Key for Decryption of Image : 22\nThe path of file : C:\\Users\\lenovo\\Pictures\\Instagram\\enc.png\nNote : Encryption key and Decryption key must be same.\nKey for Decryption : 22\nDecryption done..."
},
{
"code": null,
"e": 29494,
"s": 29393,
"text": " Here in the above Decryption program we use same procedure that we use during Encryption of image.’"
},
{
"code": null,
"e": 29600,
"s": 29494,
"text": "Below is the video which depicts the functionality of the above programs using a given image and a key. "
},
{
"code": null,
"e": 29617,
"s": 29600,
"text": "arorakashish0911"
},
{
"code": null,
"e": 29630,
"s": 29617,
"text": "cryptography"
},
{
"code": null,
"e": 29645,
"s": 29630,
"text": "python-utility"
},
{
"code": null,
"e": 29652,
"s": 29645,
"text": "Python"
},
{
"code": null,
"e": 29665,
"s": 29652,
"text": "cryptography"
},
{
"code": null,
"e": 29763,
"s": 29665,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29772,
"s": 29763,
"text": "Comments"
},
{
"code": null,
"e": 29785,
"s": 29772,
"text": "Old Comments"
},
{
"code": null,
"e": 29817,
"s": 29785,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29872,
"s": 29817,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 29928,
"s": 29872,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 29967,
"s": 29928,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 30009,
"s": 29967,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 30051,
"s": 30009,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 30082,
"s": 30051,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 30104,
"s": 30082,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 30133,
"s": 30104,
"text": "Create a directory in Python"
}
] |
Customize your Python class with Magic or Dunder methods - GeeksforGeeks
|
06 Jan, 2022
The magic methods ensure a consistent data model that retains the inherited feature of the built-in class while providing customized class behavior. These methods can enrich the class design and can enhance the readability of the language.
So, in this article, we will see how to make use of the magic methods, how it works, and the available magic methods in Python. Let’s go through each of the sections:
Magic Method Syntax
Common Magic Methods
Magic Methods For Binary Operators
Magic Methods For Unary Operators
A Few Other Magic Methods
A method that is wrapped by two underscores on both sides is called Magic Methods. The motive behind the magic method is to overload Python’s built-in methods and its operators. Here, _syntax prevents the programmers from defining the same name for custom methods. Each magic method serves its purpose. Let’s consider an example that checks for equivalence.
Example:
Python3
class EquivalenceClass(object): def __eq__(self, other): return type(self) == type(other) print(EquivalenceClass() == EquivalenceClass())print(EquivalenceClass() == 'MyClass')
True
False
The __eq__ method takes two arguments – self and the object – to check equality. What is important to understand is, __eq__ method is invoked when the two objects are compared using the == operator. Let’s go through some of the common magic methods in python.
In Python, we have a diverse range of magic methods – each serves its purpose. Here we will comb through, a few of the common magic methods:
Creation
Destruction
Type Conversion
Comparisons
Magic Methods entangled in creation, are performed when a class instance is created. Two of the magic methods associated are __init__ and __new__ methods.
The __init__ method of an object executes right away after the instance creation. Here, the method takes one positional argument – self – and any number of optional or keyword arguments. Let’s look into a simple example:
Example:
Python3
class InitClass(object): def __init__(self): print('Executing the __init__ method.') ic = InitClass()
Executing the __init__ method.
Here, the essential point to note is, you are not calling the __init__ method. Instead, the Python interpreter makes the call upon object instantiation. Let’s consider an example, which takes an optional argument:
Python3
class Square(object): def __init__(self, number = 2): self._number = number def square(self): return self._number**2 s = Square()print('Number: % i' % s._number)print('Square: % i' % s.square())
Number: 2
Square: 4
Here we can notice, the default value (2) is used by the __init__ method in the absence of an optional argument. Let’s check some facts about the __init__ method:
The __init__ method provides initial data to the object, not to create an object.
It only returns None; returning other than None raises TypeError.
It customizes the instantiation of a class.
Next, we will proceed to the __new__ method.
The __new__ method creates and returns the instance of a class. The primary argument of the __new__ method is the class that has to be instantiated, and the rest are the arguments mentioned during the class call. Let’s explore through an example:
Example:
Python3
class Students(object): def __init__(self, idNo, grade): self._idNo = idNo self._grade = grade def __new__(cls, idNo, grade): print("Creating Instance") instance = super(Students, cls).__new__(cls) if 5 <= grade <= 10: return instance else: return None def __str__(self): return '{0}({1})'.format(self.__class__.__name__, self.__dict__) stud1 = Students(1, 7)print(stud1) stud2 = Students(2, 12)print(stud2)
Creating Instance
Students({'_idNo': 1, '_grade': 7})
Creating Instance
None
In most cases, we do not need to define a __new__ method. If we go for a __new__ method implementation, then referencing the superclass is a must. Another essential point to note, the __init__ method of the instantiated class get executes, only if the __new__ method returns an instance of the same class.
The__del__ method is invoked on destroying an instance of a class – either through direct deletion or memory restoration by the garbage collector. Let’s examine the below code:
Python3
class MyClass(object): def __del__(self): print('Destroyed') MyClass()'Immutable String - not assigned to a variable'
Destroyed
What happens when we create an object without assigning them to a variable? The garbage collector will keep the record of objects, which is not referenced to a variable, and delete it when another program statement executes. Here, we created an object of MyClass without assigning it to a variable. Upon execution of the program statement (Immutable String – not assigned to a variable), the garbage collector destroys the MyClass object.
The same happens, when we delete the object directly; But here the deletion happens immediately. Just try the below code.x = MyClass()del x
Type Conversion refers to the conversion of one data type to another; Python provides several magic methods to handle the conversion.
__str__ method
__int__, __float__ and __complex__ methods
__bool__ method
The __str__ method requires one positional argument – self – and it returns a string. It is called when an object is passed to the str() constructor. Let’s consider an example:
Python3
class MyString(object): def __str__(self): return 'My String !' print(str(MyString()))
My String!
Let’s take a look at another situation that invokes the __str__ method. The scenario is the usage of %s in a format string, which in turn invokes the __str__ method.
Python3
class HelloClass(object): def __str__(self): return 'George' print('Hello, % s' % HelloClass())
Hello, George
The __int__ method executes upon calling the int constructor, and it returns an int; It converts the complex objects into primitive int type. Likewise, __float__ and _complex__ methods execute on passing the object to float and complex constructor, respectively.
The __bool__ magic method in python takes one positional argument and returns either true or false. Its purpose is either to check an object is true or false, or to explicitly convert to a Boolean.
Comparisons magic methods are invoked, when we check for equivalence (==, !=) or relations (<, and > =). Each of this operator in python is mapped to its corresponding magic methods.
1. __eq__ methodThe __eq__ method executes when two objects are compared using == operator. It takes two positional arguments – the self, and the object to check the equality.In most cases, if the object on the left side is defined, then its equivalence is checked first. Let’s see through an example:
Python3
class MyEquivalence(object): def __eq__(self, other): print('MyEquivalence:\n' '% r\n % r' %(self, other)) return self is other class YourEquivalence(object): def __eq__(self, other): print('Your Equivalence:\n' '% r\n % r' %(self, other)) return self is other eq1 = MyEquivalence()eq2 = YourEquivalence()# checking for equivalence where eq1 is at the left sideprint(eq1 == eq2)# checking for equivalence where eq2 is at the left sideprint(eq2 == eq1)
MyEquivalence:
<__main__.MyEquivalence object at 0x7fa1d38e16d8>
<__main__.YourEquivalence object at 0x7fa1d1ea37b8>
False
Your Equivalence:
<__main__.YourEquivalence object at 0x7fa1d1ea37b8>
<__main__.MyEquivalence object at 0x7fa1d38e16d8>
False
The ordering rule isn’t applicable if one object is a direct subclass of the other. Let’s examine through an example:
Python3
class MyEquivalence(object): def __eq__(self, other): print('MyEquivalence:\n' '% r\n % r' %(self, other)) return self is other class MySubEquivalence(MyEquivalence): def __eq__(self, other): print('MySubEquivalence:\n' '% r\n % r' %(self, other)) return self is other eqMain = MyEquivalence()eqSub = MySubEquivalence() # eqMain at the right sideprint(eqMain == eqSub) # eqSub at the right sideprint(eqSub == eqMain)
MyEquivalence:
<__main__.MyEquivalence object at 0x7fa1d38e16d8>
<__main__.YourEquivalence object at 0x7fa1d1ea37b8>
False
Your Equivalence:
<__main__.YourEquivalence object at 0x7fa1d1ea37b8>
<__main__.MyEquivalence object at 0x7fa1d38e16d8>
False
2. __ne__ methodThe __ne__ magic method executes, when != operator is used. In most cases, we don’t need to define the __ne__ method; Upon using the != operator, the python interpreter will execute the __eq__ method and reverse the result.
The __lt__ and __le__ methods are invoked when < and <= operators are used, respectively.And, the __gt__ and __ge__ methods are invoked on using > and >= operators, respectively. However, it’s not necessary to use all these 4 methods; usage of __lt__ and __gt__ methods will meet the purpose. Just examine the below points to understand why we don’t require all these methods:1. The __ge__ and __le__ methods can be replaced with the inverse of __lt__ and __gt__ methods, respectively.2. The disjunction of __lt__ and __eq__ methods can be used instead of the __le__ method, and similarly, the __gt__ and __eq__ methods for __ge__ method.
Let’s take a look at the below example. Here, we will compare the object based on its creation time.
Python3
import timeclass ObjectCreationTime(object): def __init__(self, objName): self._created = time.time() self._objName = objName def __lt__(self, other): print('Creation Time:\n' '% s:% f\n % s:% f' %(self._objName, self._created, other._objName, other._created)) return self._created < other._created def __gt__(self, other): print('Creation Time:\n' '% s:% f\n % s:% f' %(self._objName, self._created, other._objName, other._created)) return self._created > other._created obj1 = ObjectCreationTime('obj1')obj2 = ObjectCreationTime('obj2')print(obj1 < obj2)print(obj1 > obj2)
Creation Time:
obj1:1590679265.753279
obj2:1590679265.753280
True
Creation Time:
obj1:1590679265.753279
obj2:1590679265.753280
False
Let’s look into 3 magic methods provided by python for binary operators.
Vanilla Method
Reverse Method
In-Place Method
Consider an expression, x + y; In vanilla method, this expression maps to x.__add__(y).
Let’s consider another expression, y – x. Here, the expression maps to y.__sub__(x). Similarly, a * b maps to a.__mul__(b) and a / b maps to a.__truediv__(b), and so on. One point to note, the method of the left-side object is invoked and passes the right-side object as the parameter. In the case of x + y, the __add__ method of x is invoked and passes y as the parameter. Let’s examine with an example.
Python3
class Count(object): def __init__(self, count): self._count = count def __add__(self, other): total_count = self._count + other._count return Count(total_count) def __str__(self): return 'Count: % i' % self._count c1 = Count(2)c2 = Count(5)c3 = c1 + c2print(c3)
Count: 7
In the Vanilla method, the method of the left-side object is invoked on executing a binary operator. However, if the left side object doesn’t have a method for the binary operator to map, the reverse method is called; it checks for the method of the right-side object to map. Let’s have a look at the below example:
Python3
class Count(object): def __init__(self, count): self._count = count def __add__(self, other): total_count = self._count + other._count return Count(total_count) def __radd__(self, other): if other == 0: return self else: return self.__add__(other) def __str__(self): return 'Count:% i' % self._count c2 = Count(2)c3 = 0 + c2print(c3)
Count:2
Since 0 doesn’t have __add__ method corresponds to it, python interpreter would call __radd__ method – c2.__radd__(0). Similarly, if the __sub__ method is not defined, it would call __rsub __.
Both computation and assignment operations are performed while using the In-place methods. Some of the operators which map to In-place methods are +=, -=, *=, and so on. The In-place method names are preceded by i. For example, the statement x += y would map to x.__iadd__(y), and so on. Let’s go through the below example:
Python3
class inPlace(object): def __init__(self, value): self._value = value def __iadd__(self, other): self._value = self._value + other._value return self._value def __str__(object): return self._value inP1 = inPlace(5)inP2 = inPlace(3)inP1 += inP2print(inP1)
8
__pos__ method
__neg__ method
__invert__ method
The __pos__ method is invoked using the + operator. We have seen that + operator also functions as a binary operator. No worries, python interpreter knows which one to use – unary or binary – based on the situation.The __pos__ method takes a single positional argument – self –, performs the operation, and returns the result. Let’s examine through an example:
Python3
class unaryOp(object): def __init__(self, value): self._value = value def __pos__(self): print('__pos__ magic method') return(+self._value) up = unaryOp(5)print(+up)
__pos__ magic method
5
The __neg__ method is called using the – operator. This operator also acts as a binary operator but based on the situation the interpreter determines which magic method to map. The __neg__ magic method accepts a single positional argument – self –, operates and returns the result. Let’s check the below example:
Python3
class unaryOp(object): def __init__(self, value): self._value = value def __neg__(self): print('__neg__ magic method') return(-self._value) up = unaryOp(5)print(-up)
__neg__ magic method
-5
The last unary operator is the __invert__ method, which is invoked using ~ operator. The statement ~x is equivalent to x.__invert__(). Let’s consider an example:
Python3
class invertClass(object): def __init__(self, value): self._value = value def __invert__(self): return self._value[::-1] def __str__(self): return self._value invrt = invertClass('Hello, George')invertedValue = ~invrtprint(invertedValue)
egroeG, olleH
Let’s discuss about few other magic methods:
__len__ method
__repr__ method
__contains__ method
The len() method invokes the __len__ magic method. It takes one positional argument and returns the length of the object. Let’s see the below code:
Python3
class RectangleClass(object): def __init__(self, area, breadth): self._area = area self._breadth = breadth def __len__(self): return int(self._area / self._breadth) rc = RectangleClass(90, 5)print(len(rc))
18
The __repr__ magic method helps to represent an object in Python interactive terminal. It takes one positional argument – self.Let’s have a look, how an object is represented in Python interactive terminal without overloading the __repr__ method.
Python3
class RectangleClass(object): def __init__(self, area, breadth): self._area = area self._breadth = breadth def __len__(self): return int(self._area / self._breadth) ## use python interactive terminal to check object representation.RectangleClass(90, 5)
<__main__.RectangleClass object at 0x7f9ecaae9710>
We can see, it returns the address of the object in the memory, which is not that useful.
Let’s look into how we can overload the __repr__ method to return a useful object representation.
Python3
class RectangleClass(object): def __init__(self, area, breadth): self._area = area self._breadth = breadth def __len__(self): return int(self._area / self._breadth) def __repr__(self): """object representation""" return 'RectangleClass(area =% d, breadth =% d)' %\ (self._area, self._breadth) RectangleClass(90, 5) RectangleClass(80, 4)
RectangleClass(area=90, breadth=5)
RectangleClass(area=80, breadth=4)
The __contains__ method is called when ‘in’ expression executes. It takes two positional arguments – self and item – and returns true if the item is present or otherwise, it returns false. Let’s examine through an example:
Python3
import datetime class DateClass(object): def __init__(self, startDate, endDate): self.startDate = startDate self.endDate = endDate def __contains__(self, item): """ check whether a date is between the given range and return true or false""" return self.startDate <= item <= self.endDate dtObj = DateClass(datetime.date(2019, 1, 1), datetime.date(2021, 12, 31))result = datetime.date(2020, 6, 4) in dtObjprint("Whether (2020, 6, 4) is within the mentioned date range? ", result) result = datetime.date(2022, 8, 2) in dtObjprint("Whether (2022, 8, 2) is within the mentioned date range? ", result)
Whether (2020, 6, 4) is within the mentioned date range? True
Whether (2022, 8, 2) is within the mentioned date range? False
Hence, we can conclude that magic methods are a consistent data model to customize class behavior and enhance readability without losing their inherited feature. However, before giving a customized feature, make sure that whether customization is necessary or not.
kapoorsagar226
python-basics
python-oop-concepts
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 25759,
"s": 25731,
"text": "\n06 Jan, 2022"
},
{
"code": null,
"e": 25999,
"s": 25759,
"text": "The magic methods ensure a consistent data model that retains the inherited feature of the built-in class while providing customized class behavior. These methods can enrich the class design and can enhance the readability of the language."
},
{
"code": null,
"e": 26166,
"s": 25999,
"text": "So, in this article, we will see how to make use of the magic methods, how it works, and the available magic methods in Python. Let’s go through each of the sections:"
},
{
"code": null,
"e": 26186,
"s": 26166,
"text": "Magic Method Syntax"
},
{
"code": null,
"e": 26207,
"s": 26186,
"text": "Common Magic Methods"
},
{
"code": null,
"e": 26242,
"s": 26207,
"text": "Magic Methods For Binary Operators"
},
{
"code": null,
"e": 26276,
"s": 26242,
"text": "Magic Methods For Unary Operators"
},
{
"code": null,
"e": 26302,
"s": 26276,
"text": "A Few Other Magic Methods"
},
{
"code": null,
"e": 26660,
"s": 26302,
"text": "A method that is wrapped by two underscores on both sides is called Magic Methods. The motive behind the magic method is to overload Python’s built-in methods and its operators. Here, _syntax prevents the programmers from defining the same name for custom methods. Each magic method serves its purpose. Let’s consider an example that checks for equivalence."
},
{
"code": null,
"e": 26669,
"s": 26660,
"text": "Example:"
},
{
"code": null,
"e": 26677,
"s": 26669,
"text": "Python3"
},
{
"code": "class EquivalenceClass(object): def __eq__(self, other): return type(self) == type(other) print(EquivalenceClass() == EquivalenceClass())print(EquivalenceClass() == 'MyClass')",
"e": 26864,
"s": 26677,
"text": null
},
{
"code": null,
"e": 26876,
"s": 26864,
"text": "True\nFalse\n"
},
{
"code": null,
"e": 27136,
"s": 26876,
"text": "The __eq__ method takes two arguments – self and the object – to check equality. What is important to understand is, __eq__ method is invoked when the two objects are compared using the == operator. Let’s go through some of the common magic methods in python."
},
{
"code": null,
"e": 27277,
"s": 27136,
"text": "In Python, we have a diverse range of magic methods – each serves its purpose. Here we will comb through, a few of the common magic methods:"
},
{
"code": null,
"e": 27286,
"s": 27277,
"text": "Creation"
},
{
"code": null,
"e": 27298,
"s": 27286,
"text": "Destruction"
},
{
"code": null,
"e": 27314,
"s": 27298,
"text": "Type Conversion"
},
{
"code": null,
"e": 27326,
"s": 27314,
"text": "Comparisons"
},
{
"code": null,
"e": 27481,
"s": 27326,
"text": "Magic Methods entangled in creation, are performed when a class instance is created. Two of the magic methods associated are __init__ and __new__ methods."
},
{
"code": null,
"e": 27702,
"s": 27481,
"text": "The __init__ method of an object executes right away after the instance creation. Here, the method takes one positional argument – self – and any number of optional or keyword arguments. Let’s look into a simple example:"
},
{
"code": null,
"e": 27711,
"s": 27702,
"text": "Example:"
},
{
"code": null,
"e": 27719,
"s": 27711,
"text": "Python3"
},
{
"code": "class InitClass(object): def __init__(self): print('Executing the __init__ method.') ic = InitClass()",
"e": 27832,
"s": 27719,
"text": null
},
{
"code": null,
"e": 27863,
"s": 27832,
"text": "Executing the __init__ method."
},
{
"code": null,
"e": 28077,
"s": 27863,
"text": "Here, the essential point to note is, you are not calling the __init__ method. Instead, the Python interpreter makes the call upon object instantiation. Let’s consider an example, which takes an optional argument:"
},
{
"code": null,
"e": 28085,
"s": 28077,
"text": "Python3"
},
{
"code": "class Square(object): def __init__(self, number = 2): self._number = number def square(self): return self._number**2 s = Square()print('Number: % i' % s._number)print('Square: % i' % s.square())",
"e": 28303,
"s": 28085,
"text": null
},
{
"code": null,
"e": 28324,
"s": 28303,
"text": "Number: 2\nSquare: 4\n"
},
{
"code": null,
"e": 28487,
"s": 28324,
"text": "Here we can notice, the default value (2) is used by the __init__ method in the absence of an optional argument. Let’s check some facts about the __init__ method:"
},
{
"code": null,
"e": 28569,
"s": 28487,
"text": "The __init__ method provides initial data to the object, not to create an object."
},
{
"code": null,
"e": 28635,
"s": 28569,
"text": "It only returns None; returning other than None raises TypeError."
},
{
"code": null,
"e": 28679,
"s": 28635,
"text": "It customizes the instantiation of a class."
},
{
"code": null,
"e": 28725,
"s": 28679,
"text": "Next, we will proceed to the __new__ method. "
},
{
"code": null,
"e": 28972,
"s": 28725,
"text": "The __new__ method creates and returns the instance of a class. The primary argument of the __new__ method is the class that has to be instantiated, and the rest are the arguments mentioned during the class call. Let’s explore through an example:"
},
{
"code": null,
"e": 28981,
"s": 28972,
"text": "Example:"
},
{
"code": null,
"e": 28989,
"s": 28981,
"text": "Python3"
},
{
"code": "class Students(object): def __init__(self, idNo, grade): self._idNo = idNo self._grade = grade def __new__(cls, idNo, grade): print(\"Creating Instance\") instance = super(Students, cls).__new__(cls) if 5 <= grade <= 10: return instance else: return None def __str__(self): return '{0}({1})'.format(self.__class__.__name__, self.__dict__) stud1 = Students(1, 7)print(stud1) stud2 = Students(2, 12)print(stud2)",
"e": 29485,
"s": 28989,
"text": null
},
{
"code": null,
"e": 29565,
"s": 29485,
"text": " \nCreating Instance\nStudents({'_idNo': 1, '_grade': 7})\nCreating Instance\nNone\n"
},
{
"code": null,
"e": 29872,
"s": 29565,
"text": "In most cases, we do not need to define a __new__ method. If we go for a __new__ method implementation, then referencing the superclass is a must. Another essential point to note, the __init__ method of the instantiated class get executes, only if the __new__ method returns an instance of the same class."
},
{
"code": null,
"e": 30049,
"s": 29872,
"text": "The__del__ method is invoked on destroying an instance of a class – either through direct deletion or memory restoration by the garbage collector. Let’s examine the below code:"
},
{
"code": null,
"e": 30057,
"s": 30049,
"text": "Python3"
},
{
"code": "class MyClass(object): def __del__(self): print('Destroyed') MyClass()'Immutable String - not assigned to a variable'",
"e": 30186,
"s": 30057,
"text": null
},
{
"code": null,
"e": 30196,
"s": 30186,
"text": "Destroyed"
},
{
"code": null,
"e": 30635,
"s": 30196,
"text": "What happens when we create an object without assigning them to a variable? The garbage collector will keep the record of objects, which is not referenced to a variable, and delete it when another program statement executes. Here, we created an object of MyClass without assigning it to a variable. Upon execution of the program statement (Immutable String – not assigned to a variable), the garbage collector destroys the MyClass object."
},
{
"code": null,
"e": 30775,
"s": 30635,
"text": "The same happens, when we delete the object directly; But here the deletion happens immediately. Just try the below code.x = MyClass()del x"
},
{
"code": null,
"e": 30909,
"s": 30775,
"text": "Type Conversion refers to the conversion of one data type to another; Python provides several magic methods to handle the conversion."
},
{
"code": null,
"e": 30924,
"s": 30909,
"text": "__str__ method"
},
{
"code": null,
"e": 30967,
"s": 30924,
"text": "__int__, __float__ and __complex__ methods"
},
{
"code": null,
"e": 30983,
"s": 30967,
"text": "__bool__ method"
},
{
"code": null,
"e": 31160,
"s": 30983,
"text": "The __str__ method requires one positional argument – self – and it returns a string. It is called when an object is passed to the str() constructor. Let’s consider an example:"
},
{
"code": null,
"e": 31168,
"s": 31160,
"text": "Python3"
},
{
"code": "class MyString(object): def __str__(self): return 'My String !' print(str(MyString()))",
"e": 31266,
"s": 31168,
"text": null
},
{
"code": null,
"e": 31277,
"s": 31266,
"text": "My String!"
},
{
"code": null,
"e": 31443,
"s": 31277,
"text": "Let’s take a look at another situation that invokes the __str__ method. The scenario is the usage of %s in a format string, which in turn invokes the __str__ method."
},
{
"code": null,
"e": 31451,
"s": 31443,
"text": "Python3"
},
{
"code": "class HelloClass(object): def __str__(self): return 'George' print('Hello, % s' % HelloClass())",
"e": 31558,
"s": 31451,
"text": null
},
{
"code": null,
"e": 31572,
"s": 31558,
"text": "Hello, George"
},
{
"code": null,
"e": 31835,
"s": 31572,
"text": "The __int__ method executes upon calling the int constructor, and it returns an int; It converts the complex objects into primitive int type. Likewise, __float__ and _complex__ methods execute on passing the object to float and complex constructor, respectively."
},
{
"code": null,
"e": 32033,
"s": 31835,
"text": "The __bool__ magic method in python takes one positional argument and returns either true or false. Its purpose is either to check an object is true or false, or to explicitly convert to a Boolean."
},
{
"code": null,
"e": 32217,
"s": 32033,
"text": "Comparisons magic methods are invoked, when we check for equivalence (==, !=) or relations (<, and > =). Each of this operator in python is mapped to its corresponding magic methods. "
},
{
"code": null,
"e": 32519,
"s": 32217,
"text": "1. __eq__ methodThe __eq__ method executes when two objects are compared using == operator. It takes two positional arguments – the self, and the object to check the equality.In most cases, if the object on the left side is defined, then its equivalence is checked first. Let’s see through an example:"
},
{
"code": null,
"e": 32527,
"s": 32519,
"text": "Python3"
},
{
"code": "class MyEquivalence(object): def __eq__(self, other): print('MyEquivalence:\\n' '% r\\n % r' %(self, other)) return self is other class YourEquivalence(object): def __eq__(self, other): print('Your Equivalence:\\n' '% r\\n % r' %(self, other)) return self is other eq1 = MyEquivalence()eq2 = YourEquivalence()# checking for equivalence where eq1 is at the left sideprint(eq1 == eq2)# checking for equivalence where eq2 is at the left sideprint(eq2 == eq1)",
"e": 33041,
"s": 32527,
"text": null
},
{
"code": null,
"e": 33291,
"s": 33041,
"text": "MyEquivalence:\n<__main__.MyEquivalence object at 0x7fa1d38e16d8>\n<__main__.YourEquivalence object at 0x7fa1d1ea37b8>\nFalse\nYour Equivalence:\n<__main__.YourEquivalence object at 0x7fa1d1ea37b8>\n<__main__.MyEquivalence object at 0x7fa1d38e16d8>\nFalse\n"
},
{
"code": null,
"e": 33409,
"s": 33291,
"text": "The ordering rule isn’t applicable if one object is a direct subclass of the other. Let’s examine through an example:"
},
{
"code": null,
"e": 33417,
"s": 33409,
"text": "Python3"
},
{
"code": "class MyEquivalence(object): def __eq__(self, other): print('MyEquivalence:\\n' '% r\\n % r' %(self, other)) return self is other class MySubEquivalence(MyEquivalence): def __eq__(self, other): print('MySubEquivalence:\\n' '% r\\n % r' %(self, other)) return self is other eqMain = MyEquivalence()eqSub = MySubEquivalence() # eqMain at the right sideprint(eqMain == eqSub) # eqSub at the right sideprint(eqSub == eqMain)",
"e": 33898,
"s": 33417,
"text": null
},
{
"code": null,
"e": 34148,
"s": 33898,
"text": "MyEquivalence:\n<__main__.MyEquivalence object at 0x7fa1d38e16d8>\n<__main__.YourEquivalence object at 0x7fa1d1ea37b8>\nFalse\nYour Equivalence:\n<__main__.YourEquivalence object at 0x7fa1d1ea37b8>\n<__main__.MyEquivalence object at 0x7fa1d38e16d8>\nFalse\n"
},
{
"code": null,
"e": 34388,
"s": 34148,
"text": "2. __ne__ methodThe __ne__ magic method executes, when != operator is used. In most cases, we don’t need to define the __ne__ method; Upon using the != operator, the python interpreter will execute the __eq__ method and reverse the result."
},
{
"code": null,
"e": 35030,
"s": 34388,
"text": "The __lt__ and __le__ methods are invoked when < and <= operators are used, respectively.And, the __gt__ and __ge__ methods are invoked on using > and >= operators, respectively. However, it’s not necessary to use all these 4 methods; usage of __lt__ and __gt__ methods will meet the purpose. Just examine the below points to understand why we don’t require all these methods:1. The __ge__ and __le__ methods can be replaced with the inverse of __lt__ and __gt__ methods, respectively.2. The disjunction of __lt__ and __eq__ methods can be used instead of the __le__ method, and similarly, the __gt__ and __eq__ methods for __ge__ method."
},
{
"code": null,
"e": 35131,
"s": 35030,
"text": "Let’s take a look at the below example. Here, we will compare the object based on its creation time."
},
{
"code": null,
"e": 35139,
"s": 35131,
"text": "Python3"
},
{
"code": "import timeclass ObjectCreationTime(object): def __init__(self, objName): self._created = time.time() self._objName = objName def __lt__(self, other): print('Creation Time:\\n' '% s:% f\\n % s:% f' %(self._objName, self._created, other._objName, other._created)) return self._created < other._created def __gt__(self, other): print('Creation Time:\\n' '% s:% f\\n % s:% f' %(self._objName, self._created, other._objName, other._created)) return self._created > other._created obj1 = ObjectCreationTime('obj1')obj2 = ObjectCreationTime('obj2')print(obj1 < obj2)print(obj1 > obj2)",
"e": 35860,
"s": 35139,
"text": null
},
{
"code": null,
"e": 35994,
"s": 35860,
"text": "Creation Time:\nobj1:1590679265.753279\nobj2:1590679265.753280\nTrue\nCreation Time:\nobj1:1590679265.753279\nobj2:1590679265.753280\nFalse\n"
},
{
"code": null,
"e": 36067,
"s": 35994,
"text": "Let’s look into 3 magic methods provided by python for binary operators."
},
{
"code": null,
"e": 36082,
"s": 36067,
"text": "Vanilla Method"
},
{
"code": null,
"e": 36097,
"s": 36082,
"text": "Reverse Method"
},
{
"code": null,
"e": 36113,
"s": 36097,
"text": "In-Place Method"
},
{
"code": null,
"e": 36202,
"s": 36113,
"text": "Consider an expression, x + y; In vanilla method, this expression maps to x.__add__(y). "
},
{
"code": null,
"e": 36609,
"s": 36202,
"text": "Let’s consider another expression, y – x. Here, the expression maps to y.__sub__(x). Similarly, a * b maps to a.__mul__(b) and a / b maps to a.__truediv__(b), and so on. One point to note, the method of the left-side object is invoked and passes the right-side object as the parameter. In the case of x + y, the __add__ method of x is invoked and passes y as the parameter. Let’s examine with an example."
},
{
"code": null,
"e": 36617,
"s": 36609,
"text": "Python3"
},
{
"code": "class Count(object): def __init__(self, count): self._count = count def __add__(self, other): total_count = self._count + other._count return Count(total_count) def __str__(self): return 'Count: % i' % self._count c1 = Count(2)c2 = Count(5)c3 = c1 + c2print(c3)",
"e": 36921,
"s": 36617,
"text": null
},
{
"code": null,
"e": 36930,
"s": 36921,
"text": "Count: 7"
},
{
"code": null,
"e": 37246,
"s": 36930,
"text": "In the Vanilla method, the method of the left-side object is invoked on executing a binary operator. However, if the left side object doesn’t have a method for the binary operator to map, the reverse method is called; it checks for the method of the right-side object to map. Let’s have a look at the below example:"
},
{
"code": null,
"e": 37254,
"s": 37246,
"text": "Python3"
},
{
"code": "class Count(object): def __init__(self, count): self._count = count def __add__(self, other): total_count = self._count + other._count return Count(total_count) def __radd__(self, other): if other == 0: return self else: return self.__add__(other) def __str__(self): return 'Count:% i' % self._count c2 = Count(2)c3 = 0 + c2print(c3)",
"e": 37675,
"s": 37254,
"text": null
},
{
"code": null,
"e": 37683,
"s": 37675,
"text": "Count:2"
},
{
"code": null,
"e": 37877,
"s": 37683,
"text": "Since 0 doesn’t have __add__ method corresponds to it, python interpreter would call __radd__ method – c2.__radd__(0). Similarly, if the __sub__ method is not defined, it would call __rsub __."
},
{
"code": null,
"e": 38201,
"s": 37877,
"text": "Both computation and assignment operations are performed while using the In-place methods. Some of the operators which map to In-place methods are +=, -=, *=, and so on. The In-place method names are preceded by i. For example, the statement x += y would map to x.__iadd__(y), and so on. Let’s go through the below example:"
},
{
"code": null,
"e": 38209,
"s": 38201,
"text": "Python3"
},
{
"code": "class inPlace(object): def __init__(self, value): self._value = value def __iadd__(self, other): self._value = self._value + other._value return self._value def __str__(object): return self._value inP1 = inPlace(5)inP2 = inPlace(3)inP1 += inP2print(inP1)",
"e": 38502,
"s": 38209,
"text": null
},
{
"code": null,
"e": 38504,
"s": 38502,
"text": "8"
},
{
"code": null,
"e": 38519,
"s": 38504,
"text": "__pos__ method"
},
{
"code": null,
"e": 38534,
"s": 38519,
"text": "__neg__ method"
},
{
"code": null,
"e": 38552,
"s": 38534,
"text": "__invert__ method"
},
{
"code": null,
"e": 38913,
"s": 38552,
"text": "The __pos__ method is invoked using the + operator. We have seen that + operator also functions as a binary operator. No worries, python interpreter knows which one to use – unary or binary – based on the situation.The __pos__ method takes a single positional argument – self –, performs the operation, and returns the result. Let’s examine through an example:"
},
{
"code": null,
"e": 38921,
"s": 38913,
"text": "Python3"
},
{
"code": "class unaryOp(object): def __init__(self, value): self._value = value def __pos__(self): print('__pos__ magic method') return(+self._value) up = unaryOp(5)print(+up)",
"e": 39118,
"s": 38921,
"text": null
},
{
"code": null,
"e": 39142,
"s": 39118,
"text": "__pos__ magic method\n5\n"
},
{
"code": null,
"e": 39455,
"s": 39142,
"text": "The __neg__ method is called using the – operator. This operator also acts as a binary operator but based on the situation the interpreter determines which magic method to map. The __neg__ magic method accepts a single positional argument – self –, operates and returns the result. Let’s check the below example:"
},
{
"code": null,
"e": 39463,
"s": 39455,
"text": "Python3"
},
{
"code": "class unaryOp(object): def __init__(self, value): self._value = value def __neg__(self): print('__neg__ magic method') return(-self._value) up = unaryOp(5)print(-up)",
"e": 39657,
"s": 39463,
"text": null
},
{
"code": null,
"e": 39682,
"s": 39657,
"text": "__neg__ magic method\n-5\n"
},
{
"code": null,
"e": 39846,
"s": 39682,
"text": "The last unary operator is the __invert__ method, which is invoked using ~ operator. The statement ~x is equivalent to x.__invert__(). Let’s consider an example:"
},
{
"code": null,
"e": 39854,
"s": 39846,
"text": "Python3"
},
{
"code": "class invertClass(object): def __init__(self, value): self._value = value def __invert__(self): return self._value[::-1] def __str__(self): return self._value invrt = invertClass('Hello, George')invertedValue = ~invrtprint(invertedValue)",
"e": 40123,
"s": 39854,
"text": null
},
{
"code": null,
"e": 40137,
"s": 40123,
"text": "egroeG, olleH"
},
{
"code": null,
"e": 40182,
"s": 40137,
"text": "Let’s discuss about few other magic methods:"
},
{
"code": null,
"e": 40197,
"s": 40182,
"text": "__len__ method"
},
{
"code": null,
"e": 40213,
"s": 40197,
"text": "__repr__ method"
},
{
"code": null,
"e": 40233,
"s": 40213,
"text": "__contains__ method"
},
{
"code": null,
"e": 40381,
"s": 40233,
"text": "The len() method invokes the __len__ magic method. It takes one positional argument and returns the length of the object. Let’s see the below code:"
},
{
"code": null,
"e": 40389,
"s": 40381,
"text": "Python3"
},
{
"code": "class RectangleClass(object): def __init__(self, area, breadth): self._area = area self._breadth = breadth def __len__(self): return int(self._area / self._breadth) rc = RectangleClass(90, 5)print(len(rc))",
"e": 40633,
"s": 40389,
"text": null
},
{
"code": null,
"e": 40636,
"s": 40633,
"text": "18"
},
{
"code": null,
"e": 40883,
"s": 40636,
"text": "The __repr__ magic method helps to represent an object in Python interactive terminal. It takes one positional argument – self.Let’s have a look, how an object is represented in Python interactive terminal without overloading the __repr__ method."
},
{
"code": null,
"e": 40891,
"s": 40883,
"text": "Python3"
},
{
"code": "class RectangleClass(object): def __init__(self, area, breadth): self._area = area self._breadth = breadth def __len__(self): return int(self._area / self._breadth) ## use python interactive terminal to check object representation.RectangleClass(90, 5)",
"e": 41182,
"s": 40891,
"text": null
},
{
"code": null,
"e": 41233,
"s": 41182,
"text": "<__main__.RectangleClass object at 0x7f9ecaae9710>"
},
{
"code": null,
"e": 41323,
"s": 41233,
"text": "We can see, it returns the address of the object in the memory, which is not that useful."
},
{
"code": null,
"e": 41421,
"s": 41323,
"text": "Let’s look into how we can overload the __repr__ method to return a useful object representation."
},
{
"code": null,
"e": 41429,
"s": 41421,
"text": "Python3"
},
{
"code": "class RectangleClass(object): def __init__(self, area, breadth): self._area = area self._breadth = breadth def __len__(self): return int(self._area / self._breadth) def __repr__(self): \"\"\"object representation\"\"\" return 'RectangleClass(area =% d, breadth =% d)' %\\ (self._area, self._breadth) RectangleClass(90, 5) RectangleClass(80, 4) ",
"e": 41851,
"s": 41429,
"text": null
},
{
"code": null,
"e": 41922,
"s": 41851,
"text": "RectangleClass(area=90, breadth=5)\nRectangleClass(area=80, breadth=4)\n"
},
{
"code": null,
"e": 42145,
"s": 41922,
"text": "The __contains__ method is called when ‘in’ expression executes. It takes two positional arguments – self and item – and returns true if the item is present or otherwise, it returns false. Let’s examine through an example:"
},
{
"code": null,
"e": 42153,
"s": 42145,
"text": "Python3"
},
{
"code": "import datetime class DateClass(object): def __init__(self, startDate, endDate): self.startDate = startDate self.endDate = endDate def __contains__(self, item): \"\"\" check whether a date is between the given range and return true or false\"\"\" return self.startDate <= item <= self.endDate dtObj = DateClass(datetime.date(2019, 1, 1), datetime.date(2021, 12, 31))result = datetime.date(2020, 6, 4) in dtObjprint(\"Whether (2020, 6, 4) is within the mentioned date range? \", result) result = datetime.date(2022, 8, 2) in dtObjprint(\"Whether (2022, 8, 2) is within the mentioned date range? \", result)",
"e": 42795,
"s": 42153,
"text": null
},
{
"code": null,
"e": 42923,
"s": 42795,
"text": "Whether (2020, 6, 4) is within the mentioned date range? True\nWhether (2022, 8, 2) is within the mentioned date range? False\n"
},
{
"code": null,
"e": 43188,
"s": 42923,
"text": "Hence, we can conclude that magic methods are a consistent data model to customize class behavior and enhance readability without losing their inherited feature. However, before giving a customized feature, make sure that whether customization is necessary or not."
},
{
"code": null,
"e": 43203,
"s": 43188,
"text": "kapoorsagar226"
},
{
"code": null,
"e": 43217,
"s": 43203,
"text": "python-basics"
},
{
"code": null,
"e": 43237,
"s": 43217,
"text": "python-oop-concepts"
},
{
"code": null,
"e": 43244,
"s": 43237,
"text": "Python"
},
{
"code": null,
"e": 43342,
"s": 43244,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 43360,
"s": 43342,
"text": "Python Dictionary"
},
{
"code": null,
"e": 43395,
"s": 43360,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 43427,
"s": 43395,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 43449,
"s": 43427,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 43491,
"s": 43449,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 43521,
"s": 43491,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 43547,
"s": 43521,
"text": "Python String | replace()"
},
{
"code": null,
"e": 43591,
"s": 43547,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 43620,
"s": 43591,
"text": "*args and **kwargs in Python"
}
] |
The Power of Quality Assurance — Designing Robust QA Processes for SQL Data Analysis Pipelines | by Michael Gendy | Towards Data Science
|
“A milligram of prevention is worth a kilogram of cure” — John Robert Colombo
Mistakes happen. Bugs can appear seemingly from nowhere. Data sources can falter at a moment’s notice invalidating your entire analysis pipeline. As an analytics team, ultimately it’s your responsibility to solve these problems and ensure your reports, deliverables and insights are as accurate as possible. Designing a robust quality assurance (QA) process is paramount to solidifying confidence in your outputs as a team.
This article will outline some key steps to designing a robust QA process to save time, money and resources; this will ensure that you’re making the most positive impact possible through your analysis.
There are so many reasons why a robust QA process is invaluable to your business and team. Here’s a handful of the most meaningful outcomes of a complete QA process:
Confirms business decisions are made using the best possible insights
Increases output efficiency and reduces duplication of work
Improves reactivity to data issues
Maintains stakeholder trust and client relations
Increases analyst confidence in outputs, allowing for a faster way of working
Business decisions based on false data are costly for all parties involved. It can mean work is repeated, performance is reduced, money is lost or crucially, confidence in your outputs is hit. Confidence in the insights and recommendations you and your team are providing is crucial in gaining the trust of your stakeholders, and making a larger impact with your work. You don’t want one small mistake to affect future performance, both for you and your team. Most larger companies can devote entire teams to the QA process, however in small to medium sized companies that do not have access to such resources, it becomes the responsibility of the analytics team as a collective to ensure that proper infrastructure is built to reduce any unwanted errors in deliverables. Robust QA processes provide tangible, reliable value in the prevention of any such problems leading to efficient and effective data-driven decision making.
QA is more than just checking over your code. Pipelines with many moving parts, changing volumes and third party data sources can be difficult to manage. Forming a well-rounded and robust QA process that considers any immediate challenges, and accounts for future error scenarios, requires tackling this issue from many angles:
SQL readability and translationUnit and integration testingMonitoring data flows at all stages of the pipelineReducing dependenciesPeer review and optimisation
SQL readability and translation
Unit and integration testing
Monitoring data flows at all stages of the pipeline
Reducing dependencies
Peer review and optimisation
This article will outline the reason why each of these stages is so important, suggest best-practices to keep your performance high, and ensure your time is spent on providing as much value as possible.
Often our absolute code efficiency is at the forefront of our coding decision making. Manipulating large volumes of data in complicated queries does require diligent thought to save time and money on processing resource. However, frequently there is the opportunity to trade-off absolute performance with readability to improve how queries are evaluated.
Using a simple SQL example, let’s say we want to list the names of records I own in my record collection that are vintage. We could solve this using the following query:
SELECT t_my.record_name FROM my_records t_myINNER JOIN vintage_records t_vinON t_my.record_id = t_vin.record_id;
If I owned a very large, entirely impossible collection of billions of records, this is likely close to the best solution, as opposed to using a more computationally heavy sub-query. Yet if I had to hand this over to a friend to run the same query, it doesn’t have that understand-at-a-glance-readability that we might achieve through other means. Consider the questions the new analyst needs to figure out before running the query:
What is the aim of the query?
What are the contents of vintage_records?
Has the INNER JOIN caused any duplicates?
Is record_id a primary key?
In these cases, adding milliseconds to the run time of this query in exchange for some more transferable, readable code is an extremely worthwhile trade-off. By rewriting using a sub query and adding a simple comment, we achieve a much clearer result with very similar performance:
--Returns ALL record names from my collection that are vintageWITH vintage_record_ids AS (SELECT DISTINCT record_id FROM vintage_record)SELECT record_name FROM my_recordsWHERE record_id IN vintage_record_ids;
Same result, similar performance and much improved readability. Notice:
Clear purpose allowing for quick interpretationUse of the WITH statement allowing readability from the top-downClear name to the sub-query table outlining it’s contentsEliminating the need for a join simplifying the code
Clear purpose allowing for quick interpretation
Use of the WITH statement allowing readability from the top-down
Clear name to the sub-query table outlining it’s contents
Eliminating the need for a join simplifying the code
Good readability best-practices include commenting out the purpose of the query, utilising WITH statements (CTEs), capitalising functions, keeping queries short and having clear processing logic. Thanks to our changes, we now have clarity on many of the query’s nuances. We now know it’s purpose and that we’re returning all results from my record collection (not just unique results). We can interpret the code faster thanks to the sub-query, and don’t have to worry about any faulty JOIN logic. Slower but cleaner code is definitely the winner here.
While it may seem like it saves a small amount of time on a simple query like this, the actual value it derives will continue to pay off every time this is run. When your SQL infrastructure involves complex, multiple thousand line scripts all integrated with one another, the pay-off for writing your code in a clear manner increases exponentially. Not to mention the often overlooked factor in smaller teams — what happens when the primary analyst for these scripts is on holiday or off sick? Can another analyst pick up the script effectively? An analyst contributes greatly to making business operations more efficient, and so it’s crucial to apply this to their own processes and practices too, in the form of producing readable and transferable code.
Testing and retesting any production script is the biggest non-negotiable of all. We must both test code in isolated segments (unit testing), and test how well these isolated segments work together (integration testing). For example, testing that a temporary table is created correctly, then ensuring that any queries that use the temporary table interact with it correctly.
SQL is deceivingly simple, and learning to anticipate duplication and becoming accustomed to diagnosing faulty joins can bring a lot more peace to your day-to-day analysis. Commenting out code to evaluate if each query has produced the intended result (unit testing), and making sure they won’t break any of your other dependent queries (integration testing) is a skill worth developing in itself. At a minimum, you should include unit testing queries and comments which answer the following questions:
Are my counts before and after JOINs expected?
Have any of my primary keys been duplicated?
Are my JOIN fields in the same format?
Are my CASE WHEN statements working as intended?
Does the result make logical sense?
The next step is ensuring these individual queries work in harmony with any other queries in your script. Checking that one section of code is working correctly but failing to test how this query fits into your larger data pipeline can create unnecessary and easily avoided vulnerabilities.
Take the time and document your thought process — this will pay off greatly by preventing errors and ensuring bugs are identified and solved swiftly. Give as much detail as you can in a clear, succinct manner. If the result is correct, but counter intuitive — explain it in a comment! The goal here is to make your outputs reproducible and allow others to easily verify the result. Outlining the above during SQL script writing will soon become second nature, and you’ll develop your own intuition for bugs that arise repeatedly. In addition to building more confidence in our work, we also give our peers the ability to pick up the script, understand the purpose and evaluate its efficacy with minimal hassle.
It’s genuinely quite incredible how many seemingly insignificant changes to your data ingestion can affect your data pipelines. Here’s a handful of examples:
NULLS appearing due to trafficking issues
Formats of dates, internal IDs, country codes changing between suppliers
Duplicates appearing due to API glitches
Manually input data being incorrectly filled in
Any of these issues can affect multiple queries in seemly obscure ways, from causing JOINS to fail, breaking NOT IN statements and messing with your WHERE clauses. Without clear visibility on your data at every processing stage, often these issues can go unnoticed causing a headache down the line. Odds are, the longer the issue has been present, the bigger the consequences — catching any of these issues early can be the key to smooth operation.
Clear data visualisation is the key to solving this. An easy way to do this is by creating a pipeline monitoring table, inserting counts of key metrics at every stage of the data processing, and visualising the outputs in a BI tool:
INSERT INTO qa_pipeline(SELECT table_name,CURRENT_TIMESTAMP() as run_timestamp,count(*) as row_count ,COUNT(primary_key) as primary_key_count,COUNT(distinct_primary_key) as distinct_primary_key_count ,COUNT(*) FILTER (WHERE important_field > '') as important_field_population,SUM(important_kpi) as important_kpi_sumFROM raw_table)
This is a very useful, general format of how we want to track our data. Creating visualisations of a table such as qa_pipeline, and tracking important values such as row counts, field population, KPI sums and primary key interactions between queries can enable at-a-glance debugging. For example, in your raw tables, your primary key will always be unique. In your cleaning script where you create a new table and join in extra information, if we now see the count of primary keys increase, we know there’s some duplication caused by the cleaning script. Inversely, if we see the distinct primary key count decrease, we know some have been filtered out:
The visualisation above demonstrates the power of these qa_pipeline tables. It’s immediately obvious that every metric doubles in the final table, indicating that there’s faulty logic in the script to produce the final_output which is causing duplication. A number of issues can be discovered by simply getting a pair of eyes on the true outputs of each script or query. If we saw a significant decrease in important_kpi_sum, this would suggest that there’s an error when using important_kpi or a mistake in the aggregation logic — a clear sign that the code should be reviewed. While manually going through entire outputs regularly can demand too much resource for many analytics teams, a quick inspection of these summary visualisations every morning will lead to more proactive solutions to diagnose incorrect SQL scripts.
Another use case of the same table is making sure your data is being ingested correctly — the quality of your raw data will mirror the quality of your outputs. Viewing your ingestion table metrics using the qa_pipeline table visualisations allows for easy monitoring that your data is coming in the intended formats. Anomalous results such as low row counts, missing days and high numbers of missing fields can be identified easily and quickly:
At a quick glance, we can see there are some ingestion issues for our raw_table. On the 3rd of January when the script was run, we saw three times the amount of rows as we see distinct primary keys, indicating that the data may have been ingested three times. In addition, on the 5th of January, we can see our important_field was not completely populated, hinting at some tracking issues. After only a few seconds of looking at the visualisation, we can clearly evaluate the quality of the data and highlight any issues, further improving our ability to react to problems and resolve them efficiently.
Use your creativity in how you display these counts to suit your business use case. Your intuition is a valuable resource here — learn to anticipate how your code will affect your data and compare this consistently to the visualisations provided by these qa_pipeline tables. Setting up these INSERT INTO queries at ingestion, during data cleaning and after the deliverables have been produced gives you end-to-end clarity on how your scripts are performing, saving valuable resources on debugging and preventing any errors.
A competent analyst can work through any problem. In theory, all code should be running perfectly if the quality of the data remains the same. However, when managing the ingestion of multiple data streams from different sources, this data quality is never guaranteed. Possibly the simplest way to maintain good quality data is by taking control of it yourself, allowing full autonomy and greater reactivity when problems arise. Next time you’re ingesting third party data, consider the following:
If we found an error, how quickly could it be solved by the source?Could I gain autonomy of this data by producing it in-house?Could any manual processes be automated to reduce human error?How can we work with the sources to reduce our reliance on them?
If we found an error, how quickly could it be solved by the source?
Could I gain autonomy of this data by producing it in-house?
Could any manual processes be automated to reduce human error?
How can we work with the sources to reduce our reliance on them?
Consider this scenario:
“An international third party is supplying time series data in the form of a daily excel report. Due to daylight savings in their region, the timestamps they have provided are all an hour out, which means you’re missing an hour of data in the report provided. They’re in a completely different timezone, won’t be able to rectify the issue until the morning, and the clients demanding a crucial report be delivered by the end of the day.”
Not a fun spot to be in. You could make a strong case that the third party is not even complicit, because the process is inherently flawed for many reasons. However, if we had autonomy over the data they provided, by querying their API directly for example; we could simply make another call to correct the time frame within minutes. No more missed deadlines and no more unhappy clients.
In reality, third parties may not have the same resources, infrastructure, practices or approach that you may be used to. This difference can lead to errors in ingestion, processing or presentation which may be slow to fix if you need to ask a third party to reformat or reproduce the data for any reason. Retaining as much autonomy over your data as possible enables you to be more reactive to changes, find solutions faster and optimise the production to a level that you control.
A key attribute that’s helped me throughout my time as an analyst is my ability to learn from others. I really enjoy learning why people are successful at what they do and the traits they possess which I can apply to my own life and career. Consistent, constructive feedback from others can really accelerate your learning and challenge you to perform better, and peer review is crucial to this in an analysis environment. Having a colleague review your code can have many benefits:
Adding further confidence to your data outputs
Creates an opportunity to learn new techniques
Shares knowledge between teams and peers
Provides another angle of thinking which provokes discussion on methodologies and promotes more innovative solutions
A fresh pair of eyes can be incredibly impactful to improving your code. Having someone approach the same problem, think through the same process and come to the same conclusion is so beneficial for someone that’s been staring at the same multi-join for the last 2 hours, not able to figure out if it’s working properly. I can’t remember how many times I’ve walked over to a teammates desk with a bug I’ve been stuck on, only for them to spot it within 30 seconds, or suggest a much more efficient way of achieving the desired result. One of the biggest reasons for this is that often bugs or duplicates appear through the most difficult to notice, obscure and inconspicuous SQL interactions involving the nichest edge cases.
As an analyst, your ability to identify potential edge cases and account for them, ideally before they even occur, is paramount to preventing any problems before they even materialise. Thinking of every potential edge case alone is extremely difficult and nigh on impossible, so utilise the best resource you have — productive discussion with your team and peers. Building consistent peer review into your workflow, to ensure that no code goes to production without being seen by at least one colleague, goes a long way to increasing your own confidence as an analyst, and can drastically speed up delivery of work.
Ensuring your deliverables are as high quality as possible means accounting for as many error scenarios as possible. Once the above infrastructure and QA processes have been applied, you’ll quickly find a vast improvement in bug detection, error management, deliverable quality and stakeholder satisfaction. I hope this article has been useful and that you can apply some of these practices to improve your data pipeline processes.
If you enjoyed this article and would like to get in touch, feel free to contact me on LinkedIn: https://www.linkedin.com/in/michael-gendy-a04263161/
|
[
{
"code": null,
"e": 250,
"s": 172,
"text": "“A milligram of prevention is worth a kilogram of cure” — John Robert Colombo"
},
{
"code": null,
"e": 674,
"s": 250,
"text": "Mistakes happen. Bugs can appear seemingly from nowhere. Data sources can falter at a moment’s notice invalidating your entire analysis pipeline. As an analytics team, ultimately it’s your responsibility to solve these problems and ensure your reports, deliverables and insights are as accurate as possible. Designing a robust quality assurance (QA) process is paramount to solidifying confidence in your outputs as a team."
},
{
"code": null,
"e": 876,
"s": 674,
"text": "This article will outline some key steps to designing a robust QA process to save time, money and resources; this will ensure that you’re making the most positive impact possible through your analysis."
},
{
"code": null,
"e": 1042,
"s": 876,
"text": "There are so many reasons why a robust QA process is invaluable to your business and team. Here’s a handful of the most meaningful outcomes of a complete QA process:"
},
{
"code": null,
"e": 1112,
"s": 1042,
"text": "Confirms business decisions are made using the best possible insights"
},
{
"code": null,
"e": 1172,
"s": 1112,
"text": "Increases output efficiency and reduces duplication of work"
},
{
"code": null,
"e": 1207,
"s": 1172,
"text": "Improves reactivity to data issues"
},
{
"code": null,
"e": 1256,
"s": 1207,
"text": "Maintains stakeholder trust and client relations"
},
{
"code": null,
"e": 1334,
"s": 1256,
"text": "Increases analyst confidence in outputs, allowing for a faster way of working"
},
{
"code": null,
"e": 2262,
"s": 1334,
"text": "Business decisions based on false data are costly for all parties involved. It can mean work is repeated, performance is reduced, money is lost or crucially, confidence in your outputs is hit. Confidence in the insights and recommendations you and your team are providing is crucial in gaining the trust of your stakeholders, and making a larger impact with your work. You don’t want one small mistake to affect future performance, both for you and your team. Most larger companies can devote entire teams to the QA process, however in small to medium sized companies that do not have access to such resources, it becomes the responsibility of the analytics team as a collective to ensure that proper infrastructure is built to reduce any unwanted errors in deliverables. Robust QA processes provide tangible, reliable value in the prevention of any such problems leading to efficient and effective data-driven decision making."
},
{
"code": null,
"e": 2590,
"s": 2262,
"text": "QA is more than just checking over your code. Pipelines with many moving parts, changing volumes and third party data sources can be difficult to manage. Forming a well-rounded and robust QA process that considers any immediate challenges, and accounts for future error scenarios, requires tackling this issue from many angles:"
},
{
"code": null,
"e": 2750,
"s": 2590,
"text": "SQL readability and translationUnit and integration testingMonitoring data flows at all stages of the pipelineReducing dependenciesPeer review and optimisation"
},
{
"code": null,
"e": 2782,
"s": 2750,
"text": "SQL readability and translation"
},
{
"code": null,
"e": 2811,
"s": 2782,
"text": "Unit and integration testing"
},
{
"code": null,
"e": 2863,
"s": 2811,
"text": "Monitoring data flows at all stages of the pipeline"
},
{
"code": null,
"e": 2885,
"s": 2863,
"text": "Reducing dependencies"
},
{
"code": null,
"e": 2914,
"s": 2885,
"text": "Peer review and optimisation"
},
{
"code": null,
"e": 3117,
"s": 2914,
"text": "This article will outline the reason why each of these stages is so important, suggest best-practices to keep your performance high, and ensure your time is spent on providing as much value as possible."
},
{
"code": null,
"e": 3472,
"s": 3117,
"text": "Often our absolute code efficiency is at the forefront of our coding decision making. Manipulating large volumes of data in complicated queries does require diligent thought to save time and money on processing resource. However, frequently there is the opportunity to trade-off absolute performance with readability to improve how queries are evaluated."
},
{
"code": null,
"e": 3642,
"s": 3472,
"text": "Using a simple SQL example, let’s say we want to list the names of records I own in my record collection that are vintage. We could solve this using the following query:"
},
{
"code": null,
"e": 3755,
"s": 3642,
"text": "SELECT t_my.record_name FROM my_records t_myINNER JOIN vintage_records t_vinON t_my.record_id = t_vin.record_id;"
},
{
"code": null,
"e": 4188,
"s": 3755,
"text": "If I owned a very large, entirely impossible collection of billions of records, this is likely close to the best solution, as opposed to using a more computationally heavy sub-query. Yet if I had to hand this over to a friend to run the same query, it doesn’t have that understand-at-a-glance-readability that we might achieve through other means. Consider the questions the new analyst needs to figure out before running the query:"
},
{
"code": null,
"e": 4218,
"s": 4188,
"text": "What is the aim of the query?"
},
{
"code": null,
"e": 4260,
"s": 4218,
"text": "What are the contents of vintage_records?"
},
{
"code": null,
"e": 4302,
"s": 4260,
"text": "Has the INNER JOIN caused any duplicates?"
},
{
"code": null,
"e": 4330,
"s": 4302,
"text": "Is record_id a primary key?"
},
{
"code": null,
"e": 4612,
"s": 4330,
"text": "In these cases, adding milliseconds to the run time of this query in exchange for some more transferable, readable code is an extremely worthwhile trade-off. By rewriting using a sub query and adding a simple comment, we achieve a much clearer result with very similar performance:"
},
{
"code": null,
"e": 4821,
"s": 4612,
"text": "--Returns ALL record names from my collection that are vintageWITH vintage_record_ids AS (SELECT DISTINCT record_id FROM vintage_record)SELECT record_name FROM my_recordsWHERE record_id IN vintage_record_ids;"
},
{
"code": null,
"e": 4893,
"s": 4821,
"text": "Same result, similar performance and much improved readability. Notice:"
},
{
"code": null,
"e": 5114,
"s": 4893,
"text": "Clear purpose allowing for quick interpretationUse of the WITH statement allowing readability from the top-downClear name to the sub-query table outlining it’s contentsEliminating the need for a join simplifying the code"
},
{
"code": null,
"e": 5162,
"s": 5114,
"text": "Clear purpose allowing for quick interpretation"
},
{
"code": null,
"e": 5227,
"s": 5162,
"text": "Use of the WITH statement allowing readability from the top-down"
},
{
"code": null,
"e": 5285,
"s": 5227,
"text": "Clear name to the sub-query table outlining it’s contents"
},
{
"code": null,
"e": 5338,
"s": 5285,
"text": "Eliminating the need for a join simplifying the code"
},
{
"code": null,
"e": 5890,
"s": 5338,
"text": "Good readability best-practices include commenting out the purpose of the query, utilising WITH statements (CTEs), capitalising functions, keeping queries short and having clear processing logic. Thanks to our changes, we now have clarity on many of the query’s nuances. We now know it’s purpose and that we’re returning all results from my record collection (not just unique results). We can interpret the code faster thanks to the sub-query, and don’t have to worry about any faulty JOIN logic. Slower but cleaner code is definitely the winner here."
},
{
"code": null,
"e": 6646,
"s": 5890,
"text": "While it may seem like it saves a small amount of time on a simple query like this, the actual value it derives will continue to pay off every time this is run. When your SQL infrastructure involves complex, multiple thousand line scripts all integrated with one another, the pay-off for writing your code in a clear manner increases exponentially. Not to mention the often overlooked factor in smaller teams — what happens when the primary analyst for these scripts is on holiday or off sick? Can another analyst pick up the script effectively? An analyst contributes greatly to making business operations more efficient, and so it’s crucial to apply this to their own processes and practices too, in the form of producing readable and transferable code."
},
{
"code": null,
"e": 7021,
"s": 6646,
"text": "Testing and retesting any production script is the biggest non-negotiable of all. We must both test code in isolated segments (unit testing), and test how well these isolated segments work together (integration testing). For example, testing that a temporary table is created correctly, then ensuring that any queries that use the temporary table interact with it correctly."
},
{
"code": null,
"e": 7524,
"s": 7021,
"text": "SQL is deceivingly simple, and learning to anticipate duplication and becoming accustomed to diagnosing faulty joins can bring a lot more peace to your day-to-day analysis. Commenting out code to evaluate if each query has produced the intended result (unit testing), and making sure they won’t break any of your other dependent queries (integration testing) is a skill worth developing in itself. At a minimum, you should include unit testing queries and comments which answer the following questions:"
},
{
"code": null,
"e": 7571,
"s": 7524,
"text": "Are my counts before and after JOINs expected?"
},
{
"code": null,
"e": 7616,
"s": 7571,
"text": "Have any of my primary keys been duplicated?"
},
{
"code": null,
"e": 7655,
"s": 7616,
"text": "Are my JOIN fields in the same format?"
},
{
"code": null,
"e": 7704,
"s": 7655,
"text": "Are my CASE WHEN statements working as intended?"
},
{
"code": null,
"e": 7740,
"s": 7704,
"text": "Does the result make logical sense?"
},
{
"code": null,
"e": 8031,
"s": 7740,
"text": "The next step is ensuring these individual queries work in harmony with any other queries in your script. Checking that one section of code is working correctly but failing to test how this query fits into your larger data pipeline can create unnecessary and easily avoided vulnerabilities."
},
{
"code": null,
"e": 8742,
"s": 8031,
"text": "Take the time and document your thought process — this will pay off greatly by preventing errors and ensuring bugs are identified and solved swiftly. Give as much detail as you can in a clear, succinct manner. If the result is correct, but counter intuitive — explain it in a comment! The goal here is to make your outputs reproducible and allow others to easily verify the result. Outlining the above during SQL script writing will soon become second nature, and you’ll develop your own intuition for bugs that arise repeatedly. In addition to building more confidence in our work, we also give our peers the ability to pick up the script, understand the purpose and evaluate its efficacy with minimal hassle."
},
{
"code": null,
"e": 8900,
"s": 8742,
"text": "It’s genuinely quite incredible how many seemingly insignificant changes to your data ingestion can affect your data pipelines. Here’s a handful of examples:"
},
{
"code": null,
"e": 8942,
"s": 8900,
"text": "NULLS appearing due to trafficking issues"
},
{
"code": null,
"e": 9015,
"s": 8942,
"text": "Formats of dates, internal IDs, country codes changing between suppliers"
},
{
"code": null,
"e": 9056,
"s": 9015,
"text": "Duplicates appearing due to API glitches"
},
{
"code": null,
"e": 9104,
"s": 9056,
"text": "Manually input data being incorrectly filled in"
},
{
"code": null,
"e": 9553,
"s": 9104,
"text": "Any of these issues can affect multiple queries in seemly obscure ways, from causing JOINS to fail, breaking NOT IN statements and messing with your WHERE clauses. Without clear visibility on your data at every processing stage, often these issues can go unnoticed causing a headache down the line. Odds are, the longer the issue has been present, the bigger the consequences — catching any of these issues early can be the key to smooth operation."
},
{
"code": null,
"e": 9786,
"s": 9553,
"text": "Clear data visualisation is the key to solving this. An easy way to do this is by creating a pipeline monitoring table, inserting counts of key metrics at every stage of the data processing, and visualising the outputs in a BI tool:"
},
{
"code": null,
"e": 10117,
"s": 9786,
"text": "INSERT INTO qa_pipeline(SELECT table_name,CURRENT_TIMESTAMP() as run_timestamp,count(*) as row_count ,COUNT(primary_key) as primary_key_count,COUNT(distinct_primary_key) as distinct_primary_key_count ,COUNT(*) FILTER (WHERE important_field > '') as important_field_population,SUM(important_kpi) as important_kpi_sumFROM raw_table)"
},
{
"code": null,
"e": 10771,
"s": 10117,
"text": "This is a very useful, general format of how we want to track our data. Creating visualisations of a table such as qa_pipeline, and tracking important values such as row counts, field population, KPI sums and primary key interactions between queries can enable at-a-glance debugging. For example, in your raw tables, your primary key will always be unique. In your cleaning script where you create a new table and join in extra information, if we now see the count of primary keys increase, we know there’s some duplication caused by the cleaning script. Inversely, if we see the distinct primary key count decrease, we know some have been filtered out:"
},
{
"code": null,
"e": 11597,
"s": 10771,
"text": "The visualisation above demonstrates the power of these qa_pipeline tables. It’s immediately obvious that every metric doubles in the final table, indicating that there’s faulty logic in the script to produce the final_output which is causing duplication. A number of issues can be discovered by simply getting a pair of eyes on the true outputs of each script or query. If we saw a significant decrease in important_kpi_sum, this would suggest that there’s an error when using important_kpi or a mistake in the aggregation logic — a clear sign that the code should be reviewed. While manually going through entire outputs regularly can demand too much resource for many analytics teams, a quick inspection of these summary visualisations every morning will lead to more proactive solutions to diagnose incorrect SQL scripts."
},
{
"code": null,
"e": 12042,
"s": 11597,
"text": "Another use case of the same table is making sure your data is being ingested correctly — the quality of your raw data will mirror the quality of your outputs. Viewing your ingestion table metrics using the qa_pipeline table visualisations allows for easy monitoring that your data is coming in the intended formats. Anomalous results such as low row counts, missing days and high numbers of missing fields can be identified easily and quickly:"
},
{
"code": null,
"e": 12645,
"s": 12042,
"text": "At a quick glance, we can see there are some ingestion issues for our raw_table. On the 3rd of January when the script was run, we saw three times the amount of rows as we see distinct primary keys, indicating that the data may have been ingested three times. In addition, on the 5th of January, we can see our important_field was not completely populated, hinting at some tracking issues. After only a few seconds of looking at the visualisation, we can clearly evaluate the quality of the data and highlight any issues, further improving our ability to react to problems and resolve them efficiently."
},
{
"code": null,
"e": 13169,
"s": 12645,
"text": "Use your creativity in how you display these counts to suit your business use case. Your intuition is a valuable resource here — learn to anticipate how your code will affect your data and compare this consistently to the visualisations provided by these qa_pipeline tables. Setting up these INSERT INTO queries at ingestion, during data cleaning and after the deliverables have been produced gives you end-to-end clarity on how your scripts are performing, saving valuable resources on debugging and preventing any errors."
},
{
"code": null,
"e": 13666,
"s": 13169,
"text": "A competent analyst can work through any problem. In theory, all code should be running perfectly if the quality of the data remains the same. However, when managing the ingestion of multiple data streams from different sources, this data quality is never guaranteed. Possibly the simplest way to maintain good quality data is by taking control of it yourself, allowing full autonomy and greater reactivity when problems arise. Next time you’re ingesting third party data, consider the following:"
},
{
"code": null,
"e": 13920,
"s": 13666,
"text": "If we found an error, how quickly could it be solved by the source?Could I gain autonomy of this data by producing it in-house?Could any manual processes be automated to reduce human error?How can we work with the sources to reduce our reliance on them?"
},
{
"code": null,
"e": 13988,
"s": 13920,
"text": "If we found an error, how quickly could it be solved by the source?"
},
{
"code": null,
"e": 14049,
"s": 13988,
"text": "Could I gain autonomy of this data by producing it in-house?"
},
{
"code": null,
"e": 14112,
"s": 14049,
"text": "Could any manual processes be automated to reduce human error?"
},
{
"code": null,
"e": 14177,
"s": 14112,
"text": "How can we work with the sources to reduce our reliance on them?"
},
{
"code": null,
"e": 14201,
"s": 14177,
"text": "Consider this scenario:"
},
{
"code": null,
"e": 14639,
"s": 14201,
"text": "“An international third party is supplying time series data in the form of a daily excel report. Due to daylight savings in their region, the timestamps they have provided are all an hour out, which means you’re missing an hour of data in the report provided. They’re in a completely different timezone, won’t be able to rectify the issue until the morning, and the clients demanding a crucial report be delivered by the end of the day.”"
},
{
"code": null,
"e": 15027,
"s": 14639,
"text": "Not a fun spot to be in. You could make a strong case that the third party is not even complicit, because the process is inherently flawed for many reasons. However, if we had autonomy over the data they provided, by querying their API directly for example; we could simply make another call to correct the time frame within minutes. No more missed deadlines and no more unhappy clients."
},
{
"code": null,
"e": 15510,
"s": 15027,
"text": "In reality, third parties may not have the same resources, infrastructure, practices or approach that you may be used to. This difference can lead to errors in ingestion, processing or presentation which may be slow to fix if you need to ask a third party to reformat or reproduce the data for any reason. Retaining as much autonomy over your data as possible enables you to be more reactive to changes, find solutions faster and optimise the production to a level that you control."
},
{
"code": null,
"e": 15993,
"s": 15510,
"text": "A key attribute that’s helped me throughout my time as an analyst is my ability to learn from others. I really enjoy learning why people are successful at what they do and the traits they possess which I can apply to my own life and career. Consistent, constructive feedback from others can really accelerate your learning and challenge you to perform better, and peer review is crucial to this in an analysis environment. Having a colleague review your code can have many benefits:"
},
{
"code": null,
"e": 16040,
"s": 15993,
"text": "Adding further confidence to your data outputs"
},
{
"code": null,
"e": 16087,
"s": 16040,
"text": "Creates an opportunity to learn new techniques"
},
{
"code": null,
"e": 16128,
"s": 16087,
"text": "Shares knowledge between teams and peers"
},
{
"code": null,
"e": 16245,
"s": 16128,
"text": "Provides another angle of thinking which provokes discussion on methodologies and promotes more innovative solutions"
},
{
"code": null,
"e": 16971,
"s": 16245,
"text": "A fresh pair of eyes can be incredibly impactful to improving your code. Having someone approach the same problem, think through the same process and come to the same conclusion is so beneficial for someone that’s been staring at the same multi-join for the last 2 hours, not able to figure out if it’s working properly. I can’t remember how many times I’ve walked over to a teammates desk with a bug I’ve been stuck on, only for them to spot it within 30 seconds, or suggest a much more efficient way of achieving the desired result. One of the biggest reasons for this is that often bugs or duplicates appear through the most difficult to notice, obscure and inconspicuous SQL interactions involving the nichest edge cases."
},
{
"code": null,
"e": 17587,
"s": 16971,
"text": "As an analyst, your ability to identify potential edge cases and account for them, ideally before they even occur, is paramount to preventing any problems before they even materialise. Thinking of every potential edge case alone is extremely difficult and nigh on impossible, so utilise the best resource you have — productive discussion with your team and peers. Building consistent peer review into your workflow, to ensure that no code goes to production without being seen by at least one colleague, goes a long way to increasing your own confidence as an analyst, and can drastically speed up delivery of work."
},
{
"code": null,
"e": 18019,
"s": 17587,
"text": "Ensuring your deliverables are as high quality as possible means accounting for as many error scenarios as possible. Once the above infrastructure and QA processes have been applied, you’ll quickly find a vast improvement in bug detection, error management, deliverable quality and stakeholder satisfaction. I hope this article has been useful and that you can apply some of these practices to improve your data pipeline processes."
}
] |
Convert PySpark DataFrame to Dictionary in Python - GeeksforGeeks
|
17 Jun, 2021
In this article, we are going to see how to convert the PySpark data frame to the dictionary, where keys are column names and values are column values.
Before starting, we will create a sample Dataframe:
Python3
# Importing necessary librariesfrom pyspark.sql import SparkSession # Create a spark sessionspark = SparkSession.builder.appName('DF_to_dict').getOrCreate() # Create data in dataframedata = [(('Ram'), '1991-04-01', 'M', 3000), (('Mike'), '2000-05-19', 'M', 4000), (('Rohini'), '1978-09-05', 'M', 4000), (('Maria'), '1967-12-01', 'F', 4000), (('Jenis'), '1980-02-17', 'F', 1200)] # Column names in dataframecolumns = ["Name", "DOB", "Gender", "salary"] # Create the spark dataframedf = spark.createDataFrame(data=data, schema=columns) # Print the dataframedf.show()
Output :
Method 1: Using df.toPandas()
Convert the PySpark data frame to Pandas data frame using df.toPandas().
Syntax: DataFrame.toPandas()
Return type: Returns the pandas data frame having the same content as Pyspark Dataframe.
Get through each column value and add the list of values to the dictionary with the column name as the key.
Python3
# Declare an empty Dictionarydict = {} # Convert PySpark DataFrame to Pandas # DataFramedf = df.toPandas() # Traverse through each columnfor column in df.columns: # Add key as column_name and # value as list of column values dict[column] = df[column].values.tolist() # Print the dictionaryprint(dict)
Output :
{‘Name’: [‘Ram’, ‘Mike’, ‘Rohini’, ‘Maria’, ‘Jenis’],
‘DOB’: [‘1991-04-01’, ‘2000-05-19’, ‘1978-09-05’, ‘1967-12-01’, ‘1980-02-17’],
‘Gender’: [‘M’, ‘M’, ‘M’, ‘F’, ‘F’],
‘salary’: [3000, 4000, 4000, 4000, 1200]}
Method 2: Using df.collect()
Convert the PySpark data frame into the list of rows, and returns all the records of a data frame as a list.
Syntax: DataFrame.collect()
Return type: Returns all the records of the data frame as a list of rows.
Python3
import numpy as np # Convert the dataframe into list# of rowsrows = [list(row) for row in df.collect()] # COnvert the list into numpy arrayar = np.array(rows) # Declare an empty dictionarydict = {} # Get through each columnfor i, column in enumerate(df.columns): # Add ith column as values in dict # with key as ith column_name dict[column] = list(ar[:, i]) # Print the dictionaryprint(dict)
Output :
{‘Name’: [‘Ram’, ‘Mike’, ‘Rohini’, ‘Maria’, ‘Jenis’],
‘DOB’: [‘1991-04-01’, ‘2000-05-19’, ‘1978-09-05’, ‘1967-12-01’, ‘1980-02-17’],
‘Gender’: [‘M’, ‘M’, ‘M’, ‘F’, ‘F’],
‘salary’: [‘3000’, ‘4000’, ‘4000’, ‘4000’, ‘1200’]}
Method 3: Using pandas.DataFrame.to_dict()
Pandas data frame can be directly converted into a dictionary using the to_dict() method
Syntax: DataFrame.to_dict(orient=’dict’,)
Parameters:
orient: Indicating the type of values of the dictionary. It takes values such as {‘dict’, ‘list’, ‘series’, ‘split’, ‘records’, ‘index’}
Return type: Returns the dictionary corresponding to the data frame.
Code:
Python3
# COnvert PySpark dataframe to pandas# dataframedf = df.toPandas() # Convert the dataframe into # dictionarydict = df.to_dict(orient = 'list') # Print the dictionaryprint(dict)
Output :
{‘Name’: [‘Ram’, ‘Mike’, ‘Rohini’, ‘Maria’, ‘Jenis’],
‘DOB’: [‘1991-04-01’, ‘2000-05-19’, ‘1978-09-05’, ‘1967-12-01’, ‘1980-02-17’],
‘Gender’: [‘M’, ‘M’, ‘M’, ‘F’, ‘F’],
‘salary’: [3000, 4000, 4000, 4000, 1200]}
Converting a data frame having 2 columns to a dictionary, create a data frame with 2 columns naming ‘Location’ and ‘House_price’
Python3
# Importing necessary librariesfrom pyspark.sql import SparkSession # Create a spark sessionspark = SparkSession.builder.appName('DF_to_dict').getOrCreate() # Create data in dataframedata = [(('Hyderabad'), 120000), (('Delhi'), 124000), (('Mumbai'), 344000), (('Guntur'), 454000), (('Bandra'), 111200)] # Column names in dataframecolumns = ["Location", 'House_price'] # Create the spark dataframedf = spark.createDataFrame(data=data, schema=columns) # Print the dataframeprint('Dataframe : ')df.show() # COnvert PySpark dataframe to # pandas dataframedf = df.toPandas() # Convert the dataframe into # dictionarydict = df.to_dict(orient='list') # Print the dictionaryprint('Dictionary :')print(dict)
Output :
Picked
Python-Pyspark
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
*args and **kwargs in Python
Check if element exists in list in Python
Convert integer to string in Python
|
[
{
"code": null,
"e": 24526,
"s": 24498,
"text": "\n17 Jun, 2021"
},
{
"code": null,
"e": 24678,
"s": 24526,
"text": "In this article, we are going to see how to convert the PySpark data frame to the dictionary, where keys are column names and values are column values."
},
{
"code": null,
"e": 24730,
"s": 24678,
"text": "Before starting, we will create a sample Dataframe:"
},
{
"code": null,
"e": 24738,
"s": 24730,
"text": "Python3"
},
{
"code": "# Importing necessary librariesfrom pyspark.sql import SparkSession # Create a spark sessionspark = SparkSession.builder.appName('DF_to_dict').getOrCreate() # Create data in dataframedata = [(('Ram'), '1991-04-01', 'M', 3000), (('Mike'), '2000-05-19', 'M', 4000), (('Rohini'), '1978-09-05', 'M', 4000), (('Maria'), '1967-12-01', 'F', 4000), (('Jenis'), '1980-02-17', 'F', 1200)] # Column names in dataframecolumns = [\"Name\", \"DOB\", \"Gender\", \"salary\"] # Create the spark dataframedf = spark.createDataFrame(data=data, schema=columns) # Print the dataframedf.show()",
"e": 25362,
"s": 24738,
"text": null
},
{
"code": null,
"e": 25371,
"s": 25362,
"text": "Output :"
},
{
"code": null,
"e": 25401,
"s": 25371,
"text": "Method 1: Using df.toPandas()"
},
{
"code": null,
"e": 25474,
"s": 25401,
"text": "Convert the PySpark data frame to Pandas data frame using df.toPandas()."
},
{
"code": null,
"e": 25503,
"s": 25474,
"text": "Syntax: DataFrame.toPandas()"
},
{
"code": null,
"e": 25592,
"s": 25503,
"text": "Return type: Returns the pandas data frame having the same content as Pyspark Dataframe."
},
{
"code": null,
"e": 25700,
"s": 25592,
"text": "Get through each column value and add the list of values to the dictionary with the column name as the key."
},
{
"code": null,
"e": 25708,
"s": 25700,
"text": "Python3"
},
{
"code": "# Declare an empty Dictionarydict = {} # Convert PySpark DataFrame to Pandas # DataFramedf = df.toPandas() # Traverse through each columnfor column in df.columns: # Add key as column_name and # value as list of column values dict[column] = df[column].values.tolist() # Print the dictionaryprint(dict)",
"e": 26023,
"s": 25708,
"text": null
},
{
"code": null,
"e": 26032,
"s": 26023,
"text": "Output :"
},
{
"code": null,
"e": 26087,
"s": 26032,
"text": "{‘Name’: [‘Ram’, ‘Mike’, ‘Rohini’, ‘Maria’, ‘Jenis’], "
},
{
"code": null,
"e": 26166,
"s": 26087,
"text": "‘DOB’: [‘1991-04-01’, ‘2000-05-19’, ‘1978-09-05’, ‘1967-12-01’, ‘1980-02-17’],"
},
{
"code": null,
"e": 26205,
"s": 26166,
"text": " ‘Gender’: [‘M’, ‘M’, ‘M’, ‘F’, ‘F’], "
},
{
"code": null,
"e": 26248,
"s": 26205,
"text": " ‘salary’: [3000, 4000, 4000, 4000, 1200]}"
},
{
"code": null,
"e": 26277,
"s": 26248,
"text": "Method 2: Using df.collect()"
},
{
"code": null,
"e": 26386,
"s": 26277,
"text": "Convert the PySpark data frame into the list of rows, and returns all the records of a data frame as a list."
},
{
"code": null,
"e": 26414,
"s": 26386,
"text": "Syntax: DataFrame.collect()"
},
{
"code": null,
"e": 26489,
"s": 26414,
"text": "Return type: Returns all the records of the data frame as a list of rows."
},
{
"code": null,
"e": 26497,
"s": 26489,
"text": "Python3"
},
{
"code": "import numpy as np # Convert the dataframe into list# of rowsrows = [list(row) for row in df.collect()] # COnvert the list into numpy arrayar = np.array(rows) # Declare an empty dictionarydict = {} # Get through each columnfor i, column in enumerate(df.columns): # Add ith column as values in dict # with key as ith column_name dict[column] = list(ar[:, i]) # Print the dictionaryprint(dict)",
"e": 26905,
"s": 26497,
"text": null
},
{
"code": null,
"e": 26914,
"s": 26905,
"text": "Output :"
},
{
"code": null,
"e": 26969,
"s": 26914,
"text": "{‘Name’: [‘Ram’, ‘Mike’, ‘Rohini’, ‘Maria’, ‘Jenis’], "
},
{
"code": null,
"e": 27049,
"s": 26969,
"text": "‘DOB’: [‘1991-04-01’, ‘2000-05-19’, ‘1978-09-05’, ‘1967-12-01’, ‘1980-02-17’], "
},
{
"code": null,
"e": 27086,
"s": 27049,
"text": "‘Gender’: [‘M’, ‘M’, ‘M’, ‘F’, ‘F’],"
},
{
"code": null,
"e": 27139,
"s": 27086,
"text": " ‘salary’: [‘3000’, ‘4000’, ‘4000’, ‘4000’, ‘1200’]}"
},
{
"code": null,
"e": 27182,
"s": 27139,
"text": "Method 3: Using pandas.DataFrame.to_dict()"
},
{
"code": null,
"e": 27271,
"s": 27182,
"text": "Pandas data frame can be directly converted into a dictionary using the to_dict() method"
},
{
"code": null,
"e": 27313,
"s": 27271,
"text": "Syntax: DataFrame.to_dict(orient=’dict’,)"
},
{
"code": null,
"e": 27326,
"s": 27313,
"text": "Parameters: "
},
{
"code": null,
"e": 27463,
"s": 27326,
"text": "orient: Indicating the type of values of the dictionary. It takes values such as {‘dict’, ‘list’, ‘series’, ‘split’, ‘records’, ‘index’}"
},
{
"code": null,
"e": 27532,
"s": 27463,
"text": "Return type: Returns the dictionary corresponding to the data frame."
},
{
"code": null,
"e": 27538,
"s": 27532,
"text": "Code:"
},
{
"code": null,
"e": 27546,
"s": 27538,
"text": "Python3"
},
{
"code": "# COnvert PySpark dataframe to pandas# dataframedf = df.toPandas() # Convert the dataframe into # dictionarydict = df.to_dict(orient = 'list') # Print the dictionaryprint(dict)",
"e": 27725,
"s": 27546,
"text": null
},
{
"code": null,
"e": 27734,
"s": 27725,
"text": "Output :"
},
{
"code": null,
"e": 27789,
"s": 27734,
"text": "{‘Name’: [‘Ram’, ‘Mike’, ‘Rohini’, ‘Maria’, ‘Jenis’], "
},
{
"code": null,
"e": 27869,
"s": 27789,
"text": "‘DOB’: [‘1991-04-01’, ‘2000-05-19’, ‘1978-09-05’, ‘1967-12-01’, ‘1980-02-17’], "
},
{
"code": null,
"e": 27906,
"s": 27869,
"text": "‘Gender’: [‘M’, ‘M’, ‘M’, ‘F’, ‘F’],"
},
{
"code": null,
"e": 27949,
"s": 27906,
"text": " ‘salary’: [3000, 4000, 4000, 4000, 1200]}"
},
{
"code": null,
"e": 28078,
"s": 27949,
"text": "Converting a data frame having 2 columns to a dictionary, create a data frame with 2 columns naming ‘Location’ and ‘House_price’"
},
{
"code": null,
"e": 28086,
"s": 28078,
"text": "Python3"
},
{
"code": "# Importing necessary librariesfrom pyspark.sql import SparkSession # Create a spark sessionspark = SparkSession.builder.appName('DF_to_dict').getOrCreate() # Create data in dataframedata = [(('Hyderabad'), 120000), (('Delhi'), 124000), (('Mumbai'), 344000), (('Guntur'), 454000), (('Bandra'), 111200)] # Column names in dataframecolumns = [\"Location\", 'House_price'] # Create the spark dataframedf = spark.createDataFrame(data=data, schema=columns) # Print the dataframeprint('Dataframe : ')df.show() # COnvert PySpark dataframe to # pandas dataframedf = df.toPandas() # Convert the dataframe into # dictionarydict = df.to_dict(orient='list') # Print the dictionaryprint('Dictionary :')print(dict)",
"e": 28821,
"s": 28086,
"text": null
},
{
"code": null,
"e": 28830,
"s": 28821,
"text": "Output :"
},
{
"code": null,
"e": 28837,
"s": 28830,
"text": "Picked"
},
{
"code": null,
"e": 28852,
"s": 28837,
"text": "Python-Pyspark"
},
{
"code": null,
"e": 28859,
"s": 28852,
"text": "Python"
},
{
"code": null,
"e": 28957,
"s": 28859,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28975,
"s": 28957,
"text": "Python Dictionary"
},
{
"code": null,
"e": 29010,
"s": 28975,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 29042,
"s": 29010,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29084,
"s": 29042,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 29110,
"s": 29084,
"text": "Python String | replace()"
},
{
"code": null,
"e": 29154,
"s": 29110,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 29191,
"s": 29154,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 29220,
"s": 29191,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 29262,
"s": 29220,
"text": "Check if element exists in list in Python"
}
] |
COVID-19 data processing with Pandas DataFrame | by B. Chen | Towards Data Science
|
I published an article a couple days ago showing a step by step tutorial to building an Interactive Data Visualization for exploring Coronavirus Spreads. Several people left private notes on it asking specifically for the data processing steps.
Today, I am posting the step by step tutorial to download, load, merge, clean and aggregate the COVID-19 time series data. The data was provided by the Johns Hopkins University Center for Systems Science and Engineering (JHU CSSE) who shared their data on a public Github page. The Johns Hopkins CSSE aggregates data from primary sources, such as the World Health Organisation, national, and regional public health institutions. This data is made freely available and is updated every day.
Before we getting into the details, I would like to show you the final output of the COVID-19 data processing. Confirmed, Deaths, Recovered and Active are cumulative data. New cases, New deaths and New Recovered are day wise data. This DataFrames is ordered by Date and Country/Region.
Also, I would like to thank the following projects for their COVID-19 data processing ideas:
https://github.com/imdevskp/covid_19_jhu_data_web_scrap_and_cleaning
https://www.kaggle.com/imdevskp/covid-19-analysis-visualization-comparisons/notebook
https://www.kaggle.com/neelkudu28/covid-19-visualizations-predictions-forecasting
The main reason behind data processing is that data almost never comes in a form that is ready for us. And in my personal experience, a large amount of time spent on a data science project is on manipulating data.
Let’s take a look at the COVID-19 time series data,
Here are some problems for me:
confirmed, deaths and recovered are kept in different CSV files. That makes my life difficult for plotting them in the same data visualization.
Take a look at the above screenshot. Dates are actually displayed as column name and that is very odd data shape.
confirmed, deaths and recovered are not exactly matched because of missing data, and some countries don’t report Province/State-wise stat for recovered.
Other missing values, wrong datatypes and cases reported from three cruise ships.
This COVID-19 data processing tutorial runs the following steps:
Download raw CSV dataset from JHU CSSE public Github pageLoad raw CSV dataset and extract the common date listMerges the raw confirmed, deaths, and recovered CSV data into one DataFrame.Performs data cleanings due to missing values, wrong datatypes and cases from cruise ships.Data Aggregation: Add an active case column Active, which is calculated by active_case = confirmed — deaths — recovered. Aggregate data into Country/Region wise and group them by Date and Country/Region. After that, add day wise New cases, New deaths and New recovered by deducting the corresponding cumulative data on the previous day.
Download raw CSV dataset from JHU CSSE public Github page
Load raw CSV dataset and extract the common date list
Merges the raw confirmed, deaths, and recovered CSV data into one DataFrame.
Performs data cleanings due to missing values, wrong datatypes and cases from cruise ships.
Data Aggregation: Add an active case column Active, which is calculated by active_case = confirmed — deaths — recovered. Aggregate data into Country/Region wise and group them by Date and Country/Region. After that, add day wise New cases, New deaths and New recovered by deducting the corresponding cumulative data on the previous day.
At the end of the data processing, I will show 2 simple data visualizations with Altair for demonstration.
Let’s import the libraries we need
import pandas as pdimport wget
Go to Johns Hopkins CSSE public Github page and navigate to csse_covid_19_data/css_covid_19_time_series/
Click the global CSV dataset and click “Raw” button to get the data url.
Then, keep the urls in a collection and download using wget.download()
# url of the raw csv dataseturls = [ 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv', 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv', 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_recovered_global.csv'][wget.download(url) for url in urls]
Once download complete, it should output like below and the 3 files should appear in your working directory.
['time_series_covid19_confirmed_global.csv', 'time_series_covid19_deaths_global.csv', 'time_series_covid19_recovered_global.csv']
confirmed_df = pd .read_csv('time_series_covid19_confirmed_global.csv')deaths_df = pd .read_csv('time_series_covid19_deaths_global.csv')recovered_df = pd .read_csv('time_series_covid19_recovered_global.csv')
Let’s have a quick look at data, for example, confirmed_df.head() shows 93 columns. It should be the same on deaths_df and recovered_df
By running confirmed_df.columns , deaths_df.columns and recovered_df.columns, all of them should output the same result as below:
Notice that columns are all date from the 4th column onwards and to get the list of dates confirmed_df.columns[4:]
Before merging, we need to use melt() to unpivot DataFrames from current wide format into long format. In other words, we are kinda transposing all date columns into values. Here are the main settings for that:
Use ‘Province/State’, ‘Country/Region’, ‘Lat’, ‘Long’ as identifier variables. We will later use them for merging.
Unpivot date columns (As we saw previously columns[4:]) with variable column ‘Date’ and value column ‘Confirmed’
dates = confirmed_df.columns[4:]confirmed_df_long = confirmed_df.melt( id_vars=['Province/State', 'Country/Region', 'Lat', 'Long'], value_vars=dates, var_name='Date', value_name='Confirmed')deaths_df_long = deaths_df.melt( id_vars=['Province/State', 'Country/Region', 'Lat', 'Long'], value_vars=dates, var_name='Date', value_name='Deaths')recovered_df_long = recovered_df.melt( id_vars=['Province/State', 'Country/Region', 'Lat', 'Long'], value_vars=dates, var_name='Date', value_name='Recovered')
Above should return new long DataFrames. All of them are ordered by Date and Country/Region because raw data was already ordered by Country/Region and the date columns are already in ASC order.
Here is the example of confirmed_df_long
In addition, we have to remove recovered data for Canada due to mismatch issue (🤷♂ Canada recovered data is counted by Country-wise rather than Province/State-wise).
recovered_df_long = recovered_df_long[recovered_df_long['Country/Region']!='Canada']
After that, we use merge() to merge the 3 DataFrames one after another
# Merging confirmed_df_long and deaths_df_longfull_table = confirmed_df_long.merge( right=deaths_df_long, how='left', on=['Province/State', 'Country/Region', 'Date', 'Lat', 'Long'])# Merging full_table and recovered_df_longfull_table = full_table.merge( right=recovered_df_long, how='left', on=['Province/State', 'Country/Region', 'Date', 'Lat', 'Long'])
Now, we should get a full table with Confirmed, Deaths and Recovered columns
There are 3 tasks we would like to do
Converting Date from string to datetimeReplacing missing value NaNCoronavirus cases reported from 3 cruise ships should be treated differently
Converting Date from string to datetime
Replacing missing value NaN
Coronavirus cases reported from 3 cruise ships should be treated differently
You probably already notice that the values in the new Date column are all string with m/dd/yy format. To convert Date values from string to datetime, let’s use DataFrame.to_datetime()
full_table['Date'] = pd.to_datetime(full_table['Date'])
Missing values NaN can be detected by running full_table.isna().sum()
full_table.isna().sum()Province/State 16198Country/Region 0Lat 0Long 0Date 0Confirmed 0Deaths 0Recovered 1602dtype: int64
We found a lot NaN in Province/State, and that makes sense as many countries only report the Country-wise data. However, there are 1,602 NaNs in Recovered and let’s replace them with 0.
full_table['Recovered'] = full_table['Recovered'].fillna(0)
Apart from missing values, there are coronavirus cases reported from 3 cruise ships: Grand Princess, Diamond Princess and MS Zaandam. These data need to be extracted and treated differently due to Province/State and Country/Region mismatch over time. Here is what I was talking about:
And here is how we extract the ship data.
ship_rows = full_table['Province/State'].str.contains('Grand Princess') | full_table['Province/State'].str.contains('Diamond Princess') | full_table['Country/Region'].str.contains('Diamond Princess') | full_table['Country/Region'].str.contains('MS Zaandam')full_ship = full_table[ship_rows]
And to get rid of ship data from full_table :
full_table = full_table[~(ship_rows)]
5. Data Aggregation
So far, all the Confirmed, Deaths, Recovered are existing data from raw CSV dataset. Let’s add an active cases column Active, which is calculated by active = confirmed — deaths — recovered .
# Active Case = confirmed - deaths - recoveredfull_table['Active'] = full_table['Confirmed'] - full_table['Deaths'] - full_table['Recovered']
And here is what full_table looks like now.
Next, let’s aggregate data into Country/Region wise and group them by Date and Country/Region.
full_grouped = full_table.groupby(['Date', 'Country/Region'])['Confirmed', 'Deaths', 'Recovered', 'Active'].sum().reset_index()
sum() is to get the total count of ‘Confirmed’, ‘Deaths’, ‘Recovered’, ‘Active’ for the given Date and Country/Region.
reset_index() reset the index and use the default one, which is Date and Country/Region.
And here is what full_grouped looks like now
Now let’s add day wise New cases, New deaths and New recovered by deducting the corresponding accumulative data on the previous day.
# new cases temp = full_grouped.groupby(['Country/Region', 'Date', ])['Confirmed', 'Deaths', 'Recovered']temp = temp.sum().diff().reset_index()mask = temp['Country/Region'] != temp['Country/Region'].shift(1)temp.loc[mask, 'Confirmed'] = np.nantemp.loc[mask, 'Deaths'] = np.nantemp.loc[mask, 'Recovered'] = np.nan# renaming columnstemp.columns = ['Country/Region', 'Date', 'New cases', 'New deaths', 'New recovered']# merging new valuesfull_grouped = pd.merge(full_grouped, temp, on=['Country/Region', 'Date'])# filling na with 0full_grouped = full_grouped.fillna(0)# fixing data typescols = ['New cases', 'New deaths', 'New recovered']full_grouped[cols] = full_grouped[cols].astype('int')# full_grouped['New cases'] = full_grouped['New cases'].apply(lambda x: 0 if x<0 else x)
And finally here is the full_grouped. Be aware of that this final output is Country-wise data with
Confirmed, Deaths, Recovered and Active are cumulative data.
New cases, New deaths and New Recovered are day wise data.
This DataFrames is ordered by Date and Country/Region.
Finally, you can save this final data to a CSV file:
full_grouped.to_csv('COVID-19-time-series-clean-complete.csv')
For simplicity, let’s use Python Data Visualization library Altair to create some simple visualizations. Altair is a declarative statistical visualization library for Python, based on Vega and Vega-Lite. Altair offers a powerful and concise visualization grammar that enables you to build a wide range of statistical visualizations quickly.
For Altair installation, I would strongly recommend creating a new Virtual Environment because Altair has a lot of dependencies. Then, activate your Virtual Environment, and run pip install altair vega_datasets to install Altair along with example dataset in vega_datasets.
For tutorials on Virtual Environment, you can take a look:
towardsdatascience.com
medium.com
First, let’s import the libraries, load data and select a country, for example, United Kingdom:
import pandas as pdimport altair as altfull_grouped = pd.read_csv('COVID-19-time-series-clean-complete.csv', parse_dates=['Date'])uk = full_grouped[full_grouped['Country/Region'] == 'United Kingdom']
Then, let’s create a base chart with the common elements
base = alt.Chart(uk).mark_bar().encode( x='monthdate(Date):O',).properties( width=500)
After that, we can concatenate horizontally using the | operator
First, let’s import the libraries, load data and select a list of countries
import pandas as pdimport altair as altfull_grouped = pd.read_csv('COVID-19-time-series-clean-complete.csv', parse_dates=['Date'])countries = ['US', 'Italy', 'China', 'Spain', 'Germany', 'France', 'Iran', 'United Kingdom', 'Switzerland']selected_countries = full_grouped[full_grouped['Country/Region'].isin(countries)]
Let’s create a circle chart to display the day wise New cases,
alt.Chart(selected_countries).mark_circle().encode( x='monthdate(Date):O', y='Country/Region', color='Country/Region', size=alt.Size('New cases:Q', scale=alt.Scale(range=[0, 1000]), legend=alt.Legend(title='Daily new cases') ) ).properties( width=800, height=300)
And here is the output
This article is mainly to show everyone how to process COVID-19 data step by step using Pandas. There are only 2 simple examples in the Data Exploration section for demonstration.
If you are interested in learning Altair, you can take a look at the following two articles.
towardsdatascience.com
towardsdatascience.com
And that’s about it. Thanks for reading
|
[
{
"code": null,
"e": 417,
"s": 172,
"text": "I published an article a couple days ago showing a step by step tutorial to building an Interactive Data Visualization for exploring Coronavirus Spreads. Several people left private notes on it asking specifically for the data processing steps."
},
{
"code": null,
"e": 907,
"s": 417,
"text": "Today, I am posting the step by step tutorial to download, load, merge, clean and aggregate the COVID-19 time series data. The data was provided by the Johns Hopkins University Center for Systems Science and Engineering (JHU CSSE) who shared their data on a public Github page. The Johns Hopkins CSSE aggregates data from primary sources, such as the World Health Organisation, national, and regional public health institutions. This data is made freely available and is updated every day."
},
{
"code": null,
"e": 1193,
"s": 907,
"text": "Before we getting into the details, I would like to show you the final output of the COVID-19 data processing. Confirmed, Deaths, Recovered and Active are cumulative data. New cases, New deaths and New Recovered are day wise data. This DataFrames is ordered by Date and Country/Region."
},
{
"code": null,
"e": 1286,
"s": 1193,
"text": "Also, I would like to thank the following projects for their COVID-19 data processing ideas:"
},
{
"code": null,
"e": 1355,
"s": 1286,
"text": "https://github.com/imdevskp/covid_19_jhu_data_web_scrap_and_cleaning"
},
{
"code": null,
"e": 1440,
"s": 1355,
"text": "https://www.kaggle.com/imdevskp/covid-19-analysis-visualization-comparisons/notebook"
},
{
"code": null,
"e": 1522,
"s": 1440,
"text": "https://www.kaggle.com/neelkudu28/covid-19-visualizations-predictions-forecasting"
},
{
"code": null,
"e": 1736,
"s": 1522,
"text": "The main reason behind data processing is that data almost never comes in a form that is ready for us. And in my personal experience, a large amount of time spent on a data science project is on manipulating data."
},
{
"code": null,
"e": 1788,
"s": 1736,
"text": "Let’s take a look at the COVID-19 time series data,"
},
{
"code": null,
"e": 1819,
"s": 1788,
"text": "Here are some problems for me:"
},
{
"code": null,
"e": 1963,
"s": 1819,
"text": "confirmed, deaths and recovered are kept in different CSV files. That makes my life difficult for plotting them in the same data visualization."
},
{
"code": null,
"e": 2077,
"s": 1963,
"text": "Take a look at the above screenshot. Dates are actually displayed as column name and that is very odd data shape."
},
{
"code": null,
"e": 2230,
"s": 2077,
"text": "confirmed, deaths and recovered are not exactly matched because of missing data, and some countries don’t report Province/State-wise stat for recovered."
},
{
"code": null,
"e": 2312,
"s": 2230,
"text": "Other missing values, wrong datatypes and cases reported from three cruise ships."
},
{
"code": null,
"e": 2377,
"s": 2312,
"text": "This COVID-19 data processing tutorial runs the following steps:"
},
{
"code": null,
"e": 2991,
"s": 2377,
"text": "Download raw CSV dataset from JHU CSSE public Github pageLoad raw CSV dataset and extract the common date listMerges the raw confirmed, deaths, and recovered CSV data into one DataFrame.Performs data cleanings due to missing values, wrong datatypes and cases from cruise ships.Data Aggregation: Add an active case column Active, which is calculated by active_case = confirmed — deaths — recovered. Aggregate data into Country/Region wise and group them by Date and Country/Region. After that, add day wise New cases, New deaths and New recovered by deducting the corresponding cumulative data on the previous day."
},
{
"code": null,
"e": 3049,
"s": 2991,
"text": "Download raw CSV dataset from JHU CSSE public Github page"
},
{
"code": null,
"e": 3103,
"s": 3049,
"text": "Load raw CSV dataset and extract the common date list"
},
{
"code": null,
"e": 3180,
"s": 3103,
"text": "Merges the raw confirmed, deaths, and recovered CSV data into one DataFrame."
},
{
"code": null,
"e": 3272,
"s": 3180,
"text": "Performs data cleanings due to missing values, wrong datatypes and cases from cruise ships."
},
{
"code": null,
"e": 3609,
"s": 3272,
"text": "Data Aggregation: Add an active case column Active, which is calculated by active_case = confirmed — deaths — recovered. Aggregate data into Country/Region wise and group them by Date and Country/Region. After that, add day wise New cases, New deaths and New recovered by deducting the corresponding cumulative data on the previous day."
},
{
"code": null,
"e": 3716,
"s": 3609,
"text": "At the end of the data processing, I will show 2 simple data visualizations with Altair for demonstration."
},
{
"code": null,
"e": 3751,
"s": 3716,
"text": "Let’s import the libraries we need"
},
{
"code": null,
"e": 3782,
"s": 3751,
"text": "import pandas as pdimport wget"
},
{
"code": null,
"e": 3887,
"s": 3782,
"text": "Go to Johns Hopkins CSSE public Github page and navigate to csse_covid_19_data/css_covid_19_time_series/"
},
{
"code": null,
"e": 3960,
"s": 3887,
"text": "Click the global CSV dataset and click “Raw” button to get the data url."
},
{
"code": null,
"e": 4031,
"s": 3960,
"text": "Then, keep the urls in a collection and download using wget.download()"
},
{
"code": null,
"e": 4572,
"s": 4031,
"text": "# url of the raw csv dataseturls = [ 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv', 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv', 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_recovered_global.csv'][wget.download(url) for url in urls]"
},
{
"code": null,
"e": 4681,
"s": 4572,
"text": "Once download complete, it should output like below and the 3 files should appear in your working directory."
},
{
"code": null,
"e": 4811,
"s": 4681,
"text": "['time_series_covid19_confirmed_global.csv', 'time_series_covid19_deaths_global.csv', 'time_series_covid19_recovered_global.csv']"
},
{
"code": null,
"e": 5028,
"s": 4811,
"text": "confirmed_df = pd .read_csv('time_series_covid19_confirmed_global.csv')deaths_df = pd .read_csv('time_series_covid19_deaths_global.csv')recovered_df = pd .read_csv('time_series_covid19_recovered_global.csv')"
},
{
"code": null,
"e": 5164,
"s": 5028,
"text": "Let’s have a quick look at data, for example, confirmed_df.head() shows 93 columns. It should be the same on deaths_df and recovered_df"
},
{
"code": null,
"e": 5294,
"s": 5164,
"text": "By running confirmed_df.columns , deaths_df.columns and recovered_df.columns, all of them should output the same result as below:"
},
{
"code": null,
"e": 5409,
"s": 5294,
"text": "Notice that columns are all date from the 4th column onwards and to get the list of dates confirmed_df.columns[4:]"
},
{
"code": null,
"e": 5620,
"s": 5409,
"text": "Before merging, we need to use melt() to unpivot DataFrames from current wide format into long format. In other words, we are kinda transposing all date columns into values. Here are the main settings for that:"
},
{
"code": null,
"e": 5735,
"s": 5620,
"text": "Use ‘Province/State’, ‘Country/Region’, ‘Lat’, ‘Long’ as identifier variables. We will later use them for merging."
},
{
"code": null,
"e": 5848,
"s": 5735,
"text": "Unpivot date columns (As we saw previously columns[4:]) with variable column ‘Date’ and value column ‘Confirmed’"
},
{
"code": null,
"e": 6391,
"s": 5848,
"text": "dates = confirmed_df.columns[4:]confirmed_df_long = confirmed_df.melt( id_vars=['Province/State', 'Country/Region', 'Lat', 'Long'], value_vars=dates, var_name='Date', value_name='Confirmed')deaths_df_long = deaths_df.melt( id_vars=['Province/State', 'Country/Region', 'Lat', 'Long'], value_vars=dates, var_name='Date', value_name='Deaths')recovered_df_long = recovered_df.melt( id_vars=['Province/State', 'Country/Region', 'Lat', 'Long'], value_vars=dates, var_name='Date', value_name='Recovered')"
},
{
"code": null,
"e": 6585,
"s": 6391,
"text": "Above should return new long DataFrames. All of them are ordered by Date and Country/Region because raw data was already ordered by Country/Region and the date columns are already in ASC order."
},
{
"code": null,
"e": 6626,
"s": 6585,
"text": "Here is the example of confirmed_df_long"
},
{
"code": null,
"e": 6793,
"s": 6626,
"text": "In addition, we have to remove recovered data for Canada due to mismatch issue (🤷♂ Canada recovered data is counted by Country-wise rather than Province/State-wise)."
},
{
"code": null,
"e": 6878,
"s": 6793,
"text": "recovered_df_long = recovered_df_long[recovered_df_long['Country/Region']!='Canada']"
},
{
"code": null,
"e": 6949,
"s": 6878,
"text": "After that, we use merge() to merge the 3 DataFrames one after another"
},
{
"code": null,
"e": 7312,
"s": 6949,
"text": "# Merging confirmed_df_long and deaths_df_longfull_table = confirmed_df_long.merge( right=deaths_df_long, how='left', on=['Province/State', 'Country/Region', 'Date', 'Lat', 'Long'])# Merging full_table and recovered_df_longfull_table = full_table.merge( right=recovered_df_long, how='left', on=['Province/State', 'Country/Region', 'Date', 'Lat', 'Long'])"
},
{
"code": null,
"e": 7389,
"s": 7312,
"text": "Now, we should get a full table with Confirmed, Deaths and Recovered columns"
},
{
"code": null,
"e": 7427,
"s": 7389,
"text": "There are 3 tasks we would like to do"
},
{
"code": null,
"e": 7570,
"s": 7427,
"text": "Converting Date from string to datetimeReplacing missing value NaNCoronavirus cases reported from 3 cruise ships should be treated differently"
},
{
"code": null,
"e": 7610,
"s": 7570,
"text": "Converting Date from string to datetime"
},
{
"code": null,
"e": 7638,
"s": 7610,
"text": "Replacing missing value NaN"
},
{
"code": null,
"e": 7715,
"s": 7638,
"text": "Coronavirus cases reported from 3 cruise ships should be treated differently"
},
{
"code": null,
"e": 7900,
"s": 7715,
"text": "You probably already notice that the values in the new Date column are all string with m/dd/yy format. To convert Date values from string to datetime, let’s use DataFrame.to_datetime()"
},
{
"code": null,
"e": 7956,
"s": 7900,
"text": "full_table['Date'] = pd.to_datetime(full_table['Date'])"
},
{
"code": null,
"e": 8026,
"s": 7956,
"text": "Missing values NaN can be detected by running full_table.isna().sum()"
},
{
"code": null,
"e": 8246,
"s": 8026,
"text": "full_table.isna().sum()Province/State 16198Country/Region 0Lat 0Long 0Date 0Confirmed 0Deaths 0Recovered 1602dtype: int64"
},
{
"code": null,
"e": 8432,
"s": 8246,
"text": "We found a lot NaN in Province/State, and that makes sense as many countries only report the Country-wise data. However, there are 1,602 NaNs in Recovered and let’s replace them with 0."
},
{
"code": null,
"e": 8492,
"s": 8432,
"text": "full_table['Recovered'] = full_table['Recovered'].fillna(0)"
},
{
"code": null,
"e": 8777,
"s": 8492,
"text": "Apart from missing values, there are coronavirus cases reported from 3 cruise ships: Grand Princess, Diamond Princess and MS Zaandam. These data need to be extracted and treated differently due to Province/State and Country/Region mismatch over time. Here is what I was talking about:"
},
{
"code": null,
"e": 8819,
"s": 8777,
"text": "And here is how we extract the ship data."
},
{
"code": null,
"e": 9110,
"s": 8819,
"text": "ship_rows = full_table['Province/State'].str.contains('Grand Princess') | full_table['Province/State'].str.contains('Diamond Princess') | full_table['Country/Region'].str.contains('Diamond Princess') | full_table['Country/Region'].str.contains('MS Zaandam')full_ship = full_table[ship_rows]"
},
{
"code": null,
"e": 9156,
"s": 9110,
"text": "And to get rid of ship data from full_table :"
},
{
"code": null,
"e": 9194,
"s": 9156,
"text": "full_table = full_table[~(ship_rows)]"
},
{
"code": null,
"e": 9214,
"s": 9194,
"text": "5. Data Aggregation"
},
{
"code": null,
"e": 9405,
"s": 9214,
"text": "So far, all the Confirmed, Deaths, Recovered are existing data from raw CSV dataset. Let’s add an active cases column Active, which is calculated by active = confirmed — deaths — recovered ."
},
{
"code": null,
"e": 9547,
"s": 9405,
"text": "# Active Case = confirmed - deaths - recoveredfull_table['Active'] = full_table['Confirmed'] - full_table['Deaths'] - full_table['Recovered']"
},
{
"code": null,
"e": 9591,
"s": 9547,
"text": "And here is what full_table looks like now."
},
{
"code": null,
"e": 9686,
"s": 9591,
"text": "Next, let’s aggregate data into Country/Region wise and group them by Date and Country/Region."
},
{
"code": null,
"e": 9814,
"s": 9686,
"text": "full_grouped = full_table.groupby(['Date', 'Country/Region'])['Confirmed', 'Deaths', 'Recovered', 'Active'].sum().reset_index()"
},
{
"code": null,
"e": 9933,
"s": 9814,
"text": "sum() is to get the total count of ‘Confirmed’, ‘Deaths’, ‘Recovered’, ‘Active’ for the given Date and Country/Region."
},
{
"code": null,
"e": 10022,
"s": 9933,
"text": "reset_index() reset the index and use the default one, which is Date and Country/Region."
},
{
"code": null,
"e": 10067,
"s": 10022,
"text": "And here is what full_grouped looks like now"
},
{
"code": null,
"e": 10200,
"s": 10067,
"text": "Now let’s add day wise New cases, New deaths and New recovered by deducting the corresponding accumulative data on the previous day."
},
{
"code": null,
"e": 10977,
"s": 10200,
"text": "# new cases temp = full_grouped.groupby(['Country/Region', 'Date', ])['Confirmed', 'Deaths', 'Recovered']temp = temp.sum().diff().reset_index()mask = temp['Country/Region'] != temp['Country/Region'].shift(1)temp.loc[mask, 'Confirmed'] = np.nantemp.loc[mask, 'Deaths'] = np.nantemp.loc[mask, 'Recovered'] = np.nan# renaming columnstemp.columns = ['Country/Region', 'Date', 'New cases', 'New deaths', 'New recovered']# merging new valuesfull_grouped = pd.merge(full_grouped, temp, on=['Country/Region', 'Date'])# filling na with 0full_grouped = full_grouped.fillna(0)# fixing data typescols = ['New cases', 'New deaths', 'New recovered']full_grouped[cols] = full_grouped[cols].astype('int')# full_grouped['New cases'] = full_grouped['New cases'].apply(lambda x: 0 if x<0 else x)"
},
{
"code": null,
"e": 11076,
"s": 10977,
"text": "And finally here is the full_grouped. Be aware of that this final output is Country-wise data with"
},
{
"code": null,
"e": 11137,
"s": 11076,
"text": "Confirmed, Deaths, Recovered and Active are cumulative data."
},
{
"code": null,
"e": 11196,
"s": 11137,
"text": "New cases, New deaths and New Recovered are day wise data."
},
{
"code": null,
"e": 11251,
"s": 11196,
"text": "This DataFrames is ordered by Date and Country/Region."
},
{
"code": null,
"e": 11304,
"s": 11251,
"text": "Finally, you can save this final data to a CSV file:"
},
{
"code": null,
"e": 11367,
"s": 11304,
"text": "full_grouped.to_csv('COVID-19-time-series-clean-complete.csv')"
},
{
"code": null,
"e": 11708,
"s": 11367,
"text": "For simplicity, let’s use Python Data Visualization library Altair to create some simple visualizations. Altair is a declarative statistical visualization library for Python, based on Vega and Vega-Lite. Altair offers a powerful and concise visualization grammar that enables you to build a wide range of statistical visualizations quickly."
},
{
"code": null,
"e": 11982,
"s": 11708,
"text": "For Altair installation, I would strongly recommend creating a new Virtual Environment because Altair has a lot of dependencies. Then, activate your Virtual Environment, and run pip install altair vega_datasets to install Altair along with example dataset in vega_datasets."
},
{
"code": null,
"e": 12041,
"s": 11982,
"text": "For tutorials on Virtual Environment, you can take a look:"
},
{
"code": null,
"e": 12064,
"s": 12041,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 12075,
"s": 12064,
"text": "medium.com"
},
{
"code": null,
"e": 12171,
"s": 12075,
"text": "First, let’s import the libraries, load data and select a country, for example, United Kingdom:"
},
{
"code": null,
"e": 12371,
"s": 12171,
"text": "import pandas as pdimport altair as altfull_grouped = pd.read_csv('COVID-19-time-series-clean-complete.csv', parse_dates=['Date'])uk = full_grouped[full_grouped['Country/Region'] == 'United Kingdom']"
},
{
"code": null,
"e": 12428,
"s": 12371,
"text": "Then, let’s create a base chart with the common elements"
},
{
"code": null,
"e": 12521,
"s": 12428,
"text": "base = alt.Chart(uk).mark_bar().encode( x='monthdate(Date):O',).properties( width=500)"
},
{
"code": null,
"e": 12586,
"s": 12521,
"text": "After that, we can concatenate horizontally using the | operator"
},
{
"code": null,
"e": 12662,
"s": 12586,
"text": "First, let’s import the libraries, load data and select a list of countries"
},
{
"code": null,
"e": 12981,
"s": 12662,
"text": "import pandas as pdimport altair as altfull_grouped = pd.read_csv('COVID-19-time-series-clean-complete.csv', parse_dates=['Date'])countries = ['US', 'Italy', 'China', 'Spain', 'Germany', 'France', 'Iran', 'United Kingdom', 'Switzerland']selected_countries = full_grouped[full_grouped['Country/Region'].isin(countries)]"
},
{
"code": null,
"e": 13044,
"s": 12981,
"text": "Let’s create a circle chart to display the day wise New cases,"
},
{
"code": null,
"e": 13343,
"s": 13044,
"text": "alt.Chart(selected_countries).mark_circle().encode( x='monthdate(Date):O', y='Country/Region', color='Country/Region', size=alt.Size('New cases:Q', scale=alt.Scale(range=[0, 1000]), legend=alt.Legend(title='Daily new cases') ) ).properties( width=800, height=300)"
},
{
"code": null,
"e": 13366,
"s": 13343,
"text": "And here is the output"
},
{
"code": null,
"e": 13546,
"s": 13366,
"text": "This article is mainly to show everyone how to process COVID-19 data step by step using Pandas. There are only 2 simple examples in the Data Exploration section for demonstration."
},
{
"code": null,
"e": 13639,
"s": 13546,
"text": "If you are interested in learning Altair, you can take a look at the following two articles."
},
{
"code": null,
"e": 13662,
"s": 13639,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 13685,
"s": 13662,
"text": "towardsdatascience.com"
}
] |
Speeding up Model Training with Multithreading | by Edward Elson Kosasih | Towards Data Science
|
Waiting for model training to finish could sometimes feel frustrating. Speeding up this process is one of the topmost priority in probably every data scientist’s mind. There are a few approaches that one could try, just to name a few: hardware upgrade (faster CPU/GPU) and model-specific tweaks (e.g. for backpropagation, one can try different optimizers to enable faster convergence). But what if your budget application for hardware upgrade has been pending forever, or none of the existing optimizer bring significant improvement?
Not all hope is lost. We can still make our program more effective. Today, I’m going to talk about multithreading. Specifically, how to concurrently run (1) data loading from disk to RAM (which is CPU-intensive) and (2) model training (which usually is GPU-intensive).
First, let’s load the library dependencies.
import threadingimport timefrom tqdm import tqdm
Assume we have 2 functions: Data loading and Model training. For the sake of this tutorial, I will replace the real function with a time delay method. In this case, Data loading takes 2 seconds while Model training 3 seconds.
# replace with train model - suppose it takes 3 seconds to traindef _trainModel(): time.sleep(3) return# replace with load data function - suppose it takes 2 seconds to loaddef _loadData(): time.sleep(2) return
Suppose our model training is in form of backpropagation, which requires many epochs to run. We have chosen an arbitrary number of epochs to loop for: 10 times
# assume we loop 10 timesepochs = 10
If we run the loop as per normal, which is to alternate between data loading and model training, we can see that it takes 50 seconds in total to finish the 10 epochs. From the plot below (which is generated by tqdm), we see that each epoch takes about 5 seconds (2 seconds to load data and 3 seconds to train the model).
original time = data_loading_time + training_model_time
# without multithreading# use with for tqdm to properly shut tqdm down if exception appearswith tqdm(range(epochs)) as epochLoop: for _ in epochLoop: # loadData _loadData() # trainModel _trainModel()
Next, we’ll try to run data loading and model training in parallel with python’s threading module. First we have to create a class for each function, extending the threading.Thread parent class.
class TrainModel (threading.Thread): def __init__(self, data): threading.Thread.__init__(self) self.data = data def run(self): # return model loss self._return = _trainModel() def join(self): threading.Thread.join(self) return self._returnclass LoadData (threading.Thread): def __init__(self, filenames): threading.Thread.__init__(self) self.filenames = filenames def run(self): # return data self._return = _loadData() def join(self): threading.Thread.join(self) return self._return
We can then run the functions again by calling the generated thread classes. Here, we can observe that the time taken for 10 epochs has dropped to 30 seconds. That’s a 40% improvement (compared to 50 seconds before)! What happens here is that we’re running both data loading and model training in parallel. The time taken per epoch is no longer a sum of the two functions. It is now the maximum of the two.
multithreaded time = max(data_loading_time, training_model_time)
# with multithreading# use with for tqdm to properly shut tqdm down if exception appearswith tqdm(range(epochs)) as epochLoop: for _ in epochLoop: # loadData loadThread = LoadData(None) loadThread.start() # trainModel trainThread = TrainModel(None) trainThread.start() # only continue if both threads are done modelLoss = trainThread.join() data = loadThread.join()
We have just seen that multithreading could help to reduce the time taken per epoch in model training. Note that this method will not help much if:
there’s no more CPU resources left for another thread to be spawnedthe original time taken is dominated by a process. If model training takes 10 seconds and data loading 0.1 second, then what normally consumes 101 seconds in total (for 10 epochs) will become 100 seconds. That’s equivalent to just about 1% improvement. In other words, the max of all processes’ time should ideally be way smaller than the their sum in order for multithreading to be effective.
there’s no more CPU resources left for another thread to be spawned
the original time taken is dominated by a process. If model training takes 10 seconds and data loading 0.1 second, then what normally consumes 101 seconds in total (for 10 epochs) will become 100 seconds. That’s equivalent to just about 1% improvement. In other words, the max of all processes’ time should ideally be way smaller than the their sum in order for multithreading to be effective.
|
[
{
"code": null,
"e": 706,
"s": 172,
"text": "Waiting for model training to finish could sometimes feel frustrating. Speeding up this process is one of the topmost priority in probably every data scientist’s mind. There are a few approaches that one could try, just to name a few: hardware upgrade (faster CPU/GPU) and model-specific tweaks (e.g. for backpropagation, one can try different optimizers to enable faster convergence). But what if your budget application for hardware upgrade has been pending forever, or none of the existing optimizer bring significant improvement?"
},
{
"code": null,
"e": 975,
"s": 706,
"text": "Not all hope is lost. We can still make our program more effective. Today, I’m going to talk about multithreading. Specifically, how to concurrently run (1) data loading from disk to RAM (which is CPU-intensive) and (2) model training (which usually is GPU-intensive)."
},
{
"code": null,
"e": 1019,
"s": 975,
"text": "First, let’s load the library dependencies."
},
{
"code": null,
"e": 1068,
"s": 1019,
"text": "import threadingimport timefrom tqdm import tqdm"
},
{
"code": null,
"e": 1294,
"s": 1068,
"text": "Assume we have 2 functions: Data loading and Model training. For the sake of this tutorial, I will replace the real function with a time delay method. In this case, Data loading takes 2 seconds while Model training 3 seconds."
},
{
"code": null,
"e": 1509,
"s": 1294,
"text": "# replace with train model - suppose it takes 3 seconds to traindef _trainModel(): time.sleep(3) return# replace with load data function - suppose it takes 2 seconds to loaddef _loadData(): time.sleep(2) return"
},
{
"code": null,
"e": 1669,
"s": 1509,
"text": "Suppose our model training is in form of backpropagation, which requires many epochs to run. We have chosen an arbitrary number of epochs to loop for: 10 times"
},
{
"code": null,
"e": 1706,
"s": 1669,
"text": "# assume we loop 10 timesepochs = 10"
},
{
"code": null,
"e": 2027,
"s": 1706,
"text": "If we run the loop as per normal, which is to alternate between data loading and model training, we can see that it takes 50 seconds in total to finish the 10 epochs. From the plot below (which is generated by tqdm), we see that each epoch takes about 5 seconds (2 seconds to load data and 3 seconds to train the model)."
},
{
"code": null,
"e": 2083,
"s": 2027,
"text": "original time = data_loading_time + training_model_time"
},
{
"code": null,
"e": 2300,
"s": 2083,
"text": "# without multithreading# use with for tqdm to properly shut tqdm down if exception appearswith tqdm(range(epochs)) as epochLoop: for _ in epochLoop: # loadData _loadData() # trainModel _trainModel()"
},
{
"code": null,
"e": 2495,
"s": 2300,
"text": "Next, we’ll try to run data loading and model training in parallel with python’s threading module. First we have to create a class for each function, extending the threading.Thread parent class."
},
{
"code": null,
"e": 3093,
"s": 2495,
"text": "class TrainModel (threading.Thread): def __init__(self, data): threading.Thread.__init__(self) self.data = data def run(self): # return model loss self._return = _trainModel() def join(self): threading.Thread.join(self) return self._returnclass LoadData (threading.Thread): def __init__(self, filenames): threading.Thread.__init__(self) self.filenames = filenames def run(self): # return data self._return = _loadData() def join(self): threading.Thread.join(self) return self._return"
},
{
"code": null,
"e": 3500,
"s": 3093,
"text": "We can then run the functions again by calling the generated thread classes. Here, we can observe that the time taken for 10 epochs has dropped to 30 seconds. That’s a 40% improvement (compared to 50 seconds before)! What happens here is that we’re running both data loading and model training in parallel. The time taken per epoch is no longer a sum of the two functions. It is now the maximum of the two."
},
{
"code": null,
"e": 3565,
"s": 3500,
"text": "multithreaded time = max(data_loading_time, training_model_time)"
},
{
"code": null,
"e": 3967,
"s": 3565,
"text": "# with multithreading# use with for tqdm to properly shut tqdm down if exception appearswith tqdm(range(epochs)) as epochLoop: for _ in epochLoop: # loadData loadThread = LoadData(None) loadThread.start() # trainModel trainThread = TrainModel(None) trainThread.start() # only continue if both threads are done modelLoss = trainThread.join() data = loadThread.join()"
},
{
"code": null,
"e": 4115,
"s": 3967,
"text": "We have just seen that multithreading could help to reduce the time taken per epoch in model training. Note that this method will not help much if:"
},
{
"code": null,
"e": 4576,
"s": 4115,
"text": "there’s no more CPU resources left for another thread to be spawnedthe original time taken is dominated by a process. If model training takes 10 seconds and data loading 0.1 second, then what normally consumes 101 seconds in total (for 10 epochs) will become 100 seconds. That’s equivalent to just about 1% improvement. In other words, the max of all processes’ time should ideally be way smaller than the their sum in order for multithreading to be effective."
},
{
"code": null,
"e": 4644,
"s": 4576,
"text": "there’s no more CPU resources left for another thread to be spawned"
}
] |
_Generic keyword in C - GeeksforGeeks
|
03 Jan, 2019
A major drawback of Macro in C/C++ is that the arguments are strongly typed checked i.e. a macro can operate on different types of variables(like char, int ,double,..) without type checking.
// C program to illustrate macro function.#include<stdio.h>#define INC(P) ++Pint main(){ char *p = "Geeks"; int x = 10; printf("%s ", INC(p)); printf("%d", INC(x)); return 0;}
Output:
eeks 11
Therefore we avoid to use Macro. But after the implementation of C11 standard in C programming, we can use Macro with the help of a new keyword i.e. “_Generic”. We can define MACRO for the different types of data types. For example, the following macro INC(x) translates to INCl(x), INC(x) or INCf(x) depending on the type of x:
#define INC(x) _Generic((x), long double: INCl, \
default: INC, \
float: INCf)(x)
Example:-
// C program to illustrate macro function.#include <stdio.h>int main(void){ // _Generic keyword acts as a switch that chooses // operation based on data type of argument. printf("%d\n", _Generic( 1.0L, float:1, double:2, long double:3, default:0)); printf("%d\n", _Generic( 1L, float:1, double:2, long double:3, default:0)); printf("%d\n", _Generic( 1.0L, float:1, double:2, long double:3)); return 0;}
Output:Note: If you are running C11 compiler then the below mentioned output will be come.
3
0
3
// C program to illustrate macro function.#include <stdio.h>#define geeks(T) _Generic( (T), char: 1, int: 2, long: 3, default: 0)int main(void){ // char returns ASCII value which is int type. printf("%d\n", geeks('A')); // Here A is a string. printf("%d",geeks("A")); return 0;}
Output:
2
0
This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
AJ04
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
Command line arguments in C/C++
Left Shift and Right Shift Operators in C/C++
Different methods to reverse a string in C/C++
Substring in C++
Function Pointer in C
TCP Server-Client implementation in C
Enumeration (or enum) in C
Converting Strings to Numbers in C/C++
|
[
{
"code": null,
"e": 24258,
"s": 24230,
"text": "\n03 Jan, 2019"
},
{
"code": null,
"e": 24449,
"s": 24258,
"text": "A major drawback of Macro in C/C++ is that the arguments are strongly typed checked i.e. a macro can operate on different types of variables(like char, int ,double,..) without type checking."
},
{
"code": "// C program to illustrate macro function.#include<stdio.h>#define INC(P) ++Pint main(){ char *p = \"Geeks\"; int x = 10; printf(\"%s \", INC(p)); printf(\"%d\", INC(x)); return 0;}",
"e": 24641,
"s": 24449,
"text": null
},
{
"code": null,
"e": 24649,
"s": 24641,
"text": "Output:"
},
{
"code": null,
"e": 24658,
"s": 24649,
"text": "eeks 11\n"
},
{
"code": null,
"e": 24987,
"s": 24658,
"text": "Therefore we avoid to use Macro. But after the implementation of C11 standard in C programming, we can use Macro with the help of a new keyword i.e. “_Generic”. We can define MACRO for the different types of data types. For example, the following macro INC(x) translates to INCl(x), INC(x) or INCf(x) depending on the type of x:"
},
{
"code": null,
"e": 25130,
"s": 24987,
"text": "#define INC(x) _Generic((x), long double: INCl, \\\n default: INC, \\\n float: INCf)(x)\n"
},
{
"code": null,
"e": 25140,
"s": 25130,
"text": "Example:-"
},
{
"code": "// C program to illustrate macro function.#include <stdio.h>int main(void){ // _Generic keyword acts as a switch that chooses // operation based on data type of argument. printf(\"%d\\n\", _Generic( 1.0L, float:1, double:2, long double:3, default:0)); printf(\"%d\\n\", _Generic( 1L, float:1, double:2, long double:3, default:0)); printf(\"%d\\n\", _Generic( 1.0L, float:1, double:2, long double:3)); return 0;}",
"e": 25657,
"s": 25140,
"text": null
},
{
"code": null,
"e": 25748,
"s": 25657,
"text": "Output:Note: If you are running C11 compiler then the below mentioned output will be come."
},
{
"code": null,
"e": 25755,
"s": 25748,
"text": "3\n0\n3\n"
},
{
"code": "// C program to illustrate macro function.#include <stdio.h>#define geeks(T) _Generic( (T), char: 1, int: 2, long: 3, default: 0)int main(void){ // char returns ASCII value which is int type. printf(\"%d\\n\", geeks('A')); // Here A is a string. printf(\"%d\",geeks(\"A\")); return 0;}",
"e": 26060,
"s": 25755,
"text": null
},
{
"code": null,
"e": 26068,
"s": 26060,
"text": "Output:"
},
{
"code": null,
"e": 26073,
"s": 26068,
"text": "2\n0\n"
},
{
"code": null,
"e": 26379,
"s": 26073,
"text": "This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 26504,
"s": 26379,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 26509,
"s": 26504,
"text": "AJ04"
},
{
"code": null,
"e": 26520,
"s": 26509,
"text": "C Language"
},
{
"code": null,
"e": 26618,
"s": 26520,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26627,
"s": 26618,
"text": "Comments"
},
{
"code": null,
"e": 26640,
"s": 26627,
"text": "Old Comments"
},
{
"code": null,
"e": 26675,
"s": 26640,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 26703,
"s": 26675,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 26735,
"s": 26703,
"text": "Command line arguments in C/C++"
},
{
"code": null,
"e": 26781,
"s": 26735,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 26828,
"s": 26781,
"text": "Different methods to reverse a string in C/C++"
},
{
"code": null,
"e": 26845,
"s": 26828,
"text": "Substring in C++"
},
{
"code": null,
"e": 26867,
"s": 26845,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 26905,
"s": 26867,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 26932,
"s": 26905,
"text": "Enumeration (or enum) in C"
}
] |
How to create a Horizontal Navigation Bar in HTML and CSS?
|
30 Dec, 2020
In this article, we will try to create a navigation bar horizontally. To understand this article, we need to know some basics of HTML and CSS.
Approach:
We will create the structure of the navigation bar which will later be displayed horizontally.
The tags that we will use for this is <nav> tag and <ul> tag. Here nav tag will be acting as a container for the list of items that will be used for navigation. Ul will also be used to list the number of items that the user will navigate.
Now we have the structure of the navigation bar. So we will apply CSS properties like flex to make the navigation bar appeared horizontal.
Example:
HTML
<!DOCTYPE html><html> <head> <title> Horizontal Navigation Bar </title> </head> <body> <!-- here in nav tag used two classes that is navbar and background--> <!-- each class declared in nav tag will be used to design the form using CSS--> <nav class="navbar background"> <!-- we have used list tag that is ul to list the items--> <ul class="nav-list"> <li><a href="#Car">Car</a></li> <li><a href="#file">file</a></li> </ul> <!-- we have used rightnav in order to design the seachbar properly by using CSS--> <div class="rightNav"> <!-- the value that search bar will take is text --> <input type="text" name="search" id="search" /> <button class="btn btn-sm">Search</button> </div> </nav> </body></html>
The output of the code:
Now we have the structure of the table. So we will design the navigation bar, and we will use property like flex to make the navigation bar appear horizontal.
CSS
* {/* Here we set the margin and padding 0 */ margin: 0; padding: 0;} .navbar { display: flex; /* This is used to make the navbar sticky, So that the navbar stays at the top part even if we scroll */ position: sticky; align-items: center; justify-content: center; top: 0px; /*it specifies the mouse cursor to be displayed when it is pointed over the element */ cursor: pointer;} .nav-list { width: 50%; display: flex;} .nav-list li { list-style: none; padding: 26px 30px;} .nav-list li a { text-decoration: none; color: white;} .nav-list li a:hover { color: black;} .rightNav { width: 50%; text-align: right;} #search { padding: 5px; font-size: 17px; border: 2px solid grey; border-radius: 9px;} .background { background: rgba(0, 0, 0, 0.4) url("https://media.geeksforgeeks.org/wp-content/uploads/20201215124609/Capture-300x14.PNG"); background-blend-mode: darken; background-size: cover;}
Final Code: This is the combination of all the above codes –
HTML
<!DOCTYPE html><html> <head> <title> Horizontal Navigation Bar </title> <style> * {/* Here i made the margin and padding 0 */ margin: 0; padding: 0;} .navbar { display: flex; /* This is used to make the navbar sticky, So that the navbar stays at the top part even if we scroll */ position: sticky; align-items: center; justify-content: center; top: 0px; /*it specifies the mouse cursor to be displayed when it is pointed over the element */ cursor: pointer;} .nav-list { width: 50%; display: flex;} .nav-list li { list-style: none; padding: 26px 30px;} .nav-list li a { text-decoration: none; color: white;} .nav-list li a:hover { color: black;} .rightNav { width: 50%; text-align: right;} #search { padding: 5px; font-size: 17px; border: 2px solid grey; border-radius: 9px;} .background { background: rgba(0, 0, 0, 0.4) url("https://media.geeksforgeeks.org/wp-content/uploads/20201215124609/Capture-300x14.PNG"); background-blend-mode: darken; background-size: cover;} </style> </head> <body> <!-- here in nav tag i have used two classes that is navbar and background--> <!-- each class declared in nav tag will be used to design the form using CSS--> <nav class="navbar background"> <!-- we have used list tag that is ul to list the items--> <ul class="nav-list"> <li><a href="#Car">Car</a></li> <li><a href="#file">file</a></li> </ul> <!-- we have used rightnav in order to design the seachbar properly by using CSS--> <div class="rightNav"> <!-- the value that search bar will take is text --> <input type="text" name="search" id="search" /> <button class="btn btn-sm">Search</button> </div> </nav> </body></html>
Output:
CSS-Misc
HTML-Misc
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
Build a Survey Form using HTML and CSS
Design a web page using HTML and CSS
Form validation using jQuery
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Design a Tribute Page using HTML & CSS
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Dec, 2020"
},
{
"code": null,
"e": 171,
"s": 28,
"text": "In this article, we will try to create a navigation bar horizontally. To understand this article, we need to know some basics of HTML and CSS."
},
{
"code": null,
"e": 181,
"s": 171,
"text": "Approach:"
},
{
"code": null,
"e": 276,
"s": 181,
"text": "We will create the structure of the navigation bar which will later be displayed horizontally."
},
{
"code": null,
"e": 515,
"s": 276,
"text": "The tags that we will use for this is <nav> tag and <ul> tag. Here nav tag will be acting as a container for the list of items that will be used for navigation. Ul will also be used to list the number of items that the user will navigate."
},
{
"code": null,
"e": 655,
"s": 515,
"text": "Now we have the structure of the navigation bar. So we will apply CSS properties like flex to make the navigation bar appeared horizontal. "
},
{
"code": null,
"e": 664,
"s": 655,
"text": "Example:"
},
{
"code": null,
"e": 669,
"s": 664,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title> Horizontal Navigation Bar </title> </head> <body> <!-- here in nav tag used two classes that is navbar and background--> <!-- each class declared in nav tag will be used to design the form using CSS--> <nav class=\"navbar background\"> <!-- we have used list tag that is ul to list the items--> <ul class=\"nav-list\"> <li><a href=\"#Car\">Car</a></li> <li><a href=\"#file\">file</a></li> </ul> <!-- we have used rightnav in order to design the seachbar properly by using CSS--> <div class=\"rightNav\"> <!-- the value that search bar will take is text --> <input type=\"text\" name=\"search\" id=\"search\" /> <button class=\"btn btn-sm\">Search</button> </div> </nav> </body></html>",
"e": 1632,
"s": 669,
"text": null
},
{
"code": null,
"e": 1656,
"s": 1632,
"text": "The output of the code:"
},
{
"code": null,
"e": 1816,
"s": 1656,
"text": "Now we have the structure of the table. So we will design the navigation bar, and we will use property like flex to make the navigation bar appear horizontal. "
},
{
"code": null,
"e": 1820,
"s": 1816,
"text": "CSS"
},
{
"code": "* {/* Here we set the margin and padding 0 */ margin: 0; padding: 0;} .navbar { display: flex; /* This is used to make the navbar sticky, So that the navbar stays at the top part even if we scroll */ position: sticky; align-items: center; justify-content: center; top: 0px; /*it specifies the mouse cursor to be displayed when it is pointed over the element */ cursor: pointer;} .nav-list { width: 50%; display: flex;} .nav-list li { list-style: none; padding: 26px 30px;} .nav-list li a { text-decoration: none; color: white;} .nav-list li a:hover { color: black;} .rightNav { width: 50%; text-align: right;} #search { padding: 5px; font-size: 17px; border: 2px solid grey; border-radius: 9px;} .background { background: rgba(0, 0, 0, 0.4) url(\"https://media.geeksforgeeks.org/wp-content/uploads/20201215124609/Capture-300x14.PNG\"); background-blend-mode: darken; background-size: cover;}",
"e": 2801,
"s": 1820,
"text": null
},
{
"code": null,
"e": 2862,
"s": 2801,
"text": "Final Code: This is the combination of all the above codes –"
},
{
"code": null,
"e": 2867,
"s": 2862,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title> Horizontal Navigation Bar </title> <style> * {/* Here i made the margin and padding 0 */ margin: 0; padding: 0;} .navbar { display: flex; /* This is used to make the navbar sticky, So that the navbar stays at the top part even if we scroll */ position: sticky; align-items: center; justify-content: center; top: 0px; /*it specifies the mouse cursor to be displayed when it is pointed over the element */ cursor: pointer;} .nav-list { width: 50%; display: flex;} .nav-list li { list-style: none; padding: 26px 30px;} .nav-list li a { text-decoration: none; color: white;} .nav-list li a:hover { color: black;} .rightNav { width: 50%; text-align: right;} #search { padding: 5px; font-size: 17px; border: 2px solid grey; border-radius: 9px;} .background { background: rgba(0, 0, 0, 0.4) url(\"https://media.geeksforgeeks.org/wp-content/uploads/20201215124609/Capture-300x14.PNG\"); background-blend-mode: darken; background-size: cover;} </style> </head> <body> <!-- here in nav tag i have used two classes that is navbar and background--> <!-- each class declared in nav tag will be used to design the form using CSS--> <nav class=\"navbar background\"> <!-- we have used list tag that is ul to list the items--> <ul class=\"nav-list\"> <li><a href=\"#Car\">Car</a></li> <li><a href=\"#file\">file</a></li> </ul> <!-- we have used rightnav in order to design the seachbar properly by using CSS--> <div class=\"rightNav\"> <!-- the value that search bar will take is text --> <input type=\"text\" name=\"search\" id=\"search\" /> <button class=\"btn btn-sm\">Search</button> </div> </nav> </body></html>",
"e": 4854,
"s": 2867,
"text": null
},
{
"code": null,
"e": 4862,
"s": 4854,
"text": "Output:"
},
{
"code": null,
"e": 4871,
"s": 4862,
"text": "CSS-Misc"
},
{
"code": null,
"e": 4881,
"s": 4871,
"text": "HTML-Misc"
},
{
"code": null,
"e": 4885,
"s": 4881,
"text": "CSS"
},
{
"code": null,
"e": 4890,
"s": 4885,
"text": "HTML"
},
{
"code": null,
"e": 4907,
"s": 4890,
"text": "Web Technologies"
},
{
"code": null,
"e": 4912,
"s": 4907,
"text": "HTML"
},
{
"code": null,
"e": 5010,
"s": 4912,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5049,
"s": 5010,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 5088,
"s": 5049,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 5127,
"s": 5088,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 5164,
"s": 5127,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 5193,
"s": 5164,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 5217,
"s": 5193,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 5270,
"s": 5217,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 5330,
"s": 5270,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 5391,
"s": 5330,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
Ruby | Array max() function
|
06 Dec, 2019
Array#max() : max() is a Array class method which returns the maximum value in this array.
Syntax: Array.max()
Parameter: Array
Return: the maximum value in this array.
Example #1 :
# Ruby code for max() method # declaring arraya = %w[for geeks] # max method exampleputs "max() method form : #{a.max()}\n\n" puts "max() method form : #{a.max(2)}\n\n"
Output :
max() method form : geeks
max() method form : ["geeks", "for"]
Example #2 :
# Ruby code for max() method # declaring arraya = %w[hi I can code for geeks] # max method exampleputs "max() method form : #{a.max(4)}\n\n" puts "max() method form : #{a.max(1)}\n\n"
Output :
max() method form : ["hi", "geeks", "for", "code"]
max() method form : ["hi"]
Ruby Array-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Make a Custom Array of Hashes in Ruby?
Ruby | Array count() operation
Include v/s Extend in Ruby
Global Variable in Ruby
Ruby | Array select() function
Ruby | Enumerator each_with_index function
Ruby | Data Types
Ruby | Case Statement
Ruby | Hash delete() function
Ruby | unless Statement and unless Modifier
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Dec, 2019"
},
{
"code": null,
"e": 119,
"s": 28,
"text": "Array#max() : max() is a Array class method which returns the maximum value in this array."
},
{
"code": null,
"e": 139,
"s": 119,
"text": "Syntax: Array.max()"
},
{
"code": null,
"e": 156,
"s": 139,
"text": "Parameter: Array"
},
{
"code": null,
"e": 197,
"s": 156,
"text": "Return: the maximum value in this array."
},
{
"code": null,
"e": 210,
"s": 197,
"text": "Example #1 :"
},
{
"code": "# Ruby code for max() method # declaring arraya = %w[for geeks] # max method exampleputs \"max() method form : #{a.max()}\\n\\n\" puts \"max() method form : #{a.max(2)}\\n\\n\"",
"e": 384,
"s": 210,
"text": null
},
{
"code": null,
"e": 393,
"s": 384,
"text": "Output :"
},
{
"code": null,
"e": 459,
"s": 393,
"text": "max() method form : geeks\n\nmax() method form : [\"geeks\", \"for\"]\n\n"
},
{
"code": null,
"e": 472,
"s": 459,
"text": "Example #2 :"
},
{
"code": "# Ruby code for max() method # declaring arraya = %w[hi I can code for geeks] # max method exampleputs \"max() method form : #{a.max(4)}\\n\\n\" puts \"max() method form : #{a.max(1)}\\n\\n\"",
"e": 661,
"s": 472,
"text": null
},
{
"code": null,
"e": 670,
"s": 661,
"text": "Output :"
},
{
"code": null,
"e": 750,
"s": 670,
"text": "max() method form : [\"hi\", \"geeks\", \"for\", \"code\"]\n\nmax() method form : [\"hi\"]\n"
},
{
"code": null,
"e": 767,
"s": 750,
"text": "Ruby Array-class"
},
{
"code": null,
"e": 780,
"s": 767,
"text": "Ruby-Methods"
},
{
"code": null,
"e": 785,
"s": 780,
"text": "Ruby"
},
{
"code": null,
"e": 883,
"s": 785,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 929,
"s": 883,
"text": "How to Make a Custom Array of Hashes in Ruby?"
},
{
"code": null,
"e": 960,
"s": 929,
"text": "Ruby | Array count() operation"
},
{
"code": null,
"e": 987,
"s": 960,
"text": "Include v/s Extend in Ruby"
},
{
"code": null,
"e": 1011,
"s": 987,
"text": "Global Variable in Ruby"
},
{
"code": null,
"e": 1042,
"s": 1011,
"text": "Ruby | Array select() function"
},
{
"code": null,
"e": 1085,
"s": 1042,
"text": "Ruby | Enumerator each_with_index function"
},
{
"code": null,
"e": 1103,
"s": 1085,
"text": "Ruby | Data Types"
},
{
"code": null,
"e": 1125,
"s": 1103,
"text": "Ruby | Case Statement"
},
{
"code": null,
"e": 1155,
"s": 1125,
"text": "Ruby | Hash delete() function"
}
] |
PyQt5 QListWidget – Setting Current Item
|
01 Aug, 2020
In this article we will see how we can set the current item of the QListWidget. QListWidget is a convenience class that provides a list view with a classic item-based interface for adding and removing items. QListWidget uses an internal model to manage each QListWidgetItem in the list. Current item can be set from the list of item. Unless the selection mode is NoSelection, the item is also selected.
In order to do this we will use setCurrentItem method with the list widget object.
Syntax : list_widget.setCurrentItem(item)
Argument : It takes QListWidgetItem as argument
Return : It returns None
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QListWidget list_widget = QListWidget(self) # setting geometry to it list_widget.setGeometry(50, 70, 150, 60) # list widget items item1 = QListWidgetItem("A") item2 = QListWidgetItem("B") item3 = QListWidgetItem("C") # adding items to the list widget list_widget.addItem(item1) list_widget.addItem(item2) list_widget.addItem(item3) # setting current item list_widget.setCurrentItem(item2) # creating a label label = QLabel("GeesforGeeks", self) # setting geometry to the label label.setGeometry(230, 80, 300, 80) # making label multi line label.setWordWrap(True) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
Python PyQt-QListWidget
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Aug, 2020"
},
{
"code": null,
"e": 431,
"s": 28,
"text": "In this article we will see how we can set the current item of the QListWidget. QListWidget is a convenience class that provides a list view with a classic item-based interface for adding and removing items. QListWidget uses an internal model to manage each QListWidgetItem in the list. Current item can be set from the list of item. Unless the selection mode is NoSelection, the item is also selected."
},
{
"code": null,
"e": 514,
"s": 431,
"text": "In order to do this we will use setCurrentItem method with the list widget object."
},
{
"code": null,
"e": 556,
"s": 514,
"text": "Syntax : list_widget.setCurrentItem(item)"
},
{
"code": null,
"e": 604,
"s": 556,
"text": "Argument : It takes QListWidgetItem as argument"
},
{
"code": null,
"e": 629,
"s": 604,
"text": "Return : It returns None"
},
{
"code": null,
"e": 657,
"s": 629,
"text": "Below is the implementation"
},
{
"code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QListWidget list_widget = QListWidget(self) # setting geometry to it list_widget.setGeometry(50, 70, 150, 60) # list widget items item1 = QListWidgetItem(\"A\") item2 = QListWidgetItem(\"B\") item3 = QListWidgetItem(\"C\") # adding items to the list widget list_widget.addItem(item1) list_widget.addItem(item2) list_widget.addItem(item3) # setting current item list_widget.setCurrentItem(item2) # creating a label label = QLabel(\"GeesforGeeks\", self) # setting geometry to the label label.setGeometry(230, 80, 300, 80) # making label multi line label.setWordWrap(True) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 2063,
"s": 657,
"text": null
},
{
"code": null,
"e": 2072,
"s": 2063,
"text": "Output :"
},
{
"code": null,
"e": 2096,
"s": 2072,
"text": "Python PyQt-QListWidget"
},
{
"code": null,
"e": 2107,
"s": 2096,
"text": "Python-gui"
},
{
"code": null,
"e": 2119,
"s": 2107,
"text": "Python-PyQt"
},
{
"code": null,
"e": 2126,
"s": 2119,
"text": "Python"
},
{
"code": null,
"e": 2224,
"s": 2126,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2256,
"s": 2224,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2283,
"s": 2256,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2314,
"s": 2283,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2337,
"s": 2314,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2358,
"s": 2337,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2414,
"s": 2358,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2456,
"s": 2414,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2498,
"s": 2456,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2537,
"s": 2498,
"text": "Python | Get unique values from a list"
}
] |
Set equals() method in Java with Examples
|
09 Aug, 2019
The equals() method of java.util.Set class is used to verify the equality of an Object with a Set and compare them. The method returns true if the size of both the sets are equal and both contain the same elements.
Syntax:
public boolean equals(Object o)
Parameters: This method takes the object o as a parameter to be compared for equality with this set.
Returns Value: This method returns true if the specified object is equal to this set.
Below are the examples to illustrate the equals() method.
Example 1:
// Java program to demonstrate equals()// method of Set import java.util.*; public class GFG { public static void main(String[] argv) { // Creating object of Set Set<String> arrset1 = new HashSet<String>(); // Populating arrset1 arrset1.add("A"); arrset1.add("B"); arrset1.add("C"); arrset1.add("D"); arrset1.add("E"); // print arrset1 System.out.println("First Set: " + arrset1); // Creating another object of Set Set<String> arrset2 = new HashSet<String>(); // Populating arrset2 arrset2.add("A"); arrset2.add("B"); arrset2.add("C"); arrset2.add("D"); arrset2.add("E"); // print arrset2 System.out.println("Second Set: " + arrset2); // comparing first Set to another // using equals() method boolean value = arrset1.equals(arrset2); // print the value System.out.println("Are both set equal? " + value); }}
First Set: [A, B, C, D, E]
Second Set: [A, B, C, D, E]
Are both set equal? true
Example 2:
// Java program to demonstrate equals()// method of Set import java.util.*; public class GFG1 { public static void main(String[] argv) { // Creating object of Set Set<Integer> arrset1 = new HashSet<Integer>(); // Populating arrset1 arrset1.add(10); arrset1.add(20); arrset1.add(30); arrset1.add(40); arrset1.add(50); // print arrset1 System.out.println("First Set: " + arrset1); // Creating another object of Set Set<Integer> arrset2 = new HashSet<Integer>(); // Populating arrset2 arrset2.add(10); arrset2.add(20); arrset2.add(30); // print arrset2 System.out.println("Second Set: " + arrset2); // comparing first Set to another // using equals() method boolean value = arrset1.equals(arrset2); // print the value System.out.println("Are both set equal? " + value); }}
First Set: [50, 20, 40, 10, 30]
Second Set: [20, 10, 30]
Are both set equal? false
Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#equals(java.lang.Object)
sdkbnv
Java-Collections
Java-Functions
java-set
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Aug, 2019"
},
{
"code": null,
"e": 243,
"s": 28,
"text": "The equals() method of java.util.Set class is used to verify the equality of an Object with a Set and compare them. The method returns true if the size of both the sets are equal and both contain the same elements."
},
{
"code": null,
"e": 251,
"s": 243,
"text": "Syntax:"
},
{
"code": null,
"e": 283,
"s": 251,
"text": "public boolean equals(Object o)"
},
{
"code": null,
"e": 384,
"s": 283,
"text": "Parameters: This method takes the object o as a parameter to be compared for equality with this set."
},
{
"code": null,
"e": 470,
"s": 384,
"text": "Returns Value: This method returns true if the specified object is equal to this set."
},
{
"code": null,
"e": 528,
"s": 470,
"text": "Below are the examples to illustrate the equals() method."
},
{
"code": null,
"e": 539,
"s": 528,
"text": "Example 1:"
},
{
"code": "// Java program to demonstrate equals()// method of Set import java.util.*; public class GFG { public static void main(String[] argv) { // Creating object of Set Set<String> arrset1 = new HashSet<String>(); // Populating arrset1 arrset1.add(\"A\"); arrset1.add(\"B\"); arrset1.add(\"C\"); arrset1.add(\"D\"); arrset1.add(\"E\"); // print arrset1 System.out.println(\"First Set: \" + arrset1); // Creating another object of Set Set<String> arrset2 = new HashSet<String>(); // Populating arrset2 arrset2.add(\"A\"); arrset2.add(\"B\"); arrset2.add(\"C\"); arrset2.add(\"D\"); arrset2.add(\"E\"); // print arrset2 System.out.println(\"Second Set: \" + arrset2); // comparing first Set to another // using equals() method boolean value = arrset1.equals(arrset2); // print the value System.out.println(\"Are both set equal? \" + value); }}",
"e": 1628,
"s": 539,
"text": null
},
{
"code": null,
"e": 1709,
"s": 1628,
"text": "First Set: [A, B, C, D, E]\nSecond Set: [A, B, C, D, E]\nAre both set equal? true\n"
},
{
"code": null,
"e": 1720,
"s": 1709,
"text": "Example 2:"
},
{
"code": "// Java program to demonstrate equals()// method of Set import java.util.*; public class GFG1 { public static void main(String[] argv) { // Creating object of Set Set<Integer> arrset1 = new HashSet<Integer>(); // Populating arrset1 arrset1.add(10); arrset1.add(20); arrset1.add(30); arrset1.add(40); arrset1.add(50); // print arrset1 System.out.println(\"First Set: \" + arrset1); // Creating another object of Set Set<Integer> arrset2 = new HashSet<Integer>(); // Populating arrset2 arrset2.add(10); arrset2.add(20); arrset2.add(30); // print arrset2 System.out.println(\"Second Set: \" + arrset2); // comparing first Set to another // using equals() method boolean value = arrset1.equals(arrset2); // print the value System.out.println(\"Are both set equal? \" + value); }}",
"e": 2704,
"s": 1720,
"text": null
},
{
"code": null,
"e": 2788,
"s": 2704,
"text": "First Set: [50, 20, 40, 10, 30]\nSecond Set: [20, 10, 30]\nAre both set equal? false\n"
},
{
"code": null,
"e": 2885,
"s": 2788,
"text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#equals(java.lang.Object)"
},
{
"code": null,
"e": 2892,
"s": 2885,
"text": "sdkbnv"
},
{
"code": null,
"e": 2909,
"s": 2892,
"text": "Java-Collections"
},
{
"code": null,
"e": 2924,
"s": 2909,
"text": "Java-Functions"
},
{
"code": null,
"e": 2933,
"s": 2924,
"text": "java-set"
},
{
"code": null,
"e": 2938,
"s": 2933,
"text": "Java"
},
{
"code": null,
"e": 2943,
"s": 2938,
"text": "Java"
},
{
"code": null,
"e": 2960,
"s": 2943,
"text": "Java-Collections"
}
] |
Multithreaded download of yahoo stock history with Python – yfinance
|
15 Sep, 2021
Yfinance is a python package that enables us to fetch historical market data from Yahoo Finance API in a Pythonic way. It becomes so easy for all the Python developers to get data with the help of yfinance.
We can easily download historical stock data from yfinance, but the problem is, it is very time taking. Hence, we use multithreading for covering up the time. Multithreading enables us to download large amounts of data by executing multiple threads concurrently.
This module does not come built-in with Python. To install it type the below command in the terminal.
pip install yfinance
Let’s see the process step by step which are explained below with the implementation:
Step 1: Get all the required modules
Python3
import yfinance as yf
Step 2: Getting stocks history data
Python
# Get the stocks infoimport yfinance as yf # Ticker is a function responsible# for fetching the data MSFT is# representing info about Microsoft# Corporationmsft = yf.Ticker('MSFT') # msft.info will return all information# about microsoft corporationdata = msft.history() # printing the dataprint(data)
Output:
This is a recent year’s stock data of Microsoft Corporation. Please note that if we use data = msft.history(period=’max’) it will return all data till now.
Step 3: Downloading the data
Python3
# pip install yfinanceimport yfinance as yf # Here we use yf.download functiondata = yf.download( # tickers has value of company # shortname tickers='MSFT',) # printing the dataprint(data)
Output:
Hence, 1 of 1 download is completed. It is all data from beginning to end till now of only one company.
Step 4: Download the data from several companies
This is a code for downloading the data from companies like IBM, Apple (AAPL), Amazon(AMZN), Microsoft(MSFT), etc.
Python3
# pip install yfinanceimport yfinance as yf ticker_list = ['IBM', 'MSFT', 'AAPL', 'AMZN'] # Here we use yf.download functiondata = yf.download( # passes the ticker tickers=ticker_list, # used for access data[ticker] group_by='ticker', ) # used for making transposedata = data.T for t in ticker_list: # printing name print(t) print('\n') # used data.loc as it takes only index # labels and returns dataframe print(data.loc[t]) print('\n')
Output:
Step 5: Calculating the time of execution and using multithreading
As yfinance uses its own built-in threading technique for mass downloading. To do this, We need to assign a new parameter in a yf.download.
data = yf.download(
tickers=ticker_list,
threads=True, # Set thread value to true
group_by=’ticker’,
)
Program for calculating time, we use the time module
Python
# pip install yfinanceimport yfinance as yfimport time # Time starts from herestart = time.time() ticker_list = ['IBM', 'MSFT', 'AAPL', 'AMZN'] # Here we use yf.download functiondata = yf.download( tickers=ticker_list, threads=True, group_by='ticker', ) # used for making transposedata = data.T for t in ticker_list: print(t) # used data.loc as it takes only index # labels and returns dataframe print(data.loc[t]) # Total time calculatedprint('The program takes ', time.time()-start, 'seconds.')
Before thread:
After thread:
anikaseth98
Picked
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Sep, 2021"
},
{
"code": null,
"e": 235,
"s": 28,
"text": "Yfinance is a python package that enables us to fetch historical market data from Yahoo Finance API in a Pythonic way. It becomes so easy for all the Python developers to get data with the help of yfinance."
},
{
"code": null,
"e": 498,
"s": 235,
"text": "We can easily download historical stock data from yfinance, but the problem is, it is very time taking. Hence, we use multithreading for covering up the time. Multithreading enables us to download large amounts of data by executing multiple threads concurrently."
},
{
"code": null,
"e": 600,
"s": 498,
"text": "This module does not come built-in with Python. To install it type the below command in the terminal."
},
{
"code": null,
"e": 621,
"s": 600,
"text": "pip install yfinance"
},
{
"code": null,
"e": 707,
"s": 621,
"text": "Let’s see the process step by step which are explained below with the implementation:"
},
{
"code": null,
"e": 744,
"s": 707,
"text": "Step 1: Get all the required modules"
},
{
"code": null,
"e": 752,
"s": 744,
"text": "Python3"
},
{
"code": "import yfinance as yf",
"e": 774,
"s": 752,
"text": null
},
{
"code": null,
"e": 815,
"s": 778,
"text": "Step 2: Getting stocks history data "
},
{
"code": null,
"e": 824,
"s": 817,
"text": "Python"
},
{
"code": "# Get the stocks infoimport yfinance as yf # Ticker is a function responsible# for fetching the data MSFT is# representing info about Microsoft# Corporationmsft = yf.Ticker('MSFT') # msft.info will return all information# about microsoft corporationdata = msft.history() # printing the dataprint(data)",
"e": 1126,
"s": 824,
"text": null
},
{
"code": null,
"e": 1134,
"s": 1126,
"text": "Output:"
},
{
"code": null,
"e": 1290,
"s": 1134,
"text": "This is a recent year’s stock data of Microsoft Corporation. Please note that if we use data = msft.history(period=’max’) it will return all data till now."
},
{
"code": null,
"e": 1319,
"s": 1290,
"text": "Step 3: Downloading the data"
},
{
"code": null,
"e": 1327,
"s": 1319,
"text": "Python3"
},
{
"code": "# pip install yfinanceimport yfinance as yf # Here we use yf.download functiondata = yf.download( # tickers has value of company # shortname tickers='MSFT',) # printing the dataprint(data)",
"e": 1526,
"s": 1327,
"text": null
},
{
"code": null,
"e": 1534,
"s": 1526,
"text": "Output:"
},
{
"code": null,
"e": 1639,
"s": 1534,
"text": "Hence, 1 of 1 download is completed. It is all data from beginning to end till now of only one company."
},
{
"code": null,
"e": 1689,
"s": 1639,
"text": "Step 4: Download the data from several companies "
},
{
"code": null,
"e": 1804,
"s": 1689,
"text": "This is a code for downloading the data from companies like IBM, Apple (AAPL), Amazon(AMZN), Microsoft(MSFT), etc."
},
{
"code": null,
"e": 1812,
"s": 1804,
"text": "Python3"
},
{
"code": "# pip install yfinanceimport yfinance as yf ticker_list = ['IBM', 'MSFT', 'AAPL', 'AMZN'] # Here we use yf.download functiondata = yf.download( # passes the ticker tickers=ticker_list, # used for access data[ticker] group_by='ticker', ) # used for making transposedata = data.T for t in ticker_list: # printing name print(t) print('\\n') # used data.loc as it takes only index # labels and returns dataframe print(data.loc[t]) print('\\n')",
"e": 2302,
"s": 1812,
"text": null
},
{
"code": null,
"e": 2314,
"s": 2306,
"text": "Output:"
},
{
"code": null,
"e": 2385,
"s": 2318,
"text": "Step 5: Calculating the time of execution and using multithreading"
},
{
"code": null,
"e": 2527,
"s": 2387,
"text": "As yfinance uses its own built-in threading technique for mass downloading. To do this, We need to assign a new parameter in a yf.download."
},
{
"code": null,
"e": 2549,
"s": 2529,
"text": "data = yf.download("
},
{
"code": null,
"e": 2574,
"s": 2549,
"text": " tickers=ticker_list,"
},
{
"code": null,
"e": 2619,
"s": 2574,
"text": " threads=True, # Set thread value to true"
},
{
"code": null,
"e": 2642,
"s": 2619,
"text": " group_by=’ticker’,"
},
{
"code": null,
"e": 2644,
"s": 2642,
"text": ")"
},
{
"code": null,
"e": 2699,
"s": 2646,
"text": "Program for calculating time, we use the time module"
},
{
"code": null,
"e": 2708,
"s": 2701,
"text": "Python"
},
{
"code": "# pip install yfinanceimport yfinance as yfimport time # Time starts from herestart = time.time() ticker_list = ['IBM', 'MSFT', 'AAPL', 'AMZN'] # Here we use yf.download functiondata = yf.download( tickers=ticker_list, threads=True, group_by='ticker', ) # used for making transposedata = data.T for t in ticker_list: print(t) # used data.loc as it takes only index # labels and returns dataframe print(data.loc[t]) # Total time calculatedprint('The program takes ', time.time()-start, 'seconds.')",
"e": 3232,
"s": 2708,
"text": null
},
{
"code": null,
"e": 3247,
"s": 3232,
"text": "Before thread:"
},
{
"code": null,
"e": 3261,
"s": 3247,
"text": "After thread:"
},
{
"code": null,
"e": 3273,
"s": 3261,
"text": "anikaseth98"
},
{
"code": null,
"e": 3280,
"s": 3273,
"text": "Picked"
},
{
"code": null,
"e": 3295,
"s": 3280,
"text": "python-modules"
},
{
"code": null,
"e": 3302,
"s": 3295,
"text": "Python"
},
{
"code": null,
"e": 3400,
"s": 3302,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3432,
"s": 3400,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3459,
"s": 3432,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3480,
"s": 3459,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3503,
"s": 3480,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3534,
"s": 3503,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 3590,
"s": 3534,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 3632,
"s": 3590,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 3674,
"s": 3632,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 3713,
"s": 3674,
"text": "Python | Get unique values from a list"
}
] |
Java program to read all mobile numbers present in given file
|
24 Mar, 2018
Given the input text file, read all mobile numbers present and write to some output file.
Suppose we have a file names as input.txt and in that input file we have some Mobile Number which are mixed with some other data. Our task is to read the input file line by line and if we find any Number in that line we have to write that Mobile Number to an another file, which is output.txt file.
Example :
Mobile Number validation criteria :
The first digit should contain number between 7 to 9.
The rest 9 digit can contain any number between 0 to 9.
The mobile number can have 11 digits also by including 0at the starting.
The mobile number can be of 12 digits also by including 91at the starting
The number which satisfies the above criteria, is a valid mobile Number.
Approach : We use Regular expression, first we have to form a regular expression for Mobile Number. Whenever any Number in the input.txt file matches with that regular expression which we form for Mobile Number, that matched number will be written to output.txt file.
Below is Java implementation is above approach :
// Java program to read all mobile numbers// present in given fileimport java.util.regex.*;import java.io.*; class MobileNumberExtraction { public static void main(String[] args) throws IOException { // Write Mobile Numbers to output.txt file PrintWriter pw = new PrintWriter("output.txt"); // Regular expression for mobile number Pattern p = Pattern.compile("(0/91)?[7-9][0-9]{9}"); // BufferedReader for reading from input.txt file BufferedReader br = new BufferedReader (new FileReader("input.txt")); String line = br.readLine(); while (line != null) { Matcher m = p.matcher(line); while (m.find()) { // Write the mobile number to output.txt file pw.println(m.group()); } line = br.readLine(); } pw.flush(); }}
Output :
7873923408
7205435005
The above output is for this input.txt file :
Abstract classes may have some executable methods
and 7873923408 methods left unimplemented. Interfaces
contain no implementation code. An abstract
class can have non abstract 7205435005 methods.
All methods 1234 of an interface are abstract.
java-file-handling
Java-I/O
java-regular-expression
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n24 Mar, 2018"
},
{
"code": null,
"e": 144,
"s": 54,
"text": "Given the input text file, read all mobile numbers present and write to some output file."
},
{
"code": null,
"e": 443,
"s": 144,
"text": "Suppose we have a file names as input.txt and in that input file we have some Mobile Number which are mixed with some other data. Our task is to read the input file line by line and if we find any Number in that line we have to write that Mobile Number to an another file, which is output.txt file."
},
{
"code": null,
"e": 453,
"s": 443,
"text": "Example :"
},
{
"code": null,
"e": 489,
"s": 453,
"text": "Mobile Number validation criteria :"
},
{
"code": null,
"e": 543,
"s": 489,
"text": "The first digit should contain number between 7 to 9."
},
{
"code": null,
"e": 599,
"s": 543,
"text": "The rest 9 digit can contain any number between 0 to 9."
},
{
"code": null,
"e": 672,
"s": 599,
"text": "The mobile number can have 11 digits also by including 0at the starting."
},
{
"code": null,
"e": 746,
"s": 672,
"text": "The mobile number can be of 12 digits also by including 91at the starting"
},
{
"code": null,
"e": 819,
"s": 746,
"text": "The number which satisfies the above criteria, is a valid mobile Number."
},
{
"code": null,
"e": 1087,
"s": 819,
"text": "Approach : We use Regular expression, first we have to form a regular expression for Mobile Number. Whenever any Number in the input.txt file matches with that regular expression which we form for Mobile Number, that matched number will be written to output.txt file."
},
{
"code": null,
"e": 1136,
"s": 1087,
"text": "Below is Java implementation is above approach :"
},
{
"code": "// Java program to read all mobile numbers// present in given fileimport java.util.regex.*;import java.io.*; class MobileNumberExtraction { public static void main(String[] args) throws IOException { // Write Mobile Numbers to output.txt file PrintWriter pw = new PrintWriter(\"output.txt\"); // Regular expression for mobile number Pattern p = Pattern.compile(\"(0/91)?[7-9][0-9]{9}\"); // BufferedReader for reading from input.txt file BufferedReader br = new BufferedReader (new FileReader(\"input.txt\")); String line = br.readLine(); while (line != null) { Matcher m = p.matcher(line); while (m.find()) { // Write the mobile number to output.txt file pw.println(m.group()); } line = br.readLine(); } pw.flush(); }}",
"e": 2073,
"s": 1136,
"text": null
},
{
"code": null,
"e": 2082,
"s": 2073,
"text": "Output :"
},
{
"code": null,
"e": 2105,
"s": 2082,
"text": "7873923408\n7205435005\n"
},
{
"code": null,
"e": 2151,
"s": 2105,
"text": "The above output is for this input.txt file :"
},
{
"code": null,
"e": 2396,
"s": 2151,
"text": "Abstract classes may have some executable methods\nand 7873923408 methods left unimplemented. Interfaces \ncontain no implementation code. An abstract\nclass can have non abstract 7205435005 methods. \nAll methods 1234 of an interface are abstract."
},
{
"code": null,
"e": 2415,
"s": 2396,
"text": "java-file-handling"
},
{
"code": null,
"e": 2424,
"s": 2415,
"text": "Java-I/O"
},
{
"code": null,
"e": 2448,
"s": 2424,
"text": "java-regular-expression"
},
{
"code": null,
"e": 2453,
"s": 2448,
"text": "Java"
},
{
"code": null,
"e": 2467,
"s": 2453,
"text": "Java Programs"
},
{
"code": null,
"e": 2472,
"s": 2467,
"text": "Java"
},
{
"code": null,
"e": 2570,
"s": 2472,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2585,
"s": 2570,
"text": "Stream In Java"
},
{
"code": null,
"e": 2606,
"s": 2585,
"text": "Introduction to Java"
},
{
"code": null,
"e": 2627,
"s": 2606,
"text": "Constructors in Java"
},
{
"code": null,
"e": 2646,
"s": 2627,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 2663,
"s": 2646,
"text": "Generics in Java"
},
{
"code": null,
"e": 2689,
"s": 2663,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 2723,
"s": 2689,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 2770,
"s": 2723,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 2808,
"s": 2770,
"text": "Factory method design pattern in Java"
}
] |
Padovan Sequence
|
24 Jan, 2022
Padovan Sequence similar to Fibonacci sequence with similar recursive structure. The recursive formula is,
P(n) = P(n-2) + P(n-3)
P(0) = P(1) = P(2) = 1
Fibonacci Sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55...... Spiral of squares with side lengths which follow the Fibonacci sequence.
Padovan Sequence: 1, 1, 1, 2, 2, 3, 4, 5, 7, 9, 12, 16, 21, 28, 37,..... Spiral of equilateral triangles with side lengths which follow the Padovan sequence.
Examples:
For Padovan Sequence:
P0 = P1 = P2 = 1 ,
P(7) = P(5) + P(4)
= P(3) + P(2) + P(2) + P(1)
= P(2) + P(1) + 1 + 1 + 1
= 1 + 1 + 1 + 1 + 1
= 5
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find n'th term in Padovan Sequence// using Dynamic Programming#include<iostream>using namespace std; /* Function to calculate padovan number P(n) */int pad(int n){ /* 0th ,1st and 2nd number of the series are 1*/ int pPrevPrev = 1, pPrev = 1, pCurr = 1, pNext = 1; for (int i=3; i<=n; i++) { pNext = pPrevPrev + pPrev; pPrevPrev = pPrev; pPrev = pCurr; pCurr = pNext; } return pNext;} /* Driver Program */int main(){ int n = 12; cout << pad(n); return 0;}
// Java program to find n'th term// in Padovan Sequence using// Dynamic Programmingimport java.io.*; class GFG { /* Function to calculate padovan number P(n) */ static int pad(int n) { int []padv=new int[n]; //create array to store padovan values padv[0]=padv[1]=padv[2]=1; for (int i = 3; i <= n; i++) { padv[i]=padv[i-2]+padv[i-3]; } return padv[n-1]; } /* Driver Program */ public static void main(String args[]) { int n = 12; System.out.println(pad(n)); }} /*This code is contributed by Kanjam Bhat Lidhoo.*/
# Python program to find n'th term in Padovan# Sequence using Dynamic Programming # Function to calculate padovan number P(n)def pad(n): # 0th ,1st and 2nd number of the series are 1 pPrevPrev, pPrev, pCurr, pNext = 1, 1, 1, 1 # Find n'th Padovan number using recursive # formula. for i in range(3, n+1): pNext = pPrevPrev + pPrev pPrevPrev = pPrev pPrev = pCurr pCurr = pNext return pNext # Driver Codeprint (pad(12))
// C# program to find n'th term// in Padovan Sequence using// Dynamic Programmingusing System; class GFG { /* Function to calculate padovan number P(n) */ static int pad(int n) { /* 0th, 1st and 2nd number of the series are 1*/ int pPrevPrev = 1, pPrev = 1, pCurr = 1, pNext = 1; for (int i = 3; i <= n; i++) { pNext = pPrevPrev + pPrev; pPrevPrev = pPrev; pPrev = pCurr; pCurr = pNext; } return pNext; } /* Driver Program */ public static void Main() { int n = 12; Console.WriteLine(pad(n)); }} /*This code is contributed by vt_m.*/
<?php// PHP program to find n'th// term in Padovan Sequence// using Dynamic Programming // Function to calculate// padovan number P(n)function pad($n){ // 0th ,1st and 2nd number // of the series are 1 $pPrevPrev = 1; $pPrev = 1; $pCurr = 1; $pNext = 1; for ($i = 3; $i <= $n; $i++) { $pNext = $pPrevPrev + $pPrev; $pPrevPrev = $pPrev; $pPrev = $pCurr; $pCurr = $pNext; } return $pNext;} // Driver Code$n = 12;echo(pad($n)); // This code is contributed by Ajit.?>
<script>// Javascript program to find n'th// term in Padovan Sequence// using Dynamic Programming // Function to calculate// padovan number P(n)function pad(n) { // 0th ,1st and 2nd number // of the series are 1 let pPrevPrev = 1; let pPrev = 1; let pCurr = 1; let pNext = 1; for (let i = 3; i <= n; i++) { pNext = pPrevPrev + pPrev; pPrevPrev = pPrev; pPrev = pCurr; pCurr = pNext; } return pNext;} // Driver Codelet n = 12;document.write(pad(n)); // This code is contributed by gfgking.</script>
Output:
21
This article is contributed by Shivam Pradhan(anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
jit_t
kanjamscholar
gfgking
amartyaghoshgfg
Modular Arithmetic
series
Dynamic Programming
Mathematical
Dynamic Programming
Mathematical
series
Modular Arithmetic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Largest Sum Contiguous Subarray
Program for Fibonacci numbers
0-1 Knapsack Problem | DP-10
Longest Common Subsequence | DP-4
Subset Sum Problem | DP-25
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Merge two sorted arrays
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n24 Jan, 2022"
},
{
"code": null,
"e": 162,
"s": 53,
"text": "Padovan Sequence similar to Fibonacci sequence with similar recursive structure. The recursive formula is, "
},
{
"code": null,
"e": 213,
"s": 162,
"text": " P(n) = P(n-2) + P(n-3)\n P(0) = P(1) = P(2) = 1 "
},
{
"code": null,
"e": 350,
"s": 213,
"text": "Fibonacci Sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55...... Spiral of squares with side lengths which follow the Fibonacci sequence. "
},
{
"code": null,
"e": 510,
"s": 350,
"text": "Padovan Sequence: 1, 1, 1, 2, 2, 3, 4, 5, 7, 9, 12, 16, 21, 28, 37,..... Spiral of equilateral triangles with side lengths which follow the Padovan sequence. "
},
{
"code": null,
"e": 522,
"s": 510,
"text": "Examples: "
},
{
"code": null,
"e": 681,
"s": 522,
"text": "For Padovan Sequence:\nP0 = P1 = P2 = 1 ,\nP(7) = P(5) + P(4)\n = P(3) + P(2) + P(2) + P(1)\n = P(2) + P(1) + 1 + 1 + 1\n = 1 + 1 + 1 + 1 + 1 \n = 5"
},
{
"code": null,
"e": 689,
"s": 685,
"text": "C++"
},
{
"code": null,
"e": 694,
"s": 689,
"text": "Java"
},
{
"code": null,
"e": 702,
"s": 694,
"text": "Python3"
},
{
"code": null,
"e": 705,
"s": 702,
"text": "C#"
},
{
"code": null,
"e": 709,
"s": 705,
"text": "PHP"
},
{
"code": null,
"e": 720,
"s": 709,
"text": "Javascript"
},
{
"code": "// C++ program to find n'th term in Padovan Sequence// using Dynamic Programming#include<iostream>using namespace std; /* Function to calculate padovan number P(n) */int pad(int n){ /* 0th ,1st and 2nd number of the series are 1*/ int pPrevPrev = 1, pPrev = 1, pCurr = 1, pNext = 1; for (int i=3; i<=n; i++) { pNext = pPrevPrev + pPrev; pPrevPrev = pPrev; pPrev = pCurr; pCurr = pNext; } return pNext;} /* Driver Program */int main(){ int n = 12; cout << pad(n); return 0;}",
"e": 1251,
"s": 720,
"text": null
},
{
"code": "// Java program to find n'th term// in Padovan Sequence using// Dynamic Programmingimport java.io.*; class GFG { /* Function to calculate padovan number P(n) */ static int pad(int n) { int []padv=new int[n]; //create array to store padovan values padv[0]=padv[1]=padv[2]=1; for (int i = 3; i <= n; i++) { padv[i]=padv[i-2]+padv[i-3]; } return padv[n-1]; } /* Driver Program */ public static void main(String args[]) { int n = 12; System.out.println(pad(n)); }} /*This code is contributed by Kanjam Bhat Lidhoo.*/",
"e": 1864,
"s": 1251,
"text": null
},
{
"code": "# Python program to find n'th term in Padovan# Sequence using Dynamic Programming # Function to calculate padovan number P(n)def pad(n): # 0th ,1st and 2nd number of the series are 1 pPrevPrev, pPrev, pCurr, pNext = 1, 1, 1, 1 # Find n'th Padovan number using recursive # formula. for i in range(3, n+1): pNext = pPrevPrev + pPrev pPrevPrev = pPrev pPrev = pCurr pCurr = pNext return pNext # Driver Codeprint (pad(12))",
"e": 2332,
"s": 1864,
"text": null
},
{
"code": "// C# program to find n'th term// in Padovan Sequence using// Dynamic Programmingusing System; class GFG { /* Function to calculate padovan number P(n) */ static int pad(int n) { /* 0th, 1st and 2nd number of the series are 1*/ int pPrevPrev = 1, pPrev = 1, pCurr = 1, pNext = 1; for (int i = 3; i <= n; i++) { pNext = pPrevPrev + pPrev; pPrevPrev = pPrev; pPrev = pCurr; pCurr = pNext; } return pNext; } /* Driver Program */ public static void Main() { int n = 12; Console.WriteLine(pad(n)); }} /*This code is contributed by vt_m.*/",
"e": 3026,
"s": 2332,
"text": null
},
{
"code": "<?php// PHP program to find n'th// term in Padovan Sequence// using Dynamic Programming // Function to calculate// padovan number P(n)function pad($n){ // 0th ,1st and 2nd number // of the series are 1 $pPrevPrev = 1; $pPrev = 1; $pCurr = 1; $pNext = 1; for ($i = 3; $i <= $n; $i++) { $pNext = $pPrevPrev + $pPrev; $pPrevPrev = $pPrev; $pPrev = $pCurr; $pCurr = $pNext; } return $pNext;} // Driver Code$n = 12;echo(pad($n)); // This code is contributed by Ajit.?>",
"e": 3549,
"s": 3026,
"text": null
},
{
"code": "<script>// Javascript program to find n'th// term in Padovan Sequence// using Dynamic Programming // Function to calculate// padovan number P(n)function pad(n) { // 0th ,1st and 2nd number // of the series are 1 let pPrevPrev = 1; let pPrev = 1; let pCurr = 1; let pNext = 1; for (let i = 3; i <= n; i++) { pNext = pPrevPrev + pPrev; pPrevPrev = pPrev; pPrev = pCurr; pCurr = pNext; } return pNext;} // Driver Codelet n = 12;document.write(pad(n)); // This code is contributed by gfgking.</script>",
"e": 4105,
"s": 3549,
"text": null
},
{
"code": null,
"e": 4115,
"s": 4105,
"text": "Output: "
},
{
"code": null,
"e": 4118,
"s": 4115,
"text": "21"
},
{
"code": null,
"e": 4553,
"s": 4118,
"text": "This article is contributed by Shivam Pradhan(anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 4559,
"s": 4553,
"text": "jit_t"
},
{
"code": null,
"e": 4573,
"s": 4559,
"text": "kanjamscholar"
},
{
"code": null,
"e": 4581,
"s": 4573,
"text": "gfgking"
},
{
"code": null,
"e": 4597,
"s": 4581,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 4616,
"s": 4597,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 4623,
"s": 4616,
"text": "series"
},
{
"code": null,
"e": 4643,
"s": 4623,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 4656,
"s": 4643,
"text": "Mathematical"
},
{
"code": null,
"e": 4676,
"s": 4656,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 4689,
"s": 4676,
"text": "Mathematical"
},
{
"code": null,
"e": 4696,
"s": 4689,
"text": "series"
},
{
"code": null,
"e": 4715,
"s": 4696,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 4813,
"s": 4715,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4845,
"s": 4813,
"text": "Largest Sum Contiguous Subarray"
},
{
"code": null,
"e": 4875,
"s": 4845,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 4904,
"s": 4875,
"text": "0-1 Knapsack Problem | DP-10"
},
{
"code": null,
"e": 4938,
"s": 4904,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 4965,
"s": 4938,
"text": "Subset Sum Problem | DP-25"
},
{
"code": null,
"e": 4995,
"s": 4965,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 5038,
"s": 4995,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 5098,
"s": 5038,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 5113,
"s": 5098,
"text": "C++ Data Types"
}
] |
Python | Decimal sqrt() method
|
05 Sep, 2019
Decimal#sqrt() : sqrt() is a Decimal class method which returns the Square root of a non-negative number to context precision.
Syntax: Decimal.sqrt()
Parameter: Decimal values
Return: the Square root of a non-negative number to context precision.
Code #1 : Example for sqrt() method
# Python Program explaining # sqrt() method # loading decimal libraryfrom decimal import * # Initializing a decimal valuea = Decimal(1) b = Decimal(2) # printing Decimal valuesprint ("Decimal value a : ", a)print ("Decimal value b : ", b) # Using Decimal.sqrt() methodprint ("\n\nDecimal a with sqrt() method : ", a.sqrt()) print ("Decimal b with sqrt() method : ", b.sqrt())
Output :
Decimal value a : 1
Decimal value b : 2
Decimal a with sqrt() method : 1
Decimal b with sqrt() method : 1.414213562373095048801688724
Code #2 : Example for sqrt() method
# Python Program explaining # sqrt() method # loading decimal libraryfrom decimal import * # Initializing a decimal valuea = Decimal(300) b = Decimal(15) # printing Decimal valuesprint ("Decimal value a : ", a)print ("Decimal value b : ", b) # Using Decimal.sqrt() methodprint ("\n\nDecimal a with sqrt() method : ", a.sqrt()) print ("Decimal b with sqrt() method : ", b.sqrt())
Output :
Decimal value a : 300
Decimal value b : 15
Decimal a with sqrt() method : 17.32050807568877293527446342
Decimal b with sqrt() method : 3.872983346207416885179265400
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Sep, 2019"
},
{
"code": null,
"e": 155,
"s": 28,
"text": "Decimal#sqrt() : sqrt() is a Decimal class method which returns the Square root of a non-negative number to context precision."
},
{
"code": null,
"e": 178,
"s": 155,
"text": "Syntax: Decimal.sqrt()"
},
{
"code": null,
"e": 204,
"s": 178,
"text": "Parameter: Decimal values"
},
{
"code": null,
"e": 275,
"s": 204,
"text": "Return: the Square root of a non-negative number to context precision."
},
{
"code": null,
"e": 311,
"s": 275,
"text": "Code #1 : Example for sqrt() method"
},
{
"code": "# Python Program explaining # sqrt() method # loading decimal libraryfrom decimal import * # Initializing a decimal valuea = Decimal(1) b = Decimal(2) # printing Decimal valuesprint (\"Decimal value a : \", a)print (\"Decimal value b : \", b) # Using Decimal.sqrt() methodprint (\"\\n\\nDecimal a with sqrt() method : \", a.sqrt()) print (\"Decimal b with sqrt() method : \", b.sqrt())",
"e": 697,
"s": 311,
"text": null
},
{
"code": null,
"e": 706,
"s": 697,
"text": "Output :"
},
{
"code": null,
"e": 848,
"s": 706,
"text": "Decimal value a : 1\nDecimal value b : 2\n\n\nDecimal a with sqrt() method : 1\nDecimal b with sqrt() method : 1.414213562373095048801688724\n\n"
},
{
"code": null,
"e": 884,
"s": 848,
"text": "Code #2 : Example for sqrt() method"
},
{
"code": "# Python Program explaining # sqrt() method # loading decimal libraryfrom decimal import * # Initializing a decimal valuea = Decimal(300) b = Decimal(15) # printing Decimal valuesprint (\"Decimal value a : \", a)print (\"Decimal value b : \", b) # Using Decimal.sqrt() methodprint (\"\\n\\nDecimal a with sqrt() method : \", a.sqrt()) print (\"Decimal b with sqrt() method : \", b.sqrt())",
"e": 1275,
"s": 884,
"text": null
},
{
"code": null,
"e": 1284,
"s": 1275,
"text": "Output :"
},
{
"code": null,
"e": 1457,
"s": 1284,
"text": "Decimal value a : 300\nDecimal value b : 15\n\n\nDecimal a with sqrt() method : 17.32050807568877293527446342\nDecimal b with sqrt() method : 3.872983346207416885179265400\n\n"
},
{
"code": null,
"e": 1464,
"s": 1457,
"text": "Python"
},
{
"code": null,
"e": 1562,
"s": 1464,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1594,
"s": 1562,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1621,
"s": 1594,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1642,
"s": 1621,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1665,
"s": 1642,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1696,
"s": 1665,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1752,
"s": 1696,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1794,
"s": 1752,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1836,
"s": 1794,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1875,
"s": 1836,
"text": "Python | Get unique values from a list"
}
] |
Maximum Profit | Practice | GeeksforGeeks
|
In the stock market, a person buys a stock and sells it on some future date. Given the stock prices of N days in an array A[ ] and a positive integer K, find out the maximum profit a person can make in at-most K transactions. A transaction is equivalent to (buying + selling) of a stock and new transaction can start only when the previous transaction has been completed.
Example 1:
Input: K = 2, N = 6
A = {10, 22, 5, 75, 65, 80}
Output: 87
Explaination:
1st transaction: buy at 10 and sell at 22.
2nd transaction : buy at 5 and sell at 80.
Example 2:
Input: K = 3, N = 4
A = {20, 580, 420, 900}
Output: 1040
Explaination: The trader can make at most 2
transactions and giving him a profit of 1040.
Example 3:
Input: K = 1, N = 5
A = {100, 90, 80, 50, 25}
Output: 0
Explaination: Selling price is decreasing
daily. So seller cannot have profit.
Your Task:
You do not need to read input or print anything. Your task is to complete the function maxProfit() which takes the values K, N and the array A[] as input parameters and returns the maximum profit.
Expected Time Complexity: O(N*K)
Expected Auxiliary Space: O(N*K)
Constraints:
1 ≤ N ≤ 500
1 ≤ K ≤ 200
1 ≤ A[ i ] ≤ 1000
+1
goyalshivank7902 days ago
// easy c++ solution
int maxProfit(int K, int N, int A[]) { int dp[K+1][N]; memset(dp,0,sizeof(dp)); for(int i=1;i<=K;i++){ int maxm = INT_MIN; for(int j=1;j<N;j++){ maxm = max(dp[i-1][j-1]-A[j-1],maxm); dp[i][j] = max(dp[i][j-1],maxm + A[j]); } } return dp[K][N-1]; }
0
akkeshri140420014 days ago
int maxProfit(int K, int N, int A[]) {
// code here
vector<vector<int>>dp(K+1,vector<int>(N));
for(int i=0;i<K+1;i++){
for(int j=0;j<N;j++){
if(i==0 or j==0){
dp[i][j]=0;
}
}
}
for(int i=1;i<K+1;i++){
int maxi=INT_MIN;
for(int j=1;j<N;j++){
maxi=max(maxi,dp[i-1][j-1]-A[j-1]);
dp[i][j]=max(maxi+A[j],dp[i][j-1]);
}
}
return dp[K][N-1];
}
0
onlybkm20021 week ago
int f(int index, int buy ,int n, int cap, int arr[], vector<vector<vector<int>>> &dp)
{
if(index == n || cap == 0)
{
return 0;
}
if(dp[index][buy][cap] != -1)
{
return dp[index][buy][cap];
}
int profit;
if(buy == 1)
{
profit = max(f(index+1,0,n,cap,arr,dp)-arr[index],f(index+1,1,n,cap,arr,dp));
}
else{
profit = max(f(index+1,1,n,cap-1,arr,dp)+arr[index],f(index+1,0,n,cap,arr,dp));
}
return dp[index][buy][cap] = profit;
}
int maxProfit(int K, int N, int A[]) {
// code here
vector<vector<vector<int>>> dp(N,
vector<vector<int>>
(2,vector<int>(K+1,-1)));
return f(0,1,N,K,A,dp);
}
+1
kelvin_01791 week ago
Remember that you have a choice at every point so don't always buy the first stock , cost me 1 WA
class Solution {
public:
int n,k;
vector<vector<int>> dp;
int dynamic(int indx,int lft,int c[]){
if(lft==0 or indx==n){
return 0;
}
if(dp[indx][lft]!=-1){
return dp[indx][lft];
}
int ans=dynamic(indx+1,lft,c);
for(int i=indx+1;i<n;i++){
ans=max(ans,max(0,c[i]-c[indx]+dynamic(i+1,lft-1,c)));
}
return dp[indx][lft]=ans;
}
int maxProfit(int k, int n, int c[]) {
// code here
this->n=n;
this->k=k;
dp=vector<vector<int>>(n,vector<int>(k+1,-1));
return dynamic(0,k,c);
}
};
0
ankukumar74241 week ago
Easy dp solution*****
class Solution { public: int solve(int ind,int buy,int K,int N,int A[],vector<vector<vector<int>>>& dp){ if(ind==N || K==0)return 0; if(dp[ind][buy][K]!=-1)return dp[ind][buy][K]; if(buy){ dp[ind][buy][K]=max(-A[ind]+solve(ind+1,0,K,N,A,dp),solve(ind+1,1,K,N,A,dp)); } else{ dp[ind][buy][K]=max(A[ind]+solve(ind+1,1,K-1,N,A,dp),solve(ind+1,0,K,N,A,dp)); } return dp[ind][buy][K]; } int maxProfit(int K, int N, int A[]) { // code here vector<vector<vector<int>>> dp(N,vector<vector<int>>(2,vector<int>(K+1,-1))); return solve(0,1,K,N,A,dp); }};
0
ritikk51882 weeks ago
int solve(int i,int j ,int k,int arr[],int n,vector<vector<vector<int>>> &dp){ if(dp[i][j][k]!=-1) return dp[i][j][k]; if(k==0) return(0); if(i==n) return 0; if(j==1) return dp[i][j][k]=max(-arr[i]+solve(i+1,0,k,arr,n,dp),solve(i+1,1,k,arr,n,dp)); else return dp[i][j][k]= max(arr[i]+solve(i+1,1,k-1,arr,n,dp),solve(i+1,0,k,arr,n,dp)); } int maxProfit(int K, int N, int A[]) { vector<vector<vector<int>>> dp(N+1,vector<vector<int>>(2,vector<int>(K+1,-1))); vector<vector<int>> next(2,vector<int>(K+1,0)); for(int i=N;i>=0;i--){ vector<vector<int>> curr(2,vector<int>(K+1,0)); for(int j=0;j<=1;j++){ for(int p=0;p<=K;p++){ if(i==N) curr[j][p]=0; else if(p==0) curr[j][p]=0; else{ if(j==1) curr[j][p]=max(-A[i]+next[0][p],next[1][p]); else curr[j][p]=max(A[i]+next[1][p-1],next[0][p]); } } } next=curr; } return(next[1][K]); //return solve(0,1,K,A,N,dp);
0
nilkantr1232 weeks ago
simple memoization
int dp[501][201];
int solve(int arr[], int n, int k, int buy, int index, int prev){
if(k == 0) return 0;
if(dp[index][k] != -1)
return dp[index][k];
int res = 0;
if(buy == 1){
for(int i=index; i<n; i++){
int profit = solve(arr, n, k-1, 0, i+1, arr[i]);
res = max(profit, res);
}
}
else{
for(int i=index; i<n; i++){
if(arr[i] > prev){
int profit2 = arr[i] - prev + solve(arr, n, k-1, 1, i+1, -1);
res = max(res, profit2);
}
}
}
return dp[index][k] = res;
}
int maxProfit(int K, int N, int A[]) {
// code here
memset(dp, -1, sizeof(dp));
return solve(A, N, 2*K, 1, 0, -1);
}
0
dassourabh143 weeks ago
Easy C++ || DP
int maxProfit(int k, int n, int A[]) {
int dp[k+1][n];
for(int i=0;i<=k;i++) dp[i][0]=0;
for(int j=0;j<n;j++) dp[0][j]=0;
for(int i=1;i<=k;i++){
int pmax=INT_MIN;
for(int j=1;j<n;j++){
pmax=max(pmax, dp[i-1][j-1]-A[j-1]);
dp[i][j]=max(pmax+A[j], dp[i][j-1]);
}
}
return dp[k][n-1];
}
0
shubham4093 weeks ago
Solution in Java :-
Using Memoization and 2D array.
class Solution {
private static int[] price;
static int length ;
static int [][] dp;
static int maxProfit(int K, int N, int[] A) {
price = A;
K = 2*K;
length = N;
dp = new int[N+1][K+1];
for (int i = 0; i < N+1; i++) {
for (int j = 0; j < K+1; j++) {
dp[i][j] = Integer.MIN_VALUE;
}
}
return recurstion(0,K);
}
public static int recurstion(int i , int remiaining_purchases){
if (remiaining_purchases == 0 || i==length ){
return 0;
}
else if (remiaining_purchases%2==0){
// buy or ignore
if (dp[i][remiaining_purchases] != Integer.MIN_VALUE)
return dp[i][remiaining_purchases];
dp[i][remiaining_purchases] = Math.max(-price[i]+recurstion(i+1,remiaining_purchases-1),recurstion(i+1,remiaining_purchases));
return dp[i][remiaining_purchases];
}
else{
// sell or ignor
if (dp[i][remiaining_purchases] != Integer.MIN_VALUE)
return dp[i][remiaining_purchases];
dp[i][remiaining_purchases] = Math.max(price[i]+recurstion(i+1,remiaining_purchases-1),recurstion(i+1,remiaining_purchases));
return dp[i][remiaining_purchases];
}
}
}
Simple solution in java using 2d array.
Use -ive price when buy and +ive when to sellUse even-odd concept to track whether previously it was bought or sold. For this double transactions first.Always sell or ignore when current transaction is odd.Always buy or ignore when current transaction is even.
Use -ive price when buy and +ive when to sell
Use even-odd concept to track whether previously it was bought or sold. For this double transactions first.Always sell or ignore when current transaction is odd.Always buy or ignore when current transaction is even.
Always sell or ignore when current transaction is odd.Always buy or ignore when current transaction is even.
Always sell or ignore when current transaction is odd.
Always buy or ignore when current transaction is even.
0
simhachalammadireddi3 weeks ago
int maxProfit(int K, int N, int A[]) { vector<vector<int>>dp(N+1,vector<int>(2*K+1,0)); for(int ind=N-1;ind>=0;ind--) { for(int k=2*K-1;k>=0;k--) { if(k%2==0) dp[ind][k]=max(-A[ind]+dp[ind+1][k+1],dp[ind+1][k]); else dp[ind][k]=max(A[ind]+dp[ind+1][k+1],dp[ind+1][k]); } } return dp[0][0]; }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code.
On submission, your code is tested against multiple test cases consisting of all
possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as
the final solution code.
You can view the solutions submitted by other users from the submission tab.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems does not guarantee the
correctness of code. On submission, your code is tested against multiple test cases
consisting of all possible corner cases and stress constraints.
|
[
{
"code": null,
"e": 610,
"s": 238,
"text": "In the stock market, a person buys a stock and sells it on some future date. Given the stock prices of N days in an array A[ ] and a positive integer K, find out the maximum profit a person can make in at-most K transactions. A transaction is equivalent to (buying + selling) of a stock and new transaction can start only when the previous transaction has been completed."
},
{
"code": null,
"e": 622,
"s": 610,
"text": "\nExample 1:"
},
{
"code": null,
"e": 784,
"s": 622,
"text": "Input: K = 2, N = 6\nA = {10, 22, 5, 75, 65, 80}\nOutput: 87\nExplaination: \n1st transaction: buy at 10 and sell at 22. \n2nd transaction : buy at 5 and sell at 80.\n"
},
{
"code": null,
"e": 795,
"s": 784,
"text": "Example 2:"
},
{
"code": null,
"e": 944,
"s": 795,
"text": "Input: K = 3, N = 4\nA = {20, 580, 420, 900}\nOutput: 1040\nExplaination: The trader can make at most 2 \ntransactions and giving him a profit of 1040.\n"
},
{
"code": null,
"e": 955,
"s": 944,
"text": "Example 3:"
},
{
"code": null,
"e": 1091,
"s": 955,
"text": "Input: K = 1, N = 5\nA = {100, 90, 80, 50, 25}\nOutput: 0\nExplaination: Selling price is decreasing \ndaily. So seller cannot have profit."
},
{
"code": null,
"e": 1300,
"s": 1091,
"text": "\nYour Task:\nYou do not need to read input or print anything. Your task is to complete the function maxProfit() which takes the values K, N and the array A[] as input parameters and returns the maximum profit."
},
{
"code": null,
"e": 1367,
"s": 1300,
"text": "\nExpected Time Complexity: O(N*K)\nExpected Auxiliary Space: O(N*K)"
},
{
"code": null,
"e": 1423,
"s": 1367,
"text": "\nConstraints:\n1 ≤ N ≤ 500\n1 ≤ K ≤ 200\n1 ≤ A[ i ] ≤ 1000"
},
{
"code": null,
"e": 1426,
"s": 1423,
"text": "+1"
},
{
"code": null,
"e": 1452,
"s": 1426,
"text": "goyalshivank7902 days ago"
},
{
"code": null,
"e": 1473,
"s": 1452,
"text": "// easy c++ solution"
},
{
"code": null,
"e": 1813,
"s": 1475,
"text": "int maxProfit(int K, int N, int A[]) { int dp[K+1][N]; memset(dp,0,sizeof(dp)); for(int i=1;i<=K;i++){ int maxm = INT_MIN; for(int j=1;j<N;j++){ maxm = max(dp[i-1][j-1]-A[j-1],maxm); dp[i][j] = max(dp[i][j-1],maxm + A[j]); } } return dp[K][N-1]; }"
},
{
"code": null,
"e": 1815,
"s": 1813,
"text": "0"
},
{
"code": null,
"e": 1842,
"s": 1815,
"text": "akkeshri140420014 days ago"
},
{
"code": null,
"e": 2360,
"s": 1842,
"text": "int maxProfit(int K, int N, int A[]) {\n // code here\n vector<vector<int>>dp(K+1,vector<int>(N));\n for(int i=0;i<K+1;i++){\n for(int j=0;j<N;j++){\n if(i==0 or j==0){\n dp[i][j]=0;\n }\n }\n }\n for(int i=1;i<K+1;i++){\n int maxi=INT_MIN;\n for(int j=1;j<N;j++){\n maxi=max(maxi,dp[i-1][j-1]-A[j-1]);\n dp[i][j]=max(maxi+A[j],dp[i][j-1]);\n }\n }\n return dp[K][N-1];\n }"
},
{
"code": null,
"e": 2362,
"s": 2360,
"text": "0"
},
{
"code": null,
"e": 2384,
"s": 2362,
"text": "onlybkm20021 week ago"
},
{
"code": null,
"e": 3256,
"s": 2384,
"text": "int f(int index, int buy ,int n, int cap, int arr[], vector<vector<vector<int>>> &dp)\n {\n if(index == n || cap == 0)\n {\n return 0;\n }\n if(dp[index][buy][cap] != -1)\n {\n return dp[index][buy][cap];\n }\n int profit;\n if(buy == 1)\n {\n profit = max(f(index+1,0,n,cap,arr,dp)-arr[index],f(index+1,1,n,cap,arr,dp));\n }\n else{\n profit = max(f(index+1,1,n,cap-1,arr,dp)+arr[index],f(index+1,0,n,cap,arr,dp));\n }\n return dp[index][buy][cap] = profit; \n \n }\n\n int maxProfit(int K, int N, int A[]) {\n // code here\n vector<vector<vector<int>>> dp(N,\n vector<vector<int>> \n (2,vector<int>(K+1,-1)));\n return f(0,1,N,K,A,dp);\n }"
},
{
"code": null,
"e": 3259,
"s": 3256,
"text": "+1"
},
{
"code": null,
"e": 3281,
"s": 3259,
"text": "kelvin_01791 week ago"
},
{
"code": null,
"e": 3379,
"s": 3281,
"text": "Remember that you have a choice at every point so don't always buy the first stock , cost me 1 WA"
},
{
"code": null,
"e": 4020,
"s": 3381,
"text": " class Solution {\n public:\n int n,k;\n vector<vector<int>> dp;\n int dynamic(int indx,int lft,int c[]){\n if(lft==0 or indx==n){\n return 0;\n }\n if(dp[indx][lft]!=-1){\n return dp[indx][lft];\n }\n int ans=dynamic(indx+1,lft,c);\n for(int i=indx+1;i<n;i++){\n ans=max(ans,max(0,c[i]-c[indx]+dynamic(i+1,lft-1,c)));\n }\n return dp[indx][lft]=ans;\n }\n int maxProfit(int k, int n, int c[]) {\n // code here\n this->n=n;\n this->k=k;\n dp=vector<vector<int>>(n,vector<int>(k+1,-1));\n return dynamic(0,k,c);\n }\n};"
},
{
"code": null,
"e": 4022,
"s": 4020,
"text": "0"
},
{
"code": null,
"e": 4046,
"s": 4022,
"text": "ankukumar74241 week ago"
},
{
"code": null,
"e": 4068,
"s": 4046,
"text": "Easy dp solution*****"
},
{
"code": null,
"e": 4680,
"s": 4068,
"text": "class Solution { public: int solve(int ind,int buy,int K,int N,int A[],vector<vector<vector<int>>>& dp){ if(ind==N || K==0)return 0; if(dp[ind][buy][K]!=-1)return dp[ind][buy][K]; if(buy){ dp[ind][buy][K]=max(-A[ind]+solve(ind+1,0,K,N,A,dp),solve(ind+1,1,K,N,A,dp)); } else{ dp[ind][buy][K]=max(A[ind]+solve(ind+1,1,K-1,N,A,dp),solve(ind+1,0,K,N,A,dp)); } return dp[ind][buy][K]; } int maxProfit(int K, int N, int A[]) { // code here vector<vector<vector<int>>> dp(N,vector<vector<int>>(2,vector<int>(K+1,-1))); return solve(0,1,K,N,A,dp); }}; "
},
{
"code": null,
"e": 4682,
"s": 4680,
"text": "0"
},
{
"code": null,
"e": 4704,
"s": 4682,
"text": "ritikk51882 weeks ago"
},
{
"code": null,
"e": 5946,
"s": 4704,
"text": " int solve(int i,int j ,int k,int arr[],int n,vector<vector<vector<int>>> &dp){ if(dp[i][j][k]!=-1) return dp[i][j][k]; if(k==0) return(0); if(i==n) return 0; if(j==1) return dp[i][j][k]=max(-arr[i]+solve(i+1,0,k,arr,n,dp),solve(i+1,1,k,arr,n,dp)); else return dp[i][j][k]= max(arr[i]+solve(i+1,1,k-1,arr,n,dp),solve(i+1,0,k,arr,n,dp)); } int maxProfit(int K, int N, int A[]) { vector<vector<vector<int>>> dp(N+1,vector<vector<int>>(2,vector<int>(K+1,-1))); vector<vector<int>> next(2,vector<int>(K+1,0)); for(int i=N;i>=0;i--){ vector<vector<int>> curr(2,vector<int>(K+1,0)); for(int j=0;j<=1;j++){ for(int p=0;p<=K;p++){ if(i==N) curr[j][p]=0; else if(p==0) curr[j][p]=0; else{ if(j==1) curr[j][p]=max(-A[i]+next[0][p],next[1][p]); else curr[j][p]=max(A[i]+next[1][p-1],next[0][p]); } } } next=curr; } return(next[1][K]); //return solve(0,1,K,A,N,dp);"
},
{
"code": null,
"e": 5948,
"s": 5946,
"text": "0"
},
{
"code": null,
"e": 5971,
"s": 5948,
"text": "nilkantr1232 weeks ago"
},
{
"code": null,
"e": 5990,
"s": 5971,
"text": "simple memoization"
},
{
"code": null,
"e": 6803,
"s": 5990,
"text": "int dp[501][201];\n int solve(int arr[], int n, int k, int buy, int index, int prev){\n if(k == 0) return 0;\n \n if(dp[index][k] != -1)\n return dp[index][k];\n \n int res = 0;\n if(buy == 1){\n for(int i=index; i<n; i++){\n int profit = solve(arr, n, k-1, 0, i+1, arr[i]);\n res = max(profit, res);\n }\n }\n else{\n for(int i=index; i<n; i++){\n if(arr[i] > prev){\n int profit2 = arr[i] - prev + solve(arr, n, k-1, 1, i+1, -1);\n res = max(res, profit2);\n }\n }\n }\n return dp[index][k] = res;\n }\n \n int maxProfit(int K, int N, int A[]) {\n // code here\n memset(dp, -1, sizeof(dp));\n return solve(A, N, 2*K, 1, 0, -1);\n }"
},
{
"code": null,
"e": 6805,
"s": 6803,
"text": "0"
},
{
"code": null,
"e": 6829,
"s": 6805,
"text": "dassourabh143 weeks ago"
},
{
"code": null,
"e": 6844,
"s": 6829,
"text": "Easy C++ || DP"
},
{
"code": null,
"e": 7257,
"s": 6844,
"text": "int maxProfit(int k, int n, int A[]) {\n int dp[k+1][n];\n for(int i=0;i<=k;i++) dp[i][0]=0;\n for(int j=0;j<n;j++) dp[0][j]=0;\n \n for(int i=1;i<=k;i++){\n int pmax=INT_MIN;\n for(int j=1;j<n;j++){\n pmax=max(pmax, dp[i-1][j-1]-A[j-1]);\n dp[i][j]=max(pmax+A[j], dp[i][j-1]);\n }\n }\n return dp[k][n-1];\n }"
},
{
"code": null,
"e": 7259,
"s": 7257,
"text": "0"
},
{
"code": null,
"e": 7281,
"s": 7259,
"text": "shubham4093 weeks ago"
},
{
"code": null,
"e": 7302,
"s": 7281,
"text": "Solution in Java :- "
},
{
"code": null,
"e": 7334,
"s": 7302,
"text": "Using Memoization and 2D array."
},
{
"code": null,
"e": 8669,
"s": 7336,
"text": "class Solution {\n private static int[] price;\n static int length ;\n static int [][] dp;\n static int maxProfit(int K, int N, int[] A) {\n price = A;\n K = 2*K;\n length = N;\n dp = new int[N+1][K+1];\n for (int i = 0; i < N+1; i++) {\n for (int j = 0; j < K+1; j++) {\n dp[i][j] = Integer.MIN_VALUE;\n }\n }\n return recurstion(0,K);\n }\n public static int recurstion(int i , int remiaining_purchases){\n if (remiaining_purchases == 0 || i==length ){\n return 0;\n }\n\n else if (remiaining_purchases%2==0){\n// buy or ignore\n if (dp[i][remiaining_purchases] != Integer.MIN_VALUE)\n return dp[i][remiaining_purchases];\n dp[i][remiaining_purchases] = Math.max(-price[i]+recurstion(i+1,remiaining_purchases-1),recurstion(i+1,remiaining_purchases));\n return dp[i][remiaining_purchases];\n }\n else{\n// sell or ignor\n if (dp[i][remiaining_purchases] != Integer.MIN_VALUE)\n return dp[i][remiaining_purchases];\n dp[i][remiaining_purchases] = Math.max(price[i]+recurstion(i+1,remiaining_purchases-1),recurstion(i+1,remiaining_purchases));\n return dp[i][remiaining_purchases];\n\n }\n }\n}"
},
{
"code": null,
"e": 8709,
"s": 8669,
"text": "Simple solution in java using 2d array."
},
{
"code": null,
"e": 8983,
"s": 8709,
"text": "Use -ive price when buy and +ive when to sellUse even-odd concept to track whether previously it was bought or sold. For this double transactions first.Always sell or ignore when current transaction is odd.Always buy or ignore when current transaction is even."
},
{
"code": null,
"e": 9029,
"s": 8983,
"text": "Use -ive price when buy and +ive when to sell"
},
{
"code": null,
"e": 9258,
"s": 9029,
"text": "Use even-odd concept to track whether previously it was bought or sold. For this double transactions first.Always sell or ignore when current transaction is odd.Always buy or ignore when current transaction is even."
},
{
"code": null,
"e": 9367,
"s": 9258,
"text": "Always sell or ignore when current transaction is odd.Always buy or ignore when current transaction is even."
},
{
"code": null,
"e": 9422,
"s": 9367,
"text": "Always sell or ignore when current transaction is odd."
},
{
"code": null,
"e": 9477,
"s": 9422,
"text": "Always buy or ignore when current transaction is even."
},
{
"code": null,
"e": 9479,
"s": 9477,
"text": "0"
},
{
"code": null,
"e": 9511,
"s": 9479,
"text": "simhachalammadireddi3 weeks ago"
},
{
"code": null,
"e": 9953,
"s": 9511,
"text": " int maxProfit(int K, int N, int A[]) { vector<vector<int>>dp(N+1,vector<int>(2*K+1,0)); for(int ind=N-1;ind>=0;ind--) { for(int k=2*K-1;k>=0;k--) { if(k%2==0) dp[ind][k]=max(-A[ind]+dp[ind+1][k+1],dp[ind+1][k]); else dp[ind][k]=max(A[ind]+dp[ind+1][k+1],dp[ind+1][k]); } } return dp[0][0]; }"
},
{
"code": null,
"e": 10099,
"s": 9953,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 10135,
"s": 10099,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 10145,
"s": 10135,
"text": "\nProblem\n"
},
{
"code": null,
"e": 10155,
"s": 10145,
"text": "\nContest\n"
},
{
"code": null,
"e": 10218,
"s": 10155,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 10403,
"s": 10218,
"text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 10687,
"s": 10403,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints."
},
{
"code": null,
"e": 10833,
"s": 10687,
"text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code."
},
{
"code": null,
"e": 10910,
"s": 10833,
"text": "You can view the solutions submitted by other users from the submission tab."
},
{
"code": null,
"e": 10951,
"s": 10910,
"text": "Make sure you are not using ad-blockers."
},
{
"code": null,
"e": 10979,
"s": 10951,
"text": "Disable browser extensions."
},
{
"code": null,
"e": 11050,
"s": 10979,
"text": "We recommend using latest version of your browser for best experience."
},
{
"code": null,
"e": 11237,
"s": 11050,
"text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values."
}
] |
Smart Contract to Store Employee Details
|
26 Aug, 2020
Solidity is a high-level language. The structure of smart contracts in solidity is very similar to the structure of classes in object-oriented languages. The solidity file has an extension .sol.
Solidity’s code is encapsulated in contracts which means a contract in Solidity is a collection of code (its functions) and data (its state) that resides at a specific address on the Ethereum blockchain. A contract is a fundamental block of building an application on the Ethereum.
Example: In the below example, we aim at creating a smart contract to demonstrate how to store and retrieve the details of the employees of an organization using structure, arrays, and functions.
Solution:
Create a smart contract, StructDemo having structure Employee with data members as empid, name, department, designation. Create a dynamic array of Employee as emps.Create a function addEmployee() which takes the data of the employee and stores into a dynamic array called emps.Create a function getEmployee() which takes the employee id, searches the record in the emps array, and returns the details like name, department, and designation.
Create a smart contract, StructDemo having structure Employee with data members as empid, name, department, designation. Create a dynamic array of Employee as emps.
Create a function addEmployee() which takes the data of the employee and stores into a dynamic array called emps.
Create a function getEmployee() which takes the employee id, searches the record in the emps array, and returns the details like name, department, and designation.
Implementation:
Step 1: Open Remix-IDE.
Step 2: Select File Explorer from the left side icons and select Solidity in the environment. Click on New option below the Solidity environment. Enter the file name as StructDemo.sol and Click on the OK button.
Step 3: Enter the following Solidity Code. Select the same solidity version as in your code.
Solidity
// Solidity program // to store // Employee Detailspragma solidity ^0.6.8; // Creating a Smart Contractcontract StructDemo{ // Structure of employee struct Employee{ // State variables int empid; string name; string department; string designation; } Employee []emps; // Function to add // employee details function addEmployee( int empid, string memory name, string memory department, string memory designation ) public{ Employee memory e =Employee(empid, name, department, designation); emps.push(e); } // Function to get // details of employee function getEmployee( int empid ) public view returns( string memory, string memory, string memory){ uint i; for(i=0;i<emps.length;i++) { Employee memory e =emps[i]; // Looks for a matching // employee id if(e.empid==empid) { return(e.name, e.department, e.designation); } } // If provided employee // id is not present // it returns Not // Found return("Not Found", "Not Found", "Not Found"); }}
Step 4: Compile the file StructDemo.sol from the Solidity Compiler tab.
Step 5: Deploy the smart contract from the Deploy and Run Transaction tab.
Step 6: Then add the employee details through addEmployee() then after that, you can view details of any employee using employee id through getEmployee().
Solidity
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Solidity - Libraries
Solidity - Programming ERC-20 Token
Solidity - Break and Continue Statements
Solidity - Assembly
Creating Ownable Contracts in Solidity
What is Decentralized Voting Application (DApps)?
Solidity - Special Variables
Solidity - Basics of Contracts
Application Binary Interface(ABI) in Ethereum Virtual Machine
Solidity - Decision Making Statements
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Aug, 2020"
},
{
"code": null,
"e": 224,
"s": 28,
"text": "Solidity is a high-level language. The structure of smart contracts in solidity is very similar to the structure of classes in object-oriented languages. The solidity file has an extension .sol. "
},
{
"code": null,
"e": 507,
"s": 224,
"text": "Solidity’s code is encapsulated in contracts which means a contract in Solidity is a collection of code (its functions) and data (its state) that resides at a specific address on the Ethereum blockchain. A contract is a fundamental block of building an application on the Ethereum. "
},
{
"code": null,
"e": 703,
"s": 507,
"text": "Example: In the below example, we aim at creating a smart contract to demonstrate how to store and retrieve the details of the employees of an organization using structure, arrays, and functions."
},
{
"code": null,
"e": 713,
"s": 703,
"text": "Solution:"
},
{
"code": null,
"e": 1154,
"s": 713,
"text": "Create a smart contract, StructDemo having structure Employee with data members as empid, name, department, designation. Create a dynamic array of Employee as emps.Create a function addEmployee() which takes the data of the employee and stores into a dynamic array called emps.Create a function getEmployee() which takes the employee id, searches the record in the emps array, and returns the details like name, department, and designation."
},
{
"code": null,
"e": 1319,
"s": 1154,
"text": "Create a smart contract, StructDemo having structure Employee with data members as empid, name, department, designation. Create a dynamic array of Employee as emps."
},
{
"code": null,
"e": 1433,
"s": 1319,
"text": "Create a function addEmployee() which takes the data of the employee and stores into a dynamic array called emps."
},
{
"code": null,
"e": 1597,
"s": 1433,
"text": "Create a function getEmployee() which takes the employee id, searches the record in the emps array, and returns the details like name, department, and designation."
},
{
"code": null,
"e": 1613,
"s": 1597,
"text": "Implementation:"
},
{
"code": null,
"e": 1637,
"s": 1613,
"text": "Step 1: Open Remix-IDE."
},
{
"code": null,
"e": 1849,
"s": 1637,
"text": "Step 2: Select File Explorer from the left side icons and select Solidity in the environment. Click on New option below the Solidity environment. Enter the file name as StructDemo.sol and Click on the OK button."
},
{
"code": null,
"e": 1942,
"s": 1849,
"text": "Step 3: Enter the following Solidity Code. Select the same solidity version as in your code."
},
{
"code": null,
"e": 1951,
"s": 1942,
"text": "Solidity"
},
{
"code": "// Solidity program // to store // Employee Detailspragma solidity ^0.6.8; // Creating a Smart Contractcontract StructDemo{ // Structure of employee struct Employee{ // State variables int empid; string name; string department; string designation; } Employee []emps; // Function to add // employee details function addEmployee( int empid, string memory name, string memory department, string memory designation ) public{ Employee memory e =Employee(empid, name, department, designation); emps.push(e); } // Function to get // details of employee function getEmployee( int empid ) public view returns( string memory, string memory, string memory){ uint i; for(i=0;i<emps.length;i++) { Employee memory e =emps[i]; // Looks for a matching // employee id if(e.empid==empid) { return(e.name, e.department, e.designation); } } // If provided employee // id is not present // it returns Not // Found return(\"Not Found\", \"Not Found\", \"Not Found\"); }}",
"e": 3292,
"s": 1951,
"text": null
},
{
"code": null,
"e": 3364,
"s": 3292,
"text": "Step 4: Compile the file StructDemo.sol from the Solidity Compiler tab."
},
{
"code": null,
"e": 3439,
"s": 3364,
"text": "Step 5: Deploy the smart contract from the Deploy and Run Transaction tab."
},
{
"code": null,
"e": 3594,
"s": 3439,
"text": "Step 6: Then add the employee details through addEmployee() then after that, you can view details of any employee using employee id through getEmployee()."
},
{
"code": null,
"e": 3603,
"s": 3594,
"text": "Solidity"
},
{
"code": null,
"e": 3701,
"s": 3603,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3722,
"s": 3701,
"text": "Solidity - Libraries"
},
{
"code": null,
"e": 3758,
"s": 3722,
"text": "Solidity - Programming ERC-20 Token"
},
{
"code": null,
"e": 3799,
"s": 3758,
"text": "Solidity - Break and Continue Statements"
},
{
"code": null,
"e": 3819,
"s": 3799,
"text": "Solidity - Assembly"
},
{
"code": null,
"e": 3858,
"s": 3819,
"text": "Creating Ownable Contracts in Solidity"
},
{
"code": null,
"e": 3908,
"s": 3858,
"text": "What is Decentralized Voting Application (DApps)?"
},
{
"code": null,
"e": 3937,
"s": 3908,
"text": "Solidity - Special Variables"
},
{
"code": null,
"e": 3968,
"s": 3937,
"text": "Solidity - Basics of Contracts"
},
{
"code": null,
"e": 4030,
"s": 3968,
"text": "Application Binary Interface(ABI) in Ethereum Virtual Machine"
}
] |
attr.asdict() function in Python
|
05 Sep, 2020
Python has a library called attrs which makes code written in an object-oriented mode much easier and concise. In a class that has data, it is better to transform it into a dictionary. We can use attr.asdict() function in Python to return attrs attribute values of i as dict.
Syntax: attr.asdict (inst, recurse: bool=True, filter: __class__=None, dict_factory: , retain_collection_types: bool=False)
Parameters: inst : instance of an attrs-decorated class recurse : (boolean) recurse into classes that are also attrs-decorated dict_factory : a callable to produce dictionaries from filter : a callable that determines whether an attribute is included (True) or dropped (False) retain_collection_types : only meaningful if recurse is True.
Example 1: Let’s take a very simple example of class coordinates which accepts coordinates as attributes.
Python3
# import libraryimport attr # initialising class Coordinates, no need to# initialize __init__ method@attr.sclass Coordinates(object): # attributes x = attr.ib() y = attr.ib() c1 = Coordinates(1, 2) # converting data into dict using attr.asdict() # functionprint(attr.asdict(Coordinates(x=1, y=2)))
Output:
{'x': 1, 'y': 2}
Here, the data passed is getting converted into a dictionary form.
Example 2: Here is another example of class User Info which will accept the name and email id of the user as attributes, but will not include the email id of user in dict form of data.
Python3
import attr @attr.sclass UserInfo(object): users = attr.ib() @attr.sclass User(object): email = attr.ib() name = attr.ib() # including only name and not emailattr.asdict(UserInfo([User("lee@har.invalid", "Lee"), User("rachel@har.invalid", "Rachel")]), filter=lambda attr, value: attr.name != "email")
Output:
{'users': [{'name': 'Lee'}, {'name': 'Rachel'}]}
Here we will get a nested dictionary with email of user excluded.
Example 3: We can try a different approach for including or excluding an attribute by using the parameter filter of attr.asdict() function.
Python3
import attr @attr.sclass UserInfo(object): name = attr.ib() password = attr.ib() age = attr.ib() # excluding attributesprint(attr.asdict(UserInfo("Marco", "abc@123", 22), filter=attr.filters.exclude( attr.fields(UserInfo).password, int))) @attr.sclass Coordinates(object): x = attr.ib() y = attr.ib() z = attr.ib() # inclusing attributesprint(attr.asdict(Coordinates(20, "5", 3), filter=attr.filters.include(int)))
Output:
{'name': 'Marco'}
{'x': 20, 'z': 3}
Here, in class UserInfo, we have passed three arguments name, password, and age, out of which age is an integer value and the remaining values are string. In the filter parameter, we have excluded attributes – password and integer values(here -age), so password and age will be excluded from the dictionary.
In class Coordinates, we have passed three arguments- x, y, and z coordinates. Here y coordinate is passed as a string. In the filter parameter, we have included integer values. Thus, x and z coordinates are included in the final dictionary. If y-coordinate had been passed as an integer then it would have been included too.
python-oop-concepts
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Sep, 2020"
},
{
"code": null,
"e": 305,
"s": 28,
"text": "Python has a library called attrs which makes code written in an object-oriented mode much easier and concise. In a class that has data, it is better to transform it into a dictionary. We can use attr.asdict() function in Python to return attrs attribute values of i as dict. "
},
{
"code": null,
"e": 429,
"s": 305,
"text": "Syntax: attr.asdict (inst, recurse: bool=True, filter: __class__=None, dict_factory: , retain_collection_types: bool=False)"
},
{
"code": null,
"e": 769,
"s": 429,
"text": "Parameters: inst : instance of an attrs-decorated class recurse : (boolean) recurse into classes that are also attrs-decorated dict_factory : a callable to produce dictionaries from filter : a callable that determines whether an attribute is included (True) or dropped (False) retain_collection_types : only meaningful if recurse is True. "
},
{
"code": null,
"e": 875,
"s": 769,
"text": "Example 1: Let’s take a very simple example of class coordinates which accepts coordinates as attributes."
},
{
"code": null,
"e": 883,
"s": 875,
"text": "Python3"
},
{
"code": "# import libraryimport attr # initialising class Coordinates, no need to# initialize __init__ method@attr.sclass Coordinates(object): # attributes x = attr.ib() y = attr.ib() c1 = Coordinates(1, 2) # converting data into dict using attr.asdict() # functionprint(attr.asdict(Coordinates(x=1, y=2)))",
"e": 1201,
"s": 883,
"text": null
},
{
"code": null,
"e": 1209,
"s": 1201,
"text": "Output:"
},
{
"code": null,
"e": 1226,
"s": 1209,
"text": "{'x': 1, 'y': 2}"
},
{
"code": null,
"e": 1294,
"s": 1226,
"text": "Here, the data passed is getting converted into a dictionary form. "
},
{
"code": null,
"e": 1480,
"s": 1294,
"text": "Example 2: Here is another example of class User Info which will accept the name and email id of the user as attributes, but will not include the email id of user in dict form of data. "
},
{
"code": null,
"e": 1488,
"s": 1480,
"text": "Python3"
},
{
"code": "import attr @attr.sclass UserInfo(object): users = attr.ib() @attr.sclass User(object): email = attr.ib() name = attr.ib() # including only name and not emailattr.asdict(UserInfo([User(\"lee@har.invalid\", \"Lee\"), User(\"rachel@har.invalid\", \"Rachel\")]), filter=lambda attr, value: attr.name != \"email\")",
"e": 1839,
"s": 1488,
"text": null
},
{
"code": null,
"e": 1847,
"s": 1839,
"text": "Output:"
},
{
"code": null,
"e": 1896,
"s": 1847,
"text": "{'users': [{'name': 'Lee'}, {'name': 'Rachel'}]}"
},
{
"code": null,
"e": 1963,
"s": 1896,
"text": "Here we will get a nested dictionary with email of user excluded. "
},
{
"code": null,
"e": 2105,
"s": 1963,
"text": "Example 3: We can try a different approach for including or excluding an attribute by using the parameter filter of attr.asdict() function. "
},
{
"code": null,
"e": 2113,
"s": 2105,
"text": "Python3"
},
{
"code": "import attr @attr.sclass UserInfo(object): name = attr.ib() password = attr.ib() age = attr.ib() # excluding attributesprint(attr.asdict(UserInfo(\"Marco\", \"abc@123\", 22), filter=attr.filters.exclude( attr.fields(UserInfo).password, int))) @attr.sclass Coordinates(object): x = attr.ib() y = attr.ib() z = attr.ib() # inclusing attributesprint(attr.asdict(Coordinates(20, \"5\", 3), filter=attr.filters.include(int)))",
"e": 2613,
"s": 2113,
"text": null
},
{
"code": null,
"e": 2621,
"s": 2613,
"text": "Output:"
},
{
"code": null,
"e": 2657,
"s": 2621,
"text": "{'name': 'Marco'}\n{'x': 20, 'z': 3}"
},
{
"code": null,
"e": 2965,
"s": 2657,
"text": "Here, in class UserInfo, we have passed three arguments name, password, and age, out of which age is an integer value and the remaining values are string. In the filter parameter, we have excluded attributes – password and integer values(here -age), so password and age will be excluded from the dictionary."
},
{
"code": null,
"e": 3291,
"s": 2965,
"text": "In class Coordinates, we have passed three arguments- x, y, and z coordinates. Here y coordinate is passed as a string. In the filter parameter, we have included integer values. Thus, x and z coordinates are included in the final dictionary. If y-coordinate had been passed as an integer then it would have been included too."
},
{
"code": null,
"e": 3311,
"s": 3291,
"text": "python-oop-concepts"
},
{
"code": null,
"e": 3318,
"s": 3311,
"text": "Python"
},
{
"code": null,
"e": 3416,
"s": 3318,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3434,
"s": 3416,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3476,
"s": 3434,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3498,
"s": 3476,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3533,
"s": 3498,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 3559,
"s": 3533,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3591,
"s": 3559,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3620,
"s": 3591,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3647,
"s": 3620,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3677,
"s": 3647,
"text": "Iterate over a list in Python"
}
] |
Scala List isEmpty Operation with example
|
13 Aug, 2019
The isEmpty operation is utilized to check if the stated list is empty or not.Syntax:
m1.isEmpty
Here, m1 is Map name. isEmpty is method which returns true if the stated list is empty else it returns false.Example #1:
// Scala program of isEmpty()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a list val m1 = List(6, 8, 9, 12) // Applying isEmpty method val result = m1.isEmpty // Displays output println(result) }}
false
Example #2:
// Scala program of isEmpty()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a list val m1 = List() // Applying isEmpty method val result = m1.isEmpty // Displays output println(result) }}
true
Scala
Scala-list
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Class and Object in Scala
Type Casting in Scala
Scala Tutorial – Learn Scala with Step By Step Guide
Scala Lists
Operators in Scala
Scala | Arrays
Scala Constructors
Scala String substring() method with example
Lambda Expression in Scala
Scala Singleton and Companion Objects
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Aug, 2019"
},
{
"code": null,
"e": 114,
"s": 28,
"text": "The isEmpty operation is utilized to check if the stated list is empty or not.Syntax:"
},
{
"code": null,
"e": 125,
"s": 114,
"text": "m1.isEmpty"
},
{
"code": null,
"e": 246,
"s": 125,
"text": "Here, m1 is Map name. isEmpty is method which returns true if the stated list is empty else it returns false.Example #1:"
},
{
"code": "// Scala program of isEmpty()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a list val m1 = List(6, 8, 9, 12) // Applying isEmpty method val result = m1.isEmpty // Displays output println(result) }}",
"e": 586,
"s": 246,
"text": null
},
{
"code": null,
"e": 593,
"s": 586,
"text": "false\n"
},
{
"code": null,
"e": 605,
"s": 593,
"text": "Example #2:"
},
{
"code": "// Scala program of isEmpty()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a list val m1 = List() // Applying isEmpty method val result = m1.isEmpty // Displays output println(result) }}",
"e": 934,
"s": 605,
"text": null
},
{
"code": null,
"e": 940,
"s": 934,
"text": "true\n"
},
{
"code": null,
"e": 946,
"s": 940,
"text": "Scala"
},
{
"code": null,
"e": 957,
"s": 946,
"text": "Scala-list"
},
{
"code": null,
"e": 963,
"s": 957,
"text": "Scala"
},
{
"code": null,
"e": 1061,
"s": 963,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1087,
"s": 1061,
"text": "Class and Object in Scala"
},
{
"code": null,
"e": 1109,
"s": 1087,
"text": "Type Casting in Scala"
},
{
"code": null,
"e": 1162,
"s": 1109,
"text": "Scala Tutorial – Learn Scala with Step By Step Guide"
},
{
"code": null,
"e": 1174,
"s": 1162,
"text": "Scala Lists"
},
{
"code": null,
"e": 1193,
"s": 1174,
"text": "Operators in Scala"
},
{
"code": null,
"e": 1208,
"s": 1193,
"text": "Scala | Arrays"
},
{
"code": null,
"e": 1227,
"s": 1208,
"text": "Scala Constructors"
},
{
"code": null,
"e": 1272,
"s": 1227,
"text": "Scala String substring() method with example"
},
{
"code": null,
"e": 1299,
"s": 1272,
"text": "Lambda Expression in Scala"
}
] |
Kleene’s Theorem in TOC | Part-1
|
20 Nov, 2019
A language is said to be regular if it can be represented by using a Finite Automata or if a Regular Expression can be generated for it. This definition leads us to the general definition that; For every Regular Expression corresponding to the language, a Finite Automata can be generated.
For certain expressions like :- (a+b), ab, (a+b)* ; It’s fairly easier to make the Finite Automata by just intuition as shown below. The problem arises when we are provided with a longer Regular Expression. This brings about the need for a systematic approach towards FA generation, which has been put forward by Kleene in Kleene’s Theorem – I
Kleene’s Theorem-I :
For any Regular Expression r that represents Language L(r), there is a Finite Automata that accepts same language.
To understand Kleene’s Theorem-I, Let’s take in account the basic definition of Regular Expression where we observe that , and a single input symbol “a” can be included in a Regular Language and the corresponding operations that can be performed by the combination of these are:
Say, and be two regular expressions. Then,
+ is a regular expression too, whose corresponding language is L() U L(). is a regular expression too, whose corresponding language is L().L()* is a regular expression too, whose corresponding language is L()*
+ is a regular expression too, whose corresponding language is L() U L()
. is a regular expression too, whose corresponding language is L().L()
* is a regular expression too, whose corresponding language is L()*
We can further use this definition in association with Null Transitions to give rise to a FA by the combination of two or more smaller Finite Automata (each corresponding to a Regular Expression).
Let S accept L = {a} and T accept L = {b}, then R can be represented as a combination of S and T using the provided operations as:
R = S + T
We observe that,
In case of union operation we can have a new start state, from which, null transition proceeds to the starting state of both the Finite State Machines.The final states of both the Finite Automata’s are converted to intermediate states. The final state is unified into one which can be traversed by null transitions.
In case of union operation we can have a new start state, from which, null transition proceeds to the starting state of both the Finite State Machines.
The final states of both the Finite Automata’s are converted to intermediate states. The final state is unified into one which can be traversed by null transitions.
R = S.T
We observe that,
In case of concatenation operation we can have the same starting state as that of S, the only change occurs in the end state of S, which is converted to an intermediate state followed by a Null Transition.The Null transition is followed by the starting state of T, the final state of T is used as the end state of R.
In case of concatenation operation we can have the same starting state as that of S, the only change occurs in the end state of S, which is converted to an intermediate state followed by a Null Transition.
The Null transition is followed by the starting state of T, the final state of T is used as the end state of R.
R = S*
We observe that,
A new starting state is added, and S has been put as an intermediate state so that self looping condition could be incorporated.Starting and Ending states have been defined separately so that the self looping condition is not disturbed.
A new starting state is added, and S has been put as an intermediate state so that self looping condition could be incorporated.
Starting and Ending states have been defined separately so that the self looping condition is not disturbed.
Now that we are aware about the general operations. Let’s see how Kleene’s Theorem-I can be used to generate a FA for the given Regular Expression.
Example:
Make a Finite Automata for the expression (ab+a)*
We see that using Kleene’s Theorem – I gives a systematic approach towards the generation of a Finite Automata for the provided Regular Expression.
GATE CS
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Page Replacement Algorithms in Operating Systems
Introduction of Operating System - Set 1
Inter Process Communication (IPC)
Differences between TCP and UDP
Semaphores in Process Synchronization
Introduction of Finite Automata
Difference between DFA and NFA
Turing Machine in TOC
Chomsky Hierarchy in Theory of Computation
Boyer-Moore Majority Voting Algorithm
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n20 Nov, 2019"
},
{
"code": null,
"e": 342,
"s": 52,
"text": "A language is said to be regular if it can be represented by using a Finite Automata or if a Regular Expression can be generated for it. This definition leads us to the general definition that; For every Regular Expression corresponding to the language, a Finite Automata can be generated."
},
{
"code": null,
"e": 686,
"s": 342,
"text": "For certain expressions like :- (a+b), ab, (a+b)* ; It’s fairly easier to make the Finite Automata by just intuition as shown below. The problem arises when we are provided with a longer Regular Expression. This brings about the need for a systematic approach towards FA generation, which has been put forward by Kleene in Kleene’s Theorem – I"
},
{
"code": null,
"e": 707,
"s": 686,
"text": "Kleene’s Theorem-I :"
},
{
"code": null,
"e": 822,
"s": 707,
"text": "For any Regular Expression r that represents Language L(r), there is a Finite Automata that accepts same language."
},
{
"code": null,
"e": 1102,
"s": 822,
"text": "To understand Kleene’s Theorem-I, Let’s take in account the basic definition of Regular Expression where we observe that , and a single input symbol “a” can be included in a Regular Language and the corresponding operations that can be performed by the combination of these are:"
},
{
"code": null,
"e": 1147,
"s": 1102,
"text": "Say, and be two regular expressions. Then,"
},
{
"code": null,
"e": 1357,
"s": 1147,
"text": "+ is a regular expression too, whose corresponding language is L() U L(). is a regular expression too, whose corresponding language is L().L()* is a regular expression too, whose corresponding language is L()*"
},
{
"code": null,
"e": 1430,
"s": 1357,
"text": "+ is a regular expression too, whose corresponding language is L() U L()"
},
{
"code": null,
"e": 1501,
"s": 1430,
"text": ". is a regular expression too, whose corresponding language is L().L()"
},
{
"code": null,
"e": 1569,
"s": 1501,
"text": "* is a regular expression too, whose corresponding language is L()*"
},
{
"code": null,
"e": 1766,
"s": 1569,
"text": "We can further use this definition in association with Null Transitions to give rise to a FA by the combination of two or more smaller Finite Automata (each corresponding to a Regular Expression)."
},
{
"code": null,
"e": 1897,
"s": 1766,
"text": "Let S accept L = {a} and T accept L = {b}, then R can be represented as a combination of S and T using the provided operations as:"
},
{
"code": null,
"e": 1907,
"s": 1897,
"text": "R = S + T"
},
{
"code": null,
"e": 1924,
"s": 1907,
"text": "We observe that,"
},
{
"code": null,
"e": 2240,
"s": 1924,
"text": "In case of union operation we can have a new start state, from which, null transition proceeds to the starting state of both the Finite State Machines.The final states of both the Finite Automata’s are converted to intermediate states. The final state is unified into one which can be traversed by null transitions."
},
{
"code": null,
"e": 2392,
"s": 2240,
"text": "In case of union operation we can have a new start state, from which, null transition proceeds to the starting state of both the Finite State Machines."
},
{
"code": null,
"e": 2557,
"s": 2392,
"text": "The final states of both the Finite Automata’s are converted to intermediate states. The final state is unified into one which can be traversed by null transitions."
},
{
"code": null,
"e": 2566,
"s": 2557,
"text": "R = S.T "
},
{
"code": null,
"e": 2583,
"s": 2566,
"text": "We observe that,"
},
{
"code": null,
"e": 2900,
"s": 2583,
"text": "In case of concatenation operation we can have the same starting state as that of S, the only change occurs in the end state of S, which is converted to an intermediate state followed by a Null Transition.The Null transition is followed by the starting state of T, the final state of T is used as the end state of R."
},
{
"code": null,
"e": 3106,
"s": 2900,
"text": "In case of concatenation operation we can have the same starting state as that of S, the only change occurs in the end state of S, which is converted to an intermediate state followed by a Null Transition."
},
{
"code": null,
"e": 3218,
"s": 3106,
"text": "The Null transition is followed by the starting state of T, the final state of T is used as the end state of R."
},
{
"code": null,
"e": 3226,
"s": 3218,
"text": " R = S*"
},
{
"code": null,
"e": 3243,
"s": 3226,
"text": "We observe that,"
},
{
"code": null,
"e": 3480,
"s": 3243,
"text": "A new starting state is added, and S has been put as an intermediate state so that self looping condition could be incorporated.Starting and Ending states have been defined separately so that the self looping condition is not disturbed."
},
{
"code": null,
"e": 3609,
"s": 3480,
"text": "A new starting state is added, and S has been put as an intermediate state so that self looping condition could be incorporated."
},
{
"code": null,
"e": 3718,
"s": 3609,
"text": "Starting and Ending states have been defined separately so that the self looping condition is not disturbed."
},
{
"code": null,
"e": 3866,
"s": 3718,
"text": "Now that we are aware about the general operations. Let’s see how Kleene’s Theorem-I can be used to generate a FA for the given Regular Expression."
},
{
"code": null,
"e": 3926,
"s": 3866,
"text": "Example:\nMake a Finite Automata for the expression (ab+a)* "
},
{
"code": null,
"e": 4074,
"s": 3926,
"text": "We see that using Kleene’s Theorem – I gives a systematic approach towards the generation of a Finite Automata for the provided Regular Expression."
},
{
"code": null,
"e": 4082,
"s": 4074,
"text": "GATE CS"
},
{
"code": null,
"e": 4115,
"s": 4082,
"text": "Theory of Computation & Automata"
},
{
"code": null,
"e": 4213,
"s": 4115,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4262,
"s": 4213,
"text": "Page Replacement Algorithms in Operating Systems"
},
{
"code": null,
"e": 4303,
"s": 4262,
"text": "Introduction of Operating System - Set 1"
},
{
"code": null,
"e": 4337,
"s": 4303,
"text": "Inter Process Communication (IPC)"
},
{
"code": null,
"e": 4369,
"s": 4337,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 4407,
"s": 4369,
"text": "Semaphores in Process Synchronization"
},
{
"code": null,
"e": 4439,
"s": 4407,
"text": "Introduction of Finite Automata"
},
{
"code": null,
"e": 4470,
"s": 4439,
"text": "Difference between DFA and NFA"
},
{
"code": null,
"e": 4492,
"s": 4470,
"text": "Turing Machine in TOC"
},
{
"code": null,
"e": 4535,
"s": 4492,
"text": "Chomsky Hierarchy in Theory of Computation"
}
] |
Relational Query Evaluation | Set 1
|
14 Jul, 2020
There is a need for conversion of relational query to algebraic expressions. This expression is operated on so that final output is received. The relational algebra operators that are present are Union, Select, Join, Project, etc. These are used to formulate relational query for adequate results. Grouping, partitioning and aggregation are all parts of relational query.
Implementation :Selection of proper algorithms is necessary to optimize life and performance of disks, where data is stored. If lot of read and write operations are performed (data modification and updation) on disk, its life is reduced due to wear and tear.
Selection Operator :
One Selection Condition –In case we need to use select operator for selecting particular tuples of relation based on condition, following things can be done. If there is only one selection condition, then we need to check for presence of indexes. If indexes are present on attribute, we can easily find selection based on these indexes as indexes provide record and block pointers that can be used in searching. For any reason, if indexes are absent, then entire file needs to be searched for selection.Multiple Conjunctive Selection Condition –In the case of multiple conjunctive selection condition, if none of attributes have any index, complete file scan needs to be done for selection of relevant tuples. However, if any of attributes do have index, then we need to go to relevant attribute and select tuples whose values for attribute are equivalent to given condition, and then in those records, other conjunctive conditions can be checked.Multiple Disjunctive Selection Condition –In case attributes have multiple disjunctive selection condition, it is of no use if only one attribute has index, rather it is necessary that all attributes have index. Otherwise, complete file scan is necessary to get selections.Selection of Predicates –If index is present for multiple attributes, one can choose highly selective attribute. This can be done by using Selectivity. The selectivity of any particular attribute is ratio of the number of records satisfying condition to total number of records. The selectivity can range anywhere between and including 0 and 1. The condition is rated as highly selective if it has low value of selectivity.
One Selection Condition –In case we need to use select operator for selecting particular tuples of relation based on condition, following things can be done. If there is only one selection condition, then we need to check for presence of indexes. If indexes are present on attribute, we can easily find selection based on these indexes as indexes provide record and block pointers that can be used in searching. For any reason, if indexes are absent, then entire file needs to be searched for selection.
Multiple Conjunctive Selection Condition –In the case of multiple conjunctive selection condition, if none of attributes have any index, complete file scan needs to be done for selection of relevant tuples. However, if any of attributes do have index, then we need to go to relevant attribute and select tuples whose values for attribute are equivalent to given condition, and then in those records, other conjunctive conditions can be checked.
Multiple Disjunctive Selection Condition –In case attributes have multiple disjunctive selection condition, it is of no use if only one attribute has index, rather it is necessary that all attributes have index. Otherwise, complete file scan is necessary to get selections.
Selection of Predicates –If index is present for multiple attributes, one can choose highly selective attribute. This can be done by using Selectivity. The selectivity of any particular attribute is ratio of the number of records satisfying condition to total number of records. The selectivity can range anywhere between and including 0 and 1. The condition is rated as highly selective if it has low value of selectivity.
For the conjunction of conditions, attribute with least selectivity value is to be chosen. Tuples corresponding to condition are to be found and then other conditions are to be implemented on it. The selectivity values or their estimates can be recorded while database is in use. It can be placed in DB catalog. The DB catalog (database catalog) consists of metadata and relevant statistics about data, such as selectivity. These are used by Query optimizer which is part of RDBMS Architecture.
The formulas for estimating Selectivity are given below :
In case of key attributes selectivity is roughly –1 / (total db records)
1 / (total db records)
In case of non key attributes selectivity is roughly –1 / distinct values of columns
1 / distinct values of columns
There is also presence of Histograms in DBMS. The histogram represents distinct values of attributes or range of values of attributes in horizontal axis. Whereas, on vertical axis, it represents number of records corresponding to values in range. We can use histogram to estimate number of records that correspond to given condition in database. These estimations can be recorded offline as well.
Refer for – Relational Query Evaluation | Set 2
DBMS-Relational Algebra
DBMS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
Difference between Clustered and Non-clustered index
Introduction of B-Tree
SQL Interview Questions
Data Preprocessing in Data Mining
SQL | Views
Difference between DELETE, DROP and TRUNCATE
Difference between SQL and NoSQL
Indexing in Databases | Set 1
Difference between Primary Key and Foreign Key
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Jul, 2020"
},
{
"code": null,
"e": 400,
"s": 28,
"text": "There is a need for conversion of relational query to algebraic expressions. This expression is operated on so that final output is received. The relational algebra operators that are present are Union, Select, Join, Project, etc. These are used to formulate relational query for adequate results. Grouping, partitioning and aggregation are all parts of relational query."
},
{
"code": null,
"e": 659,
"s": 400,
"text": "Implementation :Selection of proper algorithms is necessary to optimize life and performance of disks, where data is stored. If lot of read and write operations are performed (data modification and updation) on disk, its life is reduced due to wear and tear."
},
{
"code": null,
"e": 680,
"s": 659,
"text": "Selection Operator :"
},
{
"code": null,
"e": 2324,
"s": 680,
"text": "One Selection Condition –In case we need to use select operator for selecting particular tuples of relation based on condition, following things can be done. If there is only one selection condition, then we need to check for presence of indexes. If indexes are present on attribute, we can easily find selection based on these indexes as indexes provide record and block pointers that can be used in searching. For any reason, if indexes are absent, then entire file needs to be searched for selection.Multiple Conjunctive Selection Condition –In the case of multiple conjunctive selection condition, if none of attributes have any index, complete file scan needs to be done for selection of relevant tuples. However, if any of attributes do have index, then we need to go to relevant attribute and select tuples whose values for attribute are equivalent to given condition, and then in those records, other conjunctive conditions can be checked.Multiple Disjunctive Selection Condition –In case attributes have multiple disjunctive selection condition, it is of no use if only one attribute has index, rather it is necessary that all attributes have index. Otherwise, complete file scan is necessary to get selections.Selection of Predicates –If index is present for multiple attributes, one can choose highly selective attribute. This can be done by using Selectivity. The selectivity of any particular attribute is ratio of the number of records satisfying condition to total number of records. The selectivity can range anywhere between and including 0 and 1. The condition is rated as highly selective if it has low value of selectivity."
},
{
"code": null,
"e": 2828,
"s": 2324,
"text": "One Selection Condition –In case we need to use select operator for selecting particular tuples of relation based on condition, following things can be done. If there is only one selection condition, then we need to check for presence of indexes. If indexes are present on attribute, we can easily find selection based on these indexes as indexes provide record and block pointers that can be used in searching. For any reason, if indexes are absent, then entire file needs to be searched for selection."
},
{
"code": null,
"e": 3273,
"s": 2828,
"text": "Multiple Conjunctive Selection Condition –In the case of multiple conjunctive selection condition, if none of attributes have any index, complete file scan needs to be done for selection of relevant tuples. However, if any of attributes do have index, then we need to go to relevant attribute and select tuples whose values for attribute are equivalent to given condition, and then in those records, other conjunctive conditions can be checked."
},
{
"code": null,
"e": 3547,
"s": 3273,
"text": "Multiple Disjunctive Selection Condition –In case attributes have multiple disjunctive selection condition, it is of no use if only one attribute has index, rather it is necessary that all attributes have index. Otherwise, complete file scan is necessary to get selections."
},
{
"code": null,
"e": 3971,
"s": 3547,
"text": "Selection of Predicates –If index is present for multiple attributes, one can choose highly selective attribute. This can be done by using Selectivity. The selectivity of any particular attribute is ratio of the number of records satisfying condition to total number of records. The selectivity can range anywhere between and including 0 and 1. The condition is rated as highly selective if it has low value of selectivity."
},
{
"code": null,
"e": 4466,
"s": 3971,
"text": "For the conjunction of conditions, attribute with least selectivity value is to be chosen. Tuples corresponding to condition are to be found and then other conditions are to be implemented on it. The selectivity values or their estimates can be recorded while database is in use. It can be placed in DB catalog. The DB catalog (database catalog) consists of metadata and relevant statistics about data, such as selectivity. These are used by Query optimizer which is part of RDBMS Architecture."
},
{
"code": null,
"e": 4524,
"s": 4466,
"text": "The formulas for estimating Selectivity are given below :"
},
{
"code": null,
"e": 4597,
"s": 4524,
"text": "In case of key attributes selectivity is roughly –1 / (total db records)"
},
{
"code": null,
"e": 4620,
"s": 4597,
"text": "1 / (total db records)"
},
{
"code": null,
"e": 4705,
"s": 4620,
"text": "In case of non key attributes selectivity is roughly –1 / distinct values of columns"
},
{
"code": null,
"e": 4736,
"s": 4705,
"text": "1 / distinct values of columns"
},
{
"code": null,
"e": 5133,
"s": 4736,
"text": "There is also presence of Histograms in DBMS. The histogram represents distinct values of attributes or range of values of attributes in horizontal axis. Whereas, on vertical axis, it represents number of records corresponding to values in range. We can use histogram to estimate number of records that correspond to given condition in database. These estimations can be recorded offline as well."
},
{
"code": null,
"e": 5181,
"s": 5133,
"text": "Refer for – Relational Query Evaluation | Set 2"
},
{
"code": null,
"e": 5205,
"s": 5181,
"text": "DBMS-Relational Algebra"
},
{
"code": null,
"e": 5210,
"s": 5205,
"text": "DBMS"
},
{
"code": null,
"e": 5215,
"s": 5210,
"text": "DBMS"
},
{
"code": null,
"e": 5313,
"s": 5215,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5324,
"s": 5313,
"text": "CTE in SQL"
},
{
"code": null,
"e": 5377,
"s": 5324,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 5400,
"s": 5377,
"text": "Introduction of B-Tree"
},
{
"code": null,
"e": 5424,
"s": 5400,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 5458,
"s": 5424,
"text": "Data Preprocessing in Data Mining"
},
{
"code": null,
"e": 5470,
"s": 5458,
"text": "SQL | Views"
},
{
"code": null,
"e": 5515,
"s": 5470,
"text": "Difference between DELETE, DROP and TRUNCATE"
},
{
"code": null,
"e": 5548,
"s": 5515,
"text": "Difference between SQL and NoSQL"
},
{
"code": null,
"e": 5578,
"s": 5548,
"text": "Indexing in Databases | Set 1"
}
] |
How to send response from server to client using Node.js and Express.js ?
|
06 Oct, 2021
The following approach covers how to send responses from servers using node and express. Also, we are going to see different ways to send responses from the server to the client.
Prerequisite:
Node js: It is an open-source JavaScript Back-End technology.
Express.js: It is a node.js server framework.
Required Module: Install the express module using the following command:
npm install express
Methods to send response from server to client are:
Using send() function.Using json() function.
Using send() function.
Using json() function.
Example 1: Demonstrating the use of the status() function.
index.js
const express = require('express');const app = express(); app.get('/' , (req,res)=>{ // 200 status code means OK res.status().send(200); }) // Server setupapp.listen(4000 , ()=>{ console.log("server running");});
Run the index.js file using the following command:
node index.js
Output: Now open your browser and go to http://localhost:4000/, you will see the following output:
Example 2: Sending some particular data to the client then you can use send() function.
index.js
const express = require('express');const app = express(); var computerSciencePortal = "GeeksforGeeks"; app.get('/' , (req,res)=>{ // Server will send GeeksforGeeks as response res.send(computerSciencePortal); }) // Server setupapp.listen(4000 , ()=>{ console.log("server running");});
Run the index.js file using the following command:
node index.js
Output: Now open your browser and go to http://localhost:4000/, you will see the following output:
Example 3: Sending the JSON response from the server to the client using json() function.
index.js
const express = require('express');const app = express(); // Sample JSON datavar data = { portal : "GeeksforGeeks", knowledge : "unlimited", location : "Noida" } app.get('/' , (req,res)=>{ // This will send the JSON data to the client. res.json(data); }) // Server setupapp.listen(4000 , ()=>{ console.log("server running");});
Run the index.js file using the following command:
node index.js
Output: Now open your browser and go to http://localhost:4000/, you will see the following output:
So, These are the methods that you can use to send responses from server to client using node and express.
Node.js
NodeJS-Questions
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n06 Oct, 2021"
},
{
"code": null,
"e": 232,
"s": 53,
"text": "The following approach covers how to send responses from servers using node and express. Also, we are going to see different ways to send responses from the server to the client."
},
{
"code": null,
"e": 246,
"s": 232,
"text": "Prerequisite:"
},
{
"code": null,
"e": 308,
"s": 246,
"text": "Node js: It is an open-source JavaScript Back-End technology."
},
{
"code": null,
"e": 354,
"s": 308,
"text": "Express.js: It is a node.js server framework."
},
{
"code": null,
"e": 427,
"s": 354,
"text": "Required Module: Install the express module using the following command:"
},
{
"code": null,
"e": 447,
"s": 427,
"text": "npm install express"
},
{
"code": null,
"e": 499,
"s": 447,
"text": "Methods to send response from server to client are:"
},
{
"code": null,
"e": 544,
"s": 499,
"text": "Using send() function.Using json() function."
},
{
"code": null,
"e": 567,
"s": 544,
"text": "Using send() function."
},
{
"code": null,
"e": 590,
"s": 567,
"text": "Using json() function."
},
{
"code": null,
"e": 649,
"s": 590,
"text": "Example 1: Demonstrating the use of the status() function."
},
{
"code": null,
"e": 658,
"s": 649,
"text": "index.js"
},
{
"code": "const express = require('express');const app = express(); app.get('/' , (req,res)=>{ // 200 status code means OK res.status().send(200); }) // Server setupapp.listen(4000 , ()=>{ console.log(\"server running\");});",
"e": 880,
"s": 658,
"text": null
},
{
"code": null,
"e": 931,
"s": 880,
"text": "Run the index.js file using the following command:"
},
{
"code": null,
"e": 945,
"s": 931,
"text": "node index.js"
},
{
"code": null,
"e": 1044,
"s": 945,
"text": "Output: Now open your browser and go to http://localhost:4000/, you will see the following output:"
},
{
"code": null,
"e": 1132,
"s": 1044,
"text": "Example 2: Sending some particular data to the client then you can use send() function."
},
{
"code": null,
"e": 1141,
"s": 1132,
"text": "index.js"
},
{
"code": "const express = require('express');const app = express(); var computerSciencePortal = \"GeeksforGeeks\"; app.get('/' , (req,res)=>{ // Server will send GeeksforGeeks as response res.send(computerSciencePortal); }) // Server setupapp.listen(4000 , ()=>{ console.log(\"server running\");});",
"e": 1436,
"s": 1141,
"text": null
},
{
"code": null,
"e": 1487,
"s": 1436,
"text": "Run the index.js file using the following command:"
},
{
"code": null,
"e": 1501,
"s": 1487,
"text": "node index.js"
},
{
"code": null,
"e": 1600,
"s": 1501,
"text": "Output: Now open your browser and go to http://localhost:4000/, you will see the following output:"
},
{
"code": null,
"e": 1690,
"s": 1600,
"text": "Example 3: Sending the JSON response from the server to the client using json() function."
},
{
"code": null,
"e": 1699,
"s": 1690,
"text": "index.js"
},
{
"code": "const express = require('express');const app = express(); // Sample JSON datavar data = { portal : \"GeeksforGeeks\", knowledge : \"unlimited\", location : \"Noida\" } app.get('/' , (req,res)=>{ // This will send the JSON data to the client. res.json(data); }) // Server setupapp.listen(4000 , ()=>{ console.log(\"server running\");});",
"e": 2048,
"s": 1699,
"text": null
},
{
"code": null,
"e": 2099,
"s": 2048,
"text": "Run the index.js file using the following command:"
},
{
"code": null,
"e": 2113,
"s": 2099,
"text": "node index.js"
},
{
"code": null,
"e": 2212,
"s": 2113,
"text": "Output: Now open your browser and go to http://localhost:4000/, you will see the following output:"
},
{
"code": null,
"e": 2319,
"s": 2212,
"text": "So, These are the methods that you can use to send responses from server to client using node and express."
},
{
"code": null,
"e": 2327,
"s": 2319,
"text": "Node.js"
},
{
"code": null,
"e": 2344,
"s": 2327,
"text": "NodeJS-Questions"
},
{
"code": null,
"e": 2352,
"s": 2344,
"text": "Node.js"
},
{
"code": null,
"e": 2369,
"s": 2352,
"text": "Web Technologies"
}
] |
Java Integer byteValue() Method
|
06 May, 2022
The byteValue() method of Integer class of java.lang package converts the given Integer into a byte after a narrowing primitive conversion and returns it (value of integer object as a byte). Also, remember this method does override byteValue() method of the Number class.
The package view is as follows:
--> java.lang Package
--> Integer Class
--> byteValue() Method
Syntax :
public byte byteValue()
Return Type: Returns the numeric value represented by this object after conversion to byte type.
Note: It is compatible with Java 1.5 and onwards.
Example 1:
Java
// Java program to Illustrate byteValue() Method// Of Integer Class // Importing required classimport java.lang.Integer; // Main Classclass GFG { // Main driver method public static void main(String args[]) { // Creating an Integer object and // passing custom integer input Integer a = new Integer(34); // Converting integer number to byte value // using byteValue() method byte b = a.byteValue(); // Printing the corresponding byte value System.out.println(b); }}
34
Example 2:
Java
// Java Program to Illustrate byteValue() Method// of Integer Class // Importing required classesimport java.lang.*;import java.util.*; // Main Classclass GFG { // Main driver method public static void main(String[] args) { // Creating a Byte object Byte b = new Byte("01"); // Converting Byte to byte primitive // using byteValue() method Byte bp = b.byteValue(); // Display statement System.out.println("Byte object : " + b); // Primitive byte value of custom Byte passed above String str = "Primitive byte value of Byte object : " + bp; // Printing byte primitive value System.out.println(str); }}
Byte object : 1
Primitive byte value of Byte object : 1
solankimayank
rkbhola5
Java-Functions
Java-Integer
Java-lang package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 May, 2022"
},
{
"code": null,
"e": 302,
"s": 28,
"text": "The byteValue() method of Integer class of java.lang package converts the given Integer into a byte after a narrowing primitive conversion and returns it (value of integer object as a byte). Also, remember this method does override byteValue() method of the Number class. "
},
{
"code": null,
"e": 334,
"s": 302,
"text": "The package view is as follows:"
},
{
"code": null,
"e": 411,
"s": 334,
"text": "--> java.lang Package \n --> Integer Class\n --> byteValue() Method "
},
{
"code": null,
"e": 420,
"s": 411,
"text": "Syntax :"
},
{
"code": null,
"e": 444,
"s": 420,
"text": "public byte byteValue()"
},
{
"code": null,
"e": 541,
"s": 444,
"text": "Return Type: Returns the numeric value represented by this object after conversion to byte type."
},
{
"code": null,
"e": 591,
"s": 541,
"text": "Note: It is compatible with Java 1.5 and onwards."
},
{
"code": null,
"e": 602,
"s": 591,
"text": "Example 1:"
},
{
"code": null,
"e": 607,
"s": 602,
"text": "Java"
},
{
"code": "// Java program to Illustrate byteValue() Method// Of Integer Class // Importing required classimport java.lang.Integer; // Main Classclass GFG { // Main driver method public static void main(String args[]) { // Creating an Integer object and // passing custom integer input Integer a = new Integer(34); // Converting integer number to byte value // using byteValue() method byte b = a.byteValue(); // Printing the corresponding byte value System.out.println(b); }}",
"e": 1142,
"s": 607,
"text": null
},
{
"code": null,
"e": 1145,
"s": 1142,
"text": "34"
},
{
"code": null,
"e": 1156,
"s": 1145,
"text": "Example 2:"
},
{
"code": null,
"e": 1161,
"s": 1156,
"text": "Java"
},
{
"code": "// Java Program to Illustrate byteValue() Method// of Integer Class // Importing required classesimport java.lang.*;import java.util.*; // Main Classclass GFG { // Main driver method public static void main(String[] args) { // Creating a Byte object Byte b = new Byte(\"01\"); // Converting Byte to byte primitive // using byteValue() method Byte bp = b.byteValue(); // Display statement System.out.println(\"Byte object : \" + b); // Primitive byte value of custom Byte passed above String str = \"Primitive byte value of Byte object : \" + bp; // Printing byte primitive value System.out.println(str); }}",
"e": 1868,
"s": 1161,
"text": null
},
{
"code": null,
"e": 1924,
"s": 1868,
"text": "Byte object : 1\nPrimitive byte value of Byte object : 1"
},
{
"code": null,
"e": 1938,
"s": 1924,
"text": "solankimayank"
},
{
"code": null,
"e": 1947,
"s": 1938,
"text": "rkbhola5"
},
{
"code": null,
"e": 1962,
"s": 1947,
"text": "Java-Functions"
},
{
"code": null,
"e": 1975,
"s": 1962,
"text": "Java-Integer"
},
{
"code": null,
"e": 1993,
"s": 1975,
"text": "Java-lang package"
},
{
"code": null,
"e": 1998,
"s": 1993,
"text": "Java"
},
{
"code": null,
"e": 2003,
"s": 1998,
"text": "Java"
}
] |
Test Driver
|
Test Drivers are used during Bottom-up integration testing in order to simulate the behaviour of the upper level modules that are not yet integrated. Test Drivers are the modules that act as temporary replacement for a calling module and give the same output as that of the actual product.
Drivers are also used when the software needs to interact with an external system and are usually complex than stubs.
The above diagrams clearly states that Modules 4, 5, 6 and 7 are unavailable for integration, whereas, above modules are still under development that cannot be integrated at this point of time. Hence, drivers are used to test the modules. The order of Integration will be:
4,2
5,2
6,3
7,3
2,1
3,1
+ Firstly, the integration between the modules 4,5,6 and 7
+ Test the integration between the module 4 and 5 with Driver 2
+ Test the integration between the module 6 and 7 with Driver 3
|
[
{
"code": null,
"e": 6169,
"s": 5879,
"text": "Test Drivers are used during Bottom-up integration testing in order to simulate the behaviour of the upper level modules that are not yet integrated. Test Drivers are the modules that act as temporary replacement for a calling module and give the same output as that of the actual product."
},
{
"code": null,
"e": 6287,
"s": 6169,
"text": "Drivers are also used when the software needs to interact with an external system and are usually complex than stubs."
},
{
"code": null,
"e": 6560,
"s": 6287,
"text": "The above diagrams clearly states that Modules 4, 5, 6 and 7 are unavailable for integration, whereas, above modules are still under development that cannot be integrated at this point of time. Hence, drivers are used to test the modules. The order of Integration will be:"
},
{
"code": null,
"e": 6584,
"s": 6560,
"text": "4,2\n5,2\n6,3\n7,3\n2,1\n3,1"
}
] |
How to Make, Save, and Run a Simple VBScript Program?
|
05 Aug, 2021
VBScript is a lightweight scripting version of the popular Microsoft Visual Basic, developed by as the name suggests, Microsoft. It is used to develop dynamic web pages. It is much lighter compared to Visual Basic programming language but works as a scripting language like JavaScript. To run VBScript on the client-side, the client must have to use Internet Explorer because other browsers are still not supported by the VBScript.
Just like many other simple scripting languages, VBScript can be written on a simple word editor, like notepad and other such softwares (e.g. notepad++, Wordpad, etc.). Refer the following steps to get a better idea of making a VBScript program:
Step 1: Open up a word editor of your choice (Here, notepad is used).
Step 2: For now, here is a simple VBScript program that will make a simple message dialog box to appear on the screen. The code for such a program in VBScript is:
a = msgbox("Have a good day, fellow GFG reader!", 0, "Making a VBScript program")
Code Explanation: You can put anything as long as it follows the variable declaration rules in VBScript instead of “a” which is at the beginning of the above code. Effectively, We can break and understand the above code in the following manner:
put_any_Variable_name = msgbox("Your main text here", 0, "Your title text here")
To change the property of the dialog box with respect to what you need, refer the following data:
Change “0” in the above written code with any of the numbers provided just above. To get more than one above mentioned property in you dialog box, you can simple write, for example: “0+16”, instead of “0” in above code. For reference, the code:
hydro = msgbox("Remember to drink water!", 0+64, "Hydration Check")
will give the following output:
That’s it, we have just written a basic VBScript program that will display a dialog box as output. Now onto saving this program.
Follow the steps given below to save a VBScript program:
Step 1: Press Ctrl + Shift + S on the keyboard, Or click File>Save As on the notepad window, this will open up a Save As dialog window asking where to save the current notepad document.
Step 2: Now write any file name of your choice for this notepad document but make sure you write .vbs as its extension. Make sure to add “.vbs” after writing the file name in the “File name:” field.
Step 3: Now, change the value of “Save as type:” field from “Text Documents (*.txt)” to “All Files (*.*)” by clicking on it with help of the drop down menu.
Step 4: Finally, click on save after choosing an appropriate location of where the file should be saved to.
Now, this is a very simple thing to do, simply double click on the now saved .vbs file from wherever you saved it and voila! It will run and give you the following output:
adamyaswarup087
VBScript
How To
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java Tutorial
How to Align Text in HTML?
How to Install FFmpeg on Windows?
How to Install Jupyter Notebook on MacOS?
How to setup Anaconda path to environment variable ?
How to insert spaces/tabs in text using HTML/CSS?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Node.js fs.readFileSync() Method
How to set the default value for an HTML <select> element ?
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n05 Aug, 2021"
},
{
"code": null,
"e": 486,
"s": 53,
"text": "VBScript is a lightweight scripting version of the popular Microsoft Visual Basic, developed by as the name suggests, Microsoft. It is used to develop dynamic web pages. It is much lighter compared to Visual Basic programming language but works as a scripting language like JavaScript. To run VBScript on the client-side, the client must have to use Internet Explorer because other browsers are still not supported by the VBScript. "
},
{
"code": null,
"e": 733,
"s": 486,
"text": "Just like many other simple scripting languages, VBScript can be written on a simple word editor, like notepad and other such softwares (e.g. notepad++, Wordpad, etc.). Refer the following steps to get a better idea of making a VBScript program: "
},
{
"code": null,
"e": 804,
"s": 733,
"text": "Step 1: Open up a word editor of your choice (Here, notepad is used). "
},
{
"code": null,
"e": 971,
"s": 804,
"text": " Step 2: For now, here is a simple VBScript program that will make a simple message dialog box to appear on the screen. The code for such a program in VBScript is: "
},
{
"code": null,
"e": 1053,
"s": 971,
"text": "a = msgbox(\"Have a good day, fellow GFG reader!\", 0, \"Making a VBScript program\")"
},
{
"code": null,
"e": 1302,
"s": 1055,
"text": "Code Explanation: You can put anything as long as it follows the variable declaration rules in VBScript instead of “a” which is at the beginning of the above code. Effectively, We can break and understand the above code in the following manner: "
},
{
"code": null,
"e": 1383,
"s": 1302,
"text": "put_any_Variable_name = msgbox(\"Your main text here\", 0, \"Your title text here\")"
},
{
"code": null,
"e": 1484,
"s": 1383,
"text": " To change the property of the dialog box with respect to what you need, refer the following data: "
},
{
"code": null,
"e": 1731,
"s": 1484,
"text": "Change “0” in the above written code with any of the numbers provided just above. To get more than one above mentioned property in you dialog box, you can simple write, for example: “0+16”, instead of “0” in above code. For reference, the code: "
},
{
"code": null,
"e": 1799,
"s": 1731,
"text": "hydro = msgbox(\"Remember to drink water!\", 0+64, \"Hydration Check\")"
},
{
"code": null,
"e": 1833,
"s": 1799,
"text": "will give the following output: "
},
{
"code": null,
"e": 1963,
"s": 1833,
"text": "That’s it, we have just written a basic VBScript program that will display a dialog box as output. Now onto saving this program. "
},
{
"code": null,
"e": 2023,
"s": 1965,
"text": "Follow the steps given below to save a VBScript program: "
},
{
"code": null,
"e": 2211,
"s": 2023,
"text": "Step 1: Press Ctrl + Shift + S on the keyboard, Or click File>Save As on the notepad window, this will open up a Save As dialog window asking where to save the current notepad document. "
},
{
"code": null,
"e": 2414,
"s": 2211,
"text": " Step 2: Now write any file name of your choice for this notepad document but make sure you write .vbs as its extension. Make sure to add “.vbs” after writing the file name in the “File name:” field. "
},
{
"code": null,
"e": 2575,
"s": 2414,
"text": " Step 3: Now, change the value of “Save as type:” field from “Text Documents (*.txt)” to “All Files (*.*)” by clicking on it with help of the drop down menu. "
},
{
"code": null,
"e": 2687,
"s": 2575,
"text": " Step 4: Finally, click on save after choosing an appropriate location of where the file should be saved to. "
},
{
"code": null,
"e": 2863,
"s": 2689,
"text": "Now, this is a very simple thing to do, simply double click on the now saved .vbs file from wherever you saved it and voila! It will run and give you the following output: "
},
{
"code": null,
"e": 2881,
"s": 2865,
"text": "adamyaswarup087"
},
{
"code": null,
"e": 2890,
"s": 2881,
"text": "VBScript"
},
{
"code": null,
"e": 2897,
"s": 2890,
"text": "How To"
},
{
"code": null,
"e": 2914,
"s": 2897,
"text": "Web Technologies"
},
{
"code": null,
"e": 3012,
"s": 2914,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3026,
"s": 3012,
"text": "Java Tutorial"
},
{
"code": null,
"e": 3053,
"s": 3026,
"text": "How to Align Text in HTML?"
},
{
"code": null,
"e": 3087,
"s": 3053,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 3129,
"s": 3087,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 3182,
"s": 3129,
"text": "How to setup Anaconda path to environment variable ?"
},
{
"code": null,
"e": 3232,
"s": 3182,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 3265,
"s": 3232,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3327,
"s": 3265,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3360,
"s": 3327,
"text": "Node.js fs.readFileSync() Method"
}
] |
Simulate Real-life Events in Python Using SimPy | by Khuyen Tran | Towards Data Science
|
As a restaurant manager, you want to approximate how much food your restaurant needs to prepare for tomorrow. You know how many customers come to your restaurant per day and the average time it takes to serve one customer. However, it is challenging to put all of these variables into one calculation.
Wouldn’t it be great if you can simulate this event using Python?
That is when SimPy comes in handy.
SimPy is a Python library that enables you to simulate real-life events. It can model active components such as customers, vehicles, or agents.
To install SimPy, type:
pip install simpy
In SimPy, the behaviors of active components such as customers or vehicles are modeled with processes. These processes live in an environment. They interact with the environment and with each other via events.
To understand these concepts better, let’s try to model a waiter (a process) who serves in a restaurant (an environment). Some basic things that waiters do are:
Taking orders from customers
Giving orders to the cooks
Serving food to customers
Here, the waiter is a process. The waiter lives in an env . The current simulation time is env.now . The env.timeout(duration) method models the time it takes to finish one activity.
Output:
Cool! We are able to simulate some basic things a waiter does. The outputs above make sense since it takes around:
5s to take the orders from the customers (take_order_duration = 5)
2s to give the orders to the cooks (give_order_duration = 2)
5s to serve food to the customers (serve_order_duration = 5)
Note that we don’t see “Start serving customers food at 31” because we only run the simulation for 30 s.
We can simulate customers using the same logic as above. However, since there is a limited number of customers that can be served in the restaurant, we will also model the restaurant with a limited capacity.
That could be done using thesimpy.Resource class. We will use simpy.Resource(env, capacity=2) to limit the number of customers to 2. This means new customers can get into the restaurant only when there are fewer than 2 customers in the restaurant.
Now we can specify the duration of each activity and simulate 5 customers. Note that the order of customers and their numbers are unrelated.
Output:
Cool! From the output, we can see that:
New customers come in at random times
If there are already 2 customers in the restaurant, new customers need to wait until an existing customer finish eating
Pretty cool, isn’t it?
As a manager, you think 10 items per option of food are enough to feed your customers. Let’s test this assumption by applying what we have learned so far.
We will simulate a restaurant that:
Only takes take-out orders
There is only one staff member
The customers are waiting in line to order food on the menu. The more items a customer orders, the longer the customer needs to wait.
The attributes of this restaurant are:
staff : a resource with the capacity 1 (the staff can only serve one customer at a time)
foods : options of food the restaurant offers
available : number of items per option of food
run_out : events when each option of food runs out
when_run_out : the time when each option of food runs out
rejected_customers : number of customers who leave the line because their food option runs out
We also want to create a customer who is waiting in line. A customer will:
Leave if there is not enough food left
Order food if there is enough food left
If there is no food left after the customer orders a particular kind of food, we will declare that the chosen food has run out.
Two new concepts in the code above are:
restaurant.staff.request : Request usage of the resource. In this case, the customer requests a service from the staff member.
restaurant.run_out[food].succeed : run_out is an event that can either succeed or fail. In this case, if the event run_out succeeds, it signals that the restaurant runs out of a food option.
There are new customers until the simulation reaches the time limit.
Now we have created the customers and the restaurant, let’s run the simulation. We will print messages when the restaurant runs out of a food option.
Output:
Cool! Imagine 1 second in SimPy is 1 minute in real life. If the simulation runs for 240 minutes (4 hours), and there are 10 items per food choice, then the restaurant will run out of each food choice in fewer than 240 minutes.
There is also a total of 22 customers leaving the restaurant hungry. Thus, if we want to feed all of our customers in 240 minutes, we might need to prepare more than 10 items per food option.
Note that the example above is only a simplified version of a real restaurant. To make the example closer to a real event in a restaurant, you might want to add more interactions.
You can also run the simulations more than once to get a better approximation of the number of minutes before an option of food runs out.
Check out the examples in SimPy’s documentation for other inspirations.
Congratulations! You have just learned how to use SimPy to simulate real-life events. I hope this will give you the motivation to simulate the events you are interested in.
The source code for this article can be found here:
github.com
I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter.
Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these:
|
[
{
"code": null,
"e": 474,
"s": 172,
"text": "As a restaurant manager, you want to approximate how much food your restaurant needs to prepare for tomorrow. You know how many customers come to your restaurant per day and the average time it takes to serve one customer. However, it is challenging to put all of these variables into one calculation."
},
{
"code": null,
"e": 540,
"s": 474,
"text": "Wouldn’t it be great if you can simulate this event using Python?"
},
{
"code": null,
"e": 575,
"s": 540,
"text": "That is when SimPy comes in handy."
},
{
"code": null,
"e": 719,
"s": 575,
"text": "SimPy is a Python library that enables you to simulate real-life events. It can model active components such as customers, vehicles, or agents."
},
{
"code": null,
"e": 743,
"s": 719,
"text": "To install SimPy, type:"
},
{
"code": null,
"e": 761,
"s": 743,
"text": "pip install simpy"
},
{
"code": null,
"e": 971,
"s": 761,
"text": "In SimPy, the behaviors of active components such as customers or vehicles are modeled with processes. These processes live in an environment. They interact with the environment and with each other via events."
},
{
"code": null,
"e": 1132,
"s": 971,
"text": "To understand these concepts better, let’s try to model a waiter (a process) who serves in a restaurant (an environment). Some basic things that waiters do are:"
},
{
"code": null,
"e": 1161,
"s": 1132,
"text": "Taking orders from customers"
},
{
"code": null,
"e": 1188,
"s": 1161,
"text": "Giving orders to the cooks"
},
{
"code": null,
"e": 1214,
"s": 1188,
"text": "Serving food to customers"
},
{
"code": null,
"e": 1397,
"s": 1214,
"text": "Here, the waiter is a process. The waiter lives in an env . The current simulation time is env.now . The env.timeout(duration) method models the time it takes to finish one activity."
},
{
"code": null,
"e": 1405,
"s": 1397,
"text": "Output:"
},
{
"code": null,
"e": 1520,
"s": 1405,
"text": "Cool! We are able to simulate some basic things a waiter does. The outputs above make sense since it takes around:"
},
{
"code": null,
"e": 1587,
"s": 1520,
"text": "5s to take the orders from the customers (take_order_duration = 5)"
},
{
"code": null,
"e": 1648,
"s": 1587,
"text": "2s to give the orders to the cooks (give_order_duration = 2)"
},
{
"code": null,
"e": 1709,
"s": 1648,
"text": "5s to serve food to the customers (serve_order_duration = 5)"
},
{
"code": null,
"e": 1814,
"s": 1709,
"text": "Note that we don’t see “Start serving customers food at 31” because we only run the simulation for 30 s."
},
{
"code": null,
"e": 2022,
"s": 1814,
"text": "We can simulate customers using the same logic as above. However, since there is a limited number of customers that can be served in the restaurant, we will also model the restaurant with a limited capacity."
},
{
"code": null,
"e": 2270,
"s": 2022,
"text": "That could be done using thesimpy.Resource class. We will use simpy.Resource(env, capacity=2) to limit the number of customers to 2. This means new customers can get into the restaurant only when there are fewer than 2 customers in the restaurant."
},
{
"code": null,
"e": 2411,
"s": 2270,
"text": "Now we can specify the duration of each activity and simulate 5 customers. Note that the order of customers and their numbers are unrelated."
},
{
"code": null,
"e": 2419,
"s": 2411,
"text": "Output:"
},
{
"code": null,
"e": 2459,
"s": 2419,
"text": "Cool! From the output, we can see that:"
},
{
"code": null,
"e": 2497,
"s": 2459,
"text": "New customers come in at random times"
},
{
"code": null,
"e": 2617,
"s": 2497,
"text": "If there are already 2 customers in the restaurant, new customers need to wait until an existing customer finish eating"
},
{
"code": null,
"e": 2640,
"s": 2617,
"text": "Pretty cool, isn’t it?"
},
{
"code": null,
"e": 2795,
"s": 2640,
"text": "As a manager, you think 10 items per option of food are enough to feed your customers. Let’s test this assumption by applying what we have learned so far."
},
{
"code": null,
"e": 2831,
"s": 2795,
"text": "We will simulate a restaurant that:"
},
{
"code": null,
"e": 2858,
"s": 2831,
"text": "Only takes take-out orders"
},
{
"code": null,
"e": 2889,
"s": 2858,
"text": "There is only one staff member"
},
{
"code": null,
"e": 3023,
"s": 2889,
"text": "The customers are waiting in line to order food on the menu. The more items a customer orders, the longer the customer needs to wait."
},
{
"code": null,
"e": 3062,
"s": 3023,
"text": "The attributes of this restaurant are:"
},
{
"code": null,
"e": 3151,
"s": 3062,
"text": "staff : a resource with the capacity 1 (the staff can only serve one customer at a time)"
},
{
"code": null,
"e": 3197,
"s": 3151,
"text": "foods : options of food the restaurant offers"
},
{
"code": null,
"e": 3244,
"s": 3197,
"text": "available : number of items per option of food"
},
{
"code": null,
"e": 3295,
"s": 3244,
"text": "run_out : events when each option of food runs out"
},
{
"code": null,
"e": 3353,
"s": 3295,
"text": "when_run_out : the time when each option of food runs out"
},
{
"code": null,
"e": 3448,
"s": 3353,
"text": "rejected_customers : number of customers who leave the line because their food option runs out"
},
{
"code": null,
"e": 3523,
"s": 3448,
"text": "We also want to create a customer who is waiting in line. A customer will:"
},
{
"code": null,
"e": 3562,
"s": 3523,
"text": "Leave if there is not enough food left"
},
{
"code": null,
"e": 3602,
"s": 3562,
"text": "Order food if there is enough food left"
},
{
"code": null,
"e": 3730,
"s": 3602,
"text": "If there is no food left after the customer orders a particular kind of food, we will declare that the chosen food has run out."
},
{
"code": null,
"e": 3770,
"s": 3730,
"text": "Two new concepts in the code above are:"
},
{
"code": null,
"e": 3897,
"s": 3770,
"text": "restaurant.staff.request : Request usage of the resource. In this case, the customer requests a service from the staff member."
},
{
"code": null,
"e": 4088,
"s": 3897,
"text": "restaurant.run_out[food].succeed : run_out is an event that can either succeed or fail. In this case, if the event run_out succeeds, it signals that the restaurant runs out of a food option."
},
{
"code": null,
"e": 4157,
"s": 4088,
"text": "There are new customers until the simulation reaches the time limit."
},
{
"code": null,
"e": 4307,
"s": 4157,
"text": "Now we have created the customers and the restaurant, let’s run the simulation. We will print messages when the restaurant runs out of a food option."
},
{
"code": null,
"e": 4315,
"s": 4307,
"text": "Output:"
},
{
"code": null,
"e": 4543,
"s": 4315,
"text": "Cool! Imagine 1 second in SimPy is 1 minute in real life. If the simulation runs for 240 minutes (4 hours), and there are 10 items per food choice, then the restaurant will run out of each food choice in fewer than 240 minutes."
},
{
"code": null,
"e": 4735,
"s": 4543,
"text": "There is also a total of 22 customers leaving the restaurant hungry. Thus, if we want to feed all of our customers in 240 minutes, we might need to prepare more than 10 items per food option."
},
{
"code": null,
"e": 4915,
"s": 4735,
"text": "Note that the example above is only a simplified version of a real restaurant. To make the example closer to a real event in a restaurant, you might want to add more interactions."
},
{
"code": null,
"e": 5053,
"s": 4915,
"text": "You can also run the simulations more than once to get a better approximation of the number of minutes before an option of food runs out."
},
{
"code": null,
"e": 5125,
"s": 5053,
"text": "Check out the examples in SimPy’s documentation for other inspirations."
},
{
"code": null,
"e": 5298,
"s": 5125,
"text": "Congratulations! You have just learned how to use SimPy to simulate real-life events. I hope this will give you the motivation to simulate the events you are interested in."
},
{
"code": null,
"e": 5350,
"s": 5298,
"text": "The source code for this article can be found here:"
},
{
"code": null,
"e": 5361,
"s": 5350,
"text": "github.com"
},
{
"code": null,
"e": 5521,
"s": 5361,
"text": "I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter."
}
] |
Default Constructors in C++
|
Constructors are functions of a class that are executed when new objects of the class are created. The constructors have the same name as the class and no return type, not even void. They are primarily useful for providing initial values for variables of the class. The two main types of constructors are default constructors and parameterized constructors.
Default constructors do not take any parameters. If a default constructor is not provided by the programmer explicitly, then the compiler provides a implicit default constructor. In that case, the default values of the variables are 0.
A program that demonstrates default constructors is given as follows.
Live Demo
#include <iostream>
using namespace std;
class DemoDC {
private:
int num1, num2 ;
public:
DemoDC() {
num1 = 10;
num2 = 20;
}
void display() {
cout<<"num1 = "<< num1 <<endl;
cout<<"num2 = "<< num2 <<endl;
}
};
int main() {
DemoDC obj;
obj.display();
return 0;
}
num1 = 10
num2 = 20
In the above program, the class DemoDC contains a default constructor that initialises num1 and num2 as 10 and 20. It also contains a function display() that prints the value of num1 and num2. The code snippet for this is given as follows.
class DemoDC {
private:
int num1, num2
public:
DemoDC() {
num1 = 10;
num2 = 20;
}
void display() {
cout<<"num1 = "<< num1 <<endl;
cout<<"num2 = "<< num2 <<endl;
}
};
The function main() contains the object definition for an object of class type DemoDC. Then the function display() is called. This is shown below.
DemoDC obj;
obj.display();
|
[
{
"code": null,
"e": 1420,
"s": 1062,
"text": "Constructors are functions of a class that are executed when new objects of the class are created. The constructors have the same name as the class and no return type, not even void. They are primarily useful for providing initial values for variables of the class. The two main types of constructors are default constructors and parameterized constructors."
},
{
"code": null,
"e": 1656,
"s": 1420,
"text": "Default constructors do not take any parameters. If a default constructor is not provided by the programmer explicitly, then the compiler provides a implicit default constructor. In that case, the default values of the variables are 0."
},
{
"code": null,
"e": 1726,
"s": 1656,
"text": "A program that demonstrates default constructors is given as follows."
},
{
"code": null,
"e": 1737,
"s": 1726,
"text": " Live Demo"
},
{
"code": null,
"e": 2052,
"s": 1737,
"text": "#include <iostream>\nusing namespace std;\nclass DemoDC {\n private:\n int num1, num2 ;\n public:\n DemoDC() {\n num1 = 10;\n num2 = 20;\n }\n void display() {\n cout<<\"num1 = \"<< num1 <<endl;\n cout<<\"num2 = \"<< num2 <<endl;\n }\n};\nint main() {\n DemoDC obj;\n obj.display();\n return 0;\n}"
},
{
"code": null,
"e": 2072,
"s": 2052,
"text": "num1 = 10\nnum2 = 20"
},
{
"code": null,
"e": 2312,
"s": 2072,
"text": "In the above program, the class DemoDC contains a default constructor that initialises num1 and num2 as 10 and 20. It also contains a function display() that prints the value of num1 and num2. The code snippet for this is given as follows."
},
{
"code": null,
"e": 2523,
"s": 2312,
"text": "class DemoDC {\n private:\n int num1, num2\n public:\n DemoDC() {\n num1 = 10;\n num2 = 20;\n }\n void display() {\n cout<<\"num1 = \"<< num1 <<endl;\n cout<<\"num2 = \"<< num2 <<endl;\n }\n};"
},
{
"code": null,
"e": 2670,
"s": 2523,
"text": "The function main() contains the object definition for an object of class type DemoDC. Then the function display() is called. This is shown below."
},
{
"code": null,
"e": 2697,
"s": 2670,
"text": "DemoDC obj;\nobj.display();"
}
] |
Append in Python. When choosing a collection type, it is... | by sunil kumar | Towards Data Science
|
When choosing a collection type, it is useful to understand the properties of each type and choosing the most appropriate type for a particular data set. To know the most appropriate collection type you need to know the attributes of all the available types and then choose one from it based on your use case. In this article, we will go through the List Collection Type along with the append method in the article
Lists are similar to the arrays, declared in other languages. Lists need not be of the same data types always which makes it a most powerful tool in Python and is the main difference between arrays and lists. A list can contain data Types such as Integers, Strings, as well as lists. Lists are mutable, which means they can be altered even after their creation.
List in Python are indexed and have a definite count while initializing. The elements in a list are indexed according to a definite sequence and the indexing of a list is done with 0 being the first index and the last item index is n-1 where n is the number of items in a list. Each element in the list has its indexed place in the list, which allows duplicating of elements in the list i.e we can create the same indexed item as another one with a different index and the list will still accept it, unlike Sets.
Creation :
In Python, lists are created using the square brackets and each item inside a list is separated by commas.
Code:
my_list = [‘I’ ,”think” ,”Medium” ,’is’ , ‘number’ ,1]type(my_list)Output:list
You can see from the above code that while creating a list I have given both string and numeric datatype as items inside a list.
Indexing in Lists:
The list index starts with 0 and ends with n-1.
In our list index starts with 0 and ends with 5 which we can check using the pre-built len() function.
Code:
len(my_list)Output:6
We can also check each item value based on its index as below.
Code:
my_list[0],my_list[3]Output:(‘I’, ‘is’)
Till now we discussed on Collection type List now let’s move on to the append method in Python.
Append Method
The append() method in python adds a single item to the existing list. It doesn’t return a new list of items but will modify the original list by adding the item to the end of the list.
After executing the method append on the list the size of the list increases by one.
Syntax
list_name.append(item)
Parameters
The append() method takes a single item as an input parameter and adds that to the end of the list.
The items inside a list can be numbers, strings, another list, dictionary.
The append() method only modifies the original list. It doesn’t return any value as a return but will just modify the created list.
1. Adding Number to a List:
In the code below we will look at how to add a new numeric item to a list.
Code:# list of stringsstring_list = [‘Medium’,’Python’,’Machine Learning’,’Data Science’]#adding a new int item to the string_liststring_list.append(1)#printing appended listprint(string_list)Output:[‘Medium’,’Python’,’Machine Learning’,’Data Science’,’1’]
2. Adding new list to a List:
Apart from adding a string and a numeric data type we can also add separate list to a list as below
Code:
#lets create a new listnew_list = [1,2,3,4,5]#append this list to our string_liststring_list.append(new_list)# print the appended liststring_listOutput:[‘Medium’,’Python’,’Machine Learning’,’Data Science’,’1’,[1,2,3,4,5]]
You can see from the above output that a new list is appended at the end of our old list. We will get the whole list as an indexed item using the below code.
Code:
string_list[5]Output:[1,2,3,4,5]
If you want to access the elements from this list you can do that in the same way as you access elements from a 2-D Matrix.
Code:string_list[5][1]Output:2
If you try to access an item with an index greater than the list index you will get an Index Error.
Code:string_list[6]Output: — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — -IndexError Traceback (most recent call last)<ipython-input-14–1d3b13a81e08> in <module> — → 1 string_list[6]IndexError: list index out of range
Conclusion :
Therefore from the above code samples, we understood how to append different types of data types to a list and access them.
We have many such methods in Python Lists apart from the append which will make life easier for a Python developer.
|
[
{
"code": null,
"e": 587,
"s": 172,
"text": "When choosing a collection type, it is useful to understand the properties of each type and choosing the most appropriate type for a particular data set. To know the most appropriate collection type you need to know the attributes of all the available types and then choose one from it based on your use case. In this article, we will go through the List Collection Type along with the append method in the article"
},
{
"code": null,
"e": 949,
"s": 587,
"text": "Lists are similar to the arrays, declared in other languages. Lists need not be of the same data types always which makes it a most powerful tool in Python and is the main difference between arrays and lists. A list can contain data Types such as Integers, Strings, as well as lists. Lists are mutable, which means they can be altered even after their creation."
},
{
"code": null,
"e": 1462,
"s": 949,
"text": "List in Python are indexed and have a definite count while initializing. The elements in a list are indexed according to a definite sequence and the indexing of a list is done with 0 being the first index and the last item index is n-1 where n is the number of items in a list. Each element in the list has its indexed place in the list, which allows duplicating of elements in the list i.e we can create the same indexed item as another one with a different index and the list will still accept it, unlike Sets."
},
{
"code": null,
"e": 1473,
"s": 1462,
"text": "Creation :"
},
{
"code": null,
"e": 1580,
"s": 1473,
"text": "In Python, lists are created using the square brackets and each item inside a list is separated by commas."
},
{
"code": null,
"e": 1586,
"s": 1580,
"text": "Code:"
},
{
"code": null,
"e": 1665,
"s": 1586,
"text": "my_list = [‘I’ ,”think” ,”Medium” ,’is’ , ‘number’ ,1]type(my_list)Output:list"
},
{
"code": null,
"e": 1794,
"s": 1665,
"text": "You can see from the above code that while creating a list I have given both string and numeric datatype as items inside a list."
},
{
"code": null,
"e": 1813,
"s": 1794,
"text": "Indexing in Lists:"
},
{
"code": null,
"e": 1861,
"s": 1813,
"text": "The list index starts with 0 and ends with n-1."
},
{
"code": null,
"e": 1964,
"s": 1861,
"text": "In our list index starts with 0 and ends with 5 which we can check using the pre-built len() function."
},
{
"code": null,
"e": 1970,
"s": 1964,
"text": "Code:"
},
{
"code": null,
"e": 1991,
"s": 1970,
"text": "len(my_list)Output:6"
},
{
"code": null,
"e": 2054,
"s": 1991,
"text": "We can also check each item value based on its index as below."
},
{
"code": null,
"e": 2060,
"s": 2054,
"text": "Code:"
},
{
"code": null,
"e": 2100,
"s": 2060,
"text": "my_list[0],my_list[3]Output:(‘I’, ‘is’)"
},
{
"code": null,
"e": 2196,
"s": 2100,
"text": "Till now we discussed on Collection type List now let’s move on to the append method in Python."
},
{
"code": null,
"e": 2210,
"s": 2196,
"text": "Append Method"
},
{
"code": null,
"e": 2396,
"s": 2210,
"text": "The append() method in python adds a single item to the existing list. It doesn’t return a new list of items but will modify the original list by adding the item to the end of the list."
},
{
"code": null,
"e": 2481,
"s": 2396,
"text": "After executing the method append on the list the size of the list increases by one."
},
{
"code": null,
"e": 2488,
"s": 2481,
"text": "Syntax"
},
{
"code": null,
"e": 2511,
"s": 2488,
"text": "list_name.append(item)"
},
{
"code": null,
"e": 2522,
"s": 2511,
"text": "Parameters"
},
{
"code": null,
"e": 2622,
"s": 2522,
"text": "The append() method takes a single item as an input parameter and adds that to the end of the list."
},
{
"code": null,
"e": 2697,
"s": 2622,
"text": "The items inside a list can be numbers, strings, another list, dictionary."
},
{
"code": null,
"e": 2829,
"s": 2697,
"text": "The append() method only modifies the original list. It doesn’t return any value as a return but will just modify the created list."
},
{
"code": null,
"e": 2857,
"s": 2829,
"text": "1. Adding Number to a List:"
},
{
"code": null,
"e": 2932,
"s": 2857,
"text": "In the code below we will look at how to add a new numeric item to a list."
},
{
"code": null,
"e": 3189,
"s": 2932,
"text": "Code:# list of stringsstring_list = [‘Medium’,’Python’,’Machine Learning’,’Data Science’]#adding a new int item to the string_liststring_list.append(1)#printing appended listprint(string_list)Output:[‘Medium’,’Python’,’Machine Learning’,’Data Science’,’1’]"
},
{
"code": null,
"e": 3219,
"s": 3189,
"text": "2. Adding new list to a List:"
},
{
"code": null,
"e": 3319,
"s": 3219,
"text": "Apart from adding a string and a numeric data type we can also add separate list to a list as below"
},
{
"code": null,
"e": 3325,
"s": 3319,
"text": "Code:"
},
{
"code": null,
"e": 3547,
"s": 3325,
"text": "#lets create a new listnew_list = [1,2,3,4,5]#append this list to our string_liststring_list.append(new_list)# print the appended liststring_listOutput:[‘Medium’,’Python’,’Machine Learning’,’Data Science’,’1’,[1,2,3,4,5]]"
},
{
"code": null,
"e": 3705,
"s": 3547,
"text": "You can see from the above output that a new list is appended at the end of our old list. We will get the whole list as an indexed item using the below code."
},
{
"code": null,
"e": 3711,
"s": 3705,
"text": "Code:"
},
{
"code": null,
"e": 3744,
"s": 3711,
"text": "string_list[5]Output:[1,2,3,4,5]"
},
{
"code": null,
"e": 3868,
"s": 3744,
"text": "If you want to access the elements from this list you can do that in the same way as you access elements from a 2-D Matrix."
},
{
"code": null,
"e": 3899,
"s": 3868,
"text": "Code:string_list[5][1]Output:2"
},
{
"code": null,
"e": 3999,
"s": 3899,
"text": "If you try to access an item with an index greater than the list index you will get an Index Error."
},
{
"code": null,
"e": 4245,
"s": 3999,
"text": "Code:string_list[6]Output: — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — -IndexError Traceback (most recent call last)<ipython-input-14–1d3b13a81e08> in <module> — → 1 string_list[6]IndexError: list index out of range"
},
{
"code": null,
"e": 4258,
"s": 4245,
"text": "Conclusion :"
},
{
"code": null,
"e": 4382,
"s": 4258,
"text": "Therefore from the above code samples, we understood how to append different types of data types to a list and access them."
}
] |
How to change the color of bars in histogram for values that are greater than 0 or less than 0 in R?
|
Although, the histogram represents the distribution of a complete set of values but we might want to visualize that histogram based on the division of some threshold value. For example, we might want to visualize the histogram with different bars that have values greater than 1 or less than 1. This will help us to understand the distribution of the values in whole data set that lies above or below certain value. For this purpose, we can simply use hist function with col argument to change the color of the values that are greater than or less than a fixed value.
x<-rnorm(1000000)
hist(x,col=x>0)
hist(x,col=x<0)
|
[
{
"code": null,
"e": 1630,
"s": 1062,
"text": "Although, the histogram represents the distribution of a complete set of values but we might want to visualize that histogram based on the division of some threshold value. For example, we might want to visualize the histogram with different bars that have values greater than 1 or less than 1. This will help us to understand the distribution of the values in whole data set that lies above or below certain value. For this purpose, we can simply use hist function with col argument to change the color of the values that are greater than or less than a fixed value."
},
{
"code": null,
"e": 1664,
"s": 1630,
"text": "x<-rnorm(1000000)\nhist(x,col=x>0)"
},
{
"code": null,
"e": 1680,
"s": 1664,
"text": "hist(x,col=x<0)"
}
] |
Explain if-else statement in C language
|
If-else statement takes care of true as well as false conditions. ‘true block’ is executed, when the condition is true and ‘false block’ (or) ‘else block’ is executed, when the condition is false.
Refer the syntax given below −
if (condition){
True block statement(s)
}else{
False block statement(s)
}
In if else condition, if condition is true, it enter into true block statements, execute the operation and exits from the block.
In if else condition, if condition is true, it enter into true block statements, execute the operation and exits from the block.
If condition is false, it enter into else block, which is false block based on if condition, executes that else block and exist that else block.
If condition is false, it enter into else block, which is false block based on if condition, executes that else block and exist that else block.
Following is the C program to execute If and If Else conditional operators −
Live Demo
#include<stdio.h>
void main (){
int a=4;
printf("Enter the value of a: \n");
scanf("%d",&a);
if(a%2==1){
printf("a is odd number \n");
}else{
printf("a is even number");
}
}
You will see the following output −
Run 1: Enter the value of a: 26
a is even number
Run 2: Enter the value of a: 53
a is odd number
|
[
{
"code": null,
"e": 1259,
"s": 1062,
"text": "If-else statement takes care of true as well as false conditions. ‘true block’ is executed, when the condition is true and ‘false block’ (or) ‘else block’ is executed, when the condition is false."
},
{
"code": null,
"e": 1290,
"s": 1259,
"text": "Refer the syntax given below −"
},
{
"code": null,
"e": 1370,
"s": 1290,
"text": "if (condition){\n True block statement(s)\n}else{\n False block statement(s)\n}"
},
{
"code": null,
"e": 1499,
"s": 1370,
"text": "In if else condition, if condition is true, it enter into true block statements, execute the operation and exits from the block."
},
{
"code": null,
"e": 1628,
"s": 1499,
"text": "In if else condition, if condition is true, it enter into true block statements, execute the operation and exits from the block."
},
{
"code": null,
"e": 1773,
"s": 1628,
"text": "If condition is false, it enter into else block, which is false block based on if condition, executes that else block and exist that else block."
},
{
"code": null,
"e": 1918,
"s": 1773,
"text": "If condition is false, it enter into else block, which is false block based on if condition, executes that else block and exist that else block."
},
{
"code": null,
"e": 1995,
"s": 1918,
"text": "Following is the C program to execute If and If Else conditional operators −"
},
{
"code": null,
"e": 2006,
"s": 1995,
"text": " Live Demo"
},
{
"code": null,
"e": 2210,
"s": 2006,
"text": "#include<stdio.h>\nvoid main (){\n int a=4;\n printf(\"Enter the value of a: \\n\");\n scanf(\"%d\",&a);\n if(a%2==1){\n printf(\"a is odd number \\n\");\n }else{\n printf(\"a is even number\");\n }\n}"
},
{
"code": null,
"e": 2246,
"s": 2210,
"text": "You will see the following output −"
},
{
"code": null,
"e": 2343,
"s": 2246,
"text": "Run 1: Enter the value of a: 26\na is even number\nRun 2: Enter the value of a: 53\na is odd number"
}
] |
How to replace the names of multiple object keys with the values provided using JavaScript ? - GeeksforGeeks
|
12 Jan, 2022
The following approach covers how to replace the names of multiple object keys with the values provided by the user using JavaScript.
Problem Statement: You are given an object which contains different key-value pairs in which key symbolizes the property and value itself is known as the property value, and you need to change one or more key’s original name with the name provided by the user using JavaScript.
As an example take the above-illustrated object initially. This object contains key-value pairs like Name: “Hello” and so on. So let us suppose we are targeting the Name key and further we are going to change this Name key as FirstName key name by the following approach.
Before directly jumping into the approaches to solve the above-illustrated problem, let us first declare the object which we are going to use to solve the query.
Example: By using the following syntax let’s first create an object:
Javascript
<script> let object = { name: "Hello", age: 20, gender: "Male", }; console.log(object);</script>
Output:
{ name: 'Hello', age: 20, gender: 'Male' }
Now let us see the approaches to solve the above-illustrated problem.
Approach 1:
This is the native approach and quite a simple one too.
In this approach we will directly pick up the object key and will change the name of that picked key with the name provided by the user.
After providing the key name we will then delete the previously declared one and replace it with new one.
We will write the logic part in a method (or function) and further will call that method which will execute our result.
Example 1:
Javascript
<script> let object = { name: "Hello", age: 20, gender: "Male", }; let renmeObjectKey = (object) => { object.FirstName = object.name; delete object.name; }; renmeObjectKey(object); console.log(object);</script>
Output:
{ age: 20, gender: 'Male', FirstName: 'Hello' }
Now suppose you want to target age key in the object with name provided by yourself.
Example 2:
Javascript
<script> let object = { name: "Hello", age: 20, gender: "Male", }; let renmeObjectKey = (object) => { object.FirstName = object.name; object.currentAge = object.age; delete object.name; delete object.age; }; renmeObjectKey(object); console.log(object);</script>
Now along with the name key, age key is also replaced with the new name provided by the user.
Output:
{ gender: 'Male', FirstName: 'Hello', currentAge: 20 }
Note: The only thing you could notice here is that the position of the object gets changed, but its value remains preserved and same too.
Approach 2:
In this approach we will declare a method which is completely responsible for executing our result.
Inside the parameters of this method, we will pass in two arguments, first one is keysMap object which we will accept it from user that actually contains the new key name which will be going to replace from the previous key name and second one is the object which we are referring to.
Now inside that method we will use Object.keys() which will accept our object initially and will target all our object keys, and then we will execute reduce() over it which will accept two things: first is accumulator value which will act as our result variable and second one is the key which we are targeting currently.
Then afterwards we will write our logic part and for that we will first take into our account of spread operator which will spread our object into an array, and then we will render out the object keys and replace it with own passed key name.
Then later we will pass our method inside a new variable which we will declare as our result variable and then will console.log() our result.
Example:
Javascript
<script> let object = { name: "Hello", age: 20, gender: "Male", }; let renameKeys = (keysMap, object) => Object.keys(object).reduce( (acc, key) => ({ ...acc, ...{ [keysMap[key] || key]: object[key] }, }), {} ); let result = renameKeys({ name: "FirstName" }, object); console.log(result);</script>
Output:
{ FirstName: 'Hello', age: 20, gender: 'Male' }
Note: This approach will preserve the position of the key and also the value.
ES6
JavaScript-ES
JavaScript-Questions
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
How to calculate the number of days between two dates in javascript?
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Roadmap to Become a Web Developer in 2022
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
|
[
{
"code": null,
"e": 37995,
"s": 37967,
"text": "\n12 Jan, 2022"
},
{
"code": null,
"e": 38129,
"s": 37995,
"text": "The following approach covers how to replace the names of multiple object keys with the values provided by the user using JavaScript."
},
{
"code": null,
"e": 38407,
"s": 38129,
"text": "Problem Statement: You are given an object which contains different key-value pairs in which key symbolizes the property and value itself is known as the property value, and you need to change one or more key’s original name with the name provided by the user using JavaScript."
},
{
"code": null,
"e": 38679,
"s": 38407,
"text": "As an example take the above-illustrated object initially. This object contains key-value pairs like Name: “Hello” and so on. So let us suppose we are targeting the Name key and further we are going to change this Name key as FirstName key name by the following approach."
},
{
"code": null,
"e": 38841,
"s": 38679,
"text": "Before directly jumping into the approaches to solve the above-illustrated problem, let us first declare the object which we are going to use to solve the query."
},
{
"code": null,
"e": 38910,
"s": 38841,
"text": "Example: By using the following syntax let’s first create an object:"
},
{
"code": null,
"e": 38921,
"s": 38910,
"text": "Javascript"
},
{
"code": "<script> let object = { name: \"Hello\", age: 20, gender: \"Male\", }; console.log(object);</script>",
"e": 39032,
"s": 38921,
"text": null
},
{
"code": null,
"e": 39040,
"s": 39032,
"text": "Output:"
},
{
"code": null,
"e": 39083,
"s": 39040,
"text": "{ name: 'Hello', age: 20, gender: 'Male' }"
},
{
"code": null,
"e": 39153,
"s": 39083,
"text": "Now let us see the approaches to solve the above-illustrated problem."
},
{
"code": null,
"e": 39166,
"s": 39153,
"text": "Approach 1: "
},
{
"code": null,
"e": 39222,
"s": 39166,
"text": "This is the native approach and quite a simple one too."
},
{
"code": null,
"e": 39359,
"s": 39222,
"text": "In this approach we will directly pick up the object key and will change the name of that picked key with the name provided by the user."
},
{
"code": null,
"e": 39465,
"s": 39359,
"text": "After providing the key name we will then delete the previously declared one and replace it with new one."
},
{
"code": null,
"e": 39585,
"s": 39465,
"text": "We will write the logic part in a method (or function) and further will call that method which will execute our result."
},
{
"code": null,
"e": 39597,
"s": 39585,
"text": "Example 1: "
},
{
"code": null,
"e": 39608,
"s": 39597,
"text": "Javascript"
},
{
"code": "<script> let object = { name: \"Hello\", age: 20, gender: \"Male\", }; let renmeObjectKey = (object) => { object.FirstName = object.name; delete object.name; }; renmeObjectKey(object); console.log(object);</script>",
"e": 39842,
"s": 39608,
"text": null
},
{
"code": null,
"e": 39850,
"s": 39842,
"text": "Output:"
},
{
"code": null,
"e": 39898,
"s": 39850,
"text": "{ age: 20, gender: 'Male', FirstName: 'Hello' }"
},
{
"code": null,
"e": 39983,
"s": 39898,
"text": "Now suppose you want to target age key in the object with name provided by yourself."
},
{
"code": null,
"e": 39995,
"s": 39983,
"text": "Example 2: "
},
{
"code": null,
"e": 40006,
"s": 39995,
"text": "Javascript"
},
{
"code": "<script> let object = { name: \"Hello\", age: 20, gender: \"Male\", }; let renmeObjectKey = (object) => { object.FirstName = object.name; object.currentAge = object.age; delete object.name; delete object.age; }; renmeObjectKey(object); console.log(object);</script>",
"e": 40297,
"s": 40006,
"text": null
},
{
"code": null,
"e": 40391,
"s": 40297,
"text": "Now along with the name key, age key is also replaced with the new name provided by the user."
},
{
"code": null,
"e": 40399,
"s": 40391,
"text": "Output:"
},
{
"code": null,
"e": 40454,
"s": 40399,
"text": "{ gender: 'Male', FirstName: 'Hello', currentAge: 20 }"
},
{
"code": null,
"e": 40592,
"s": 40454,
"text": "Note: The only thing you could notice here is that the position of the object gets changed, but its value remains preserved and same too."
},
{
"code": null,
"e": 40605,
"s": 40592,
"text": "Approach 2: "
},
{
"code": null,
"e": 40705,
"s": 40605,
"text": "In this approach we will declare a method which is completely responsible for executing our result."
},
{
"code": null,
"e": 40990,
"s": 40705,
"text": "Inside the parameters of this method, we will pass in two arguments, first one is keysMap object which we will accept it from user that actually contains the new key name which will be going to replace from the previous key name and second one is the object which we are referring to."
},
{
"code": null,
"e": 41312,
"s": 40990,
"text": "Now inside that method we will use Object.keys() which will accept our object initially and will target all our object keys, and then we will execute reduce() over it which will accept two things: first is accumulator value which will act as our result variable and second one is the key which we are targeting currently."
},
{
"code": null,
"e": 41554,
"s": 41312,
"text": "Then afterwards we will write our logic part and for that we will first take into our account of spread operator which will spread our object into an array, and then we will render out the object keys and replace it with own passed key name."
},
{
"code": null,
"e": 41696,
"s": 41554,
"text": "Then later we will pass our method inside a new variable which we will declare as our result variable and then will console.log() our result."
},
{
"code": null,
"e": 41706,
"s": 41696,
"text": "Example: "
},
{
"code": null,
"e": 41717,
"s": 41706,
"text": "Javascript"
},
{
"code": "<script> let object = { name: \"Hello\", age: 20, gender: \"Male\", }; let renameKeys = (keysMap, object) => Object.keys(object).reduce( (acc, key) => ({ ...acc, ...{ [keysMap[key] || key]: object[key] }, }), {} ); let result = renameKeys({ name: \"FirstName\" }, object); console.log(result);</script>",
"e": 42067,
"s": 41717,
"text": null
},
{
"code": null,
"e": 42075,
"s": 42067,
"text": "Output:"
},
{
"code": null,
"e": 42123,
"s": 42075,
"text": "{ FirstName: 'Hello', age: 20, gender: 'Male' }"
},
{
"code": null,
"e": 42201,
"s": 42123,
"text": "Note: This approach will preserve the position of the key and also the value."
},
{
"code": null,
"e": 42205,
"s": 42201,
"text": "ES6"
},
{
"code": null,
"e": 42219,
"s": 42205,
"text": "JavaScript-ES"
},
{
"code": null,
"e": 42240,
"s": 42219,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 42247,
"s": 42240,
"text": "Picked"
},
{
"code": null,
"e": 42258,
"s": 42247,
"text": "JavaScript"
},
{
"code": null,
"e": 42275,
"s": 42258,
"text": "Web Technologies"
},
{
"code": null,
"e": 42373,
"s": 42275,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 42418,
"s": 42373,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 42479,
"s": 42418,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 42548,
"s": 42479,
"text": "How to calculate the number of days between two dates in javascript?"
},
{
"code": null,
"e": 42620,
"s": 42548,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 42672,
"s": 42620,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 42714,
"s": 42672,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 42776,
"s": 42714,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 42819,
"s": 42776,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 42852,
"s": 42819,
"text": "Installation of Node.js on Linux"
}
] |
Area of Circumcircle and Incircle of a Right Kite - GeeksforGeeks
|
20 Jul, 2021
Given two positive integers A and B representing the sides of the right kite, the task is to find the area of the circumcircle and incircle of a right kite.
A right kite is a kite that can be inscribed in a circle with two opposite angles are at right angles. The line of symmetry of the kite is also the diameter of the circumcircle of the kite. It divides the kite into two congruent right-angled triangles having sides as A and B of a right kite.
Examples:
Input: A = 3, B = 4Output: Area of circumcircle of Right Kite is 19.625, Area of incircle of Right Kite is 3.14
Input: A = 10, B = 5Output: Area of circumcircle of Right Kite is 98.125, Area of incircle of Right Kite is 28.26
Approach: There are some observations to solve this problem. Follow the steps below to solve this problem:
Here, a = AB = AD and b = BC = CD
In the kite ABCD with opposite angles B and D as 90°, thus the opposite angles can be calculated as tan (A/2) = b/a and tan(C/2) = a/b
Let p as the length of diagonal AC and q as the length of diagonal BD.
Diagonal AC can be easily calculated using the Pythagoras Theorem. Hence p = (a2 + b2)1⁄2
Since the diagonal is equal to the diameter of the circumcircle of the kite, the radius of the circumcircle is calculated as R = (a2 + b2)1⁄2/2
Thus, the area of the circumcircle will be pi * R* R
Also, all kites are tangential quadrilaterals, therefore the radius of the incircle can be calculated by r = Area of kite/Semiperimeter of the kite i.e r = a*b/(a+b).
Thus, the area of the incircle will be pi*r*r.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std;#define pi 3.14 // Function to calculate the area of// circumcircle of right kitedouble AreaOfCircumcircle(int a, int b){ // Find the radius double radius = sqrt(a * a + b * b) / 2; return pi * radius * radius;} // Function to calculate the area of// incircle of right kitedouble AreaOfIncircle(int a, int b){ // Find the radius double radius = (a * b) / (a + b); return pi * radius * radius;} // Driver Codeint main(){ // Given Input int a, b; a = 10; b = 5; // Function Call double circumarea = AreaOfCircumcircle( a, b); cout << "Area of circumcircle of Right Kite is" << " " << circumarea << endl; // Function Call double inarea = AreaOfIncircle( a, b); cout << "Area of incircle of Right Kite is" << " " << inarea << endl; return 0;}
// Java program for the above approachpublic class GFG { static double pi = 3.14; // Function to calculate the area of // circumcircle of right kite static double AreaOfCircumcircle(int a, int b) { // Find the radius double radius = Math.sqrt(a * a + b * b) / 2; return pi * radius * radius; } // Function to calculate the area of // incircle of right kite static double AreaOfIncircle(int a, int b) { // Find the radius double radius = (a * b) / (a + b); return pi * radius * radius; } // Driver code public static void main(String[] args) { // Given Input int a, b; a = 10; b = 5; // Function Call double circumarea = AreaOfCircumcircle(a, b); System.out.printf( "Area of circumcircle of Right Kite is %.3f\n", circumarea); // Function Call double inarea = AreaOfIncircle(a, b); System.out.printf( "Area of incircle of Right Kite is %.2f\n", inarea); }} // This code is contributed by abhinavjain194
# Python program for the above approach# Function to calculate the area of# circumcircle of right kiteimport mathpi = 3.14 def AreaOfCircumcircle(a, b): # Find the radius radius = math.sqrt(a * a + b * b)/ 2 return pi * radius * radius # Function to calculate the area of# incircle of right kitedef AreaOfIncircle( a, b): # Find the radius radius = (a * b) // (a + b) return pi * (radius**2) # Driver Code# Given Inputa = 10b = 5 # Function Callcircumarea = AreaOfCircumcircle(a, b)print("Area of circumcircle of Right Kite is" ," " , format(circumarea,".3f")) # Function Callinarea = AreaOfIncircle(a, b)print("Area of incircle of Right Kite is" ," " , format(inarea,".2f")) # this code is contributed by shivanisinghss2110
// C# program for the above approachusing System; class GFG{ static double pi = 3.14; // Function to calculate the area of// circumcircle of right kitestatic double AreaOfCircumcircle(int a, int b){ // Find the radius double radius = Math.Sqrt(a * a + b * b) / 2; return pi * radius * radius;} // Function to calculate the area of// incircle of right kitestatic double AreaOfIncircle(int a, int b){ // Find the radius double radius = (a * b) / (a + b); return pi * radius * radius;} // Driver codepublic static void Main(){ // Given Input int a, b; a = 10; b = 5; // Function Call double circumarea = AreaOfCircumcircle(a, b); Console.WriteLine( "Area of circumcircle of Right Kite is " + circumarea); // Function Call double inarea = AreaOfIncircle(a, b); Console.WriteLine( "Area of incircle of Right Kite is " + inarea);}} // This code is contributed by subhammahato348
<script> // JavaScript Program for the above approach var pi = 3.14 // Function to calculate the area of // circumcircle of right kite function AreaOfCircumcircle(a, b) { // Find the radius let radius = Math.sqrt(a * a + b * b) / 2; return pi * radius * radius; } // Function to calculate the area of // incircle of right kite function AreaOfIncircle(a, b) { // Find the radius let radius = (a * b) / (a + b); return pi * radius * radius; } // Driver Code // Given Input let a, b; a = 10; b = 5; // Function Call let circumarea = AreaOfCircumcircle(a, b); document.write("Area of circumcircle of Right Kite is " + (circumarea.toFixed(3)) + "<br>"); // Function Call let inarea = AreaOfIncircle( a, b); document.write("Area of incircle of Right Kite is " + (inarea.toFixed(3)) + "<br>"); // This code is contributed by Potta Lokesh </script>
Area of circumcircle of Right Kite is 98.125
Area of incircle of Right Kite is 28.26
Time Complexity: O(1)Auxiliary Space: O(1)
lokeshpotta20
abhinavjain194
subhammahato348
shivanisinghss2110
area-volume-programs
Geometric
Mathematical
Mathematical
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convex Hull using Divide and Conquer Algorithm
Orientation of 3 ordered points
Equation of circle when three points on the circle are given
Program to find slope of a line
Program to find line passing through 2 Points
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
|
[
{
"code": null,
"e": 25380,
"s": 25352,
"text": "\n20 Jul, 2021"
},
{
"code": null,
"e": 25537,
"s": 25380,
"text": "Given two positive integers A and B representing the sides of the right kite, the task is to find the area of the circumcircle and incircle of a right kite."
},
{
"code": null,
"e": 25830,
"s": 25537,
"text": "A right kite is a kite that can be inscribed in a circle with two opposite angles are at right angles. The line of symmetry of the kite is also the diameter of the circumcircle of the kite. It divides the kite into two congruent right-angled triangles having sides as A and B of a right kite."
},
{
"code": null,
"e": 25840,
"s": 25830,
"text": "Examples:"
},
{
"code": null,
"e": 25952,
"s": 25840,
"text": "Input: A = 3, B = 4Output: Area of circumcircle of Right Kite is 19.625, Area of incircle of Right Kite is 3.14"
},
{
"code": null,
"e": 26066,
"s": 25952,
"text": "Input: A = 10, B = 5Output: Area of circumcircle of Right Kite is 98.125, Area of incircle of Right Kite is 28.26"
},
{
"code": null,
"e": 26173,
"s": 26066,
"text": "Approach: There are some observations to solve this problem. Follow the steps below to solve this problem:"
},
{
"code": null,
"e": 26207,
"s": 26173,
"text": "Here, a = AB = AD and b = BC = CD"
},
{
"code": null,
"e": 26342,
"s": 26207,
"text": "In the kite ABCD with opposite angles B and D as 90°, thus the opposite angles can be calculated as tan (A/2) = b/a and tan(C/2) = a/b"
},
{
"code": null,
"e": 26413,
"s": 26342,
"text": "Let p as the length of diagonal AC and q as the length of diagonal BD."
},
{
"code": null,
"e": 26503,
"s": 26413,
"text": "Diagonal AC can be easily calculated using the Pythagoras Theorem. Hence p = (a2 + b2)1⁄2"
},
{
"code": null,
"e": 26647,
"s": 26503,
"text": "Since the diagonal is equal to the diameter of the circumcircle of the kite, the radius of the circumcircle is calculated as R = (a2 + b2)1⁄2/2"
},
{
"code": null,
"e": 26701,
"s": 26647,
"text": "Thus, the area of the circumcircle will be pi * R* R "
},
{
"code": null,
"e": 26868,
"s": 26701,
"text": "Also, all kites are tangential quadrilaterals, therefore the radius of the incircle can be calculated by r = Area of kite/Semiperimeter of the kite i.e r = a*b/(a+b)."
},
{
"code": null,
"e": 26915,
"s": 26868,
"text": "Thus, the area of the incircle will be pi*r*r."
},
{
"code": null,
"e": 26966,
"s": 26915,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26970,
"s": 26966,
"text": "C++"
},
{
"code": null,
"e": 26975,
"s": 26970,
"text": "Java"
},
{
"code": null,
"e": 26983,
"s": 26975,
"text": "Python3"
},
{
"code": null,
"e": 26986,
"s": 26983,
"text": "C#"
},
{
"code": null,
"e": 26997,
"s": 26986,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std;#define pi 3.14 // Function to calculate the area of// circumcircle of right kitedouble AreaOfCircumcircle(int a, int b){ // Find the radius double radius = sqrt(a * a + b * b) / 2; return pi * radius * radius;} // Function to calculate the area of// incircle of right kitedouble AreaOfIncircle(int a, int b){ // Find the radius double radius = (a * b) / (a + b); return pi * radius * radius;} // Driver Codeint main(){ // Given Input int a, b; a = 10; b = 5; // Function Call double circumarea = AreaOfCircumcircle( a, b); cout << \"Area of circumcircle of Right Kite is\" << \" \" << circumarea << endl; // Function Call double inarea = AreaOfIncircle( a, b); cout << \"Area of incircle of Right Kite is\" << \" \" << inarea << endl; return 0;}",
"e": 27922,
"s": 26997,
"text": null
},
{
"code": "// Java program for the above approachpublic class GFG { static double pi = 3.14; // Function to calculate the area of // circumcircle of right kite static double AreaOfCircumcircle(int a, int b) { // Find the radius double radius = Math.sqrt(a * a + b * b) / 2; return pi * radius * radius; } // Function to calculate the area of // incircle of right kite static double AreaOfIncircle(int a, int b) { // Find the radius double radius = (a * b) / (a + b); return pi * radius * radius; } // Driver code public static void main(String[] args) { // Given Input int a, b; a = 10; b = 5; // Function Call double circumarea = AreaOfCircumcircle(a, b); System.out.printf( \"Area of circumcircle of Right Kite is %.3f\\n\", circumarea); // Function Call double inarea = AreaOfIncircle(a, b); System.out.printf( \"Area of incircle of Right Kite is %.2f\\n\", inarea); }} // This code is contributed by abhinavjain194",
"e": 29040,
"s": 27922,
"text": null
},
{
"code": "# Python program for the above approach# Function to calculate the area of# circumcircle of right kiteimport mathpi = 3.14 def AreaOfCircumcircle(a, b): # Find the radius radius = math.sqrt(a * a + b * b)/ 2 return pi * radius * radius # Function to calculate the area of# incircle of right kitedef AreaOfIncircle( a, b): # Find the radius radius = (a * b) // (a + b) return pi * (radius**2) # Driver Code# Given Inputa = 10b = 5 # Function Callcircumarea = AreaOfCircumcircle(a, b)print(\"Area of circumcircle of Right Kite is\" ,\" \" , format(circumarea,\".3f\")) # Function Callinarea = AreaOfIncircle(a, b)print(\"Area of incircle of Right Kite is\" ,\" \" , format(inarea,\".2f\")) # this code is contributed by shivanisinghss2110",
"e": 29788,
"s": 29040,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ static double pi = 3.14; // Function to calculate the area of// circumcircle of right kitestatic double AreaOfCircumcircle(int a, int b){ // Find the radius double radius = Math.Sqrt(a * a + b * b) / 2; return pi * radius * radius;} // Function to calculate the area of// incircle of right kitestatic double AreaOfIncircle(int a, int b){ // Find the radius double radius = (a * b) / (a + b); return pi * radius * radius;} // Driver codepublic static void Main(){ // Given Input int a, b; a = 10; b = 5; // Function Call double circumarea = AreaOfCircumcircle(a, b); Console.WriteLine( \"Area of circumcircle of Right Kite is \" + circumarea); // Function Call double inarea = AreaOfIncircle(a, b); Console.WriteLine( \"Area of incircle of Right Kite is \" + inarea);}} // This code is contributed by subhammahato348",
"e": 30752,
"s": 29788,
"text": null
},
{
"code": "<script> // JavaScript Program for the above approach var pi = 3.14 // Function to calculate the area of // circumcircle of right kite function AreaOfCircumcircle(a, b) { // Find the radius let radius = Math.sqrt(a * a + b * b) / 2; return pi * radius * radius; } // Function to calculate the area of // incircle of right kite function AreaOfIncircle(a, b) { // Find the radius let radius = (a * b) / (a + b); return pi * radius * radius; } // Driver Code // Given Input let a, b; a = 10; b = 5; // Function Call let circumarea = AreaOfCircumcircle(a, b); document.write(\"Area of circumcircle of Right Kite is \" + (circumarea.toFixed(3)) + \"<br>\"); // Function Call let inarea = AreaOfIncircle( a, b); document.write(\"Area of incircle of Right Kite is \" + (inarea.toFixed(3)) + \"<br>\"); // This code is contributed by Potta Lokesh </script>",
"e": 31863,
"s": 30752,
"text": null
},
{
"code": null,
"e": 31948,
"s": 31863,
"text": "Area of circumcircle of Right Kite is 98.125\nArea of incircle of Right Kite is 28.26"
},
{
"code": null,
"e": 31991,
"s": 31948,
"text": "Time Complexity: O(1)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 32005,
"s": 31991,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 32020,
"s": 32005,
"text": "abhinavjain194"
},
{
"code": null,
"e": 32036,
"s": 32020,
"text": "subhammahato348"
},
{
"code": null,
"e": 32055,
"s": 32036,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 32076,
"s": 32055,
"text": "area-volume-programs"
},
{
"code": null,
"e": 32086,
"s": 32076,
"text": "Geometric"
},
{
"code": null,
"e": 32099,
"s": 32086,
"text": "Mathematical"
},
{
"code": null,
"e": 32112,
"s": 32099,
"text": "Mathematical"
},
{
"code": null,
"e": 32122,
"s": 32112,
"text": "Geometric"
},
{
"code": null,
"e": 32220,
"s": 32122,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32267,
"s": 32220,
"text": "Convex Hull using Divide and Conquer Algorithm"
},
{
"code": null,
"e": 32299,
"s": 32267,
"text": "Orientation of 3 ordered points"
},
{
"code": null,
"e": 32360,
"s": 32299,
"text": "Equation of circle when three points on the circle are given"
},
{
"code": null,
"e": 32392,
"s": 32360,
"text": "Program to find slope of a line"
},
{
"code": null,
"e": 32438,
"s": 32392,
"text": "Program to find line passing through 2 Points"
},
{
"code": null,
"e": 32468,
"s": 32438,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 32528,
"s": 32468,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 32543,
"s": 32528,
"text": "C++ Data Types"
},
{
"code": null,
"e": 32586,
"s": 32543,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Perl defined Function
|
This function returns true if EXPR has a value other than the undef value, or checks the value of $_ if EXPR is not specified. This can be used with many functions to detect a failure in operation, since they return undef if there was a problem. A simple Boolean test does not differentiate between false, zero, an empty string, or the string .0., which are all equally false.
If EXPR is a function or function reference, then it returns true if the function has been defined. When used with entire arrays and hashes, it will not always produce intuitive results. If a hash element is specified, it returns true if the corresponding value has been defined, but does not determine whether the specified key exists in the hash.
Following is the simple syntax for this function −
defined EXPR
defined
This function returns 0 if EXPR contains undef and 1 if EXPR contains a valid value or reference.
Following is the example code showing its basic usage −
#!/usr/bin/perl
$var1 = "This is defined";
if( defined($var1) ) {
print "$var1\n";
}
if( defined($var2) ) {
print "var2 is also defined\n";
} else {
print "var2 is not defined\n";
}
When above code is executed, it produces the following result −
This is defined
var2 is not defined
46 Lectures
4.5 hours
Devi Killada
11 Lectures
1.5 hours
Harshit Srivastava
30 Lectures
6 hours
TELCOMA Global
24 Lectures
2 hours
Mohammad Nauman
68 Lectures
7 hours
Stone River ELearning
58 Lectures
6.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2597,
"s": 2220,
"text": "This function returns true if EXPR has a value other than the undef value, or checks the value of $_ if EXPR is not specified. This can be used with many functions to detect a failure in operation, since they return undef if there was a problem. A simple Boolean test does not differentiate between false, zero, an empty string, or the string .0., which are all equally false."
},
{
"code": null,
"e": 2946,
"s": 2597,
"text": "If EXPR is a function or function reference, then it returns true if the function has been defined. When used with entire arrays and hashes, it will not always produce intuitive results. If a hash element is specified, it returns true if the corresponding value has been defined, but does not determine whether the specified key exists in the hash."
},
{
"code": null,
"e": 2997,
"s": 2946,
"text": "Following is the simple syntax for this function −"
},
{
"code": null,
"e": 3020,
"s": 2997,
"text": "defined EXPR\n\ndefined\n"
},
{
"code": null,
"e": 3118,
"s": 3020,
"text": "This function returns 0 if EXPR contains undef and 1 if EXPR contains a valid value or reference."
},
{
"code": null,
"e": 3174,
"s": 3118,
"text": "Following is the example code showing its basic usage −"
},
{
"code": null,
"e": 3367,
"s": 3174,
"text": "#!/usr/bin/perl\n\n$var1 = \"This is defined\";\n\nif( defined($var1) ) {\n print \"$var1\\n\";\n}\nif( defined($var2) ) {\n print \"var2 is also defined\\n\";\n} else {\n print \"var2 is not defined\\n\";\n}"
},
{
"code": null,
"e": 3431,
"s": 3367,
"text": "When above code is executed, it produces the following result −"
},
{
"code": null,
"e": 3468,
"s": 3431,
"text": "This is defined\nvar2 is not defined\n"
},
{
"code": null,
"e": 3503,
"s": 3468,
"text": "\n 46 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3517,
"s": 3503,
"text": " Devi Killada"
},
{
"code": null,
"e": 3552,
"s": 3517,
"text": "\n 11 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3572,
"s": 3552,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 3605,
"s": 3572,
"text": "\n 30 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3621,
"s": 3605,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 3654,
"s": 3621,
"text": "\n 24 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3671,
"s": 3654,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 3704,
"s": 3671,
"text": "\n 68 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3727,
"s": 3704,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 3762,
"s": 3727,
"text": "\n 58 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3785,
"s": 3762,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 3792,
"s": 3785,
"text": " Print"
},
{
"code": null,
"e": 3803,
"s": 3792,
"text": " Add Notes"
}
] |
How to send parameters from a notification-click to an Android activity?
|
This example demonstrate about How to send parameters from a notification-click to an Android activity.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<? xml version = "1.0" encoding = "utf-8" ?>
<RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android"
xmlns: tools = "http://schemas.android.com/tools"
android :layout_width = "match_parent"
android :layout_height = "match_parent"
tools :context = ".MainActivity" >
<TextView
android :id = "@+id/tvNotify"
android :layout_width = "match_parent"
android :layout_height = "wrap_content"
android :layout_above = "@+id/btnNotify"
android :layout_margin = "16dp" />
<Button
android :id = "@+id/btnNotify"
android :layout_width = "match_parent"
android :layout_height = "wrap_content"
android :layout_centerInParent= "true"
android :layout_margin= "16dp"
android :onClick= "createNotification"
android :text= "create notification" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
package app.tutorialspoint.com.notifyme ;
import android.app.NotificationChannel ;
import android.app.NotificationManager ;
import android.app.PendingIntent ;
import android.content.Context ;
import android.content.Intent ;
import android.os.Bundle ;
import android.support.v4.app.NotificationCompat ;
import android.support.v7.app.AppCompatActivity ;
import android.view.View ;
import android.widget.TextView ;
public class MainActivity extends AppCompatActivity {
public static final String NOTIFICATION_CHANNEL_ID = "10001" ;
private final static String default_notification_channel_id = "default" ;
@Override
protected void onCreate (Bundle savedInstanceState) {
super .onCreate(savedInstanceState) ;
setContentView(R.layout. activity_main ) ;
onNewIntent(getIntent()) ;
}
@Override
protected void onNewIntent (Intent intent) {
super .onNewIntent(intent) ;
Bundle extras = intent.getExtras() ;
if (extras != null ) {
if (extras.containsKey( "NotificationMessage" )) {
String msg = extras.getString( "NotificationMessage" ) ;
TextView tvNotify = findViewById(R.id. tvNotify ) ;
tvNotify.setText(msg) ;
}
}
}
public void createNotification (View view) {
Intent notificationIntent = new Intent(MainActivity. this, MainActivity. class ) ;
notificationIntent.putExtra( "NotificationMessage" , "I am from Notification" ) ;
notificationIntent.addCategory(Intent. CATEGORY_LAUNCHER ) ;
notificationIntent.setAction(Intent. ACTION_MAIN ) ;
notificationIntent.setFlags(Intent. FLAG_ACTIVITY_CLEAR_TOP | Intent. FLAG_ACTIVITY_SINGLE_TOP ) ;
PendingIntent resultIntent = PendingIntent. getActivity (MainActivity. this, 0 , notificationIntent , 0 ) ;
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder
(MainActivity. this, default_notification_channel_id )
.setSmallIcon(R.drawable. ic_launcher_foreground )
.setContentTitle( "Test" )
.setContentText( "Hello! This is my first push notification" )
.setContentIntent(resultIntent) ;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context. NOTIFICATION_SERVICE ) ;
if (android.os.Build.VERSION. SDK_INT >= android.os.Build.VERSION_CODES. O ) {
int importance = NotificationManager. IMPORTANCE_HIGH ;
NotificationChannel notificationChannel = new
NotificationChannel( NOTIFICATION_CHANNEL_ID , "NOTIFICATION_CHANNEL_NAME" , importance) ;
mBuilder.setChannelId( NOTIFICATION_CHANNEL_ID ) ;
assert mNotificationManager != null;
mNotificationManager.createNotificationChannel(notificationChannel) ;
}
assert mNotificationManager != null;
mNotificationManager.notify(( int ) System. currentTimeMillis () , mBuilder.build()) ;
}
}
Step 4 − Add the following code to androidManifest.xml
<? xml version = "1.0" encoding = "utf-8" ?>
<manifest xmlns: android = "http://schemas.android.com/apk/res/android"
package = "app.tutorialspoint.com.notifyme" >
<application
android :allowBackup = "true"
android :icon = "@mipmap/ic_launcher"
android :label = "@string/app_name"
android :roundIcon = "@mipmap/ic_launcher_round"
android :supportsRtl = "true"
android :theme = "@style/AppTheme" >
<activity android :name = ".MainActivity" >
<intent-filter>
<action android :name = "android.intent.action.MAIN" />
<category android :name= "android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code
|
[
{
"code": null,
"e": 1166,
"s": 1062,
"text": "This example demonstrate about How to send parameters from a notification-click to an Android activity."
},
{
"code": null,
"e": 1295,
"s": 1166,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1360,
"s": 1295,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2217,
"s": 1360,
"text": "<? xml version = \"1.0\" encoding = \"utf-8\" ?>\n<RelativeLayout xmlns: android = \"http://schemas.android.com/apk/res/android\"\n xmlns: tools = \"http://schemas.android.com/tools\"\n android :layout_width = \"match_parent\"\n android :layout_height = \"match_parent\"\n tools :context = \".MainActivity\" >\n <TextView\n android :id = \"@+id/tvNotify\"\n android :layout_width = \"match_parent\"\n android :layout_height = \"wrap_content\"\n android :layout_above = \"@+id/btnNotify\"\n android :layout_margin = \"16dp\" />\n <Button\n android :id = \"@+id/btnNotify\"\n android :layout_width = \"match_parent\"\n android :layout_height = \"wrap_content\"\n android :layout_centerInParent= \"true\"\n android :layout_margin= \"16dp\"\n android :onClick= \"createNotification\"\n android :text= \"create notification\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2274,
"s": 2217,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 5188,
"s": 2274,
"text": "package app.tutorialspoint.com.notifyme ;\nimport android.app.NotificationChannel ;\nimport android.app.NotificationManager ;\nimport android.app.PendingIntent ;\nimport android.content.Context ;\nimport android.content.Intent ;\nimport android.os.Bundle ;\nimport android.support.v4.app.NotificationCompat ;\nimport android.support.v7.app.AppCompatActivity ;\nimport android.view.View ;\nimport android.widget.TextView ;\npublic class MainActivity extends AppCompatActivity {\n public static final String NOTIFICATION_CHANNEL_ID = \"10001\" ;\n private final static String default_notification_channel_id = \"default\" ;\n @Override\n protected void onCreate (Bundle savedInstanceState) {\n super .onCreate(savedInstanceState) ;\n setContentView(R.layout. activity_main ) ;\n onNewIntent(getIntent()) ;\n }\n @Override\n protected void onNewIntent (Intent intent) {\n super .onNewIntent(intent) ;\n Bundle extras = intent.getExtras() ;\n if (extras != null ) {\n if (extras.containsKey( \"NotificationMessage\" )) {\n String msg = extras.getString( \"NotificationMessage\" ) ;\n TextView tvNotify = findViewById(R.id. tvNotify ) ;\n tvNotify.setText(msg) ;\n }\n }\n }\n public void createNotification (View view) {\n Intent notificationIntent = new Intent(MainActivity. this, MainActivity. class ) ;\n notificationIntent.putExtra( \"NotificationMessage\" , \"I am from Notification\" ) ;\n notificationIntent.addCategory(Intent. CATEGORY_LAUNCHER ) ;\n notificationIntent.setAction(Intent. ACTION_MAIN ) ;\n notificationIntent.setFlags(Intent. FLAG_ACTIVITY_CLEAR_TOP | Intent. FLAG_ACTIVITY_SINGLE_TOP ) ;\n PendingIntent resultIntent = PendingIntent. getActivity (MainActivity. this, 0 , notificationIntent , 0 ) ;\n NotificationCompat.Builder mBuilder = new NotificationCompat.Builder\n (MainActivity. this, default_notification_channel_id )\n .setSmallIcon(R.drawable. ic_launcher_foreground )\n .setContentTitle( \"Test\" )\n .setContentText( \"Hello! This is my first push notification\" )\n .setContentIntent(resultIntent) ;\n NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context. NOTIFICATION_SERVICE ) ;\n if (android.os.Build.VERSION. SDK_INT >= android.os.Build.VERSION_CODES. O ) {\n int importance = NotificationManager. IMPORTANCE_HIGH ;\n NotificationChannel notificationChannel = new\n NotificationChannel( NOTIFICATION_CHANNEL_ID , \"NOTIFICATION_CHANNEL_NAME\" , importance) ;\n mBuilder.setChannelId( NOTIFICATION_CHANNEL_ID ) ;\n assert mNotificationManager != null;\n mNotificationManager.createNotificationChannel(notificationChannel) ;\n }\n assert mNotificationManager != null;\n mNotificationManager.notify(( int ) System. currentTimeMillis () , mBuilder.build()) ;\n }\n}"
},
{
"code": null,
"e": 5243,
"s": 5188,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 5973,
"s": 5243,
"text": "<? xml version = \"1.0\" encoding = \"utf-8\" ?>\n<manifest xmlns: android = \"http://schemas.android.com/apk/res/android\"\n package = \"app.tutorialspoint.com.notifyme\" >\n <application\n android :allowBackup = \"true\"\n android :icon = \"@mipmap/ic_launcher\"\n android :label = \"@string/app_name\"\n android :roundIcon = \"@mipmap/ic_launcher_round\"\n android :supportsRtl = \"true\"\n android :theme = \"@style/AppTheme\" >\n <activity android :name = \".MainActivity\" >\n <intent-filter>\n <action android :name = \"android.intent.action.MAIN\" />\n <category android :name= \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 6320,
"s": 5973,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
},
{
"code": null,
"e": 6362,
"s": 6320,
"text": "Click here to download the project code"
}
] |
Watchdog timer in Arduino
|
A watchdog timer is an essential part of any microcontroller. It resets the program if the program gets stuck anywhere. Very briefly, this is how the watchdog timer works −
The timer keeps incrementing.
The timer keeps incrementing.
The program has to ensure that it keeps resetting the timer, i.e. does not allow it to overflow.
The program has to ensure that it keeps resetting the timer, i.e. does not allow it to overflow.
If the timer overflows, it means that the program was stuck somewhere and therefore was unable to reset the timer. An interrupt is generated on timer overflow which resets the microcontroller.
If the timer overflows, it means that the program was stuck somewhere and therefore was unable to reset the timer. An interrupt is generated on timer overflow which resets the microcontroller.
To implement watchdog timer in Arduino, we use the avr wdt library.
The code is given below −
#include<avr/wdt.h>
void setup() {
Serial.begin(9600);
wdt_disable(); //Disable WDT
delay(3000);
wdt_enable(WDTO_2S); //Enable WDT with a timeout of 2 seconds
Serial.println("WDT Enabled");
}
void loop() {
for(int i = 0; i<5; i++)
{
Serial.println("Looping");
delay(1000);
wdt_reset(); //Reset the watchdog
}
while(1); //Watchdog timer should get triggered here
}
As you can see, we initialize Serial and first disable watchdog timer. Then a delay of 3 seconds is introduced. The program won't reset here, because the watchdog is disabled. Now, the watchdog timer with a timeout of 2 seconds is enabled. It means, if the program doesn't reset this timer within every 2 seconds, then the watchdog will get triggered and restart the microcontroller.
Within the loop, we first print to the Serial for 5 seconds, making sure to reset the watchdog every second. The program works fine so far. Then, we enter into an infinite while loop. Over here, since we are not resetting the wdt, it will get triggered and restart the Arduino.
Note that the preset watchdog timeout values are available from 15 ms to 8 s.
|
[
{
"code": null,
"e": 1235,
"s": 1062,
"text": "A watchdog timer is an essential part of any microcontroller. It resets the program if the program gets stuck anywhere. Very briefly, this is how the watchdog timer works −"
},
{
"code": null,
"e": 1265,
"s": 1235,
"text": "The timer keeps incrementing."
},
{
"code": null,
"e": 1295,
"s": 1265,
"text": "The timer keeps incrementing."
},
{
"code": null,
"e": 1392,
"s": 1295,
"text": "The program has to ensure that it keeps resetting the timer, i.e. does not allow it to overflow."
},
{
"code": null,
"e": 1489,
"s": 1392,
"text": "The program has to ensure that it keeps resetting the timer, i.e. does not allow it to overflow."
},
{
"code": null,
"e": 1682,
"s": 1489,
"text": "If the timer overflows, it means that the program was stuck somewhere and therefore was unable to reset the timer. An interrupt is generated on timer overflow which resets the microcontroller."
},
{
"code": null,
"e": 1875,
"s": 1682,
"text": "If the timer overflows, it means that the program was stuck somewhere and therefore was unable to reset the timer. An interrupt is generated on timer overflow which resets the microcontroller."
},
{
"code": null,
"e": 1943,
"s": 1875,
"text": "To implement watchdog timer in Arduino, we use the avr wdt library."
},
{
"code": null,
"e": 1969,
"s": 1943,
"text": "The code is given below −"
},
{
"code": null,
"e": 2378,
"s": 1969,
"text": "#include<avr/wdt.h>\nvoid setup() {\n Serial.begin(9600);\n wdt_disable(); //Disable WDT\n delay(3000);\n wdt_enable(WDTO_2S); //Enable WDT with a timeout of 2 seconds\n Serial.println(\"WDT Enabled\");\n}\nvoid loop() {\n for(int i = 0; i<5; i++)\n {\n Serial.println(\"Looping\");\n delay(1000);\n wdt_reset(); //Reset the watchdog\n }\n while(1); //Watchdog timer should get triggered here\n}"
},
{
"code": null,
"e": 2762,
"s": 2378,
"text": "As you can see, we initialize Serial and first disable watchdog timer. Then a delay of 3 seconds is introduced. The program won't reset here, because the watchdog is disabled. Now, the watchdog timer with a timeout of 2 seconds is enabled. It means, if the program doesn't reset this timer within every 2 seconds, then the watchdog will get triggered and restart the microcontroller."
},
{
"code": null,
"e": 3040,
"s": 2762,
"text": "Within the loop, we first print to the Serial for 5 seconds, making sure to reset the watchdog every second. The program works fine so far. Then, we enter into an infinite while loop. Over here, since we are not resetting the wdt, it will get triggered and restart the Arduino."
},
{
"code": null,
"e": 3118,
"s": 3040,
"text": "Note that the preset watchdog timeout values are available from 15 ms to 8 s."
}
] |
Difference between Exception and Error in Java
|
Exceptions and errors both are subclasses of Throwable class. The error indicates a problem that mainly occurs due to the lack of system resources and our application should not catch these types of problems. Some of the examples of errors are system crash error and out of memory error. Errors mostly occur at runtime that's they belong to an unchecked type.
Exceptions are the problems which can occur at runtime and compile time. It mainly occurs in the code written by the developers. Exceptions are divided into two categories such as checked exceptions and unchecked exceptions.
public class ErrorExample {
public static void main(String[] args){
recursiveMethod(10)
}
public static void recursiveMethod(int i){
while(i!=0){
i=i+1;
recursiveMethod(i);
}
}
}
Exception in thread "main" java.lang.StackOverflowError
at ErrorExample.ErrorExample(Main.java:42)
public class ExceptionExample {
public static void main(String[] args){
int x = 100;
int y = 0;
int z = x / y;
}
}
java.lang.ArithmeticException: / by zero
at ExceptionExample.main(ExceptionExample.java:7)
|
[
{
"code": null,
"e": 1423,
"s": 1062,
"text": "Exceptions and errors both are subclasses of Throwable class. The error indicates a problem that mainly occurs due to the lack of system resources and our application should not catch these types of problems. Some of the examples of errors are system crash error and out of memory error. Errors mostly occur at runtime that's they belong to an unchecked type. "
},
{
"code": null,
"e": 1650,
"s": 1423,
"text": "Exceptions are the problems which can occur at runtime and compile time. It mainly occurs in the code written by the developers. Exceptions are divided into two categories such as checked exceptions and unchecked exceptions. "
},
{
"code": null,
"e": 1877,
"s": 1650,
"text": "public class ErrorExample {\n public static void main(String[] args){\n recursiveMethod(10)\n }\n public static void recursiveMethod(int i){\n while(i!=0){\n i=i+1;\n recursiveMethod(i);\n }\n }\n}"
},
{
"code": null,
"e": 1979,
"s": 1877,
"text": "Exception in thread \"main\" java.lang.StackOverflowError\n at ErrorExample.ErrorExample(Main.java:42)"
},
{
"code": null,
"e": 2118,
"s": 1979,
"text": "public class ExceptionExample {\n public static void main(String[] args){\n int x = 100;\n int y = 0;\n int z = x / y;\n }\n}"
},
{
"code": null,
"e": 2212,
"s": 2118,
"text": "java.lang.ArithmeticException: / by zero\n at ExceptionExample.main(ExceptionExample.java:7)"
}
] |
Number of ways of distributing N identical objects in R distinct groups with no groups empty - GeeksforGeeks
|
18 Jan, 2022
Given two integer N and R, the task is to calculate the number of ways to distribute N identical objects into R distinct groups such that no groups are left empty.
Examples:
Input: N = 4, R = 2 Output: 3 No of objects in 1st group = 1, in second group = 3 No of objects in 1st group = 2, in second group = 2 No of objects in 1st group = 3, in second group = 1
Input: N = 5, R = 3 Output: 6
Approach: Idea is to use Multinomial theorem. Let us suppose that x1 objects are placed in the first group, x2 objects are placed in second group and xR objects are placed in the Rth group. It is given that, x1 + x2 + x3 +...+ xR = N for all xi ≥ 1 for 1 ≤ i ≤ R Now replace every xi with yi + 1 for all 1 ≤ i ≤ R. Now all the y variables are greater than or equal to zero. The equation becomes, y1 + y2 + y3 + ... + yR + R = N for all yi ≥ 0 for 1 ≤ i ≤ R y1 + y2 + y3 + ... + yR = N – R It now reduces to that standard multinomial equation whose solution is (N – R) + R – 1CR – 1. The solution of this equation is given by N – 1CR – 1.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to return the// value of ncr effectivelyint ncr(int n, int r){ // Initialize the answer int ans = 1; for (int i = 1; i <= r; i += 1) { // Divide simultaneously by // i to avoid overflow ans *= (n - r + i); ans /= i; } return ans;} // Function to return the number of// ways to distribute N identical// objects in R distinct objectsint NoOfDistributions(int N, int R){ return ncr(N - 1, R - 1);} // Driver codeint main(){ int N = 4; int R = 3; cout << NoOfDistributions(N, R); return 0;}
// Java implementation of the above approachimport java.io.*; class GFG{ // Function to return the // value of ncr effectively static int ncr(int n, int r) { // Initialize the answer int ans = 1; for (int i = 1; i <= r; i += 1) { // Divide simultaneously by // i to avoid overflow ans *= (n - r + i); ans /= i; } return ans; } // Function to return the number of // ways to distribute N identical // objects in R distinct objects static int NoOfDistributions(int N, int R) { return ncr(N - 1, R - 1); } // Driver code public static void main (String[] args) { int N = 4; int R = 3; System.out.println(NoOfDistributions(N, R)); }} // This code is contributed by ajit
# Python3 implementation of the above approach # Function to return the# value of ncr effectivelydef ncr(n, r): # Initialize the answer ans = 1 for i in range(1,r+1): # Divide simultaneously by # i to avoid overflow ans *= (n - r + i) ans //= i return ans # Function to return the number of# ways to distribute N identical# objects in R distinct objectsdef NoOfDistributions(N, R): return ncr(N - 1, R - 1) # Driver code N = 4R = 3 print(NoOfDistributions(N, R)) # This code is contributed by mohit kumar 29
// C# implementation of the above approachusing System; class GFG{ // Function to return the // value of ncr effectively static int ncr(int n, int r) { // Initialize the answer int ans = 1; for (int i = 1; i <= r; i += 1) { // Divide simultaneously by // i to avoid overflow ans *= (n - r + i); ans /= i; } return ans; } // Function to return the number of // ways to distribute N identical // objects in R distinct objects static int NoOfDistributions(int N, int R) { return ncr(N - 1, R - 1); } // Driver code static public void Main () { int N = 4; int R = 3; Console.WriteLine(NoOfDistributions(N, R)); }} // This code is contributed by AnkitRai01
<script> // Javascript implementation of the above approach // Function to return the// value of ncr effectivelyfunction ncr(n, r){ // Initialize the answer let ans = 1; for(let i = 1; i <= r; i += 1) { // Divide simultaneously by // i to avoid overflow ans *= (n - r + i); ans = parseInt(ans / i); } return ans;} // Function to return the number of// ways to distribute N identical// objects in R distinct objectsfunction NoOfDistributions(N, R){ return ncr(N - 1, R - 1);} // Driver codelet N = 4;let R = 3; document.write(NoOfDistributions(N, R)); // This code is contributed by rishavmahato348 </script>
3
Time Complexity: O(R)
mohit kumar 29
ankthon
jit_t
rishavmahato348
varshagumber28
Numbers
Mathematical
Mathematical
Numbers
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Program to find GCD or HCF of two numbers
Modulo Operator (%) in C/C++ with Examples
Merge two sorted arrays
Prime Numbers
Program to find sum of elements in a given array
Program for factorial of a number
Operators in C / C++
Euclidean algorithms (Basic and Extended)
Sieve of Eratosthenes
Program for Decimal to Binary Conversion
|
[
{
"code": null,
"e": 25218,
"s": 25190,
"text": "\n18 Jan, 2022"
},
{
"code": null,
"e": 25382,
"s": 25218,
"text": "Given two integer N and R, the task is to calculate the number of ways to distribute N identical objects into R distinct groups such that no groups are left empty."
},
{
"code": null,
"e": 25393,
"s": 25382,
"text": "Examples: "
},
{
"code": null,
"e": 25579,
"s": 25393,
"text": "Input: N = 4, R = 2 Output: 3 No of objects in 1st group = 1, in second group = 3 No of objects in 1st group = 2, in second group = 2 No of objects in 1st group = 3, in second group = 1"
},
{
"code": null,
"e": 25611,
"s": 25579,
"text": "Input: N = 5, R = 3 Output: 6 "
},
{
"code": null,
"e": 26249,
"s": 25611,
"text": "Approach: Idea is to use Multinomial theorem. Let us suppose that x1 objects are placed in the first group, x2 objects are placed in second group and xR objects are placed in the Rth group. It is given that, x1 + x2 + x3 +...+ xR = N for all xi ≥ 1 for 1 ≤ i ≤ R Now replace every xi with yi + 1 for all 1 ≤ i ≤ R. Now all the y variables are greater than or equal to zero. The equation becomes, y1 + y2 + y3 + ... + yR + R = N for all yi ≥ 0 for 1 ≤ i ≤ R y1 + y2 + y3 + ... + yR = N – R It now reduces to that standard multinomial equation whose solution is (N – R) + R – 1CR – 1. The solution of this equation is given by N – 1CR – 1."
},
{
"code": null,
"e": 26301,
"s": 26249,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26305,
"s": 26301,
"text": "C++"
},
{
"code": null,
"e": 26310,
"s": 26305,
"text": "Java"
},
{
"code": null,
"e": 26318,
"s": 26310,
"text": "Python3"
},
{
"code": null,
"e": 26321,
"s": 26318,
"text": "C#"
},
{
"code": null,
"e": 26332,
"s": 26321,
"text": "Javascript"
},
{
"code": "// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to return the// value of ncr effectivelyint ncr(int n, int r){ // Initialize the answer int ans = 1; for (int i = 1; i <= r; i += 1) { // Divide simultaneously by // i to avoid overflow ans *= (n - r + i); ans /= i; } return ans;} // Function to return the number of// ways to distribute N identical// objects in R distinct objectsint NoOfDistributions(int N, int R){ return ncr(N - 1, R - 1);} // Driver codeint main(){ int N = 4; int R = 3; cout << NoOfDistributions(N, R); return 0;}",
"e": 26982,
"s": 26332,
"text": null
},
{
"code": "// Java implementation of the above approachimport java.io.*; class GFG{ // Function to return the // value of ncr effectively static int ncr(int n, int r) { // Initialize the answer int ans = 1; for (int i = 1; i <= r; i += 1) { // Divide simultaneously by // i to avoid overflow ans *= (n - r + i); ans /= i; } return ans; } // Function to return the number of // ways to distribute N identical // objects in R distinct objects static int NoOfDistributions(int N, int R) { return ncr(N - 1, R - 1); } // Driver code public static void main (String[] args) { int N = 4; int R = 3; System.out.println(NoOfDistributions(N, R)); }} // This code is contributed by ajit",
"e": 27847,
"s": 26982,
"text": null
},
{
"code": "# Python3 implementation of the above approach # Function to return the# value of ncr effectivelydef ncr(n, r): # Initialize the answer ans = 1 for i in range(1,r+1): # Divide simultaneously by # i to avoid overflow ans *= (n - r + i) ans //= i return ans # Function to return the number of# ways to distribute N identical# objects in R distinct objectsdef NoOfDistributions(N, R): return ncr(N - 1, R - 1) # Driver code N = 4R = 3 print(NoOfDistributions(N, R)) # This code is contributed by mohit kumar 29",
"e": 28408,
"s": 27847,
"text": null
},
{
"code": "// C# implementation of the above approachusing System; class GFG{ // Function to return the // value of ncr effectively static int ncr(int n, int r) { // Initialize the answer int ans = 1; for (int i = 1; i <= r; i += 1) { // Divide simultaneously by // i to avoid overflow ans *= (n - r + i); ans /= i; } return ans; } // Function to return the number of // ways to distribute N identical // objects in R distinct objects static int NoOfDistributions(int N, int R) { return ncr(N - 1, R - 1); } // Driver code static public void Main () { int N = 4; int R = 3; Console.WriteLine(NoOfDistributions(N, R)); }} // This code is contributed by AnkitRai01",
"e": 29254,
"s": 28408,
"text": null
},
{
"code": "<script> // Javascript implementation of the above approach // Function to return the// value of ncr effectivelyfunction ncr(n, r){ // Initialize the answer let ans = 1; for(let i = 1; i <= r; i += 1) { // Divide simultaneously by // i to avoid overflow ans *= (n - r + i); ans = parseInt(ans / i); } return ans;} // Function to return the number of// ways to distribute N identical// objects in R distinct objectsfunction NoOfDistributions(N, R){ return ncr(N - 1, R - 1);} // Driver codelet N = 4;let R = 3; document.write(NoOfDistributions(N, R)); // This code is contributed by rishavmahato348 </script>",
"e": 29926,
"s": 29254,
"text": null
},
{
"code": null,
"e": 29928,
"s": 29926,
"text": "3"
},
{
"code": null,
"e": 29953,
"s": 29930,
"text": "Time Complexity: O(R) "
},
{
"code": null,
"e": 29968,
"s": 29953,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 29976,
"s": 29968,
"text": "ankthon"
},
{
"code": null,
"e": 29982,
"s": 29976,
"text": "jit_t"
},
{
"code": null,
"e": 29998,
"s": 29982,
"text": "rishavmahato348"
},
{
"code": null,
"e": 30013,
"s": 29998,
"text": "varshagumber28"
},
{
"code": null,
"e": 30021,
"s": 30013,
"text": "Numbers"
},
{
"code": null,
"e": 30034,
"s": 30021,
"text": "Mathematical"
},
{
"code": null,
"e": 30047,
"s": 30034,
"text": "Mathematical"
},
{
"code": null,
"e": 30055,
"s": 30047,
"text": "Numbers"
},
{
"code": null,
"e": 30153,
"s": 30055,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30162,
"s": 30153,
"text": "Comments"
},
{
"code": null,
"e": 30175,
"s": 30162,
"text": "Old Comments"
},
{
"code": null,
"e": 30217,
"s": 30175,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 30260,
"s": 30217,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 30284,
"s": 30260,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 30298,
"s": 30284,
"text": "Prime Numbers"
},
{
"code": null,
"e": 30347,
"s": 30298,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 30381,
"s": 30347,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 30402,
"s": 30381,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 30444,
"s": 30402,
"text": "Euclidean algorithms (Basic and Extended)"
},
{
"code": null,
"e": 30466,
"s": 30444,
"text": "Sieve of Eratosthenes"
}
] |
HTML | DOM Datalist Object - GeeksforGeeks
|
24 Jan, 2022
The DOM Datalist Object is used to represent the HTML <Datalist> element. The Datalist element is accessed by getElementById().Properties: It has a ‘Option’ attribute which is used to return the collection of all options value in a datalist.Syntax:
document.getElementById("gfg");
Collections
options: It is used to return the number of options in a <datalist> element. Where “gfg” is the ID assigned to the “Datalist” Tag.Example-1:
html
<!DOCTYPE html><html> <body> <center> <h1 style="color:green;font-size:39px;"> GeeksForGeeks </h1> <h2>DOM Datalist object</h2> <form> <label>Your Cars Name: </label> <input list="gfg"> <datalist id="cars"> <option value="BMW" /> <option value="Bentley" /> <option value="Mercedes" /> <option value="Audi" /> <option value="Volkswagen" /> </datalist> </form> <br> <button onclick="myGeeks()">Submit</button> <p id="sudo"></p> <script> function myGeeks() { var g = document.getElementById("gfg").options.length; document.getElementById("sudo").innerHTML = "There are " + g + " options in the list."; } </script></center> </body> </html>
Output:Before Clicking On Button:
After Clicking On Button:
Example-2:
html
<!DOCTYPE html><html> <body> <center> <h1 style="color:green;font-size:39px;"> GeeksForGeeks </h1> <h2>DOM Datalist object</h2> <form id="GFG"> <b><label>Your cars name:</label></b> </form> <br> <button onclick="myGeeks()">Submit</button> <script> function myGeeks() { var g = document.createElement("INPUT"); g.setAttribute("list", "cars"); document.getElementById("GFG").appendChild(g); var f = document.createElement("DATALIST"); f.setAttribute("id", "cars"); document.getElementById("GFG").appendChild(f); var w = document.createElement("OPTION"); w.setAttribute("value", "BMW"); document.getElementById("cars").appendChild(w); var x = document.createElement("OPTION"); x.setAttribute("value", "Mercedes"); document.getElementById("cars").appendChild(x); } </script> </center> </body> </html>
Output:Before Clicking On Button:
After clicking On Button:
Supported Browsers: The browser supported by DOM Datalist Object are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
hritikbhatnagar2182
HTML-DOM
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to set the default value for an HTML <select> element ?
How to update Node.js and NPM to next version ?
How to set input type date in dd-mm-yyyy format using HTML ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
|
[
{
"code": null,
"e": 23878,
"s": 23850,
"text": "\n24 Jan, 2022"
},
{
"code": null,
"e": 24129,
"s": 23878,
"text": "The DOM Datalist Object is used to represent the HTML <Datalist> element. The Datalist element is accessed by getElementById().Properties: It has a ‘Option’ attribute which is used to return the collection of all options value in a datalist.Syntax: "
},
{
"code": null,
"e": 24162,
"s": 24129,
"text": "document.getElementById(\"gfg\"); "
},
{
"code": null,
"e": 24175,
"s": 24162,
"text": "Collections "
},
{
"code": null,
"e": 24318,
"s": 24175,
"text": "options: It is used to return the number of options in a <datalist> element. Where “gfg” is the ID assigned to the “Datalist” Tag.Example-1: "
},
{
"code": null,
"e": 24323,
"s": 24318,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <body> <center> <h1 style=\"color:green;font-size:39px;\"> GeeksForGeeks </h1> <h2>DOM Datalist object</h2> <form> <label>Your Cars Name: </label> <input list=\"gfg\"> <datalist id=\"cars\"> <option value=\"BMW\" /> <option value=\"Bentley\" /> <option value=\"Mercedes\" /> <option value=\"Audi\" /> <option value=\"Volkswagen\" /> </datalist> </form> <br> <button onclick=\"myGeeks()\">Submit</button> <p id=\"sudo\"></p> <script> function myGeeks() { var g = document.getElementById(\"gfg\").options.length; document.getElementById(\"sudo\").innerHTML = \"There are \" + g + \" options in the list.\"; } </script></center> </body> </html>",
"e": 25185,
"s": 24323,
"text": null
},
{
"code": null,
"e": 25221,
"s": 25185,
"text": "Output:Before Clicking On Button: "
},
{
"code": null,
"e": 25249,
"s": 25221,
"text": "After Clicking On Button: "
},
{
"code": null,
"e": 25262,
"s": 25249,
"text": "Example-2: "
},
{
"code": null,
"e": 25267,
"s": 25262,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <body> <center> <h1 style=\"color:green;font-size:39px;\"> GeeksForGeeks </h1> <h2>DOM Datalist object</h2> <form id=\"GFG\"> <b><label>Your cars name:</label></b> </form> <br> <button onclick=\"myGeeks()\">Submit</button> <script> function myGeeks() { var g = document.createElement(\"INPUT\"); g.setAttribute(\"list\", \"cars\"); document.getElementById(\"GFG\").appendChild(g); var f = document.createElement(\"DATALIST\"); f.setAttribute(\"id\", \"cars\"); document.getElementById(\"GFG\").appendChild(f); var w = document.createElement(\"OPTION\"); w.setAttribute(\"value\", \"BMW\"); document.getElementById(\"cars\").appendChild(w); var x = document.createElement(\"OPTION\"); x.setAttribute(\"value\", \"Mercedes\"); document.getElementById(\"cars\").appendChild(x); } </script> </center> </body> </html>",
"e": 26362,
"s": 25267,
"text": null
},
{
"code": null,
"e": 26398,
"s": 26362,
"text": "Output:Before Clicking On Button: "
},
{
"code": null,
"e": 26426,
"s": 26398,
"text": "After clicking On Button: "
},
{
"code": null,
"e": 26511,
"s": 26426,
"text": "Supported Browsers: The browser supported by DOM Datalist Object are listed below: "
},
{
"code": null,
"e": 26525,
"s": 26511,
"text": "Google Chrome"
},
{
"code": null,
"e": 26543,
"s": 26525,
"text": "Internet Explorer"
},
{
"code": null,
"e": 26551,
"s": 26543,
"text": "Firefox"
},
{
"code": null,
"e": 26557,
"s": 26551,
"text": "Opera"
},
{
"code": null,
"e": 26564,
"s": 26557,
"text": "Safari"
},
{
"code": null,
"e": 26703,
"s": 26566,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 26723,
"s": 26703,
"text": "hritikbhatnagar2182"
},
{
"code": null,
"e": 26732,
"s": 26723,
"text": "HTML-DOM"
},
{
"code": null,
"e": 26737,
"s": 26732,
"text": "HTML"
},
{
"code": null,
"e": 26754,
"s": 26737,
"text": "Web Technologies"
},
{
"code": null,
"e": 26759,
"s": 26754,
"text": "HTML"
},
{
"code": null,
"e": 26857,
"s": 26759,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26919,
"s": 26857,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 26969,
"s": 26919,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 27029,
"s": 26969,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 27077,
"s": 27029,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 27138,
"s": 27077,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 27180,
"s": 27138,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 27213,
"s": 27180,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27275,
"s": 27213,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 27318,
"s": 27275,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How to get almost increasing sequence of integers in JavaScript ?
|
A sequence of numbers is said to be in a strictly increasing sequence if every succeeding element in the sequence is greater than its preceding element.
We are required to write a JavaScript function that takes in an array of Numbers as the only argument. The function should check whether we can form a strictly increasing sequence of the numbers by removing no more than one element from the array.
Following is the code −
const almostIncreasingSequence = (arr = []) => {
if (isIncreasingSequence(arr)) {
return true;
};
for (let i = 0; i < arr.length > 0; i++) {
let copy = arr.slice(0);
copy.splice(i, 1);
if (isIncreasingSequence(copy)) {
return true;
};
};
return false;
};
const isIncreasingSequence = (arr = []) => {
for (let i = 0; i < arr.length - 1; i++) {
if (arr[i] >= arr[i + 1]) {
return false;
};
};
return true;
};
console.log(almostIncreasingSequence([1, 3, 2, 1]));
console.log(almostIncreasingSequence([1, 3, 2]));
Following is the output on console −
false
true
|
[
{
"code": null,
"e": 1215,
"s": 1062,
"text": "A sequence of numbers is said to be in a strictly increasing sequence if every succeeding element in the sequence is greater than its preceding element."
},
{
"code": null,
"e": 1463,
"s": 1215,
"text": "We are required to write a JavaScript function that takes in an array of Numbers as the only argument. The function should check whether we can form a strictly increasing sequence of the numbers by removing no more than one element from the array."
},
{
"code": null,
"e": 1487,
"s": 1463,
"text": "Following is the code −"
},
{
"code": null,
"e": 2081,
"s": 1487,
"text": "const almostIncreasingSequence = (arr = []) => {\n if (isIncreasingSequence(arr)) {\n return true;\n };\n for (let i = 0; i < arr.length > 0; i++) {\n let copy = arr.slice(0);\n copy.splice(i, 1);\n if (isIncreasingSequence(copy)) {\n return true;\n };\n };\n return false;\n};\nconst isIncreasingSequence = (arr = []) => {\n for (let i = 0; i < arr.length - 1; i++) {\n if (arr[i] >= arr[i + 1]) {\n return false;\n };\n };\n return true;\n};\nconsole.log(almostIncreasingSequence([1, 3, 2, 1]));\nconsole.log(almostIncreasingSequence([1, 3, 2]));"
},
{
"code": null,
"e": 2118,
"s": 2081,
"text": "Following is the output on console −"
},
{
"code": null,
"e": 2129,
"s": 2118,
"text": "false\ntrue"
}
] |
Difference Between get() and load() in Hibernate
|
In hibernate, get() and load() are two methods which is used to fetch data for the given identifier. They both belong to Hibernate session class. Get() method return null, If no row is available in the session cache or the database for the given identifier whereas load() method throws object not found exception.
1
Basic
It is used to fetch data from the database for the given identifier
It is also used to fetch data from the database for the given identifier
2
Null Object
It object not found for the given identifier then it will return null object
It will throw object not found exception
3
Lazy or Eager loading
It returns fully initialized object so this method eager load the object
It always returns proxy object so this method is lazy load the object
4
Performance
It is slower than load() because it return fully initialized object which impact the performance of the application
It is slightly faster.
5.
Use Case
If you are not sure that object exist then use get() method
If you are sure that object exist then use load() method
@Entity
public class User {
@Id
Integer id;
String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.journaldev.hibernate.util.HibernateUtil;
public class GetExample {
public static void main(String[] args) {
//get session factory to start transcation
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
//Get Example
User user = (User) session.get(User.class, new Integer(2));
System.out.println("User ID= "+user.getId());
System.out.println("User Name= "+user.getName());
//Close resources
tx.commit();
sessionFactory.close();
}
}
@Entity
public class User {
@Id
Integer id;
String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.journaldev.hibernate.util.HibernateUtil;
public class LoadExample {
public static void main(String[] args) {
//get session factory to start transcation
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
//Load Example
User user = (User) session.load(User.class, new Integer(2));
System.out.println("User ID= "+user.getId());
System.out.println("User Name= "+user.getName());
//Close resources
tx.commit();
sessionFactory.close();
}
}
|
[
{
"code": null,
"e": 1377,
"s": 1062,
"text": "In hibernate, get() and load() are two methods which is used to fetch data for the given identifier. They both belong to Hibernate session class. Get() method return null, If no row is available in the session cache or the database for the given identifier whereas load() method throws object not found exception. "
},
{
"code": null,
"e": 1379,
"s": 1377,
"text": "1"
},
{
"code": null,
"e": 1386,
"s": 1379,
"text": "Basic "
},
{
"code": null,
"e": 1457,
"s": 1386,
"text": "It is used to fetch data from the database for the given identifier "
},
{
"code": null,
"e": 1532,
"s": 1457,
"text": "It is also used to fetch data from the database for the given identifier "
},
{
"code": null,
"e": 1534,
"s": 1532,
"text": "2"
},
{
"code": null,
"e": 1547,
"s": 1534,
"text": "Null Object "
},
{
"code": null,
"e": 1625,
"s": 1547,
"text": "It object not found for the given identifier then it will return null object "
},
{
"code": null,
"e": 1667,
"s": 1625,
"text": "It will throw object not found exception "
},
{
"code": null,
"e": 1669,
"s": 1667,
"text": "3"
},
{
"code": null,
"e": 1692,
"s": 1669,
"text": "Lazy or Eager loading "
},
{
"code": null,
"e": 1767,
"s": 1692,
"text": "It returns fully initialized object so this method eager load the object "
},
{
"code": null,
"e": 1839,
"s": 1767,
"text": "It always returns proxy object so this method is lazy load the object "
},
{
"code": null,
"e": 1841,
"s": 1839,
"text": "4"
},
{
"code": null,
"e": 1854,
"s": 1841,
"text": "Performance "
},
{
"code": null,
"e": 1971,
"s": 1854,
"text": "It is slower than load() because it return fully initialized object which impact the performance of the application "
},
{
"code": null,
"e": 1994,
"s": 1971,
"text": "It is slightly faster."
},
{
"code": null,
"e": 1997,
"s": 1994,
"text": "5."
},
{
"code": null,
"e": 2006,
"s": 1997,
"text": "Use Case"
},
{
"code": null,
"e": 2067,
"s": 2006,
"text": "If you are not sure that object exist then use get() method "
},
{
"code": null,
"e": 2125,
"s": 2067,
"text": "If you are sure that object exist then use load() method "
},
{
"code": null,
"e": 3147,
"s": 2125,
"text": "@Entity\npublic class User {\n @Id\n Integer id;\n String name;\n public Integer getId() {\n return id;\n }\n public void setId(Integer id) {\n this.id = id;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n}\nimport org.hibernate.Session;\nimport org.hibernate.SessionFactory;\nimport org.hibernate.Transaction;\nimport com.journaldev.hibernate.util.HibernateUtil;\npublic class GetExample {\n public static void main(String[] args) {\n //get session factory to start transcation\n SessionFactory sessionFactory = HibernateUtil.getSessionFactory();\n Session session = sessionFactory.openSession();\n Transaction tx = session.beginTransaction();\n //Get Example\n User user = (User) session.get(User.class, new Integer(2));\n System.out.println(\"User ID= \"+user.getId());\n System.out.println(\"User Name= \"+user.getName());\n //Close resources\n tx.commit();\n sessionFactory.close();\n }\n}"
},
{
"code": null,
"e": 4174,
"s": 3147,
"text": "@Entity\npublic class User {\n @Id\n Integer id;\n String name;\n public Integer getId() {\n return id;\n }\n public void setId(Integer id) {\n this.id = id;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n}\nimport org.hibernate.Session;\nimport org.hibernate.SessionFactory;\nimport org.hibernate.Transaction;\nimport com.journaldev.hibernate.util.HibernateUtil;\npublic class LoadExample {\n public static void main(String[] args) {\n //get session factory to start transcation\n SessionFactory sessionFactory = HibernateUtil.getSessionFactory();\n Session session = sessionFactory.openSession();\n Transaction tx = session.beginTransaction();\n //Load Example\n User user = (User) session.load(User.class, new Integer(2));\n System.out.println(\"User ID= \"+user.getId());\n System.out.println(\"User Name= \"+user.getName()); \n //Close resources\n tx.commit();\n sessionFactory.close();\n }\n}"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.