title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Common Loss functions in machine learning | by Ravindra Parmar | Towards Data Science | Machines learn by means of a loss function. It’s a method of evaluating how well specific algorithm models the given data. If predictions deviates too much from actual results, loss function would cough up a very large number. Gradually, with the help of some optimization function, loss function learns to reduce the error in prediction. In this article we will go through several loss functions and their applications in the domain of machine/deep learning.
There’s no one-size-fits-all loss function to algorithms in machine learning. There are various factors involved in choosing a loss function for specific problem such as type of machine learning algorithm chosen, ease of calculating the derivatives and to some degree the percentage of outliers in the data set.
Broadly, loss functions can be classified into two major categories depending upon the type of learning task we are dealing with — Regression losses and Classification losses. In classification, we are trying to predict output from set of finite categorical values i.e Given large data set of images of hand written digits, categorizing them into one of 0–9 digits. Regression, on the other hand, deals with predicting a continuous value for example given floor area, number of rooms, size of rooms, predict the price of room.
NOTE n - Number of training examples. i - ith training example in a data set. y(i) - Ground truth label for ith training example. y_hat(i) - Prediction for ith training example.
Mean Square Error/Quadratic Loss/L2 Loss
Mathematical formulation :-
As the name suggests, Mean square error is measured as the average of squared difference between predictions and actual observations. It’s only concerned with the average magnitude of error irrespective of their direction. However, due to squaring, predictions which are far away from actual values are penalized heavily in comparison to less deviated predictions. Plus MSE has nice mathematical properties which makes it easier to calculate gradients.
import numpy as npy_hat = np.array([0.000, 0.166, 0.333])y_true = np.array([0.000, 0.254, 0.998])def rmse(predictions, targets): differences = predictions - targets differences_squared = differences ** 2 mean_of_differences_squared = differences_squared.mean() rmse_val = np.sqrt(mean_of_differences_squared) return rmse_valprint("d is: " + str(["%.8f" % elem for elem in y_hat]))print("p is: " + str(["%.8f" % elem for elem in y_true]))rmse_val = rmse(y_hat, y_true)print("rms error is: " + str(rmse_val))
Mean Absolute Error/L1 Loss
Mathematical formulation :-
Mean absolute error, on the other hand, is measured as the average of sum of absolute differences between predictions and actual observations. Like MSE, this as well measures the magnitude of error without considering their direction. Unlike MSE, MAE needs more complicated tools such as linear programming to compute the gradients. Plus MAE is more robust to outliers since it does not make use of square.
import numpy as npy_hat = np.array([0.000, 0.166, 0.333])y_true = np.array([0.000, 0.254, 0.998])print("d is: " + str(["%.8f" % elem for elem in y_hat]))print("p is: " + str(["%.8f" % elem for elem in y_true]))def mae(predictions, targets): differences = predictions - targets absolute_differences = np.absolute(differences) mean_absolute_differences = absolute_differences.mean() return mean_absolute_differencesmae_val = mae(y_hat, y_true)print ("mae error is: " + str(mae_val))
Mean Bias Error
This is much less common in machine learning domain as compared to it’s counterpart. This is same as MSE with the only difference that we don’t take absolute values. Clearly there’s a need for caution as positive and negative errors could cancel each other out. Although less accurate in practice, it could determine if the model has positive bias or negative bias.
Mathematical formulation :-
Hinge Loss/Multi class SVM Loss
In simple terms, the score of correct category should be greater than sum of scores of all incorrect categories by some safety margin (usually one). And hence hinge loss is used for maximum-margin classification, most notably for support vector machines. Although not differentiable, it’s a convex function which makes it easy to work with usual convex optimizers used in machine learning domain.
Mathematical formulation :-
Consider an example where we have three training examples and three classes to predict — Dog, cat and horse. Below the values predicted by our algorithm for each of the classes :-
Computing hinge losses for all 3 training examples :-
## 1st training examplemax(0, (1.49) - (-0.39) + 1) + max(0, (4.21) - (-0.39) + 1)max(0, 2.88) + max(0, 5.6)2.88 + 5.68.48 (High loss as very wrong prediction)## 2nd training examplemax(0, (-4.61) - (3.28)+ 1) + max(0, (1.46) - (3.28)+ 1)max(0, -6.89) + max(0, -0.82)0 + 00 (Zero loss as correct prediction)## 3rd training examplemax(0, (1.03) - (-2.27)+ 1) + max(0, (-2.37) - (-2.27)+ 1)max(0, 4.3) + max(0, 0.9)4.3 + 0.95.2 (High loss as very wrong prediction)
Cross Entropy Loss/Negative Log Likelihood
This is the most common setting for classification problems. Cross-entropy loss increases as the predicted probability diverges from the actual label.
Mathematical formulation :-
Notice that when actual label is 1 (y(i) = 1), second half of function disappears whereas in case actual label is 0 (y(i) = 0) first half is dropped off. In short, we are just multiplying the log of the actual predicted probability for the ground truth class. An important aspect of this is that cross entropy loss penalizes heavily the predictions that are confident but wrong.
import numpy as nppredictions = np.array([[0.25,0.25,0.25,0.25], [0.01,0.01,0.01,0.96]])targets = np.array([[0,0,0,1], [0,0,0,1]])def cross_entropy(predictions, targets, epsilon=1e-10): predictions = np.clip(predictions, epsilon, 1. - epsilon) N = predictions.shape[0] ce_loss = -np.sum(np.sum(targets * np.log(predictions + 1e-5)))/N return ce_losscross_entropy_loss = cross_entropy(predictions, targets)print ("Cross entropy loss is: " + str(cross_entropy_loss)) | [
{
"code": null,
"e": 631,
"s": 171,
"text": "Machines learn by means of a loss function. It’s a method of evaluating how well specific algorithm models the given data. If predictions deviates too much from actual results, loss function would cough up a very large number. Gradually, with the help of some optimization function, loss function learns to reduce the error in prediction. In this article we will go through several loss functions and their applications in the domain of machine/deep learning."
},
{
"code": null,
"e": 943,
"s": 631,
"text": "There’s no one-size-fits-all loss function to algorithms in machine learning. There are various factors involved in choosing a loss function for specific problem such as type of machine learning algorithm chosen, ease of calculating the derivatives and to some degree the percentage of outliers in the data set."
},
{
"code": null,
"e": 1470,
"s": 943,
"text": "Broadly, loss functions can be classified into two major categories depending upon the type of learning task we are dealing with — Regression losses and Classification losses. In classification, we are trying to predict output from set of finite categorical values i.e Given large data set of images of hand written digits, categorizing them into one of 0–9 digits. Regression, on the other hand, deals with predicting a continuous value for example given floor area, number of rooms, size of rooms, predict the price of room."
},
{
"code": null,
"e": 1695,
"s": 1470,
"text": "NOTE n - Number of training examples. i - ith training example in a data set. y(i) - Ground truth label for ith training example. y_hat(i) - Prediction for ith training example."
},
{
"code": null,
"e": 1736,
"s": 1695,
"text": "Mean Square Error/Quadratic Loss/L2 Loss"
},
{
"code": null,
"e": 1764,
"s": 1736,
"text": "Mathematical formulation :-"
},
{
"code": null,
"e": 2217,
"s": 1764,
"text": "As the name suggests, Mean square error is measured as the average of squared difference between predictions and actual observations. It’s only concerned with the average magnitude of error irrespective of their direction. However, due to squaring, predictions which are far away from actual values are penalized heavily in comparison to less deviated predictions. Plus MSE has nice mathematical properties which makes it easier to calculate gradients."
},
{
"code": null,
"e": 2739,
"s": 2217,
"text": "import numpy as npy_hat = np.array([0.000, 0.166, 0.333])y_true = np.array([0.000, 0.254, 0.998])def rmse(predictions, targets): differences = predictions - targets differences_squared = differences ** 2 mean_of_differences_squared = differences_squared.mean() rmse_val = np.sqrt(mean_of_differences_squared) return rmse_valprint(\"d is: \" + str([\"%.8f\" % elem for elem in y_hat]))print(\"p is: \" + str([\"%.8f\" % elem for elem in y_true]))rmse_val = rmse(y_hat, y_true)print(\"rms error is: \" + str(rmse_val))"
},
{
"code": null,
"e": 2767,
"s": 2739,
"text": "Mean Absolute Error/L1 Loss"
},
{
"code": null,
"e": 2795,
"s": 2767,
"text": "Mathematical formulation :-"
},
{
"code": null,
"e": 3202,
"s": 2795,
"text": "Mean absolute error, on the other hand, is measured as the average of sum of absolute differences between predictions and actual observations. Like MSE, this as well measures the magnitude of error without considering their direction. Unlike MSE, MAE needs more complicated tools such as linear programming to compute the gradients. Plus MAE is more robust to outliers since it does not make use of square."
},
{
"code": null,
"e": 3695,
"s": 3202,
"text": "import numpy as npy_hat = np.array([0.000, 0.166, 0.333])y_true = np.array([0.000, 0.254, 0.998])print(\"d is: \" + str([\"%.8f\" % elem for elem in y_hat]))print(\"p is: \" + str([\"%.8f\" % elem for elem in y_true]))def mae(predictions, targets): differences = predictions - targets absolute_differences = np.absolute(differences) mean_absolute_differences = absolute_differences.mean() return mean_absolute_differencesmae_val = mae(y_hat, y_true)print (\"mae error is: \" + str(mae_val))"
},
{
"code": null,
"e": 3711,
"s": 3695,
"text": "Mean Bias Error"
},
{
"code": null,
"e": 4077,
"s": 3711,
"text": "This is much less common in machine learning domain as compared to it’s counterpart. This is same as MSE with the only difference that we don’t take absolute values. Clearly there’s a need for caution as positive and negative errors could cancel each other out. Although less accurate in practice, it could determine if the model has positive bias or negative bias."
},
{
"code": null,
"e": 4105,
"s": 4077,
"text": "Mathematical formulation :-"
},
{
"code": null,
"e": 4137,
"s": 4105,
"text": "Hinge Loss/Multi class SVM Loss"
},
{
"code": null,
"e": 4534,
"s": 4137,
"text": "In simple terms, the score of correct category should be greater than sum of scores of all incorrect categories by some safety margin (usually one). And hence hinge loss is used for maximum-margin classification, most notably for support vector machines. Although not differentiable, it’s a convex function which makes it easy to work with usual convex optimizers used in machine learning domain."
},
{
"code": null,
"e": 4562,
"s": 4534,
"text": "Mathematical formulation :-"
},
{
"code": null,
"e": 4742,
"s": 4562,
"text": "Consider an example where we have three training examples and three classes to predict — Dog, cat and horse. Below the values predicted by our algorithm for each of the classes :-"
},
{
"code": null,
"e": 4796,
"s": 4742,
"text": "Computing hinge losses for all 3 training examples :-"
},
{
"code": null,
"e": 5259,
"s": 4796,
"text": "## 1st training examplemax(0, (1.49) - (-0.39) + 1) + max(0, (4.21) - (-0.39) + 1)max(0, 2.88) + max(0, 5.6)2.88 + 5.68.48 (High loss as very wrong prediction)## 2nd training examplemax(0, (-4.61) - (3.28)+ 1) + max(0, (1.46) - (3.28)+ 1)max(0, -6.89) + max(0, -0.82)0 + 00 (Zero loss as correct prediction)## 3rd training examplemax(0, (1.03) - (-2.27)+ 1) + max(0, (-2.37) - (-2.27)+ 1)max(0, 4.3) + max(0, 0.9)4.3 + 0.95.2 (High loss as very wrong prediction)"
},
{
"code": null,
"e": 5302,
"s": 5259,
"text": "Cross Entropy Loss/Negative Log Likelihood"
},
{
"code": null,
"e": 5453,
"s": 5302,
"text": "This is the most common setting for classification problems. Cross-entropy loss increases as the predicted probability diverges from the actual label."
},
{
"code": null,
"e": 5481,
"s": 5453,
"text": "Mathematical formulation :-"
},
{
"code": null,
"e": 5860,
"s": 5481,
"text": "Notice that when actual label is 1 (y(i) = 1), second half of function disappears whereas in case actual label is 0 (y(i) = 0) first half is dropped off. In short, we are just multiplying the log of the actual predicted probability for the ground truth class. An important aspect of this is that cross entropy loss penalizes heavily the predictions that are confident but wrong."
}
]
|
How to Assign Labels with Sklearn One Hot Encoder | by Vitalii Dodonov | Towards Data Science | Most machine learning algorithms don’t work with categorical data out of the box. It is a common practice to apply label encoder or one hot encoder to a categorical variable before using it in predictive modelling.
Sklearn library in Python is a go-to for most Machine Learning practitioners. It provides outstanding generalized functionality that allows us to perform complex operations with a single line of code. At the same time, some of its functionality is too general and may be a challenge to work with.
One hot encoding is a process of transforming a categorical variable into N binary columns where N is the number of unique values in the original column. For example, in my recent study about stock price behaviour during COVID-19
towardsdatascience.com
I used one hot encoding to break down industry sector classifications
into its binary column representation like so:
One hot transformation can be accomplished using the default sklearn package:
sklearn.preprocessing.OneHotEncoder# df = some DataFrameencoder = OneHotEncoder()encoder.fit_transform(df)
The output of the code above implementation looks like this:
It is correct, but it doesn’t provide labels, which makes it difficult to know the meaning behind the new columns. Without this knowledge, analyzing the output of predictive models would be impossible. Some guidance on label assignments is provided in the documentation but it is still a challenge to work with. Hence, there is a need for a better solution.
An elegant way to add labels to the One Hot Encoder output while keeping the “one line” implementation is to create a wrapper class that assigns labels during the transform() operation “inside the box”. Here is the code:
With this wrapper, the output loos like this:
I will now break down its implementation and explain how it works in detail.
from sklearn.preprocessing import OneHotEncoder as SklearnOneHotEncoderclass OneHotEncoder(SklearnOneHotEncoder): def __init__(self, **kwargs): super(OneHotEncoder, self).__init__(**kwargs) self.fit_flag = False
This class inherits from the sklearn.preprocessing.OneHotEncoder, which means all the original functionality is preserved. I also add self.fit_flag property to keep track of whether the encoder has been fit or not.
def fit(self, X, **kwargs): out = super().fit(X) self.fit_flag = True return out
The fit() method is essentially the original fit() method. I use super().fit(X) to access the original method from sklearn.preprocessing.OneHotEncoder and then update self.fit_flag to True before returning the output.
def transform(self, X, **kwargs): sparse_matrix = super(OneHotEncoder, self).transform(X) new_columns = self.get_new_columns(X=X) d_out = pd.DataFrame(sparse_matrix.toarray(), columns=new_columns, index=X.index) return d_outdef get_new_columns(self, X): new_columns = [] for i, column in enumerate(X.columns): j = 0 while j < len(self.categories_[i]): new_columns.append(f'{column}_<{self.categories_[i][j]}>') j += 1 return new_columns
Transform method is more involved because this is where I implement label assignments. The sparse_matrix variable is created first, storing the output from the original transform() method. I then call get_new_column() method which I wrote to access OneHotEncoder’s internal properties to retrieve class names.
The get_new_columns() method is essentially a nested iterator with two levels. At the first level, I iterate over columns in the original DataFrame. At the second level, I iterate over values in self.categories_[i] where self.categories_ belongs to the original OneHotEncoder and “i” is the ordinal index of columns in the table being transformed. At each step, I append column name to a list which will be returned once the iterations are complete. Eventually, the length of the new_columns variable is equivalent to the horizontal dimension of the sparse_matrix once it is converted to an array.
In the final step, I convert the sparse_matrix to an array using built-in functionality, then create a DataFrame with the column names returned by the get_new_columns() method.
def fit_transform(self, X, **kwargs): self.fit(X) return self.transform(X)
The last method consists of sequential execution of my modified fit() and transform() methods, returning a One Hot DataFrame with the assigned column names.
I hope you found this tutorial useful. Feel free to grab the code snippet above and use it in your own applications. | [
{
"code": null,
"e": 387,
"s": 172,
"text": "Most machine learning algorithms don’t work with categorical data out of the box. It is a common practice to apply label encoder or one hot encoder to a categorical variable before using it in predictive modelling."
},
{
"code": null,
"e": 684,
"s": 387,
"text": "Sklearn library in Python is a go-to for most Machine Learning practitioners. It provides outstanding generalized functionality that allows us to perform complex operations with a single line of code. At the same time, some of its functionality is too general and may be a challenge to work with."
},
{
"code": null,
"e": 914,
"s": 684,
"text": "One hot encoding is a process of transforming a categorical variable into N binary columns where N is the number of unique values in the original column. For example, in my recent study about stock price behaviour during COVID-19"
},
{
"code": null,
"e": 937,
"s": 914,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1007,
"s": 937,
"text": "I used one hot encoding to break down industry sector classifications"
},
{
"code": null,
"e": 1054,
"s": 1007,
"text": "into its binary column representation like so:"
},
{
"code": null,
"e": 1132,
"s": 1054,
"text": "One hot transformation can be accomplished using the default sklearn package:"
},
{
"code": null,
"e": 1239,
"s": 1132,
"text": "sklearn.preprocessing.OneHotEncoder# df = some DataFrameencoder = OneHotEncoder()encoder.fit_transform(df)"
},
{
"code": null,
"e": 1300,
"s": 1239,
"text": "The output of the code above implementation looks like this:"
},
{
"code": null,
"e": 1658,
"s": 1300,
"text": "It is correct, but it doesn’t provide labels, which makes it difficult to know the meaning behind the new columns. Without this knowledge, analyzing the output of predictive models would be impossible. Some guidance on label assignments is provided in the documentation but it is still a challenge to work with. Hence, there is a need for a better solution."
},
{
"code": null,
"e": 1879,
"s": 1658,
"text": "An elegant way to add labels to the One Hot Encoder output while keeping the “one line” implementation is to create a wrapper class that assigns labels during the transform() operation “inside the box”. Here is the code:"
},
{
"code": null,
"e": 1925,
"s": 1879,
"text": "With this wrapper, the output loos like this:"
},
{
"code": null,
"e": 2002,
"s": 1925,
"text": "I will now break down its implementation and explain how it works in detail."
},
{
"code": null,
"e": 2231,
"s": 2002,
"text": "from sklearn.preprocessing import OneHotEncoder as SklearnOneHotEncoderclass OneHotEncoder(SklearnOneHotEncoder): def __init__(self, **kwargs): super(OneHotEncoder, self).__init__(**kwargs) self.fit_flag = False"
},
{
"code": null,
"e": 2446,
"s": 2231,
"text": "This class inherits from the sklearn.preprocessing.OneHotEncoder, which means all the original functionality is preserved. I also add self.fit_flag property to keep track of whether the encoder has been fit or not."
},
{
"code": null,
"e": 2536,
"s": 2446,
"text": "def fit(self, X, **kwargs): out = super().fit(X) self.fit_flag = True return out"
},
{
"code": null,
"e": 2754,
"s": 2536,
"text": "The fit() method is essentially the original fit() method. I use super().fit(X) to access the original method from sklearn.preprocessing.OneHotEncoder and then update self.fit_flag to True before returning the output."
},
{
"code": null,
"e": 3248,
"s": 2754,
"text": "def transform(self, X, **kwargs): sparse_matrix = super(OneHotEncoder, self).transform(X) new_columns = self.get_new_columns(X=X) d_out = pd.DataFrame(sparse_matrix.toarray(), columns=new_columns, index=X.index) return d_outdef get_new_columns(self, X): new_columns = [] for i, column in enumerate(X.columns): j = 0 while j < len(self.categories_[i]): new_columns.append(f'{column}_<{self.categories_[i][j]}>') j += 1 return new_columns"
},
{
"code": null,
"e": 3558,
"s": 3248,
"text": "Transform method is more involved because this is where I implement label assignments. The sparse_matrix variable is created first, storing the output from the original transform() method. I then call get_new_column() method which I wrote to access OneHotEncoder’s internal properties to retrieve class names."
},
{
"code": null,
"e": 4156,
"s": 3558,
"text": "The get_new_columns() method is essentially a nested iterator with two levels. At the first level, I iterate over columns in the original DataFrame. At the second level, I iterate over values in self.categories_[i] where self.categories_ belongs to the original OneHotEncoder and “i” is the ordinal index of columns in the table being transformed. At each step, I append column name to a list which will be returned once the iterations are complete. Eventually, the length of the new_columns variable is equivalent to the horizontal dimension of the sparse_matrix once it is converted to an array."
},
{
"code": null,
"e": 4333,
"s": 4156,
"text": "In the final step, I convert the sparse_matrix to an array using built-in functionality, then create a DataFrame with the column names returned by the get_new_columns() method."
},
{
"code": null,
"e": 4414,
"s": 4333,
"text": "def fit_transform(self, X, **kwargs): self.fit(X) return self.transform(X)"
},
{
"code": null,
"e": 4571,
"s": 4414,
"text": "The last method consists of sequential execution of my modified fit() and transform() methods, returning a One Hot DataFrame with the assigned column names."
}
]
|
Railway Reservation System in C - GeeksforGeeks | 17 Jan, 2022
Railway ticket booking system is implemented by C programming. It is as same as one can see while we are going for online ticket booking. The following series of steps are being followed while booking a railway ticket in this software-
The first step is to provide the total number of passengers and submit all the necessary details of the passengers.The next step is to enter the source and destination.A list of available trains will appear. Among them, the user has to choose one.The ticket value will be evaluated. The system will ask to enter the seat choice by showing the seat matrix. At last, a receipt will be generated on the screen.
The first step is to provide the total number of passengers and submit all the necessary details of the passengers.
The next step is to enter the source and destination.
A list of available trains will appear. Among them, the user has to choose one.
The ticket value will be evaluated. The system will ask to enter the seat choice by showing the seat matrix. At last, a receipt will be generated on the screen.
Approach:
The first step is to implement a structure for taking the details of the passengers, like name, gender, and age.
Five functions are defined void details(int), void add_node(char, char, int), int seat(int), int cal(int, int, int), void bill(int, int) to work smoothly.
There are three elements in the structure like two strings one for taking passenger name and gender and one integer for taking passenger age. Also, a structure pointer will be used which helps to link the next node of another passenger. It is similar to the linked list.
Character arrays are defined and some integer arrays are defined globally.
Take the number of passengers as input and these details are sent to the details() function.
Execute a for loop to take details of each passenger. The details inputted by the user will be sent to the add_node() function.
In the add_node function, every detail will store in a node for each passenger. These nodes will link each other. This is based on the linked list concept.
Take the input for source place, destination place and it will give some choice of trains available. Based on that user has to give a choice. Then call the cal() function.
In cal() function, the user has to give a choice for sleeper or a.c. class. If the user chooses a.c. class another three options will open where the user has to give another choice based on that the system will add 18% GST on the amount and make total amount.
Call the seat() function where a seat matrix will be given to the user and the user has to choose a seat same with the number of passengers.
At last, call the bill() function where the total bill amount with all the necessary details will be displayed.
Below is the implementation of the above approach:
C
// C program for the above approach#include <conio.h>#include <stdio.h>#include <stdlib.h>#include <string.h> // Defining Structuretypedef struct mynode { char name[20]; char gen[6]; int age; struct mynode* link;} Node; Node* start = NULL; void details(int);int seat(int);int cal(int, int, int);void bill(int, int); // Global variableschar source[20], des[20], train[40];char station[40], cla[40];int time1, time2, a[55]; // Driver Codevoid main(){ int i, j, a1, a2, b, c, int x = 0, d, e, r; char o; printf("Enter Number Of Passengers: "); fflush(stdin); scanf("%d", &j); // Calling details() function with // argument number of passenger details(j); printf("Enter The Source Place: "); fflush(stdin); gets(source); printf("Enter The Destination Place: "); gets(des); printf("\t\tThe Following Trains " "Are Available.....\n"); printf("\t\t1. Rajdhani Express.." ".......10:00 " "a.m........Sealdah Station\n"); printf("\t\t2. Satabdi Express..." ".......05:00 " "p.m........Howrah Station\n"); printf("\t\t3. Humsafar Express..." ".......11:00 " "p.m........Kolkata Chitpur" " Station\n"); printf("\t\t4. Garib-Rath Express" ".........05:00 " "p.m........Sealdah Station\n"); printf("\t\t5. Duronto Express..." ".........07:00 " "a.m.........Santraganchi" "Station\n"); scanf("%d", &i); do { switch (i) { case 1: { strcpy(train, "Rajdhani Express"); strcpy(station, "Sealdah Station"); time1 = 10; time2 = 00; a1 = 2099; a2 = 1560; // Calling cal() function // with the three argument // and return value d = cal(a1, a2, j); printf("Total Bill Amount:" " %d\n", d); }; break; case 2: { strcpy(train, "Satabdi Express"); strcpy(station, "Howrah Station"); time1 = 05; time2 = 00; a1 = 1801; a2 = 981; // Calling cal() function with // three argument & return value d = cal(a1, a2, j); printf("Total Bill Amount:" "%d\n", d); }; break; case 3: { strcpy(train, "Humsafar Express"); strcpy(station, "Kolkata Chitpur Express"); time1 = 11; time2 = 00; a1 = 2199; a2 = 1780; // Calling cal() function with // three argument & return value d = cal(a1, a2, j); printf("Total Bill Amount: %d\n", d); }; break; case 4: { strcpy(train, "Garib-Rath Express"); strcpy(station, "Sealdah Station"); time1 = 05; time2 = 00; a1 = 1759; a2 = 1200; // Calling cal() function with // three argument & return value d = cal(a1, a2, j); printf("Total Bill Amount: %d\n", d); }; break; case 5: { strcpy(train, "Duronto Express"); strcpy(station, "Santraganchi Station"); time1 = 07; time2 = 00; a1 = 2205; a2 = 1905; // Calling cal() function with // three argument & return value d = cal(a1, a2, j); printf("Total Bill Amount: %d\n", d); }; break; default: printf("Enter Correct choice.....\n"); x = 1; break; } } while (x); printf("Now Book Your Seats......\n"); // Calling seat() function with number // of passenger seat(j); // Calling bill() function with // the number of passenger // and amount argument bill(d, j);} // Function for calculation of amountint cal(int y1, int y2, int h){ int b, c, i, t, r, n; printf("\t\tEnter Your Choice......\n"); printf("\t\t1. Slepper Class....\n"); printf("\t\t2. A.C Class.......\n"); scanf("%d", &i); switch (i) { case 1: { strcpy(cla, "Slepper Class"); b = y2 * h; c = b + (b * 0.18); } break; case 2: { printf("\t\tEnter Your Choice....\n"); printf("\t\t1. 3A Class....\n"); printf("\t\t2. 2A Class....\n"); printf("\t\t3. 1st Class A.C.....\n"); scanf("%d", &n); switch (n) { case 1: { strcpy(cla, "3A Class"); b = y1 * h; c = b + (b * 0.18); } break; case 2: { strcpy(cla, "2A Class"); b = (y1 + 1000) * h; c = b + (b * 0.18); } break; case 3: { strcpy(cla, "1st Class A.C."); b = (y1 + 5000) * h; c = b + (b * 0.18); } break; default: { printf("\t\tEnter Right Choice......\n"); } } } break; default: { printf("\t\tEnter Right Choice......\n"); } } return c;} // Function for taking details// of passengersvoid details(int k){ int i, a; char val[20], gen[6]; for (i = 1; i <= k; i++) { printf("Enter The %dth Passenger Name: ", i); fflush(stdin); gets(val); printf("Enter The %dth Passenger Gender: ", i); fflush(stdin); gets(gen); printf("Enter The %dth Passenger Age: ", i); fflush(stdin); scanf("%d", &a); // Calling add_node() function add_node(val, gen, a); }} // Function to add details in node// for each passengersvoid add_node(char lol[20], char der[6], int b){ Node *newptr = NULL, *ptr; newptr = (Node*)malloc(sizeof(Node)); strcpy(newptr->name, lol); strcpy(newptr->gen, der); newptr->age = b; newptr->link = NULL; if (start == NULL) start = newptr; else { ptr = start; while (ptr->link != NULL) ptr = ptr->link; ptr->link = newptr; }} // Function for choosing seatsint seat(int p){ int i; printf("\t -:SEAT MATRIX:- \n"); printf("\t(U) (M) (L) (L) " " (U)\n\n"); printf("\t01 02 03\t04 " "05\n\n"); printf("\t06 07 08\t09 " "10\n"); printf("\t11 12 13\t14 " "15\n\n"); printf("\t16 17 18\t19 " "20\n"); printf("\t21 22 23\t24 " "25\n\n"); printf("\t26 27 28\t29 " "30\n"); printf("\t31 32 33\t34 " "35\n\n"); printf("\t36 37 38\t39 " "40\n"); printf("\t41 42 43\t44 " "45\n\n"); printf("\t46 47 48\t49 " "50\n"); printf("\t51 52 53\t54 " "55\n\n"); printf("\t56 57 58\t59 " "60\n"); printf("\tEnter Seat Numbers: \n"); for (i = 0; i < p; i++) scanf("%d", &a[i]);} // Function for printing receiptvoid bill(int y, int j){ int i; Node* ptr = start; for (i = 1; i <= j; i++) { printf("\t\t\%dst Passenger Name: ", i); puts(ptr->name); printf("\t\t%dst Passenger Gender: ", i); puts(ptr->gen); printf("\t\t%dst Passenger Age: %d\n\n", i, ptr->age); ptr = ptr->link; } printf("\t\tSource Place: "); puts(source); printf("\t\tDestination Place: "); puts(des); printf("\t\tThe Boarding Station: "); puts(station); printf("\t\tTrain Is: "); puts(train); printf("\t\tAllocated Class: "); puts(cla); printf("\t\tBoarding Time: %d:%d\n", time1, time2); printf("\t\tTotal Bill Amount: %d\n", y); printf("\t\tAllocated Seats Are: \n"); for (i = 0; i < j; i++) { printf("\t\t%d ", a[i]); } printf("\n"); printf("\t\t\t\tThank You......\n");}
Output:
simmytarika5
Project-Ideas
C Language
C Programs
Project
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Exception Handling in C++
Multithreading in C
'this' pointer in C++
Arrow operator -> in C/C++ with Examples
Strings in C
Arrow operator -> in C/C++ with Examples
C Program to read contents of Whole File
Header files in C/C++ and its uses
Basics of File Handling in C | [
{
"code": null,
"e": 25479,
"s": 25451,
"text": "\n17 Jan, 2022"
},
{
"code": null,
"e": 25715,
"s": 25479,
"text": "Railway ticket booking system is implemented by C programming. It is as same as one can see while we are going for online ticket booking. The following series of steps are being followed while booking a railway ticket in this software-"
},
{
"code": null,
"e": 26123,
"s": 25715,
"text": "The first step is to provide the total number of passengers and submit all the necessary details of the passengers.The next step is to enter the source and destination.A list of available trains will appear. Among them, the user has to choose one.The ticket value will be evaluated. The system will ask to enter the seat choice by showing the seat matrix. At last, a receipt will be generated on the screen."
},
{
"code": null,
"e": 26239,
"s": 26123,
"text": "The first step is to provide the total number of passengers and submit all the necessary details of the passengers."
},
{
"code": null,
"e": 26293,
"s": 26239,
"text": "The next step is to enter the source and destination."
},
{
"code": null,
"e": 26373,
"s": 26293,
"text": "A list of available trains will appear. Among them, the user has to choose one."
},
{
"code": null,
"e": 26534,
"s": 26373,
"text": "The ticket value will be evaluated. The system will ask to enter the seat choice by showing the seat matrix. At last, a receipt will be generated on the screen."
},
{
"code": null,
"e": 26544,
"s": 26534,
"text": "Approach:"
},
{
"code": null,
"e": 26657,
"s": 26544,
"text": "The first step is to implement a structure for taking the details of the passengers, like name, gender, and age."
},
{
"code": null,
"e": 26812,
"s": 26657,
"text": "Five functions are defined void details(int), void add_node(char, char, int), int seat(int), int cal(int, int, int), void bill(int, int) to work smoothly."
},
{
"code": null,
"e": 27083,
"s": 26812,
"text": "There are three elements in the structure like two strings one for taking passenger name and gender and one integer for taking passenger age. Also, a structure pointer will be used which helps to link the next node of another passenger. It is similar to the linked list."
},
{
"code": null,
"e": 27158,
"s": 27083,
"text": "Character arrays are defined and some integer arrays are defined globally."
},
{
"code": null,
"e": 27251,
"s": 27158,
"text": "Take the number of passengers as input and these details are sent to the details() function."
},
{
"code": null,
"e": 27379,
"s": 27251,
"text": "Execute a for loop to take details of each passenger. The details inputted by the user will be sent to the add_node() function."
},
{
"code": null,
"e": 27535,
"s": 27379,
"text": "In the add_node function, every detail will store in a node for each passenger. These nodes will link each other. This is based on the linked list concept."
},
{
"code": null,
"e": 27707,
"s": 27535,
"text": "Take the input for source place, destination place and it will give some choice of trains available. Based on that user has to give a choice. Then call the cal() function."
},
{
"code": null,
"e": 27967,
"s": 27707,
"text": "In cal() function, the user has to give a choice for sleeper or a.c. class. If the user chooses a.c. class another three options will open where the user has to give another choice based on that the system will add 18% GST on the amount and make total amount."
},
{
"code": null,
"e": 28108,
"s": 27967,
"text": "Call the seat() function where a seat matrix will be given to the user and the user has to choose a seat same with the number of passengers."
},
{
"code": null,
"e": 28220,
"s": 28108,
"text": "At last, call the bill() function where the total bill amount with all the necessary details will be displayed."
},
{
"code": null,
"e": 28271,
"s": 28220,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 28273,
"s": 28271,
"text": "C"
},
{
"code": "// C program for the above approach#include <conio.h>#include <stdio.h>#include <stdlib.h>#include <string.h> // Defining Structuretypedef struct mynode { char name[20]; char gen[6]; int age; struct mynode* link;} Node; Node* start = NULL; void details(int);int seat(int);int cal(int, int, int);void bill(int, int); // Global variableschar source[20], des[20], train[40];char station[40], cla[40];int time1, time2, a[55]; // Driver Codevoid main(){ int i, j, a1, a2, b, c, int x = 0, d, e, r; char o; printf(\"Enter Number Of Passengers: \"); fflush(stdin); scanf(\"%d\", &j); // Calling details() function with // argument number of passenger details(j); printf(\"Enter The Source Place: \"); fflush(stdin); gets(source); printf(\"Enter The Destination Place: \"); gets(des); printf(\"\\t\\tThe Following Trains \" \"Are Available.....\\n\"); printf(\"\\t\\t1. Rajdhani Express..\" \".......10:00 \" \"a.m........Sealdah Station\\n\"); printf(\"\\t\\t2. Satabdi Express...\" \".......05:00 \" \"p.m........Howrah Station\\n\"); printf(\"\\t\\t3. Humsafar Express...\" \".......11:00 \" \"p.m........Kolkata Chitpur\" \" Station\\n\"); printf(\"\\t\\t4. Garib-Rath Express\" \".........05:00 \" \"p.m........Sealdah Station\\n\"); printf(\"\\t\\t5. Duronto Express...\" \".........07:00 \" \"a.m.........Santraganchi\" \"Station\\n\"); scanf(\"%d\", &i); do { switch (i) { case 1: { strcpy(train, \"Rajdhani Express\"); strcpy(station, \"Sealdah Station\"); time1 = 10; time2 = 00; a1 = 2099; a2 = 1560; // Calling cal() function // with the three argument // and return value d = cal(a1, a2, j); printf(\"Total Bill Amount:\" \" %d\\n\", d); }; break; case 2: { strcpy(train, \"Satabdi Express\"); strcpy(station, \"Howrah Station\"); time1 = 05; time2 = 00; a1 = 1801; a2 = 981; // Calling cal() function with // three argument & return value d = cal(a1, a2, j); printf(\"Total Bill Amount:\" \"%d\\n\", d); }; break; case 3: { strcpy(train, \"Humsafar Express\"); strcpy(station, \"Kolkata Chitpur Express\"); time1 = 11; time2 = 00; a1 = 2199; a2 = 1780; // Calling cal() function with // three argument & return value d = cal(a1, a2, j); printf(\"Total Bill Amount: %d\\n\", d); }; break; case 4: { strcpy(train, \"Garib-Rath Express\"); strcpy(station, \"Sealdah Station\"); time1 = 05; time2 = 00; a1 = 1759; a2 = 1200; // Calling cal() function with // three argument & return value d = cal(a1, a2, j); printf(\"Total Bill Amount: %d\\n\", d); }; break; case 5: { strcpy(train, \"Duronto Express\"); strcpy(station, \"Santraganchi Station\"); time1 = 07; time2 = 00; a1 = 2205; a2 = 1905; // Calling cal() function with // three argument & return value d = cal(a1, a2, j); printf(\"Total Bill Amount: %d\\n\", d); }; break; default: printf(\"Enter Correct choice.....\\n\"); x = 1; break; } } while (x); printf(\"Now Book Your Seats......\\n\"); // Calling seat() function with number // of passenger seat(j); // Calling bill() function with // the number of passenger // and amount argument bill(d, j);} // Function for calculation of amountint cal(int y1, int y2, int h){ int b, c, i, t, r, n; printf(\"\\t\\tEnter Your Choice......\\n\"); printf(\"\\t\\t1. Slepper Class....\\n\"); printf(\"\\t\\t2. A.C Class.......\\n\"); scanf(\"%d\", &i); switch (i) { case 1: { strcpy(cla, \"Slepper Class\"); b = y2 * h; c = b + (b * 0.18); } break; case 2: { printf(\"\\t\\tEnter Your Choice....\\n\"); printf(\"\\t\\t1. 3A Class....\\n\"); printf(\"\\t\\t2. 2A Class....\\n\"); printf(\"\\t\\t3. 1st Class A.C.....\\n\"); scanf(\"%d\", &n); switch (n) { case 1: { strcpy(cla, \"3A Class\"); b = y1 * h; c = b + (b * 0.18); } break; case 2: { strcpy(cla, \"2A Class\"); b = (y1 + 1000) * h; c = b + (b * 0.18); } break; case 3: { strcpy(cla, \"1st Class A.C.\"); b = (y1 + 5000) * h; c = b + (b * 0.18); } break; default: { printf(\"\\t\\tEnter Right Choice......\\n\"); } } } break; default: { printf(\"\\t\\tEnter Right Choice......\\n\"); } } return c;} // Function for taking details// of passengersvoid details(int k){ int i, a; char val[20], gen[6]; for (i = 1; i <= k; i++) { printf(\"Enter The %dth Passenger Name: \", i); fflush(stdin); gets(val); printf(\"Enter The %dth Passenger Gender: \", i); fflush(stdin); gets(gen); printf(\"Enter The %dth Passenger Age: \", i); fflush(stdin); scanf(\"%d\", &a); // Calling add_node() function add_node(val, gen, a); }} // Function to add details in node// for each passengersvoid add_node(char lol[20], char der[6], int b){ Node *newptr = NULL, *ptr; newptr = (Node*)malloc(sizeof(Node)); strcpy(newptr->name, lol); strcpy(newptr->gen, der); newptr->age = b; newptr->link = NULL; if (start == NULL) start = newptr; else { ptr = start; while (ptr->link != NULL) ptr = ptr->link; ptr->link = newptr; }} // Function for choosing seatsint seat(int p){ int i; printf(\"\\t -:SEAT MATRIX:- \\n\"); printf(\"\\t(U) (M) (L) (L) \" \" (U)\\n\\n\"); printf(\"\\t01 02 03\\t04 \" \"05\\n\\n\"); printf(\"\\t06 07 08\\t09 \" \"10\\n\"); printf(\"\\t11 12 13\\t14 \" \"15\\n\\n\"); printf(\"\\t16 17 18\\t19 \" \"20\\n\"); printf(\"\\t21 22 23\\t24 \" \"25\\n\\n\"); printf(\"\\t26 27 28\\t29 \" \"30\\n\"); printf(\"\\t31 32 33\\t34 \" \"35\\n\\n\"); printf(\"\\t36 37 38\\t39 \" \"40\\n\"); printf(\"\\t41 42 43\\t44 \" \"45\\n\\n\"); printf(\"\\t46 47 48\\t49 \" \"50\\n\"); printf(\"\\t51 52 53\\t54 \" \"55\\n\\n\"); printf(\"\\t56 57 58\\t59 \" \"60\\n\"); printf(\"\\tEnter Seat Numbers: \\n\"); for (i = 0; i < p; i++) scanf(\"%d\", &a[i]);} // Function for printing receiptvoid bill(int y, int j){ int i; Node* ptr = start; for (i = 1; i <= j; i++) { printf(\"\\t\\t\\%dst Passenger Name: \", i); puts(ptr->name); printf(\"\\t\\t%dst Passenger Gender: \", i); puts(ptr->gen); printf(\"\\t\\t%dst Passenger Age: %d\\n\\n\", i, ptr->age); ptr = ptr->link; } printf(\"\\t\\tSource Place: \"); puts(source); printf(\"\\t\\tDestination Place: \"); puts(des); printf(\"\\t\\tThe Boarding Station: \"); puts(station); printf(\"\\t\\tTrain Is: \"); puts(train); printf(\"\\t\\tAllocated Class: \"); puts(cla); printf(\"\\t\\tBoarding Time: %d:%d\\n\", time1, time2); printf(\"\\t\\tTotal Bill Amount: %d\\n\", y); printf(\"\\t\\tAllocated Seats Are: \\n\"); for (i = 0; i < j; i++) { printf(\"\\t\\t%d \", a[i]); } printf(\"\\n\"); printf(\"\\t\\t\\t\\tThank You......\\n\");}",
"e": 36363,
"s": 28273,
"text": null
},
{
"code": null,
"e": 36371,
"s": 36363,
"text": "Output:"
},
{
"code": null,
"e": 36384,
"s": 36371,
"text": "simmytarika5"
},
{
"code": null,
"e": 36398,
"s": 36384,
"text": "Project-Ideas"
},
{
"code": null,
"e": 36409,
"s": 36398,
"text": "C Language"
},
{
"code": null,
"e": 36420,
"s": 36409,
"text": "C Programs"
},
{
"code": null,
"e": 36428,
"s": 36420,
"text": "Project"
},
{
"code": null,
"e": 36526,
"s": 36428,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36564,
"s": 36526,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 36590,
"s": 36564,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 36610,
"s": 36590,
"text": "Multithreading in C"
},
{
"code": null,
"e": 36632,
"s": 36610,
"text": "'this' pointer in C++"
},
{
"code": null,
"e": 36673,
"s": 36632,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 36686,
"s": 36673,
"text": "Strings in C"
},
{
"code": null,
"e": 36727,
"s": 36686,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 36768,
"s": 36727,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 36803,
"s": 36768,
"text": "Header files in C/C++ and its uses"
}
]
|
Given a n-ary tree, count number of nodes which have more number of children than parents - GeeksforGeeks | 21 May, 2021
Given a N-ary tree represented as adjacency list, we need to write a program to count all such nodes in this tree which has more number of children than its parent.For Example,
In the above tree, the count will be 1 as there is only one such node which is ‘2’ which has more number of children than its parent. 2 has three children (4, 5 and 6) whereas its parent, 1 has only two children (2 and 3).
We can solve this problem using both BFS and DFS algorithms. We will explain here in details about how to solve this problem using BFS algorithm. As the tree is represented using adjacency list representation. So, for any node say ‘u’ the number of children of this node can be given as adj[u].size(). Now the idea is to apply BFS on the given tree and while traversing the children of a node ‘u’ say ‘v’ we will simply check is adj[v].size() > adj[u].size(). Below is the implementation of above idea:
CPP
Java
Python3
C#
Javascript
// C++ program to count number of nodes// which has more children than its parent #include<bits/stdc++.h>using namespace std; // function to count number of nodes// which has more children than its parentint countNodes(vector<int> adj[], int root){ int count = 0; // queue for applying BFS queue<int> q; // BFS algorithm q.push(root); while (!q.empty()) { int node = q.front(); q.pop(); // traverse children of node for( int i=0;i<adj[node].size();i++) { // children of node int children = adj[node][i]; // if number of childs of children // is greater than number of childs // of node, then increment count if (adj[children].size() > adj[node].size()) count++; q.push(children); } } return count;} // Driver program to test above functionsint main(){ // adjacency list for n-ary tree vector<int> adj[10]; // construct n ary tree as shown // in above diagram adj[1].push_back(2); adj[1].push_back(3); adj[2].push_back(4); adj[2].push_back(5); adj[2].push_back(6); adj[3].push_back(9); adj[5].push_back(7); adj[5].push_back(8); int root = 1; cout << countNodes(adj, root); return 0;}
// Java program to count number of nodes// which has more children than its parentimport java.util.*; class GFG{ // function to count number of nodes// which has more children than its parentstatic int countNodes(Vector<Integer> adj[], int root){ int count = 0; // queue for applying BFS Queue<Integer> q = new LinkedList<>(); // BFS algorithm q.add(root); while (!q.isEmpty()) { int node = q.peek(); q.remove(); // traverse children of node for( int i=0;i<adj[node].size();i++) { // children of node int children = adj[node].get(i); // if number of childs of children // is greater than number of childs // of node, then increment count if (adj[children].size() > adj[node].size()) count++; q.add(children); } } return count;} // Driver codepublic static void main(String[] args){ // adjacency list for n-array tree Vector<Integer> []adj = new Vector[10]; for(int i= 0; i < 10 ; i++) { adj[i] = new Vector<>(); } // conn array tree as shown // in above diagram adj[1].add(2); adj[1].add(3); adj[2].add(4); adj[2].add(5); adj[2].add(6); adj[3].add(9); adj[5].add(7); adj[5].add(8); int root = 1; System.out.print(countNodes(adj, root));}} // This code is contributed by Rajput-Ji
# Python3 program to count number of nodes# which has more children than its parentfrom collections import deque adj = [[] for i in range(100)] # function to count number of nodes# which has more children than its parentdef countNodes(root): count = 0 # queue for applying BFS q = deque() # BFS algorithm q.append(root) while len(q) > 0: node = q.popleft() # traverse children of node for i in adj[node]: # children of node children = i # if number of childs of children # is greater than number of childs # of node, then increment count if (len(adj[children]) > len(adj[node])): count += 1 q.append(children) return count # Driver program to test above functions # construct n ary tree as shown# in above diagramadj[1].append(2)adj[1].append(3)adj[2].append(4)adj[2].append(5)adj[2].append(6)adj[3].append(9)adj[5].append(7)adj[5].append(8) root = 1 print(countNodes(root)) # This code is contributed by mohit kumar 29
// C# program to count number of nodes// which has more children than its parentusing System;using System.Collections.Generic; class GFG{ // function to count number of nodes// which has more children than its parentstatic int countNodes(List<int> []adj, int root){ int count = 0; // queue for applying BFS List<int> q = new List<int>(); // BFS algorithm q.Add(root); while (q.Count != 0) { int node = q[0]; q.RemoveAt(0); // traverse children of node for( int i = 0; i < adj[node].Count; i++) { // children of node int children = adj[node][i]; // if number of childs of children // is greater than number of childs // of node, then increment count if (adj[children].Count > adj[node].Count) count++; q.Add(children); } } return count;} // Driver codepublic static void Main(String[] args){ // adjacency list for n-array tree List<int> []adj = new List<int>[10]; for(int i= 0; i < 10 ; i++) { adj[i] = new List<int>(); } // conn array tree as shown // in above diagram adj[1].Add(2); adj[1].Add(3); adj[2].Add(4); adj[2].Add(5); adj[2].Add(6); adj[3].Add(9); adj[5].Add(7); adj[5].Add(8); int root = 1; Console.Write(countNodes(adj, root));}} // This code is contributed by PrinciRaj1992
<script>// Javascript program to count number of nodes// which has more children than its parent // function to count number of nodes// which has more children than its parent function countNodes(adj,root) { let count = 0; // queue for applying BFS let q = []; // BFS algorithm q.push(root); while (q.length!=0) { let node = q[0]; q.shift(); // traverse children of node for( let i=0;i<adj[node].length;i++) { // children of node let children = adj[node][i]; // if number of childs of children // is greater than number of childs // of node, then increment count if (adj[children].length > adj[node].length) count++; q.push(children); } } return count; } // Driver code // adjacency list for n-array tree let adj = []; for(let i= 0; i < 10 ; i++) { adj[i] = []; } // conn array tree as shown // in above diagram adj[1].push(2); adj[1].push(3); adj[2].push(4); adj[2].push(5); adj[2].push(6); adj[3].push(9); adj[5].push(7); adj[5].push(8); let root = 1; document.write(countNodes(adj, root)); // This code is contributed by patel2127</script>
Output:
1
Time Complexity: O( n ) , where n is the number of nodes in the tree.
YouTubeGeeksforGeeks508K subscribersCount number of nodes having more number of children than parents in n-ary tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:42•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=7lB1zyIbCN0" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. 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.
Akanksha_Rai
mohit kumar 29
Rajput-Ji
princiraj1992
patel2127
n-ary-tree
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Binary Tree | Set 3 (Types of Binary Tree)
Binary Tree | Set 2 (Properties)
Decision Tree
A program to check if a binary tree is BST or not
Introduction to Tree Data Structure
Lowest Common Ancestor in a Binary Tree | Set 1
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
Expression Tree
BFS vs DFS for Binary Tree
Deletion in a Binary Tree | [
{
"code": null,
"e": 26483,
"s": 26455,
"text": "\n21 May, 2021"
},
{
"code": null,
"e": 26662,
"s": 26483,
"text": "Given a N-ary tree represented as adjacency list, we need to write a program to count all such nodes in this tree which has more number of children than its parent.For Example, "
},
{
"code": null,
"e": 26885,
"s": 26662,
"text": "In the above tree, the count will be 1 as there is only one such node which is ‘2’ which has more number of children than its parent. 2 has three children (4, 5 and 6) whereas its parent, 1 has only two children (2 and 3)."
},
{
"code": null,
"e": 27392,
"s": 26887,
"text": "We can solve this problem using both BFS and DFS algorithms. We will explain here in details about how to solve this problem using BFS algorithm. As the tree is represented using adjacency list representation. So, for any node say ‘u’ the number of children of this node can be given as adj[u].size(). Now the idea is to apply BFS on the given tree and while traversing the children of a node ‘u’ say ‘v’ we will simply check is adj[v].size() > adj[u].size(). Below is the implementation of above idea: "
},
{
"code": null,
"e": 27396,
"s": 27392,
"text": "CPP"
},
{
"code": null,
"e": 27401,
"s": 27396,
"text": "Java"
},
{
"code": null,
"e": 27409,
"s": 27401,
"text": "Python3"
},
{
"code": null,
"e": 27412,
"s": 27409,
"text": "C#"
},
{
"code": null,
"e": 27423,
"s": 27412,
"text": "Javascript"
},
{
"code": "// C++ program to count number of nodes// which has more children than its parent #include<bits/stdc++.h>using namespace std; // function to count number of nodes// which has more children than its parentint countNodes(vector<int> adj[], int root){ int count = 0; // queue for applying BFS queue<int> q; // BFS algorithm q.push(root); while (!q.empty()) { int node = q.front(); q.pop(); // traverse children of node for( int i=0;i<adj[node].size();i++) { // children of node int children = adj[node][i]; // if number of childs of children // is greater than number of childs // of node, then increment count if (adj[children].size() > adj[node].size()) count++; q.push(children); } } return count;} // Driver program to test above functionsint main(){ // adjacency list for n-ary tree vector<int> adj[10]; // construct n ary tree as shown // in above diagram adj[1].push_back(2); adj[1].push_back(3); adj[2].push_back(4); adj[2].push_back(5); adj[2].push_back(6); adj[3].push_back(9); adj[5].push_back(7); adj[5].push_back(8); int root = 1; cout << countNodes(adj, root); return 0;}",
"e": 28734,
"s": 27423,
"text": null
},
{
"code": "// Java program to count number of nodes// which has more children than its parentimport java.util.*; class GFG{ // function to count number of nodes// which has more children than its parentstatic int countNodes(Vector<Integer> adj[], int root){ int count = 0; // queue for applying BFS Queue<Integer> q = new LinkedList<>(); // BFS algorithm q.add(root); while (!q.isEmpty()) { int node = q.peek(); q.remove(); // traverse children of node for( int i=0;i<adj[node].size();i++) { // children of node int children = adj[node].get(i); // if number of childs of children // is greater than number of childs // of node, then increment count if (adj[children].size() > adj[node].size()) count++; q.add(children); } } return count;} // Driver codepublic static void main(String[] args){ // adjacency list for n-array tree Vector<Integer> []adj = new Vector[10]; for(int i= 0; i < 10 ; i++) { adj[i] = new Vector<>(); } // conn array tree as shown // in above diagram adj[1].add(2); adj[1].add(3); adj[2].add(4); adj[2].add(5); adj[2].add(6); adj[3].add(9); adj[5].add(7); adj[5].add(8); int root = 1; System.out.print(countNodes(adj, root));}} // This code is contributed by Rajput-Ji",
"e": 30146,
"s": 28734,
"text": null
},
{
"code": "# Python3 program to count number of nodes# which has more children than its parentfrom collections import deque adj = [[] for i in range(100)] # function to count number of nodes# which has more children than its parentdef countNodes(root): count = 0 # queue for applying BFS q = deque() # BFS algorithm q.append(root) while len(q) > 0: node = q.popleft() # traverse children of node for i in adj[node]: # children of node children = i # if number of childs of children # is greater than number of childs # of node, then increment count if (len(adj[children]) > len(adj[node])): count += 1 q.append(children) return count # Driver program to test above functions # construct n ary tree as shown# in above diagramadj[1].append(2)adj[1].append(3)adj[2].append(4)adj[2].append(5)adj[2].append(6)adj[3].append(9)adj[5].append(7)adj[5].append(8) root = 1 print(countNodes(root)) # This code is contributed by mohit kumar 29",
"e": 31209,
"s": 30146,
"text": null
},
{
"code": "// C# program to count number of nodes// which has more children than its parentusing System;using System.Collections.Generic; class GFG{ // function to count number of nodes// which has more children than its parentstatic int countNodes(List<int> []adj, int root){ int count = 0; // queue for applying BFS List<int> q = new List<int>(); // BFS algorithm q.Add(root); while (q.Count != 0) { int node = q[0]; q.RemoveAt(0); // traverse children of node for( int i = 0; i < adj[node].Count; i++) { // children of node int children = adj[node][i]; // if number of childs of children // is greater than number of childs // of node, then increment count if (adj[children].Count > adj[node].Count) count++; q.Add(children); } } return count;} // Driver codepublic static void Main(String[] args){ // adjacency list for n-array tree List<int> []adj = new List<int>[10]; for(int i= 0; i < 10 ; i++) { adj[i] = new List<int>(); } // conn array tree as shown // in above diagram adj[1].Add(2); adj[1].Add(3); adj[2].Add(4); adj[2].Add(5); adj[2].Add(6); adj[3].Add(9); adj[5].Add(7); adj[5].Add(8); int root = 1; Console.Write(countNodes(adj, root));}} // This code is contributed by PrinciRaj1992",
"e": 32639,
"s": 31209,
"text": null
},
{
"code": "<script>// Javascript program to count number of nodes// which has more children than its parent // function to count number of nodes// which has more children than its parent function countNodes(adj,root) { let count = 0; // queue for applying BFS let q = []; // BFS algorithm q.push(root); while (q.length!=0) { let node = q[0]; q.shift(); // traverse children of node for( let i=0;i<adj[node].length;i++) { // children of node let children = adj[node][i]; // if number of childs of children // is greater than number of childs // of node, then increment count if (adj[children].length > adj[node].length) count++; q.push(children); } } return count; } // Driver code // adjacency list for n-array tree let adj = []; for(let i= 0; i < 10 ; i++) { adj[i] = []; } // conn array tree as shown // in above diagram adj[1].push(2); adj[1].push(3); adj[2].push(4); adj[2].push(5); adj[2].push(6); adj[3].push(9); adj[5].push(7); adj[5].push(8); let root = 1; document.write(countNodes(adj, root)); // This code is contributed by patel2127</script>",
"e": 33970,
"s": 32639,
"text": null
},
{
"code": null,
"e": 33980,
"s": 33970,
"text": "Output: "
},
{
"code": null,
"e": 33982,
"s": 33980,
"text": "1"
},
{
"code": null,
"e": 34053,
"s": 33982,
"text": "Time Complexity: O( n ) , where n is the number of nodes in the tree. "
},
{
"code": null,
"e": 34931,
"s": 34053,
"text": "YouTubeGeeksforGeeks508K subscribersCount number of nodes having more number of children than parents in n-ary tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:42•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=7lB1zyIbCN0\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 35352,
"s": 34931,
"text": "This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. 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": 35365,
"s": 35352,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 35380,
"s": 35365,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 35390,
"s": 35380,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 35404,
"s": 35390,
"text": "princiraj1992"
},
{
"code": null,
"e": 35414,
"s": 35404,
"text": "patel2127"
},
{
"code": null,
"e": 35425,
"s": 35414,
"text": "n-ary-tree"
},
{
"code": null,
"e": 35430,
"s": 35425,
"text": "Tree"
},
{
"code": null,
"e": 35435,
"s": 35430,
"text": "Tree"
},
{
"code": null,
"e": 35533,
"s": 35435,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35576,
"s": 35533,
"text": "Binary Tree | Set 3 (Types of Binary Tree)"
},
{
"code": null,
"e": 35609,
"s": 35576,
"text": "Binary Tree | Set 2 (Properties)"
},
{
"code": null,
"e": 35623,
"s": 35609,
"text": "Decision Tree"
},
{
"code": null,
"e": 35673,
"s": 35623,
"text": "A program to check if a binary tree is BST or not"
},
{
"code": null,
"e": 35709,
"s": 35673,
"text": "Introduction to Tree Data Structure"
},
{
"code": null,
"e": 35757,
"s": 35709,
"text": "Lowest Common Ancestor in a Binary Tree | Set 1"
},
{
"code": null,
"e": 35840,
"s": 35757,
"text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree"
},
{
"code": null,
"e": 35856,
"s": 35840,
"text": "Expression Tree"
},
{
"code": null,
"e": 35883,
"s": 35856,
"text": "BFS vs DFS for Binary Tree"
}
]
|
jQuery UI Buttonset items Option - GeeksforGeeks | 10 Jan, 2022
jQuery UI consists of GUI widgets, visual effects, and themes implemented using HTML, CSS, and jQuery. jQuery UI is great for building UI interfaces for the webpages. The jQuery UI buttonset widget is used to give a visual grouping for a group of related buttons.
The jQuery UI buttonset items option is used for setting or getting the items for the specified buttonset widget.
Syntax: For initializing the buttonset with the items option.
$( ".selector" ).buttonset({
items: "GFG"
});
Setting the items option.$( ".selector" ).buttonset( "option", "items", "GFG" );
Setting the items option.
$( ".selector" ).buttonset( "option", "items", "GFG" );
Getting the value of items option.var items = $( ".selector" ).buttonset( "option", "items" );
Getting the value of items option.
var items = $( ".selector" ).buttonset( "option", "items" );
CDN Link: First, add jQuery UI scripts needed for your project.
<link rel=”stylesheet” href=”//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css”><script src=”//code.jquery.com/jquery-1.12.4.js”></script><script src=”//code.jquery.com/ui/1.12.1/jquery-ui.js”></script>
Example: This example demonstrates the jQuery UI buttonset items option.
HTML
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css"> <script src="//code.jquery.com/jquery-1.12.4.js"> </script> <script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"> </script></head> <body> <center> <h1 style="color:green;"> GeeksforGeeks </h1> <h3>jQuery UI Buttonset items Option</h3> <form> <fieldset> <legend>Button_Set</legend> <div id="ButtonSet_Radio"> <input id="Company" type="radio" checked="checked"> <label for="Company">GeeksforGeeks</label> <input id="Department" type="radio"> <label for="Department">Computer Science</label> </div> </fieldset> </form> <input type="button" id="Button_for_items" style="padding:5px 15px; margin-top:40px;" value="Value of the items option"> <div id="log"></div> </center> <script> $(document).ready(function () { $("#ButtonSet_Radio").buttonset({ items: "GFG" }); $("#ButtonSet_Radio").buttonset("option", "items", "GFG"); $("#Button_for_items").on('click', function () { var a = $("#ButtonSet_Radio") .buttonset("option", "items"); $("#log").html(a); }); }); </script></body> </html>
Output:
Reference: https://api.jqueryui.com/buttonset/#option-items
jQuery-UI
jQuery-UI-Buttonset
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Show and Hide div elements using radio buttons?
How to prevent Body from scrolling when a modal is opened using jQuery ?
jQuery | ajax() Method
jQuery | removeAttr() with Examples
How to get the value in an input text box using jQuery ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 27144,
"s": 27116,
"text": "\n10 Jan, 2022"
},
{
"code": null,
"e": 27408,
"s": 27144,
"text": "jQuery UI consists of GUI widgets, visual effects, and themes implemented using HTML, CSS, and jQuery. jQuery UI is great for building UI interfaces for the webpages. The jQuery UI buttonset widget is used to give a visual grouping for a group of related buttons."
},
{
"code": null,
"e": 27522,
"s": 27408,
"text": "The jQuery UI buttonset items option is used for setting or getting the items for the specified buttonset widget."
},
{
"code": null,
"e": 27584,
"s": 27522,
"text": "Syntax: For initializing the buttonset with the items option."
},
{
"code": null,
"e": 27631,
"s": 27584,
"text": "$( \".selector\" ).buttonset({\n items: \"GFG\"\n});"
},
{
"code": null,
"e": 27713,
"s": 27631,
"text": "Setting the items option.$( \".selector\" ).buttonset( \"option\", \"items\", \"GFG\" ); "
},
{
"code": null,
"e": 27739,
"s": 27713,
"text": "Setting the items option."
},
{
"code": null,
"e": 27795,
"s": 27739,
"text": "$( \".selector\" ).buttonset( \"option\", \"items\", \"GFG\" );"
},
{
"code": null,
"e": 27892,
"s": 27797,
"text": "Getting the value of items option.var items = $( \".selector\" ).buttonset( \"option\", \"items\" );"
},
{
"code": null,
"e": 27927,
"s": 27892,
"text": "Getting the value of items option."
},
{
"code": null,
"e": 27988,
"s": 27927,
"text": "var items = $( \".selector\" ).buttonset( \"option\", \"items\" );"
},
{
"code": null,
"e": 28052,
"s": 27988,
"text": "CDN Link: First, add jQuery UI scripts needed for your project."
},
{
"code": null,
"e": 28265,
"s": 28052,
"text": "<link rel=”stylesheet” href=”//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css”><script src=”//code.jquery.com/jquery-1.12.4.js”></script><script src=”//code.jquery.com/ui/1.12.1/jquery-ui.js”></script>"
},
{
"code": null,
"e": 28338,
"s": 28265,
"text": "Example: This example demonstrates the jQuery UI buttonset items option."
},
{
"code": null,
"e": 28343,
"s": 28338,
"text": "HTML"
},
{
"code": "<!doctype html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <link rel=\"stylesheet\" href=\"//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css\"> <script src=\"//code.jquery.com/jquery-1.12.4.js\"> </script> <script src=\"//code.jquery.com/ui/1.12.1/jquery-ui.js\"> </script></head> <body> <center> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h3>jQuery UI Buttonset items Option</h3> <form> <fieldset> <legend>Button_Set</legend> <div id=\"ButtonSet_Radio\"> <input id=\"Company\" type=\"radio\" checked=\"checked\"> <label for=\"Company\">GeeksforGeeks</label> <input id=\"Department\" type=\"radio\"> <label for=\"Department\">Computer Science</label> </div> </fieldset> </form> <input type=\"button\" id=\"Button_for_items\" style=\"padding:5px 15px; margin-top:40px;\" value=\"Value of the items option\"> <div id=\"log\"></div> </center> <script> $(document).ready(function () { $(\"#ButtonSet_Radio\").buttonset({ items: \"GFG\" }); $(\"#ButtonSet_Radio\").buttonset(\"option\", \"items\", \"GFG\"); $(\"#Button_for_items\").on('click', function () { var a = $(\"#ButtonSet_Radio\") .buttonset(\"option\", \"items\"); $(\"#log\").html(a); }); }); </script></body> </html>",
"e": 29904,
"s": 28343,
"text": null
},
{
"code": null,
"e": 29912,
"s": 29904,
"text": "Output:"
},
{
"code": null,
"e": 29972,
"s": 29912,
"text": "Reference: https://api.jqueryui.com/buttonset/#option-items"
},
{
"code": null,
"e": 29982,
"s": 29972,
"text": "jQuery-UI"
},
{
"code": null,
"e": 30002,
"s": 29982,
"text": "jQuery-UI-Buttonset"
},
{
"code": null,
"e": 30009,
"s": 30002,
"text": "JQuery"
},
{
"code": null,
"e": 30026,
"s": 30009,
"text": "Web Technologies"
},
{
"code": null,
"e": 30124,
"s": 30026,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30179,
"s": 30124,
"text": "How to Show and Hide div elements using radio buttons?"
},
{
"code": null,
"e": 30252,
"s": 30179,
"text": "How to prevent Body from scrolling when a modal is opened using jQuery ?"
},
{
"code": null,
"e": 30275,
"s": 30252,
"text": "jQuery | ajax() Method"
},
{
"code": null,
"e": 30311,
"s": 30275,
"text": "jQuery | removeAttr() with Examples"
},
{
"code": null,
"e": 30368,
"s": 30311,
"text": "How to get the value in an input text box using jQuery ?"
},
{
"code": null,
"e": 30408,
"s": 30368,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30441,
"s": 30408,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 30486,
"s": 30441,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 30529,
"s": 30486,
"text": "How to fetch data from an API in ReactJS ?"
}
]
|
What is the difference between position:sticky and position:fixed in CSS ? - GeeksforGeeks | 31 Oct, 2021
In this article, we will discuss two very similar CSS Properties which are position: sticky and position: fixed.
The Position property in CSS specifies the positioning for an HTML element or entity. The element’s position can be set by specifying the top, right, bottom, and left properties. These specify the distance of an HTML element from the edge of the viewport. To set the position by these four properties, we have to declare the positioning method. There are five positioning properties available in CSS:
Fixed: The position of the element will be positioned relative to the viewport.
Static: The elements will be positioned according to the normal flow of the page.
Relative: The element remains in the normal flow of the document but left, right, top, and bottom affects.
Absolute: The position of the element will be relative to the closest positioned ancestor.
Sticky: The element with position: sticky and top: 0 played a role between fixed & relative based on the position where it is placed.
We will discuss only the position: fixed and sticky properties. Both of these are used to fix the element to a certain position in the HTML page. Please refer to the CSS Positioning Elements article for more details.
The position: fixed means fixed to the viewport. We provide the position values (top, bottom, right, or left) and the element stays there when the user is scrolling. No matter what is happening on screen the fixed element will not move at all.
Syntax:
selector {
position: fixed;
}
Example: When we use the position: fixed property, the element stays fixed to its position irrespective of what is happening on screen it is fixed at the viewport.
HTML
<html><head> <style> body { margin: 0; padding: 20px; font-family: sans-serif; background: #efefef; } .fixed { position: fixed; background: #088523; color: #ffffff; padding: 30px; top: 250; left: 10; } span { padding: 5px; border: 1px #ffffff dotted; } </style></head> <body> <div class="fixed">This div has <span>position: fixed;</span> </div> <h1> What We Offer We provide a variety of services for you to learn, thrive and also have fun! Free Tutorials, Millions of Articles, Live, Online and Classroom Courses, Frequent Coding Competitions, Webinars by Industry Experts, Internship opportunities and Job Opportunities. <br/> <br/> What We Offer We provide a variety of services for you to learn, thrive and also have fun! Free Tutorials, Millions of Articles, Live, Online and Classroom Courses, Frequent Coding Competitions, Webinars by Industry Experts, Internship opportunities and Job Opportunities. <br/> <br/> What We Offer We provide a variety of services for you to learn, thrive and also have fun! Free Tutorials, Millions of Articles, Live, Online and Classroom Courses, Frequent Coding Competitions, Webinars by Industry Experts, Internship opportunities and Job Opportunities. <br/> <br/> What We Offer We provide a variety of services for you to learn, thrive and also have fun! Free Tutorials, Millions of Articles, Live, Online and Classroom Courses, Frequent Coding Competitions, Webinars by Industry Experts, Internship opportunities and Job Opportunities. </h1> </body></html>
Output:
The position: sticky means the element will scroll until it reaches the offset value given to it by the user and then stays in its position. Sticky element always stays within its parent block and as soon as the parent block leaves the screen as an effect of scrolling, sticky elements also leave with it.
Syntax:
selector {
position: sticky;
}
Example: When we use the position: sticky property, the element scrolls till it touches the top, will be fixed at that place in spite of further scrolling.
HTML
<html><head> <style> body { margin: 0; padding: 20px; font-family: sans-serif; background: #efefef; } .sticky { position: sticky; background: #088523; color: #ffffff; padding: 30px; top: 0; left: 10; } span { padding: 5px; border: 1px #ffffff dotted; } </style></head> <body> <h1> What We Offer We provide a variety of services for you to learn, thrive and also have fun! Free Tutorials, Millions of Articles, Live, Online and Classroom Courses, Frequent Coding Competitions, Webinars by Industry Experts, Internship opportunities and Job Opportunities. <br/> <div class="sticky">This div has <span>position: sticky;</span> </div> <br/> What We Offer We provide a variety of services for you to learn, thrive and also have fun! Free Tutorials, Millions of Articles, Live, Online and Classroom Courses, Frequent Coding Competitions, Webinars by Industry Experts, Internship opportunities and Job Opportunities. <br/> <br/> What We Offer We provide a variety of services for you to learn, thrive and also have fun! Free Tutorials, Millions of Articles, Live, Online and Classroom Courses, Frequent Coding Competitions, Webinars by Industry Experts, Internship opportunities and Job Opportunities. <br/> <br/> What We Offer We provide a variety of services for you to learn, thrive and also have fun! Free Tutorials, Millions of Articles, Live, Online and Classroom Courses, Frequent Coding Competitions, Webinars by Industry Experts, Internship opportunities and Job Opportunities. <br/> <br/> What We Offer We provide a variety of services for you to learn, thrive and also have fun! Free Tutorials, Millions of Articles, Live, Online and Classroom Courses, Frequent Coding Competitions, Webinars by Industry Experts, Internship opportunities and Job Opportunities. </h1></body></html>
Output:
Difference between position: fixed and position: sticky property:
Element with position: fixed property is fixed to the viewport and doesn’t move irrespective of scrolling.
Element with position: sticky property can scroll to an offset value provided by the user.
Element with position: fixed property never leaves the viewport position it was fixed to.
Element with position: sticky property leaves the viewport when its parent element scrolls off the viewport.
This property is supported by all the browsers.
This property is only supported by all modern browsers.
Supported browsers:
position: fixed is supported by:
Google Chrome 1.0
Internet Explorer 7.0
Microsoft Edge 12.0
Firefox 1.0
Opera 4.0
Safari 1.0
position: sticky is supported by:
Google Chrome 56.0
Microsoft Edge 16.0
Firefox 32.0
Opera 43,0
Safari 13.0
CSS-Properties
CSS-Questions
Picked
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set space between the flexbox ?
Design a web page using HTML and CSS
Form validation using jQuery
How to style a checkbox using CSS?
Search Bar using HTML, CSS and JavaScript
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 26621,
"s": 26593,
"text": "\n31 Oct, 2021"
},
{
"code": null,
"e": 26734,
"s": 26621,
"text": "In this article, we will discuss two very similar CSS Properties which are position: sticky and position: fixed."
},
{
"code": null,
"e": 27135,
"s": 26734,
"text": "The Position property in CSS specifies the positioning for an HTML element or entity. The element’s position can be set by specifying the top, right, bottom, and left properties. These specify the distance of an HTML element from the edge of the viewport. To set the position by these four properties, we have to declare the positioning method. There are five positioning properties available in CSS:"
},
{
"code": null,
"e": 27215,
"s": 27135,
"text": "Fixed: The position of the element will be positioned relative to the viewport."
},
{
"code": null,
"e": 27297,
"s": 27215,
"text": "Static: The elements will be positioned according to the normal flow of the page."
},
{
"code": null,
"e": 27404,
"s": 27297,
"text": "Relative: The element remains in the normal flow of the document but left, right, top, and bottom affects."
},
{
"code": null,
"e": 27495,
"s": 27404,
"text": "Absolute: The position of the element will be relative to the closest positioned ancestor."
},
{
"code": null,
"e": 27629,
"s": 27495,
"text": "Sticky: The element with position: sticky and top: 0 played a role between fixed & relative based on the position where it is placed."
},
{
"code": null,
"e": 27846,
"s": 27629,
"text": "We will discuss only the position: fixed and sticky properties. Both of these are used to fix the element to a certain position in the HTML page. Please refer to the CSS Positioning Elements article for more details."
},
{
"code": null,
"e": 28090,
"s": 27846,
"text": "The position: fixed means fixed to the viewport. We provide the position values (top, bottom, right, or left) and the element stays there when the user is scrolling. No matter what is happening on screen the fixed element will not move at all."
},
{
"code": null,
"e": 28100,
"s": 28092,
"text": "Syntax:"
},
{
"code": null,
"e": 28135,
"s": 28100,
"text": "selector {\n position: fixed;\n}"
},
{
"code": null,
"e": 28299,
"s": 28135,
"text": "Example: When we use the position: fixed property, the element stays fixed to its position irrespective of what is happening on screen it is fixed at the viewport."
},
{
"code": null,
"e": 28304,
"s": 28299,
"text": "HTML"
},
{
"code": "<html><head> <style> body { margin: 0; padding: 20px; font-family: sans-serif; background: #efefef; } .fixed { position: fixed; background: #088523; color: #ffffff; padding: 30px; top: 250; left: 10; } span { padding: 5px; border: 1px #ffffff dotted; } </style></head> <body> <div class=\"fixed\">This div has <span>position: fixed;</span> </div> <h1> What We Offer We provide a variety of services for you to learn, thrive and also have fun! Free Tutorials, Millions of Articles, Live, Online and Classroom Courses, Frequent Coding Competitions, Webinars by Industry Experts, Internship opportunities and Job Opportunities. <br/> <br/> What We Offer We provide a variety of services for you to learn, thrive and also have fun! Free Tutorials, Millions of Articles, Live, Online and Classroom Courses, Frequent Coding Competitions, Webinars by Industry Experts, Internship opportunities and Job Opportunities. <br/> <br/> What We Offer We provide a variety of services for you to learn, thrive and also have fun! Free Tutorials, Millions of Articles, Live, Online and Classroom Courses, Frequent Coding Competitions, Webinars by Industry Experts, Internship opportunities and Job Opportunities. <br/> <br/> What We Offer We provide a variety of services for you to learn, thrive and also have fun! Free Tutorials, Millions of Articles, Live, Online and Classroom Courses, Frequent Coding Competitions, Webinars by Industry Experts, Internship opportunities and Job Opportunities. </h1> </body></html>",
"e": 30186,
"s": 28304,
"text": null
},
{
"code": null,
"e": 30194,
"s": 30186,
"text": "Output:"
},
{
"code": null,
"e": 30500,
"s": 30194,
"text": "The position: sticky means the element will scroll until it reaches the offset value given to it by the user and then stays in its position. Sticky element always stays within its parent block and as soon as the parent block leaves the screen as an effect of scrolling, sticky elements also leave with it."
},
{
"code": null,
"e": 30508,
"s": 30500,
"text": "Syntax:"
},
{
"code": null,
"e": 30544,
"s": 30508,
"text": "selector {\n position: sticky;\n}"
},
{
"code": null,
"e": 30700,
"s": 30544,
"text": "Example: When we use the position: sticky property, the element scrolls till it touches the top, will be fixed at that place in spite of further scrolling."
},
{
"code": null,
"e": 30705,
"s": 30700,
"text": "HTML"
},
{
"code": "<html><head> <style> body { margin: 0; padding: 20px; font-family: sans-serif; background: #efefef; } .sticky { position: sticky; background: #088523; color: #ffffff; padding: 30px; top: 0; left: 10; } span { padding: 5px; border: 1px #ffffff dotted; } </style></head> <body> <h1> What We Offer We provide a variety of services for you to learn, thrive and also have fun! Free Tutorials, Millions of Articles, Live, Online and Classroom Courses, Frequent Coding Competitions, Webinars by Industry Experts, Internship opportunities and Job Opportunities. <br/> <div class=\"sticky\">This div has <span>position: sticky;</span> </div> <br/> What We Offer We provide a variety of services for you to learn, thrive and also have fun! Free Tutorials, Millions of Articles, Live, Online and Classroom Courses, Frequent Coding Competitions, Webinars by Industry Experts, Internship opportunities and Job Opportunities. <br/> <br/> What We Offer We provide a variety of services for you to learn, thrive and also have fun! Free Tutorials, Millions of Articles, Live, Online and Classroom Courses, Frequent Coding Competitions, Webinars by Industry Experts, Internship opportunities and Job Opportunities. <br/> <br/> What We Offer We provide a variety of services for you to learn, thrive and also have fun! Free Tutorials, Millions of Articles, Live, Online and Classroom Courses, Frequent Coding Competitions, Webinars by Industry Experts, Internship opportunities and Job Opportunities. <br/> <br/> What We Offer We provide a variety of services for you to learn, thrive and also have fun! Free Tutorials, Millions of Articles, Live, Online and Classroom Courses, Frequent Coding Competitions, Webinars by Industry Experts, Internship opportunities and Job Opportunities. </h1></body></html>",
"e": 32933,
"s": 30705,
"text": null
},
{
"code": null,
"e": 32941,
"s": 32933,
"text": "Output:"
},
{
"code": null,
"e": 33007,
"s": 32941,
"text": "Difference between position: fixed and position: sticky property:"
},
{
"code": null,
"e": 33114,
"s": 33007,
"text": "Element with position: fixed property is fixed to the viewport and doesn’t move irrespective of scrolling."
},
{
"code": null,
"e": 33206,
"s": 33114,
"text": "Element with position: sticky property can scroll to an offset value provided by the user. "
},
{
"code": null,
"e": 33296,
"s": 33206,
"text": "Element with position: fixed property never leaves the viewport position it was fixed to."
},
{
"code": null,
"e": 33405,
"s": 33296,
"text": "Element with position: sticky property leaves the viewport when its parent element scrolls off the viewport."
},
{
"code": null,
"e": 33453,
"s": 33405,
"text": "This property is supported by all the browsers."
},
{
"code": null,
"e": 33509,
"s": 33453,
"text": "This property is only supported by all modern browsers."
},
{
"code": null,
"e": 33529,
"s": 33509,
"text": "Supported browsers:"
},
{
"code": null,
"e": 33562,
"s": 33529,
"text": "position: fixed is supported by:"
},
{
"code": null,
"e": 33580,
"s": 33562,
"text": "Google Chrome 1.0"
},
{
"code": null,
"e": 33602,
"s": 33580,
"text": "Internet Explorer 7.0"
},
{
"code": null,
"e": 33622,
"s": 33602,
"text": "Microsoft Edge 12.0"
},
{
"code": null,
"e": 33634,
"s": 33622,
"text": "Firefox 1.0"
},
{
"code": null,
"e": 33644,
"s": 33634,
"text": "Opera 4.0"
},
{
"code": null,
"e": 33655,
"s": 33644,
"text": "Safari 1.0"
},
{
"code": null,
"e": 33689,
"s": 33655,
"text": "position: sticky is supported by:"
},
{
"code": null,
"e": 33708,
"s": 33689,
"text": "Google Chrome 56.0"
},
{
"code": null,
"e": 33728,
"s": 33708,
"text": "Microsoft Edge 16.0"
},
{
"code": null,
"e": 33741,
"s": 33728,
"text": "Firefox 32.0"
},
{
"code": null,
"e": 33752,
"s": 33741,
"text": "Opera 43,0"
},
{
"code": null,
"e": 33764,
"s": 33752,
"text": "Safari 13.0"
},
{
"code": null,
"e": 33779,
"s": 33764,
"text": "CSS-Properties"
},
{
"code": null,
"e": 33793,
"s": 33779,
"text": "CSS-Questions"
},
{
"code": null,
"e": 33800,
"s": 33793,
"text": "Picked"
},
{
"code": null,
"e": 33804,
"s": 33800,
"text": "CSS"
},
{
"code": null,
"e": 33821,
"s": 33804,
"text": "Web Technologies"
},
{
"code": null,
"e": 33919,
"s": 33821,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33958,
"s": 33919,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 33995,
"s": 33958,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 34024,
"s": 33995,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 34059,
"s": 34024,
"text": "How to style a checkbox using CSS?"
},
{
"code": null,
"e": 34101,
"s": 34059,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 34141,
"s": 34101,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 34174,
"s": 34141,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 34219,
"s": 34174,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 34262,
"s": 34219,
"text": "How to fetch data from an API in ReactJS ?"
}
]
|
Java Program To Check If A Singly Linked List Is Palindrome - GeeksforGeeks | 29 Mar, 2022
Given a singly linked list of characters, write a function that returns true if the given list is a palindrome, else false.
METHOD 1 (Use a Stack):
A simple solution is to use a stack of list nodes. This mainly involves three steps.
Traverse the given list from head to tail and push every visited node to stack.
Traverse the list again. For every visited node, pop a node from the stack and compare data of popped node with the currently visited node.
If all nodes matched, then return true, else false.
Below image is a dry run of the above approach:
Below is the implementation of the above approach :
Java
// Java program to check if linked list// is palindrome recursivelyimport java.util.*; class linkedList{ public static void main(String args[]) { Node one = new Node(1); Node two = new Node(2); Node three = new Node(3); Node four = new Node(4); Node five = new Node(3); Node six = new Node(2); Node seven = new Node(1); one.ptr = two; two.ptr = three; three.ptr = four; four.ptr = five; five.ptr = six; six.ptr = seven; boolean condition = isPalindrome(one); System.out.println("isPalidrome :" + condition); } static boolean isPalindrome(Node head) { Node slow = head; boolean ispalin = true; Stack<Integer> stack = new Stack<Integer>(); while (slow != null) { stack.push(slow.data); slow = slow.ptr; } while (head != null) { int i = stack.pop(); if (head.data == i) { ispalin = true; } else { ispalin = false; break; } head = head.ptr; } return ispalin; }} class Node{ int data; Node ptr; Node(int d) { ptr = null; data = d; }}
Output:
isPalindrome: true
Time complexity: O(n).
METHOD 2 (By reversing the list): This method takes O(n) time and O(1) extra space. 1) Get the middle of the linked list. 2) Reverse the second half of the linked list. 3) Check if the first half and second half are identical. 4) Construct the original linked list by reversing the second half again and attaching it back to the first half
To divide the list into two halves, method 2 of this post is used.
When a number of nodes are even, the first and second half contain exactly half nodes. The challenging thing in this method is to handle the case when the number of nodes is odd. We don’t want the middle node as part of the lists as we are going to compare them for equality. For odd cases, we use a separate variable ‘midnode’.
Java
// Java program to check if linked list// is palindrome class LinkedList{ // Head of list Node head; Node slow_ptr, fast_ptr, second_half; // Linked list Node class Node { char data; Node next; Node(char d) { data = d; next = null; } } /* Function to check if given linked list is palindrome or not */ boolean isPalindrome(Node head) { slow_ptr = head; fast_ptr = head; Node prev_of_slow_ptr = head; // To handle odd size list Node midnode = null; // Initialize result boolean res = true; if (head != null && head.next != null) { /* Get the middle of the list. Move slow_ptr by 1 and fast_ptrr by 2, slow_ptr will have the middle node */ while (fast_ptr != null && fast_ptr.next != null) { fast_ptr = fast_ptr.next.next; /*We need previous of the slow_ptr for linked lists with odd elements */ prev_of_slow_ptr = slow_ptr; slow_ptr = slow_ptr.next; } /* fast_ptr would become NULL when there are even elements in the list and not NULL for odd elements. We need to skip the middle node for odd case and store it somewhere so that we can restore the original list */ if (fast_ptr != null) { midnode = slow_ptr; slow_ptr = slow_ptr.next; } // Now reverse the second half and // compare it with first half second_half = slow_ptr; // NULL terminate first half prev_of_slow_ptr.next = null; // Reverse the second half reverse(); // compare res = compareLists(head, second_half); // Construct the original list back // Reverse the second half again reverse(); if (midnode != null) { // If there was a mid node (odd size case) // which was not part of either first half // or second half. prev_of_slow_ptr.next = midnode; midnode.next = second_half; } else prev_of_slow_ptr.next = second_half; } return res; } /* Function to reverse the linked list Note that this function may change the head */ void reverse() { Node prev = null; Node current = second_half; Node next; while (current != null) { next = current.next; current.next = prev; prev = current; current = next; } second_half = prev; } // Function to check if two input // lists have same data boolean compareLists(Node head1, Node head2) { Node temp1 = head1; Node temp2 = head2; while (temp1 != null && temp2 != null) { if (temp1.data == temp2.data) { temp1 = temp1.next; temp2 = temp2.next; } else return false; } // Both are empty return 1 if (temp1 == null && temp2 == null) return true; /* Will reach here when one is NULL and other is not */ return false; } /* Push a node to linked list. Note that this function changes the head */ public void push(char new_data) { /* Allocate the Node & Put in the data */ Node new_node = new Node(new_data); // Link the old list off the new one new_node.next = head; // Move the head to point to new Node head = new_node; } // A utility function to print a // given linked list void printList(Node ptr) { while (ptr != null) { System.out.print(ptr.data + "->"); ptr = ptr.next; } System.out.println("NULL"); } // Driver code public static void main(String[] args) { // Start with the empty list LinkedList llist = new LinkedList(); char str[] = {'a', 'b', 'a', 'c', 'a', 'b', 'a'}; String string = new String(str); for (int i = 0; i < 7; i++) { llist.push(str[i]); llist.printList(llist.head); if (llist.isPalindrome(llist.head) != false) { System.out.println("Is Palindrome"); System.out.println(""); } else { System.out.println("Not Palindrome"); System.out.println(""); } } }}
Output:
a->NULL
Is Palindrome
b->a->NULL
Not Palindrome
a->b->a->NULL
Is Palindrome
c->a->b->a->NULL
Not Palindrome
a->c->a->b->a->NULL
Not Palindrome
b->a->c->a->b->a->NULL
Not Palindrome
a->b->a->c->a->b->a->NULL
Is Palindrome
Time Complexity: O(n) Auxiliary Space: O(1)
METHOD 3 (Using Recursion): Use two pointers left and right. Move right and left using recursion and check for following in each recursive call. 1) Sub-list is a palindrome. 2) Value at current left and right are matching.
If both above conditions are true then return true.
The idea is to use function call stack as a container. Recursively traverse till the end of the list. When we return from the last NULL, we will be at the last node. The last node is to be compared with the first node of the list.
In order to access the first node of the list, we need the list head to be available in the last call of recursion. Hence, we pass head also to the recursive function. If they both match we need to compare (2, n-2) nodes. Again when recursion falls back to (n-2)nd node, we need a reference to 2nd node from the head. We advance the head pointer in the previous call, to refer to the next node in the list.However, the trick is identifying a double-pointer. Passing a single pointer is as good as pass-by-value, and we will pass the same pointer again and again. We need to pass the address of the head pointer for reflecting the changes in parent recursive calls.Thanks to Sharad Chandra for suggesting this approach.
Java
// Java program to implement// the above approachpublic class LinkedList{ // Head of the list Node head; Node left; public class Node { public char data; public Node next; // Linked list node public Node(char d) { data = d; next = null; } } // Initial parameters to this // function are &head and head boolean isPalindromeUtil(Node right) { left = head; // Stop recursion when right // becomes null if (right == null) return true; // If sub-list is not palindrome then // no need to check for the current // left and right, return false boolean isp = isPalindromeUtil(right.next); if (isp == false) return false; // Check values at current left and right boolean isp1 = (right.data == left.data); left = left.next; // Move left to next node; return isp1; } // A wrapper over isPalindrome(Node head) boolean isPalindrome(Node head) { boolean result = isPalindromeUtil(head); return result; } // Push a node to linked list. // Note that this function changes // the head public void push(char new_data) { // Allocate the node and put in // the data Node new_node = new Node(new_data); // Link the old list off the the // new one new_node.next = head; // Move the head to point to // new node head = new_node; } // A utility function to print a // given linked list void printList(Node ptr) { while (ptr != null) { System.out.print(ptr.data + "->"); ptr = ptr.next; } System.out.println("Null"); } // Driver Code public static void main(String[] args) { LinkedList llist = new LinkedList(); char[] str = {'a', 'b', 'a', 'c', 'a', 'b', 'a'}; for(int i = 0; i < 7; i++) { llist.push(str[i]); llist.printList(llist.head); if (llist.isPalindrome(llist.head)) { System.out.println("Is Palindrome"); System.out.println(""); } else { System.out.println("Not Palindrome"); System.out.println(""); } } }}// This code is contributed by abhinavjain194
Output:
a->NULL
Not Palindrome
b->a->NULL
Not Palindrome
a->b->a->NULL
Is Palindrome
c->a->b->a->NULL
Not Palindrome
a->c->a->b->a->NULL
Not Palindrome
b->a->c->a->b->a->NULL
Not Palindrome
a->b->a->c->a->b->a->NULL
Is Palindrome
Time Complexity: O(n) Auxiliary Space: O(n) if Function Call Stack size is considered, otherwise O(1).
Please refer complete article on Function to check if a singly linked list is palindrome for more details!
sweetyty
varshagumber28
Accolite
Adobe
Amazon
KLA Tencor
Kritikal Solutions
Linked Lists
Microsoft
palindrome
Snapdeal
Yodlee Infotech
Java
Java Programs
Linked List
Accolite
Amazon
Microsoft
Snapdeal
Adobe
Yodlee Infotech
KLA Tencor
Kritikal Solutions
Linked List
Java
palindrome
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Generics in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Iterate through List in Java | [
{
"code": null,
"e": 25303,
"s": 25275,
"text": "\n29 Mar, 2022"
},
{
"code": null,
"e": 25427,
"s": 25303,
"text": "Given a singly linked list of characters, write a function that returns true if the given list is a palindrome, else false."
},
{
"code": null,
"e": 25452,
"s": 25427,
"text": "METHOD 1 (Use a Stack): "
},
{
"code": null,
"e": 25537,
"s": 25452,
"text": "A simple solution is to use a stack of list nodes. This mainly involves three steps."
},
{
"code": null,
"e": 25617,
"s": 25537,
"text": "Traverse the given list from head to tail and push every visited node to stack."
},
{
"code": null,
"e": 25757,
"s": 25617,
"text": "Traverse the list again. For every visited node, pop a node from the stack and compare data of popped node with the currently visited node."
},
{
"code": null,
"e": 25809,
"s": 25757,
"text": "If all nodes matched, then return true, else false."
},
{
"code": null,
"e": 25858,
"s": 25809,
"text": "Below image is a dry run of the above approach: "
},
{
"code": null,
"e": 25911,
"s": 25858,
"text": "Below is the implementation of the above approach : "
},
{
"code": null,
"e": 25916,
"s": 25911,
"text": "Java"
},
{
"code": "// Java program to check if linked list// is palindrome recursivelyimport java.util.*; class linkedList{ public static void main(String args[]) { Node one = new Node(1); Node two = new Node(2); Node three = new Node(3); Node four = new Node(4); Node five = new Node(3); Node six = new Node(2); Node seven = new Node(1); one.ptr = two; two.ptr = three; three.ptr = four; four.ptr = five; five.ptr = six; six.ptr = seven; boolean condition = isPalindrome(one); System.out.println(\"isPalidrome :\" + condition); } static boolean isPalindrome(Node head) { Node slow = head; boolean ispalin = true; Stack<Integer> stack = new Stack<Integer>(); while (slow != null) { stack.push(slow.data); slow = slow.ptr; } while (head != null) { int i = stack.pop(); if (head.data == i) { ispalin = true; } else { ispalin = false; break; } head = head.ptr; } return ispalin; }} class Node{ int data; Node ptr; Node(int d) { ptr = null; data = d; }}",
"e": 27224,
"s": 25916,
"text": null
},
{
"code": null,
"e": 27233,
"s": 27224,
"text": "Output: "
},
{
"code": null,
"e": 27253,
"s": 27233,
"text": " isPalindrome: true"
},
{
"code": null,
"e": 27276,
"s": 27253,
"text": "Time complexity: O(n)."
},
{
"code": null,
"e": 27616,
"s": 27276,
"text": "METHOD 2 (By reversing the list): This method takes O(n) time and O(1) extra space. 1) Get the middle of the linked list. 2) Reverse the second half of the linked list. 3) Check if the first half and second half are identical. 4) Construct the original linked list by reversing the second half again and attaching it back to the first half"
},
{
"code": null,
"e": 27684,
"s": 27616,
"text": "To divide the list into two halves, method 2 of this post is used. "
},
{
"code": null,
"e": 28014,
"s": 27684,
"text": "When a number of nodes are even, the first and second half contain exactly half nodes. The challenging thing in this method is to handle the case when the number of nodes is odd. We don’t want the middle node as part of the lists as we are going to compare them for equality. For odd cases, we use a separate variable ‘midnode’. "
},
{
"code": null,
"e": 28019,
"s": 28014,
"text": "Java"
},
{
"code": "// Java program to check if linked list// is palindrome class LinkedList{ // Head of list Node head; Node slow_ptr, fast_ptr, second_half; // Linked list Node class Node { char data; Node next; Node(char d) { data = d; next = null; } } /* Function to check if given linked list is palindrome or not */ boolean isPalindrome(Node head) { slow_ptr = head; fast_ptr = head; Node prev_of_slow_ptr = head; // To handle odd size list Node midnode = null; // Initialize result boolean res = true; if (head != null && head.next != null) { /* Get the middle of the list. Move slow_ptr by 1 and fast_ptrr by 2, slow_ptr will have the middle node */ while (fast_ptr != null && fast_ptr.next != null) { fast_ptr = fast_ptr.next.next; /*We need previous of the slow_ptr for linked lists with odd elements */ prev_of_slow_ptr = slow_ptr; slow_ptr = slow_ptr.next; } /* fast_ptr would become NULL when there are even elements in the list and not NULL for odd elements. We need to skip the middle node for odd case and store it somewhere so that we can restore the original list */ if (fast_ptr != null) { midnode = slow_ptr; slow_ptr = slow_ptr.next; } // Now reverse the second half and // compare it with first half second_half = slow_ptr; // NULL terminate first half prev_of_slow_ptr.next = null; // Reverse the second half reverse(); // compare res = compareLists(head, second_half); // Construct the original list back // Reverse the second half again reverse(); if (midnode != null) { // If there was a mid node (odd size case) // which was not part of either first half // or second half. prev_of_slow_ptr.next = midnode; midnode.next = second_half; } else prev_of_slow_ptr.next = second_half; } return res; } /* Function to reverse the linked list Note that this function may change the head */ void reverse() { Node prev = null; Node current = second_half; Node next; while (current != null) { next = current.next; current.next = prev; prev = current; current = next; } second_half = prev; } // Function to check if two input // lists have same data boolean compareLists(Node head1, Node head2) { Node temp1 = head1; Node temp2 = head2; while (temp1 != null && temp2 != null) { if (temp1.data == temp2.data) { temp1 = temp1.next; temp2 = temp2.next; } else return false; } // Both are empty return 1 if (temp1 == null && temp2 == null) return true; /* Will reach here when one is NULL and other is not */ return false; } /* Push a node to linked list. Note that this function changes the head */ public void push(char new_data) { /* Allocate the Node & Put in the data */ Node new_node = new Node(new_data); // Link the old list off the new one new_node.next = head; // Move the head to point to new Node head = new_node; } // A utility function to print a // given linked list void printList(Node ptr) { while (ptr != null) { System.out.print(ptr.data + \"->\"); ptr = ptr.next; } System.out.println(\"NULL\"); } // Driver code public static void main(String[] args) { // Start with the empty list LinkedList llist = new LinkedList(); char str[] = {'a', 'b', 'a', 'c', 'a', 'b', 'a'}; String string = new String(str); for (int i = 0; i < 7; i++) { llist.push(str[i]); llist.printList(llist.head); if (llist.isPalindrome(llist.head) != false) { System.out.println(\"Is Palindrome\"); System.out.println(\"\"); } else { System.out.println(\"Not Palindrome\"); System.out.println(\"\"); } } }}",
"e": 32923,
"s": 28019,
"text": null
},
{
"code": null,
"e": 32932,
"s": 32923,
"text": "Output: "
},
{
"code": null,
"e": 33159,
"s": 32932,
"text": "a->NULL\nIs Palindrome\n\nb->a->NULL\nNot Palindrome\n\na->b->a->NULL\nIs Palindrome\n\nc->a->b->a->NULL\nNot Palindrome\n\na->c->a->b->a->NULL\nNot Palindrome\n\nb->a->c->a->b->a->NULL\nNot Palindrome\n\na->b->a->c->a->b->a->NULL\nIs Palindrome"
},
{
"code": null,
"e": 33205,
"s": 33159,
"text": "Time Complexity: O(n) Auxiliary Space: O(1) "
},
{
"code": null,
"e": 33428,
"s": 33205,
"text": "METHOD 3 (Using Recursion): Use two pointers left and right. Move right and left using recursion and check for following in each recursive call. 1) Sub-list is a palindrome. 2) Value at current left and right are matching."
},
{
"code": null,
"e": 33480,
"s": 33428,
"text": "If both above conditions are true then return true."
},
{
"code": null,
"e": 33711,
"s": 33480,
"text": "The idea is to use function call stack as a container. Recursively traverse till the end of the list. When we return from the last NULL, we will be at the last node. The last node is to be compared with the first node of the list."
},
{
"code": null,
"e": 34430,
"s": 33711,
"text": "In order to access the first node of the list, we need the list head to be available in the last call of recursion. Hence, we pass head also to the recursive function. If they both match we need to compare (2, n-2) nodes. Again when recursion falls back to (n-2)nd node, we need a reference to 2nd node from the head. We advance the head pointer in the previous call, to refer to the next node in the list.However, the trick is identifying a double-pointer. Passing a single pointer is as good as pass-by-value, and we will pass the same pointer again and again. We need to pass the address of the head pointer for reflecting the changes in parent recursive calls.Thanks to Sharad Chandra for suggesting this approach."
},
{
"code": null,
"e": 34435,
"s": 34430,
"text": "Java"
},
{
"code": "// Java program to implement// the above approachpublic class LinkedList{ // Head of the list Node head; Node left; public class Node { public char data; public Node next; // Linked list node public Node(char d) { data = d; next = null; } } // Initial parameters to this // function are &head and head boolean isPalindromeUtil(Node right) { left = head; // Stop recursion when right // becomes null if (right == null) return true; // If sub-list is not palindrome then // no need to check for the current // left and right, return false boolean isp = isPalindromeUtil(right.next); if (isp == false) return false; // Check values at current left and right boolean isp1 = (right.data == left.data); left = left.next; // Move left to next node; return isp1; } // A wrapper over isPalindrome(Node head) boolean isPalindrome(Node head) { boolean result = isPalindromeUtil(head); return result; } // Push a node to linked list. // Note that this function changes // the head public void push(char new_data) { // Allocate the node and put in // the data Node new_node = new Node(new_data); // Link the old list off the the // new one new_node.next = head; // Move the head to point to // new node head = new_node; } // A utility function to print a // given linked list void printList(Node ptr) { while (ptr != null) { System.out.print(ptr.data + \"->\"); ptr = ptr.next; } System.out.println(\"Null\"); } // Driver Code public static void main(String[] args) { LinkedList llist = new LinkedList(); char[] str = {'a', 'b', 'a', 'c', 'a', 'b', 'a'}; for(int i = 0; i < 7; i++) { llist.push(str[i]); llist.printList(llist.head); if (llist.isPalindrome(llist.head)) { System.out.println(\"Is Palindrome\"); System.out.println(\"\"); } else { System.out.println(\"Not Palindrome\"); System.out.println(\"\"); } } }}// This code is contributed by abhinavjain194",
"e": 36919,
"s": 34435,
"text": null
},
{
"code": null,
"e": 36928,
"s": 36919,
"text": "Output: "
},
{
"code": null,
"e": 37156,
"s": 36928,
"text": "a->NULL\nNot Palindrome\n\nb->a->NULL\nNot Palindrome\n\na->b->a->NULL\nIs Palindrome\n\nc->a->b->a->NULL\nNot Palindrome\n\na->c->a->b->a->NULL\nNot Palindrome\n\nb->a->c->a->b->a->NULL\nNot Palindrome\n\na->b->a->c->a->b->a->NULL\nIs Palindrome"
},
{
"code": null,
"e": 37259,
"s": 37156,
"text": "Time Complexity: O(n) Auxiliary Space: O(n) if Function Call Stack size is considered, otherwise O(1)."
},
{
"code": null,
"e": 37367,
"s": 37259,
"text": "Please refer complete article on Function to check if a singly linked list is palindrome for more details! "
},
{
"code": null,
"e": 37376,
"s": 37367,
"text": "sweetyty"
},
{
"code": null,
"e": 37391,
"s": 37376,
"text": "varshagumber28"
},
{
"code": null,
"e": 37400,
"s": 37391,
"text": "Accolite"
},
{
"code": null,
"e": 37406,
"s": 37400,
"text": "Adobe"
},
{
"code": null,
"e": 37413,
"s": 37406,
"text": "Amazon"
},
{
"code": null,
"e": 37424,
"s": 37413,
"text": "KLA Tencor"
},
{
"code": null,
"e": 37443,
"s": 37424,
"text": "Kritikal Solutions"
},
{
"code": null,
"e": 37456,
"s": 37443,
"text": "Linked Lists"
},
{
"code": null,
"e": 37466,
"s": 37456,
"text": "Microsoft"
},
{
"code": null,
"e": 37477,
"s": 37466,
"text": "palindrome"
},
{
"code": null,
"e": 37486,
"s": 37477,
"text": "Snapdeal"
},
{
"code": null,
"e": 37502,
"s": 37486,
"text": "Yodlee Infotech"
},
{
"code": null,
"e": 37507,
"s": 37502,
"text": "Java"
},
{
"code": null,
"e": 37521,
"s": 37507,
"text": "Java Programs"
},
{
"code": null,
"e": 37533,
"s": 37521,
"text": "Linked List"
},
{
"code": null,
"e": 37542,
"s": 37533,
"text": "Accolite"
},
{
"code": null,
"e": 37549,
"s": 37542,
"text": "Amazon"
},
{
"code": null,
"e": 37559,
"s": 37549,
"text": "Microsoft"
},
{
"code": null,
"e": 37568,
"s": 37559,
"text": "Snapdeal"
},
{
"code": null,
"e": 37574,
"s": 37568,
"text": "Adobe"
},
{
"code": null,
"e": 37590,
"s": 37574,
"text": "Yodlee Infotech"
},
{
"code": null,
"e": 37601,
"s": 37590,
"text": "KLA Tencor"
},
{
"code": null,
"e": 37620,
"s": 37601,
"text": "Kritikal Solutions"
},
{
"code": null,
"e": 37632,
"s": 37620,
"text": "Linked List"
},
{
"code": null,
"e": 37637,
"s": 37632,
"text": "Java"
},
{
"code": null,
"e": 37648,
"s": 37637,
"text": "palindrome"
},
{
"code": null,
"e": 37746,
"s": 37648,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37761,
"s": 37746,
"text": "Stream In Java"
},
{
"code": null,
"e": 37782,
"s": 37761,
"text": "Constructors in Java"
},
{
"code": null,
"e": 37801,
"s": 37782,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 37831,
"s": 37801,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 37848,
"s": 37831,
"text": "Generics in Java"
},
{
"code": null,
"e": 37874,
"s": 37848,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 37908,
"s": 37874,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 37955,
"s": 37908,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 37987,
"s": 37955,
"text": "How to Iterate HashMap in Java?"
}
]
|
Java Program to Find the Index of the TreeSet Element - GeeksforGeeks | 27 Jun, 2021
Unlike the List classes like ArrayList or a LinkedList, the TreeSet class does not allow accessing elements using the index. There are no direct methods to access the TreeSet elements using the index and thus finding an index of an element is not straightforward.
Methods: There are primarily three standard methods as follows:
By converting TreeSet to a ListUsing an IteratorUsing the headSet() method of the TreeSet class
By converting TreeSet to a List
Using an Iterator
Using the headSet() method of the TreeSet class
Method 1: By converting TreeSet to a List
The List class like ArrayList or a LinkedList provides the indexOf() method to find the element index. We can convert the TreeSet to ArrayList and then use the indexOf() method. This method returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.
Syntax:
public int indexOf(Object o) ;
Parameters: This function has a single parameter, i.e, the element to be searched in the list.
Returns: This method returns the index of the first occurrence of the given element in the list and returns “-1” if the element is not in the list.
Example
Java
// Java Program to find the index of TreeSet element// using List by converting TreeSet to a List // Importing ArrayList, List and TreeSet classes// from java.util packageimport java.util.ArrayList;import java.util.List;import java.util.TreeSet; // Classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating a object of the TreeSet class // Declaring object of Integer type TreeSet<Integer> treeSet = new TreeSet<Integer>(); // Adding the element to the TreeSet // Custom inputs treeSet.add(34); treeSet.add(23); treeSet.add(43); treeSet.add(41); treeSet.add(35); treeSet.add(33); // Printing all the elements in the TreeSet object System.out.println("TreeSet contains: " + treeSet); // Printing indexes of elements using indexOf() // method Index of element number 1 System.out.println("Index of 23: " + indexOf(treeSet, 23)); // Index of element number 2 System.out.println("Index of 43: " + indexOf(treeSet, 43)); // Index of element number 3 System.out.println("Index of 35: " + indexOf(treeSet, 35)); // Index of element number 4 System.out.println("Index of 55: " + indexOf(treeSet, 55)); } // Method - indexOf() private static int indexOf(TreeSet<Integer> set, Integer element) { // Step 1: Convert TreeSet to ArrayList or // LinkedList List<Integer> list = new ArrayList<Integer>(set); // Step 2: Use the indexOf method of the List return list.indexOf(element); }}
TreeSet contains: [23, 33, 34, 35, 41, 43]
Index of 23: 0
Index of 43: 5
Index of 35: 3
Index of 55: -1
Method 2: Using an Iterator
Procedure:
Iterator over TreeSet elements using the iterator method.Once the iterator is fetched, iterate through the elements and search for the specified element as per requirements either from the user or custom inputs as shown below for understanding purposes.
Iterator over TreeSet elements using the iterator method.
Once the iterator is fetched, iterate through the elements and search for the specified element as per requirements either from the user or custom inputs as shown below for understanding purposes.
Example
Java
// Java Program to find the index of the element// in the TreeSet using Iterator// Using an Iterator // Importing Iterator and TreeSet class from// java.util packageimport java.util.Iterator;import java.util.TreeSet; // Classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an object of TreeSet class // Declaring object of Integer type TreeSet<Integer> treeSet = new TreeSet<Integer>(); // Adding the elements to the TreeSet // Custom inputs treeSet.add(34); treeSet.add(23); treeSet.add(43); treeSet.add(41); treeSet.add(35); treeSet.add(33); // Printing the element in the TreeSet System.out.println("TreeSet contains: " + treeSet); // Printing the indexes of elements in above TreeSet // object System.out.println("Index of 23: " + indexOf(treeSet, 23)); System.out.println("Index of 43: " + indexOf(treeSet, 43)); System.out.println("Index of 35: " + indexOf(treeSet, 35)); System.out.println("Index of 55: " + indexOf(treeSet, 55)); } // Method - indexOf() private static int indexOf(TreeSet<Integer> set, Integer element) { int index = -1; // Get an iterator Iterator<Integer> itr = set.iterator(); Integer currentElement = null; int currentIndex = 0; // Condition check using hasNext() method which // holds true till single element in List is // remaining while (itr.hasNext()) { currentElement = itr.next(); // Checking if the current element equals // the element whose index is tried to search if (currentElement.equals(element)) { // Return the index of the element return currentIndex; } // Increment the index number currentIndex++; } // Return the index -1 // if the element do not exists return index; }}
TreeSet contains: [23, 33, 34, 35, 41, 43]
Index of 23: 0
Index of 43: 5
Index of 35: 3
Index of 55: -1
Method: 3 Using the headSet() method of the TreeSet class
The headSet() method of the TreeSet class returns a view of part of the TreeSet whose elements are less than the specified element. Since the elements of the TreeSet are automatically sorted either in the natural order of the elements or by a custom comparator, the headset size will be equal to the number of elements that are smaller or lower than the specified element. If we were to put the TreeSet elements in a List, then that number would be equal to the index of the element.
Illustration:
If the TreeSet contains [1, 2, 3, 4] then the headset of element 3 will contain elements [1, 2]. The size of the headset will be 2 and that will be the index of element 3. Thus, if we get the size of the headset, then it will be equal to the position of the element for which we have to find the index.
Example
Java
// Java Program to find the index of element// in TreeSet using HeadSet// Using the headSet() method of the TreeSet class // Importing TreeSet class from// java.util packageimport java.util.TreeSet; // Classpublic class GFG { // Main driver method public static void main(String[] args) { // Making the new object of TreeSet class TreeSet<Integer> treeSet = new TreeSet<Integer>(); // Adding the elements to the TreeSet treeSet.add(34); treeSet.add(23); treeSet.add(43); treeSet.add(41); treeSet.add(35); treeSet.add(33); // Printing the elements of the TreeSet System.out.println("TreeSet contains: " + treeSet); // Printing the indexes of elements // in above TreeSet object System.out.println("Index of 23: " + indexOf(treeSet, 23)); System.out.println("Index of 43: " + indexOf(treeSet, 43)); System.out.println("Index of 35: " + indexOf(treeSet, 35)); System.out.println("Index of 55: " + indexOf(treeSet, 55)); } // Method - indexOf() method private static int indexOf(TreeSet<Integer> set, Integer element) { int index = -1; // If the element exists in the TreeSet if (set.contains(element)) { // The element index will be equal to the // size of the headSet for the element index = set.headSet(element).size(); } // Return the index of the element // Value will be -1 if the element // do not exist in the TreeSet return index; }}
TreeSet contains: [23, 33, 34, 35, 41, 43]
Index of 23: 0
Index of 43: 5
Index of 35: 3
Index of 55: -1
anikaseth98
Java-Collections
java-treeset
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Iterate through List in Java | [
{
"code": null,
"e": 25225,
"s": 25197,
"text": "\n27 Jun, 2021"
},
{
"code": null,
"e": 25490,
"s": 25225,
"text": "Unlike the List classes like ArrayList or a LinkedList, the TreeSet class does not allow accessing elements using the index. There are no direct methods to access the TreeSet elements using the index and thus finding an index of an element is not straightforward. "
},
{
"code": null,
"e": 25554,
"s": 25490,
"text": "Methods: There are primarily three standard methods as follows:"
},
{
"code": null,
"e": 25650,
"s": 25554,
"text": "By converting TreeSet to a ListUsing an IteratorUsing the headSet() method of the TreeSet class"
},
{
"code": null,
"e": 25682,
"s": 25650,
"text": "By converting TreeSet to a List"
},
{
"code": null,
"e": 25700,
"s": 25682,
"text": "Using an Iterator"
},
{
"code": null,
"e": 25748,
"s": 25700,
"text": "Using the headSet() method of the TreeSet class"
},
{
"code": null,
"e": 25790,
"s": 25748,
"text": "Method 1: By converting TreeSet to a List"
},
{
"code": null,
"e": 26110,
"s": 25790,
"text": "The List class like ArrayList or a LinkedList provides the indexOf() method to find the element index. We can convert the TreeSet to ArrayList and then use the indexOf() method. This method returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element."
},
{
"code": null,
"e": 26118,
"s": 26110,
"text": "Syntax:"
},
{
"code": null,
"e": 26149,
"s": 26118,
"text": "public int indexOf(Object o) ;"
},
{
"code": null,
"e": 26244,
"s": 26149,
"text": "Parameters: This function has a single parameter, i.e, the element to be searched in the list."
},
{
"code": null,
"e": 26392,
"s": 26244,
"text": "Returns: This method returns the index of the first occurrence of the given element in the list and returns “-1” if the element is not in the list."
},
{
"code": null,
"e": 26400,
"s": 26392,
"text": "Example"
},
{
"code": null,
"e": 26405,
"s": 26400,
"text": "Java"
},
{
"code": "// Java Program to find the index of TreeSet element// using List by converting TreeSet to a List // Importing ArrayList, List and TreeSet classes// from java.util packageimport java.util.ArrayList;import java.util.List;import java.util.TreeSet; // Classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating a object of the TreeSet class // Declaring object of Integer type TreeSet<Integer> treeSet = new TreeSet<Integer>(); // Adding the element to the TreeSet // Custom inputs treeSet.add(34); treeSet.add(23); treeSet.add(43); treeSet.add(41); treeSet.add(35); treeSet.add(33); // Printing all the elements in the TreeSet object System.out.println(\"TreeSet contains: \" + treeSet); // Printing indexes of elements using indexOf() // method Index of element number 1 System.out.println(\"Index of 23: \" + indexOf(treeSet, 23)); // Index of element number 2 System.out.println(\"Index of 43: \" + indexOf(treeSet, 43)); // Index of element number 3 System.out.println(\"Index of 35: \" + indexOf(treeSet, 35)); // Index of element number 4 System.out.println(\"Index of 55: \" + indexOf(treeSet, 55)); } // Method - indexOf() private static int indexOf(TreeSet<Integer> set, Integer element) { // Step 1: Convert TreeSet to ArrayList or // LinkedList List<Integer> list = new ArrayList<Integer>(set); // Step 2: Use the indexOf method of the List return list.indexOf(element); }}",
"e": 28176,
"s": 26405,
"text": null
},
{
"code": null,
"e": 28283,
"s": 28179,
"text": "TreeSet contains: [23, 33, 34, 35, 41, 43]\nIndex of 23: 0\nIndex of 43: 5\nIndex of 35: 3\nIndex of 55: -1"
},
{
"code": null,
"e": 28313,
"s": 28285,
"text": "Method 2: Using an Iterator"
},
{
"code": null,
"e": 28327,
"s": 28315,
"text": "Procedure: "
},
{
"code": null,
"e": 28583,
"s": 28329,
"text": "Iterator over TreeSet elements using the iterator method.Once the iterator is fetched, iterate through the elements and search for the specified element as per requirements either from the user or custom inputs as shown below for understanding purposes."
},
{
"code": null,
"e": 28641,
"s": 28583,
"text": "Iterator over TreeSet elements using the iterator method."
},
{
"code": null,
"e": 28838,
"s": 28641,
"text": "Once the iterator is fetched, iterate through the elements and search for the specified element as per requirements either from the user or custom inputs as shown below for understanding purposes."
},
{
"code": null,
"e": 28848,
"s": 28840,
"text": "Example"
},
{
"code": null,
"e": 28855,
"s": 28850,
"text": "Java"
},
{
"code": "// Java Program to find the index of the element// in the TreeSet using Iterator// Using an Iterator // Importing Iterator and TreeSet class from// java.util packageimport java.util.Iterator;import java.util.TreeSet; // Classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an object of TreeSet class // Declaring object of Integer type TreeSet<Integer> treeSet = new TreeSet<Integer>(); // Adding the elements to the TreeSet // Custom inputs treeSet.add(34); treeSet.add(23); treeSet.add(43); treeSet.add(41); treeSet.add(35); treeSet.add(33); // Printing the element in the TreeSet System.out.println(\"TreeSet contains: \" + treeSet); // Printing the indexes of elements in above TreeSet // object System.out.println(\"Index of 23: \" + indexOf(treeSet, 23)); System.out.println(\"Index of 43: \" + indexOf(treeSet, 43)); System.out.println(\"Index of 35: \" + indexOf(treeSet, 35)); System.out.println(\"Index of 55: \" + indexOf(treeSet, 55)); } // Method - indexOf() private static int indexOf(TreeSet<Integer> set, Integer element) { int index = -1; // Get an iterator Iterator<Integer> itr = set.iterator(); Integer currentElement = null; int currentIndex = 0; // Condition check using hasNext() method which // holds true till single element in List is // remaining while (itr.hasNext()) { currentElement = itr.next(); // Checking if the current element equals // the element whose index is tried to search if (currentElement.equals(element)) { // Return the index of the element return currentIndex; } // Increment the index number currentIndex++; } // Return the index -1 // if the element do not exists return index; }}",
"e": 31025,
"s": 28855,
"text": null
},
{
"code": null,
"e": 31132,
"s": 31028,
"text": "TreeSet contains: [23, 33, 34, 35, 41, 43]\nIndex of 23: 0\nIndex of 43: 5\nIndex of 35: 3\nIndex of 55: -1"
},
{
"code": null,
"e": 31192,
"s": 31134,
"text": "Method: 3 Using the headSet() method of the TreeSet class"
},
{
"code": null,
"e": 31678,
"s": 31194,
"text": "The headSet() method of the TreeSet class returns a view of part of the TreeSet whose elements are less than the specified element. Since the elements of the TreeSet are automatically sorted either in the natural order of the elements or by a custom comparator, the headset size will be equal to the number of elements that are smaller or lower than the specified element. If we were to put the TreeSet elements in a List, then that number would be equal to the index of the element."
},
{
"code": null,
"e": 31694,
"s": 31680,
"text": "Illustration:"
},
{
"code": null,
"e": 31999,
"s": 31696,
"text": "If the TreeSet contains [1, 2, 3, 4] then the headset of element 3 will contain elements [1, 2]. The size of the headset will be 2 and that will be the index of element 3. Thus, if we get the size of the headset, then it will be equal to the position of the element for which we have to find the index."
},
{
"code": null,
"e": 32010,
"s": 32001,
"text": "Example "
},
{
"code": null,
"e": 32017,
"s": 32012,
"text": "Java"
},
{
"code": "// Java Program to find the index of element// in TreeSet using HeadSet// Using the headSet() method of the TreeSet class // Importing TreeSet class from// java.util packageimport java.util.TreeSet; // Classpublic class GFG { // Main driver method public static void main(String[] args) { // Making the new object of TreeSet class TreeSet<Integer> treeSet = new TreeSet<Integer>(); // Adding the elements to the TreeSet treeSet.add(34); treeSet.add(23); treeSet.add(43); treeSet.add(41); treeSet.add(35); treeSet.add(33); // Printing the elements of the TreeSet System.out.println(\"TreeSet contains: \" + treeSet); // Printing the indexes of elements // in above TreeSet object System.out.println(\"Index of 23: \" + indexOf(treeSet, 23)); System.out.println(\"Index of 43: \" + indexOf(treeSet, 43)); System.out.println(\"Index of 35: \" + indexOf(treeSet, 35)); System.out.println(\"Index of 55: \" + indexOf(treeSet, 55)); } // Method - indexOf() method private static int indexOf(TreeSet<Integer> set, Integer element) { int index = -1; // If the element exists in the TreeSet if (set.contains(element)) { // The element index will be equal to the // size of the headSet for the element index = set.headSet(element).size(); } // Return the index of the element // Value will be -1 if the element // do not exist in the TreeSet return index; }}",
"e": 33731,
"s": 32017,
"text": null
},
{
"code": null,
"e": 33838,
"s": 33734,
"text": "TreeSet contains: [23, 33, 34, 35, 41, 43]\nIndex of 23: 0\nIndex of 43: 5\nIndex of 35: 3\nIndex of 55: -1"
},
{
"code": null,
"e": 33852,
"s": 33840,
"text": "anikaseth98"
},
{
"code": null,
"e": 33869,
"s": 33852,
"text": "Java-Collections"
},
{
"code": null,
"e": 33882,
"s": 33869,
"text": "java-treeset"
},
{
"code": null,
"e": 33889,
"s": 33882,
"text": "Picked"
},
{
"code": null,
"e": 33913,
"s": 33889,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 33918,
"s": 33913,
"text": "Java"
},
{
"code": null,
"e": 33932,
"s": 33918,
"text": "Java Programs"
},
{
"code": null,
"e": 33951,
"s": 33932,
"text": "Technical Scripter"
},
{
"code": null,
"e": 33956,
"s": 33951,
"text": "Java"
},
{
"code": null,
"e": 33973,
"s": 33956,
"text": "Java-Collections"
},
{
"code": null,
"e": 34071,
"s": 33973,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34086,
"s": 34071,
"text": "Stream In Java"
},
{
"code": null,
"e": 34107,
"s": 34086,
"text": "Constructors in Java"
},
{
"code": null,
"e": 34126,
"s": 34107,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 34156,
"s": 34126,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 34202,
"s": 34156,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 34228,
"s": 34202,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 34262,
"s": 34228,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 34309,
"s": 34262,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 34341,
"s": 34309,
"text": "How to Iterate HashMap in Java?"
}
]
|
CSS border-radius Property - GeeksforGeeks | 21 Oct, 2021
The border-radius property in CSS is used to round the corners of the outer border edges of an element. This property can contain one, two, three, or four values. The border-radius property is used to set the border-radius. This property is not applicable to the table elements when border-collapse is collapsing.
Syntax:
border-radius: 1-4 length|% / 1-4 length|%|initial|inherit;
Property Values:
length: It represents the shape of the corners & the default value is 0.
percentage(%): It represents the shape of the corners in %.
initial: It is used to set an element’s CSS property to its default value.
inherit: It is used to inherit a property to an element from its parent element property value.
The 4 values for each radius can be specified in the following order as top-left, top-right, bottom-right, bottom-left. If the bottom-left is removed then it will be the same as the top-right. Similarly, If the bottom-right & top-right will be removed then it will be the same as the top-left & the top-left respectively.
border-radius: border-radius property can contain one, two, three, or four values.
border-radius: 35px; It is used to set border-radius of each corners. It is the combination of four properties: border-top-left-radius, border-top-right-radius, border-bottom-left-radius, border-bottom-right-radius. It sets all corner to the same value.
Example: This example illustrates the border-radius property whose value is specified by the single value.
HTML
<!DOCTYPE html><html><head> <title>Rounded Corners</title> <style> .GFG { border-radius: 35px; background: #009900; padding: 30px; text-align: center; width: 300px; height: 120px; } </style></head> <body> <div class="GFG"> <h2>GeeksforGeeks</h2> <p>border-radius: 35px;</p> </div></body></html>
Output:
border-radius: 20px 40px; This property is used to set first value as top-left and bottom right corner and second value as top right and bottom left corners.
Example: This example illustrates the border-radius property whose value is specified by the double values.
HTML
<!DOCTYPE html><html> <head> <title>Rounded Corners</title> <style> .GFG { border-radius: 20px 40px; background: #009900; padding: 30px; text-align: center; width: 300px; height: 120px; } </style></head> <body> <div class="GFG"> <h2>GeeksforGeeks</h2> <p>border-radius: 20px 40px;</p> </div></body> </html>
Output:
border-radius: 20px 40px 60px; This property is used to set first value to top-left corner, second value applied to top-right and bottom left corners and third value applied to bottom right corner.
Example: This example illustrates the border-radius property whose value is specified by the triple values.
HTML
<!DOCTYPE html><html><head> <title>Rounded Corners</title> <style> .GFG { border-radius: 20px 40px 60px; background: #009900; padding: 30px; text-align: center; width: 300px; height: 120px; } </style></head> <body> <div class="GFG"> <h2>GeeksforGeeks</h2> <p>border-radius: 20px 40px 60px;</p> </div></body></html>
Output:
border-radius: 20px 40px 60px 80px; This property is used to set first, second, third and fourth value of border radius to top-left, top-right, bottom-right and bottom-left corners respectively.
Example: This example illustrates the border-radius property whose value is specified by the four values.
HTML
<!DOCTYPE html><html><head> <title>Rounded Corners</title> <style> .GFG { border-radius: 20px 40px 60px 80px; background: #009900; padding: 30px; text-align: center; width: 300px; height: 120px; } </style></head> <body> <div class="GFG"> <h2>GeeksforGeeks</h2> <p>border-radius: 20px 40px 60px 80px;</p> </div></body></html>
Output:
Now, we will understand the shorthand properties for the given below border-radius property.
border-top-left-radius: This property is used to specify the radius of the top left corner of an element.
Example: This example illustrates the border-radius property where the property value is applied for the top left corner of an element.
HTML
<!DOCTYPE html><html><head> <title>Rounded Corners</title> <style> .GFG { border-top-left-radius: 35px; background: #009900; padding: 30px; text-align: center; width: 300px; height: 120px; } </style></head> <body> <div class="GFG"> <h2>GeeksforGeeks</h2> <p>border-top-left-radius: 35px;</p> </div></body></html>
Output:
border-top-right-radius: This property s used to define the radius of the right top corner of the border of a given element.
Example: This example illustrates the border-radius property where the property value is applied for the top-right corner of an element.
HTML
<!DOCTYPE html><html><head> <title>Rounded Corners</title> <style> .GFG { border-top-right-radius: 35px; background: #009900; padding: 30px; text-align: center; width: 300px; height: 120px; } </style></head> <body> <div class="GFG"> <h2>GeeksforGeeks</h2> <p>border-top-right-radius: 35px;</p> </div></body></html>
Output:
border-bottom-left-radius: This property is used to define the radius of the bottom left corner of the border i.e. it makes the bottom-left of the border round.
Example: This example illustrates the border-radius property where the property value is applied for the bottom-left corner of an element.
HTML
<!DOCTYPE html><html><head> <title>Rounded Corners</title> <style> .GFG { border-bottom-left-radius: 35px; background: #009900; padding: 30px; text-align: center; width: 300px; height: 120px; } </style></head> <body> <div class="GFG"> <h2>GeeksforGeeks</h2> <p>border-bottom-left-radius: 35px;</p> </div></body></html>
Output:
border-bottom-right-radius: This property is used to define the radius of the right bottom corner of the border of a given element.
Example: This example illustrates the border-radius property where the property value is applied for the bottom-right corner of an element.
HTML
<!DOCTYPE html><html><head> <title>Rounded Corners</title> <style> .GFG { border-bottom-right-radius: 35px; background: #009900; padding: 30px; text-align: center; width: 300px; height: 120px; } </style></head> <body> <div class="GFG"> <h2>GeeksforGeeks</h2> <p>border-bottom-right-radius: 35px;</p> </div></body></html>
Output:
mixed border-radius property: This property is used to set all corners as the given value.
Example: This example illustrates the border-radius property where the property value is applied for all the corners of an element.
HTML
<!DOCTYPE html><html><head> <title>Rounded Corners</title> <style> .GFG { border-top-left-radius: 35px; border-top-right-radius: 35px; border-bottom-left-radius: 35px; border-bottom-right-radius: 35px; background: #009900; padding: 30px; text-align: center; width: 300px; height: 120px; } </style></head> <body> <div class="GFG"> <h2>GeeksforGeeks</h2> <p>border-top-left-radius: 35px; <br>border-top-right-radius: 35px; <br>border-bottom-left-radius: 35px; <br>border-bottom-right-radius: 35px;</p> </div></body></html>
Output:
Shorthands:
Apply Radius value to all four corners:
border-radius: value;
Apply value1 to top-left and bottom-right corners and value2 to top-right and bottom-left corners:
border-radius: value1 value2;
Apply value1 to top-left corner, value2 to top-right and bottom-left corners and value3 to bottom-right corner:
border-radius: value1 value2 value3;
Apply value1 to top-left corner, value2 to top-right corner , value3 to bottom-right corner and value4 to bottom-left corner:
border-radius: value1 value2 value3 value4;
Supported Browsers:
Google chrome 5.0, 4.0 -webkit-
Internet Explorer 9.0
Microsoft Edge 12.0
Firefox 4.0, 3.0 -moz-
Opera 10.5
Safari 5.0, 3.1 -webkit-
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
motamarriphani
nidhi_biet
ManasChhabra2
bhaskargeeksforgeeks
CSS-Properties
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to create footer to stay at the bottom of a Web page?
How to apply style to parent if it has child with CSS?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property | [
{
"code": null,
"e": 24929,
"s": 24901,
"text": "\n21 Oct, 2021"
},
{
"code": null,
"e": 25243,
"s": 24929,
"text": "The border-radius property in CSS is used to round the corners of the outer border edges of an element. This property can contain one, two, three, or four values. The border-radius property is used to set the border-radius. This property is not applicable to the table elements when border-collapse is collapsing."
},
{
"code": null,
"e": 25253,
"s": 25243,
"text": "Syntax: "
},
{
"code": null,
"e": 25313,
"s": 25253,
"text": "border-radius: 1-4 length|% / 1-4 length|%|initial|inherit;"
},
{
"code": null,
"e": 25330,
"s": 25313,
"text": "Property Values:"
},
{
"code": null,
"e": 25403,
"s": 25330,
"text": "length: It represents the shape of the corners & the default value is 0."
},
{
"code": null,
"e": 25463,
"s": 25403,
"text": "percentage(%): It represents the shape of the corners in %."
},
{
"code": null,
"e": 25538,
"s": 25463,
"text": "initial: It is used to set an element’s CSS property to its default value."
},
{
"code": null,
"e": 25634,
"s": 25538,
"text": "inherit: It is used to inherit a property to an element from its parent element property value."
},
{
"code": null,
"e": 25956,
"s": 25634,
"text": "The 4 values for each radius can be specified in the following order as top-left, top-right, bottom-right, bottom-left. If the bottom-left is removed then it will be the same as the top-right. Similarly, If the bottom-right & top-right will be removed then it will be the same as the top-left & the top-left respectively."
},
{
"code": null,
"e": 26041,
"s": 25956,
"text": "border-radius: border-radius property can contain one, two, three, or four values. "
},
{
"code": null,
"e": 26295,
"s": 26041,
"text": "border-radius: 35px; It is used to set border-radius of each corners. It is the combination of four properties: border-top-left-radius, border-top-right-radius, border-bottom-left-radius, border-bottom-right-radius. It sets all corner to the same value."
},
{
"code": null,
"e": 26402,
"s": 26295,
"text": "Example: This example illustrates the border-radius property whose value is specified by the single value."
},
{
"code": null,
"e": 26407,
"s": 26402,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <title>Rounded Corners</title> <style> .GFG { border-radius: 35px; background: #009900; padding: 30px; text-align: center; width: 300px; height: 120px; } </style></head> <body> <div class=\"GFG\"> <h2>GeeksforGeeks</h2> <p>border-radius: 35px;</p> </div></body></html>",
"e": 26781,
"s": 26407,
"text": null
},
{
"code": null,
"e": 26789,
"s": 26781,
"text": "Output:"
},
{
"code": null,
"e": 26947,
"s": 26789,
"text": "border-radius: 20px 40px; This property is used to set first value as top-left and bottom right corner and second value as top right and bottom left corners."
},
{
"code": null,
"e": 27055,
"s": 26947,
"text": "Example: This example illustrates the border-radius property whose value is specified by the double values."
},
{
"code": null,
"e": 27060,
"s": 27055,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Rounded Corners</title> <style> .GFG { border-radius: 20px 40px; background: #009900; padding: 30px; text-align: center; width: 300px; height: 120px; } </style></head> <body> <div class=\"GFG\"> <h2>GeeksforGeeks</h2> <p>border-radius: 20px 40px;</p> </div></body> </html>",
"e": 27480,
"s": 27060,
"text": null
},
{
"code": null,
"e": 27488,
"s": 27480,
"text": "Output:"
},
{
"code": null,
"e": 27686,
"s": 27488,
"text": "border-radius: 20px 40px 60px; This property is used to set first value to top-left corner, second value applied to top-right and bottom left corners and third value applied to bottom right corner."
},
{
"code": null,
"e": 27794,
"s": 27686,
"text": "Example: This example illustrates the border-radius property whose value is specified by the triple values."
},
{
"code": null,
"e": 27799,
"s": 27794,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <title>Rounded Corners</title> <style> .GFG { border-radius: 20px 40px 60px; background: #009900; padding: 30px; text-align: center; width: 300px; height: 120px; } </style></head> <body> <div class=\"GFG\"> <h2>GeeksforGeeks</h2> <p>border-radius: 20px 40px 60px;</p> </div></body></html>",
"e": 28193,
"s": 27799,
"text": null
},
{
"code": null,
"e": 28201,
"s": 28193,
"text": "Output:"
},
{
"code": null,
"e": 28396,
"s": 28201,
"text": "border-radius: 20px 40px 60px 80px; This property is used to set first, second, third and fourth value of border radius to top-left, top-right, bottom-right and bottom-left corners respectively."
},
{
"code": null,
"e": 28502,
"s": 28396,
"text": "Example: This example illustrates the border-radius property whose value is specified by the four values."
},
{
"code": null,
"e": 28507,
"s": 28502,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <title>Rounded Corners</title> <style> .GFG { border-radius: 20px 40px 60px 80px; background: #009900; padding: 30px; text-align: center; width: 300px; height: 120px; } </style></head> <body> <div class=\"GFG\"> <h2>GeeksforGeeks</h2> <p>border-radius: 20px 40px 60px 80px;</p> </div></body></html>",
"e": 28911,
"s": 28507,
"text": null
},
{
"code": null,
"e": 28919,
"s": 28911,
"text": "Output:"
},
{
"code": null,
"e": 29012,
"s": 28919,
"text": "Now, we will understand the shorthand properties for the given below border-radius property."
},
{
"code": null,
"e": 29118,
"s": 29012,
"text": "border-top-left-radius: This property is used to specify the radius of the top left corner of an element."
},
{
"code": null,
"e": 29254,
"s": 29118,
"text": "Example: This example illustrates the border-radius property where the property value is applied for the top left corner of an element."
},
{
"code": null,
"e": 29259,
"s": 29254,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <title>Rounded Corners</title> <style> .GFG { border-top-left-radius: 35px; background: #009900; padding: 30px; text-align: center; width: 300px; height: 120px; } </style></head> <body> <div class=\"GFG\"> <h2>GeeksforGeeks</h2> <p>border-top-left-radius: 35px;</p> </div></body></html>",
"e": 29651,
"s": 29259,
"text": null
},
{
"code": null,
"e": 29659,
"s": 29651,
"text": "Output:"
},
{
"code": null,
"e": 29784,
"s": 29659,
"text": "border-top-right-radius: This property s used to define the radius of the right top corner of the border of a given element."
},
{
"code": null,
"e": 29921,
"s": 29784,
"text": "Example: This example illustrates the border-radius property where the property value is applied for the top-right corner of an element."
},
{
"code": null,
"e": 29926,
"s": 29921,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <title>Rounded Corners</title> <style> .GFG { border-top-right-radius: 35px; background: #009900; padding: 30px; text-align: center; width: 300px; height: 120px; } </style></head> <body> <div class=\"GFG\"> <h2>GeeksforGeeks</h2> <p>border-top-right-radius: 35px;</p> </div></body></html>",
"e": 30320,
"s": 29926,
"text": null
},
{
"code": null,
"e": 30328,
"s": 30320,
"text": "Output:"
},
{
"code": null,
"e": 30489,
"s": 30328,
"text": "border-bottom-left-radius: This property is used to define the radius of the bottom left corner of the border i.e. it makes the bottom-left of the border round."
},
{
"code": null,
"e": 30628,
"s": 30489,
"text": "Example: This example illustrates the border-radius property where the property value is applied for the bottom-left corner of an element."
},
{
"code": null,
"e": 30633,
"s": 30628,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <title>Rounded Corners</title> <style> .GFG { border-bottom-left-radius: 35px; background: #009900; padding: 30px; text-align: center; width: 300px; height: 120px; } </style></head> <body> <div class=\"GFG\"> <h2>GeeksforGeeks</h2> <p>border-bottom-left-radius: 35px;</p> </div></body></html>",
"e": 31031,
"s": 30633,
"text": null
},
{
"code": null,
"e": 31039,
"s": 31031,
"text": "Output:"
},
{
"code": null,
"e": 31171,
"s": 31039,
"text": "border-bottom-right-radius: This property is used to define the radius of the right bottom corner of the border of a given element."
},
{
"code": null,
"e": 31311,
"s": 31171,
"text": "Example: This example illustrates the border-radius property where the property value is applied for the bottom-right corner of an element."
},
{
"code": null,
"e": 31316,
"s": 31311,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <title>Rounded Corners</title> <style> .GFG { border-bottom-right-radius: 35px; background: #009900; padding: 30px; text-align: center; width: 300px; height: 120px; } </style></head> <body> <div class=\"GFG\"> <h2>GeeksforGeeks</h2> <p>border-bottom-right-radius: 35px;</p> </div></body></html>",
"e": 31716,
"s": 31316,
"text": null
},
{
"code": null,
"e": 31724,
"s": 31716,
"text": "Output:"
},
{
"code": null,
"e": 31815,
"s": 31724,
"text": "mixed border-radius property: This property is used to set all corners as the given value."
},
{
"code": null,
"e": 31947,
"s": 31815,
"text": "Example: This example illustrates the border-radius property where the property value is applied for all the corners of an element."
},
{
"code": null,
"e": 31952,
"s": 31947,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <title>Rounded Corners</title> <style> .GFG { border-top-left-radius: 35px; border-top-right-radius: 35px; border-bottom-left-radius: 35px; border-bottom-right-radius: 35px; background: #009900; padding: 30px; text-align: center; width: 300px; height: 120px; } </style></head> <body> <div class=\"GFG\"> <h2>GeeksforGeeks</h2> <p>border-top-left-radius: 35px; <br>border-top-right-radius: 35px; <br>border-bottom-left-radius: 35px; <br>border-bottom-right-radius: 35px;</p> </div></body></html>",
"e": 32606,
"s": 31952,
"text": null
},
{
"code": null,
"e": 32614,
"s": 32606,
"text": "Output:"
},
{
"code": null,
"e": 32626,
"s": 32614,
"text": "Shorthands:"
},
{
"code": null,
"e": 32666,
"s": 32626,
"text": "Apply Radius value to all four corners:"
},
{
"code": null,
"e": 32689,
"s": 32666,
"text": "border-radius: value; "
},
{
"code": null,
"e": 32788,
"s": 32689,
"text": "Apply value1 to top-left and bottom-right corners and value2 to top-right and bottom-left corners:"
},
{
"code": null,
"e": 32819,
"s": 32788,
"text": "border-radius: value1 value2; "
},
{
"code": null,
"e": 32931,
"s": 32819,
"text": "Apply value1 to top-left corner, value2 to top-right and bottom-left corners and value3 to bottom-right corner:"
},
{
"code": null,
"e": 32969,
"s": 32931,
"text": "border-radius: value1 value2 value3; "
},
{
"code": null,
"e": 33095,
"s": 32969,
"text": "Apply value1 to top-left corner, value2 to top-right corner , value3 to bottom-right corner and value4 to bottom-left corner:"
},
{
"code": null,
"e": 33139,
"s": 33095,
"text": "border-radius: value1 value2 value3 value4;"
},
{
"code": null,
"e": 33159,
"s": 33139,
"text": "Supported Browsers:"
},
{
"code": null,
"e": 33191,
"s": 33159,
"text": "Google chrome 5.0, 4.0 -webkit-"
},
{
"code": null,
"e": 33213,
"s": 33191,
"text": "Internet Explorer 9.0"
},
{
"code": null,
"e": 33233,
"s": 33213,
"text": "Microsoft Edge 12.0"
},
{
"code": null,
"e": 33256,
"s": 33233,
"text": "Firefox 4.0, 3.0 -moz-"
},
{
"code": null,
"e": 33267,
"s": 33256,
"text": "Opera 10.5"
},
{
"code": null,
"e": 33292,
"s": 33267,
"text": "Safari 5.0, 3.1 -webkit-"
},
{
"code": null,
"e": 33429,
"s": 33292,
"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": 33444,
"s": 33429,
"text": "motamarriphani"
},
{
"code": null,
"e": 33455,
"s": 33444,
"text": "nidhi_biet"
},
{
"code": null,
"e": 33469,
"s": 33455,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 33490,
"s": 33469,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 33505,
"s": 33490,
"text": "CSS-Properties"
},
{
"code": null,
"e": 33509,
"s": 33505,
"text": "CSS"
},
{
"code": null,
"e": 33514,
"s": 33509,
"text": "HTML"
},
{
"code": null,
"e": 33531,
"s": 33514,
"text": "Web Technologies"
},
{
"code": null,
"e": 33536,
"s": 33531,
"text": "HTML"
},
{
"code": null,
"e": 33634,
"s": 33536,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33684,
"s": 33634,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 33746,
"s": 33684,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 33794,
"s": 33746,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 33852,
"s": 33794,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 33907,
"s": 33852,
"text": "How to apply style to parent if it has child with CSS?"
},
{
"code": null,
"e": 33957,
"s": 33907,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 34019,
"s": 33957,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 34067,
"s": 34019,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 34127,
"s": 34067,
"text": "How to set the default value for an HTML <select> element ?"
}
]
|
Shell Script to Display All Words of a File in Ascending Order - GeeksforGeeks | 19 Jul, 2021
Here we will see a shell script that will arrange all the words from a file in ascending order, which comes in handy when we have many words that need to be sorted in ascending order. The script helps to analyze the data easily and represent it in a much more organized manner.
Approach:
Store the value of the file into a filename variable.Store the words into a TEMP file.Sort the words using the sort command.If TEMP file exists then delete it.
Store the value of the file into a filename variable.
Store the words into a TEMP file.
Sort the words using the sort command.
If TEMP file exists then delete it.
Example:
There is a File named : words.txt which contain the following word,
Input: word.txt.
Word.txt contains: creature, assorted, bent.
Output:
assorted
bent
creature
The Shell Script is given below:
# Shell Script to Display All Words of a File in Ascending Order
# echo is for printing the message
echo -n "Enter name of the file :"
# read file name
read filename
# condition checking if the file exists
# if file do not exists the print "file does not exist"
if [ ! -f $filename ]
then
echo "File does not exist"
else
# in for loop we are comparing the words and storing it in TEMP file
for i in $(cat $filename)
do
echo $i >> "TEMP"
done
# printing the sorted value in ascending order
echo "***SORTED WORDS IN ASCENDING ORDER***"
echo "$(sort "TEMP")"
fi
# condition checking if the TEMP file exists
# if the TEMP file already exists then it will delete it
if [ -f "TEMP" ]
then
rm "TEMP"
fi
Input: words.txt containing 100 words.
Output:
ruhelaa48
Picked
Shell Script
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
curl command in Linux with Examples
Conditional Statements | Shell Script
UDP Server-Client implementation in C
Tail command in Linux with examples
Cat command in Linux with examples
touch command in Linux with Examples
Compiling with g++
echo command in Linux with Examples
ps command in Linux with Examples | [
{
"code": null,
"e": 25269,
"s": 25241,
"text": "\n19 Jul, 2021"
},
{
"code": null,
"e": 25547,
"s": 25269,
"text": "Here we will see a shell script that will arrange all the words from a file in ascending order, which comes in handy when we have many words that need to be sorted in ascending order. The script helps to analyze the data easily and represent it in a much more organized manner."
},
{
"code": null,
"e": 25557,
"s": 25547,
"text": "Approach:"
},
{
"code": null,
"e": 25717,
"s": 25557,
"text": "Store the value of the file into a filename variable.Store the words into a TEMP file.Sort the words using the sort command.If TEMP file exists then delete it."
},
{
"code": null,
"e": 25771,
"s": 25717,
"text": "Store the value of the file into a filename variable."
},
{
"code": null,
"e": 25805,
"s": 25771,
"text": "Store the words into a TEMP file."
},
{
"code": null,
"e": 25844,
"s": 25805,
"text": "Sort the words using the sort command."
},
{
"code": null,
"e": 25880,
"s": 25844,
"text": "If TEMP file exists then delete it."
},
{
"code": null,
"e": 25890,
"s": 25880,
"text": "Example: "
},
{
"code": null,
"e": 25959,
"s": 25890,
"text": "There is a File named : words.txt which contain the following word, "
},
{
"code": null,
"e": 25976,
"s": 25959,
"text": "Input: word.txt."
},
{
"code": null,
"e": 26021,
"s": 25976,
"text": "Word.txt contains: creature, assorted, bent."
},
{
"code": null,
"e": 26030,
"s": 26021,
"text": "Output: "
},
{
"code": null,
"e": 26039,
"s": 26030,
"text": "assorted"
},
{
"code": null,
"e": 26044,
"s": 26039,
"text": "bent"
},
{
"code": null,
"e": 26053,
"s": 26044,
"text": "creature"
},
{
"code": null,
"e": 26086,
"s": 26053,
"text": "The Shell Script is given below:"
},
{
"code": null,
"e": 26788,
"s": 26086,
"text": "# Shell Script to Display All Words of a File in Ascending Order\n# echo is for printing the message\necho -n \"Enter name of the file :\"\n# read file name \nread filename\n# condition checking if the file exists\n# if file do not exists the print \"file does not exist\"\nif [ ! -f $filename ]\nthen\n echo \"File does not exist\"\nelse\n# in for loop we are comparing the words and storing it in TEMP file\nfor i in $(cat $filename)\ndo\n echo $i >> \"TEMP\"\ndone\n# printing the sorted value in ascending order\necho \"***SORTED WORDS IN ASCENDING ORDER***\"\necho \"$(sort \"TEMP\")\"\nfi\n# condition checking if the TEMP file exists\n# if the TEMP file already exists then it will delete it\nif [ -f \"TEMP\" ]\nthen\nrm \"TEMP\"\nfi"
},
{
"code": null,
"e": 26828,
"s": 26788,
"text": "Input: words.txt containing 100 words."
},
{
"code": null,
"e": 26836,
"s": 26828,
"text": "Output:"
},
{
"code": null,
"e": 26846,
"s": 26836,
"text": "ruhelaa48"
},
{
"code": null,
"e": 26853,
"s": 26846,
"text": "Picked"
},
{
"code": null,
"e": 26866,
"s": 26853,
"text": "Shell Script"
},
{
"code": null,
"e": 26877,
"s": 26866,
"text": "Linux-Unix"
},
{
"code": null,
"e": 26975,
"s": 26877,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27013,
"s": 26975,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 27049,
"s": 27013,
"text": "curl command in Linux with Examples"
},
{
"code": null,
"e": 27087,
"s": 27049,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 27125,
"s": 27087,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 27161,
"s": 27125,
"text": "Tail command in Linux with examples"
},
{
"code": null,
"e": 27196,
"s": 27161,
"text": "Cat command in Linux with examples"
},
{
"code": null,
"e": 27233,
"s": 27196,
"text": "touch command in Linux with Examples"
},
{
"code": null,
"e": 27252,
"s": 27233,
"text": "Compiling with g++"
},
{
"code": null,
"e": 27288,
"s": 27252,
"text": "echo command in Linux with Examples"
}
]
|
Longest palindrome subsequence with O(n) space - GeeksforGeeks | CoursesFor Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore MoreFor StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore MoreSchool CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore moreAll Courses
For Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More
LIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore More
DSA Live Classes
System Design
Java Backend Development
Full Stack LIVE
Explore More
Self-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More
DSA- Self Paced
SDE Theory
Must-Do Coding Questions
Explore More
For StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More
LIVECompetitive ProgrammingData Structures with C++Data ScienceExplore More
Competitive Programming
Data Structures with C++
Data Science
Explore More
Self-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More
DSA- Self Paced
CIP
JAVA / Python / C++
Explore More
School CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore more
School Guide
Python Programming
Learn To Make Apps
Explore more
All Courses
TutorialsAlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll AlgorithmsData StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data StructuresInterview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice QuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlinML & Data ScienceMachine LearningData ScienceCS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware EngineeringGATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CSWeb TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftware DesignsSoftware Design PatternsSystem Design TutorialSchool LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesCS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved PapersStudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers
AlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll Algorithms
Analysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity Question
Asymptotic Analysis
Worst, Average and Best Cases
Asymptotic Notations
Little o and little omega notations
Lower and Upper Bound Theory
Analysis of Loops
Solving Recurrences
Amortized Analysis
What does 'Space Complexity' mean ?
Pseudo-polynomial Algorithms
Polynomial Time Approximation Scheme
A Time Complexity Question
Searching Algorithms
Sorting Algorithms
Graph Algorithms
Pattern Searching
Geometric Algorithms
Mathematical
Bitwise Algorithms
Randomized Algorithms
Greedy Algorithms
Dynamic Programming
Divide and Conquer
Backtracking
Branch and Bound
All Algorithms
Data StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data Structures
Arrays
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Hashing
Graph
Advanced Data Structure
Matrix
Strings
All Data Structures
Interview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice Quizzes
Company Preparation
Top Topics
Practice Company Questions
Interview Experiences
Experienced Interviews
Internship Interviews
Competititve Programming
Design Patterns
System Design Tutorial
Multiple Choice Quizzes
LanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlin
C
C++
Java
Python
C#
JavaScript
jQuery
SQL
PHP
Scala
Perl
Go Language
HTML
CSS
Kotlin
ML & Data ScienceMachine LearningData Science
Machine Learning
Data Science
CS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware Engineering
Mathematics
Operating System
DBMS
Computer Networks
Computer Organization and Architecture
Theory of Computation
Compiler Design
Digital Logic
Software Engineering
GATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CS
GATE Computer Science Notes
Last Minute Notes
GATE CS Solved Papers
GATE CS Original Papers and Official Keys
GATE 2021 Dates
GATE CS 2021 Syllabus
Important Topics for GATE CS
Web TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHP
HTML
CSS
JavaScript
AngularJS
ReactJS
NodeJS
Bootstrap
jQuery
PHP
Software DesignsSoftware Design PatternsSystem Design Tutorial
Software Design Patterns
System Design Tutorial
School LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes
School Programming
MathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculus
Number System
Algebra
Trigonometry
Statistics
Probability
Geometry
Mensuration
Calculus
Maths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 12 Notes
NCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
RD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Physics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
CS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers
ISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer Exam
ISRO CS Original Papers and Official Keys
ISRO CS Solved Papers
ISRO CS Syllabus for Scientist/Engineer Exam
UGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers
UGC NET CS Notes Paper II
UGC NET CS Notes Paper III
UGC NET CS Solved Papers
StudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers
Campus Ambassador Program
School Ambassador Program
Project
Geek of the Month
Campus Geek of the Month
Placement Course
Competititve Programming
Testimonials
Student Chapter
Geek on the Top
Internship
Careers
JobsApply for JobsPost a JobJOB-A-THON
Apply for Jobs
Post a Job
JOB-A-THON
PracticeAll DSA ProblemsProblem of the DayInterview Series: Weekly ContestsBi-Wizard Coding: School ContestsContests and EventsPractice SDE SheetCurated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems
All DSA Problems
Problem of the Day
Interview Series: Weekly Contests
Bi-Wizard Coding: School Contests
Contests and Events
Practice SDE Sheet
Curated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems
Top 50 Array Problems
Top 50 String Problems
Top 50 Tree Problems
Top 50 Graph Problems
Top 50 DP Problems
WriteCome write articles for us and get featuredPracticeLearn and code with the best industry expertsPremiumGet access to ad-free content, doubt assistance and more!JobsCome and find your dream job with usGeeks DigestQuizzesGeeks CampusGblog ArticlesIDECampus Mantri
Geeks Digest
Quizzes
Geeks Campus
Gblog Articles
IDE
Campus Mantri
Sign In
Sign In
Home
Saved Videos
Courses
For Working Professionals
LIVE
DSA Live Classes
System Design
Java Backend Development
Full Stack LIVE
Explore More
Self-Paced
DSA- Self Paced
SDE Theory
Must-Do Coding Questions
Explore More
For Students
LIVE
Competitive Programming
Data Structures with C++
Data Science
Explore More
Self-Paced
DSA- Self Paced
CIP
JAVA / Python / C++
Explore More
School Courses
School Guide
Python Programming
Learn To Make Apps
Explore more
Algorithms
Searching Algorithms
Sorting Algorithms
Graph Algorithms
Pattern Searching
Geometric Algorithms
Mathematical
Bitwise Algorithms
Randomized Algorithms
Greedy Algorithms
Dynamic Programming
Divide and Conquer
Backtracking
Branch and Bound
All Algorithms
Analysis of Algorithms
Asymptotic Analysis
Worst, Average and Best Cases
Asymptotic Notations
Little o and little omega notations
Lower and Upper Bound Theory
Analysis of Loops
Solving Recurrences
Amortized Analysis
What does 'Space Complexity' mean ?
Pseudo-polynomial Algorithms
Polynomial Time Approximation Scheme
A Time Complexity Question
Data Structures
Arrays
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Hashing
Graph
Advanced Data Structure
Matrix
Strings
All Data Structures
Interview Corner
Company Preparation
Top Topics
Practice Company Questions
Interview Experiences
Experienced Interviews
Internship Interviews
Competititve Programming
Design Patterns
System Design Tutorial
Multiple Choice Quizzes
Languages
C
C++
Java
Python
C#
JavaScript
jQuery
SQL
PHP
Scala
Perl
Go Language
HTML
CSS
Kotlin
ML & Data Science
Machine Learning
Data Science
CS Subjects
Mathematics
Operating System
DBMS
Computer Networks
Computer Organization and Architecture
Theory of Computation
Compiler Design
Digital Logic
Software Engineering
GATE
GATE Computer Science Notes
Last Minute Notes
GATE CS Solved Papers
GATE CS Original Papers and Official Keys
GATE 2021 Dates
GATE CS 2021 Syllabus
Important Topics for GATE CS
Web Technologies
HTML
CSS
JavaScript
AngularJS
ReactJS
NodeJS
Bootstrap
jQuery
PHP
Software Designs
Software Design Patterns
System Design Tutorial
School Learning
School Programming
Mathematics
Number System
Algebra
Trigonometry
Statistics
Probability
Geometry
Mensuration
Calculus
Maths Notes (Class 8-12)
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 12 Notes
NCERT Solutions
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
RD Sharma Solutions
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Physics Notes (Class 8-11)
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
CS Exams/PSUs
ISRO
ISRO CS Original Papers and Official Keys
ISRO CS Solved Papers
ISRO CS Syllabus for Scientist/Engineer Exam
UGC NET
UGC NET CS Notes Paper II
UGC NET CS Notes Paper III
UGC NET CS Solved Papers
Student
Campus Ambassador Program
School Ambassador Program
Project
Geek of the Month
Campus Geek of the Month
Placement Course
Competititve Programming
Testimonials
Student Chapter
Geek on the Top
Internship
Careers
Curated DSA Lists
Top 50 Array Problems
Top 50 String Problems
Top 50 Tree Problems
Top 50 Graph Problems
Top 50 DP Problems
Tutorials
Jobs
Apply for Jobs
Post a Job
JOB-A-THON
Practice
All DSA Problems
Problem of the Day
Interview Series: Weekly Contests
Bi-Wizard Coding: School Contests
Contests and Events
Practice SDE Sheet
For Working Professionals
LIVE
DSA Live Classes
System Design
Java Backend Development
Full Stack LIVE
Explore More
DSA Live Classes
System Design
Java Backend Development
Full Stack LIVE
Explore More
Self-Paced
DSA- Self Paced
SDE Theory
Must-Do Coding Questions
Explore More
DSA- Self Paced
SDE Theory
Must-Do Coding Questions
Explore More
For Students
LIVE
Competitive Programming
Data Structures with C++
Data Science
Explore More
Competitive Programming
Data Structures with C++
Data Science
Explore More
Self-Paced
DSA- Self Paced
CIP
JAVA / Python / C++
Explore More
DSA- Self Paced
CIP
JAVA / Python / C++
Explore More
School Courses
School Guide
Python Programming
Learn To Make Apps
Explore more
School Guide
Python Programming
Learn To Make Apps
Explore more
Algorithms
Searching Algorithms
Sorting Algorithms
Graph Algorithms
Pattern Searching
Geometric Algorithms
Mathematical
Bitwise Algorithms
Randomized Algorithms
Greedy Algorithms
Dynamic Programming
Divide and Conquer
Backtracking
Branch and Bound
All Algorithms
Searching Algorithms
Sorting Algorithms
Graph Algorithms
Pattern Searching
Geometric Algorithms
Mathematical
Bitwise Algorithms
Randomized Algorithms
Greedy Algorithms
Dynamic Programming
Divide and Conquer
Backtracking
Branch and Bound
All Algorithms
Analysis of Algorithms
Asymptotic Analysis
Worst, Average and Best Cases
Asymptotic Notations
Little o and little omega notations
Lower and Upper Bound Theory
Analysis of Loops
Solving Recurrences
Amortized Analysis
What does 'Space Complexity' mean ?
Pseudo-polynomial Algorithms
Polynomial Time Approximation Scheme
A Time Complexity Question
Asymptotic Analysis
Worst, Average and Best Cases
Asymptotic Notations
Little o and little omega notations
Lower and Upper Bound Theory
Analysis of Loops
Solving Recurrences
Amortized Analysis
What does 'Space Complexity' mean ?
Pseudo-polynomial Algorithms
Polynomial Time Approximation Scheme
A Time Complexity Question
Data Structures
Arrays
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Hashing
Graph
Advanced Data Structure
Matrix
Strings
All Data Structures
Arrays
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Hashing
Graph
Advanced Data Structure
Matrix
Strings
All Data Structures
Interview Corner
Company Preparation
Top Topics
Practice Company Questions
Interview Experiences
Experienced Interviews
Internship Interviews
Competititve Programming
Design Patterns
System Design Tutorial
Multiple Choice Quizzes
Company Preparation
Top Topics
Practice Company Questions
Interview Experiences
Experienced Interviews
Internship Interviews
Competititve Programming
Design Patterns
System Design Tutorial
Multiple Choice Quizzes
Languages
C
C++
Java
Python
C#
JavaScript
jQuery
SQL
PHP
Scala
Perl
Go Language
HTML
CSS
Kotlin
C
C++
Java
Python
C#
JavaScript
jQuery
SQL
PHP
Scala
Perl
Go Language
HTML
CSS
Kotlin
ML & Data Science
Machine Learning
Data Science
Machine Learning
Data Science
CS Subjects
Mathematics
Operating System
DBMS
Computer Networks
Computer Organization and Architecture
Theory of Computation
Compiler Design
Digital Logic
Software Engineering
Mathematics
Operating System
DBMS
Computer Networks
Computer Organization and Architecture
Theory of Computation
Compiler Design
Digital Logic
Software Engineering
GATE
GATE Computer Science Notes
Last Minute Notes
GATE CS Solved Papers
GATE CS Original Papers and Official Keys
GATE 2021 Dates
GATE CS 2021 Syllabus
Important Topics for GATE CS
GATE Computer Science Notes
Last Minute Notes
GATE CS Solved Papers
GATE CS Original Papers and Official Keys
GATE 2021 Dates
GATE CS 2021 Syllabus
Important Topics for GATE CS
Web Technologies
HTML
CSS
JavaScript
AngularJS
ReactJS
NodeJS
Bootstrap
jQuery
PHP
HTML
CSS
JavaScript
AngularJS
ReactJS
NodeJS
Bootstrap
jQuery
PHP
Software Designs
Software Design Patterns
System Design Tutorial
Software Design Patterns
System Design Tutorial
School Learning
School Programming
School Programming
Mathematics
Number System
Algebra
Trigonometry
Statistics
Probability
Geometry
Mensuration
Calculus
Number System
Algebra
Trigonometry
Statistics
Probability
Geometry
Mensuration
Calculus
Maths Notes (Class 8-12)
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 12 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 12 Notes
NCERT Solutions
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
RD Sharma Solutions
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Physics Notes (Class 8-11)
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
CS Exams/PSUs
ISRO
ISRO CS Original Papers and Official Keys
ISRO CS Solved Papers
ISRO CS Syllabus for Scientist/Engineer Exam
ISRO CS Original Papers and Official Keys
ISRO CS Solved Papers
ISRO CS Syllabus for Scientist/Engineer Exam
UGC NET
UGC NET CS Notes Paper II
UGC NET CS Notes Paper III
UGC NET CS Solved Papers
UGC NET CS Notes Paper II
UGC NET CS Notes Paper III
UGC NET CS Solved Papers
Student
Campus Ambassador Program
School Ambassador Program
Project
Geek of the Month
Campus Geek of the Month
Placement Course
Competititve Programming
Testimonials
Student Chapter
Geek on the Top
Internship
Careers
Campus Ambassador Program
School Ambassador Program
Project
Geek of the Month
Campus Geek of the Month
Placement Course
Competititve Programming
Testimonials
Student Chapter
Geek on the Top
Internship
Careers
Curated DSA Lists
Top 50 Array Problems
Top 50 String Problems
Top 50 Tree Problems
Top 50 Graph Problems
Top 50 DP Problems
Top 50 Array Problems
Top 50 String Problems
Top 50 Tree Problems
Top 50 Graph Problems
Top 50 DP Problems
Tutorials
Jobs
Apply for Jobs
Post a Job
JOB-A-THON
Apply for Jobs
Post a Job
JOB-A-THON
Practice
All DSA Problems
Problem of the Day
Interview Series: Weekly Contests
Bi-Wizard Coding: School Contests
Contests and Events
Practice SDE Sheet
All DSA Problems
Problem of the Day
Interview Series: Weekly Contests
Bi-Wizard Coding: School Contests
Contests and Events
Practice SDE Sheet
GBlog
Puzzles
What's New ?
Array
Matrix
Strings
Hashing
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Graph
Searching
Sorting
Divide & Conquer
Mathematical
Geometric
Bitwise
Greedy
Backtracking
Branch and Bound
Dynamic Programming
Pattern Searching
Randomized
Program for Fibonacci numbers
0-1 Knapsack Problem | DP-10
Largest Sum Contiguous Subarray
Longest Common Subsequence | DP-4
Longest Increasing Subsequence | DP-3
Coin Change | DP-7
Subset Sum Problem | DP-25
Longest Palindromic Substring | Set 1
Sieve of Eratosthenes
Bellman–Ford Algorithm | DP-23
Matrix Chain Multiplication | DP-8
Floyd Warshall Algorithm | DP-16
Minimum number of jumps to reach end
Efficient program to print all prime factors of a given number
Edit Distance | DP-5
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Find minimum number of coins that make a given value
Top 20 Dynamic Programming Interview Questions
Overlapping Subproblems Property in Dynamic Programming | DP-1
Cutting a Rod | DP-13
Longest Common Substring | DP-29
Tabulation vs Memoization
Longest Palindromic Subsequence | DP-12
Program for nth Catalan Number
Partition a set into two subsets such that the difference of subset sums is minimum
Egg Dropping Puzzle | DP-11
Count all possible paths from top left to bottom right of a mXn matrix
Count ways to reach the n'th stair
Longest Increasing Subsequence Size (N log N)
Partition problem | DP-18
Program for Fibonacci numbers
0-1 Knapsack Problem | DP-10
Largest Sum Contiguous Subarray
Longest Common Subsequence | DP-4
Longest Increasing Subsequence | DP-3
Coin Change | DP-7
Subset Sum Problem | DP-25
Longest Palindromic Substring | Set 1
Sieve of Eratosthenes
Bellman–Ford Algorithm | DP-23
Matrix Chain Multiplication | DP-8
Floyd Warshall Algorithm | DP-16
Minimum number of jumps to reach end
Efficient program to print all prime factors of a given number
Edit Distance | DP-5
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Find minimum number of coins that make a given value
Top 20 Dynamic Programming Interview Questions
Overlapping Subproblems Property in Dynamic Programming | DP-1
Cutting a Rod | DP-13
Longest Common Substring | DP-29
Tabulation vs Memoization
Longest Palindromic Subsequence | DP-12
Program for nth Catalan Number
Partition a set into two subsets such that the difference of subset sums is minimum
Egg Dropping Puzzle | DP-11
Count all possible paths from top left to bottom right of a mXn matrix
Count ways to reach the n'th stair
Longest Increasing Subsequence Size (N log N)
Partition problem | DP-18
Difficulty Level :
Hard
Given a sequence, find the length of the longest palindromic subsequence in it.
Examples:
Input : abbaab
Output : 4
Input : geeksforgeeks
Output : 5
We have discussed a Dynamic Programming solution for Longest Palindromic Subsequence which is based on below recursive formula.
// Every single character is a palindrome of length 1L(i, i) = 1 for all indexes i in given sequence
// IF first and last characters are not sameIf (X[i] != X[j]) L(i, j) = max{L(i + 1, j), L(i, j – 1)}
// If there are only 2 characters and both are sameElse if (j == i + 1) L(i, j) = 2
// If there are more than two characters, and first// and last characters are sameElse L(i, j) = L(i + 1, j – 1) + 2
The solution discussed above takes O(n2) extra space. In this post a space optimized solution is discussed that requires O(n) extra space. The idea is to create a one dimensional array a[] of same size as given string. We make sure that a[i] stores length of longest palindromic subsequence of prefix ending with i (or substring s[0..i]).
C++
Java
Python3
C#
PHP
// A Space optimized Dynamic Programming based C++// program for LPS problem#include <bits/stdc++.h>using namespace std; // Returns the length of the longest palindromic// subsequence in strint lps(string &s){ int n = s.length(); // a[i] is going to store length of longest // palindromic subsequence of substring s[0..i] int a[n]; // Pick starting point for (int i = n - 1; i >= 0; i--) { int back_up = 0; // Pick ending points and see if s[i] // increases length of longest common // subsequence ending with s[j]. for (int j = i; j < n; j++) { // similar to 2D array L[i][j] == 1 // i.e., handling substrings of length // one. if (j == i) a[j] = 1; // Similar to 2D array L[i][j] = L[i+1][j-1]+2 // i.e., handling case when corner characters // are same. else if (s[i] == s[j]) { // value a[j] is depend upon previous // unupdated value of a[j-1] but in // previous loop value of a[j-1] is // changed. To store the unupdated // value of a[j-1] back_up variable // is used. int temp = a[j]; a[j] = back_up + 2; back_up = temp; } // similar to 2D array L[i][j] = max(L[i][j-1], // a[i+1][j]) else { back_up = a[j]; a[j] = max(a[j - 1], a[j]); } } } return a[n - 1];} /* Driver program to test above functions */int main(){ string str = "GEEKSFORGEEKS"; cout << lps(str); return 0;}
// A Space optimized Dynamic Programming // based Java program for LPS problem class GFG { // Returns the length of the longest // palindromic subsequence in str static int lps(String s) { int n = s.length(); // a[i] is going to store length // of longest palindromic subsequence // of substring s[0..i] int a[] = new int[n]; // Pick starting point for (int i = n - 1; i >= 0; i--) { int back_up = 0; // Pick ending points and see if s[i] // increases length of longest common // subsequence ending with s[j]. for (int j = i; j < n; j++) { // similar to 2D array L[i][j] == 1 // i.e., handling substrings of length // one. if (j == i) a[j] = 1; // Similar to 2D array L[i][j] = L[i+1][j-1]+2 // i.e., handling case when corner characters // are same. else if (s.charAt(i) == s.charAt(j)) { int temp = a[j]; a[j] = back_up + 2; back_up = temp; } // similar to 2D array L[i][j] = max(L[i][j-1], // a[i+1][j]) else { back_up = a[j]; a[j] = Math.max(a[j - 1], a[j]); } } } return a[n - 1]; } /* Driver program to test above functions */ public static void main(String[] args) { String str = "GEEKSFORGEEKS"; System.out.println(lps(str)); }} //This article is contributed by prerna saini.
# A Space optimized Dynamic Programming # based Python3 program for LPS problem # Returns the length of the longest # palindromic subsequence in strdef lps(s): n = len(s) # a[i] is going to store length # of longest palindromic subsequence # of substring s[0..i] a = [0] * n # Pick starting point for i in range(n-1, -1, -1): back_up = 0 # Pick ending points and see if s[i] # increases length of longest common # subsequence ending with s[j]. for j in range(i, n): # similar to 2D array L[i][j] == 1 # i.e., handling substrings of length # one. if j == i: a[j] = 1 # Similar to 2D array L[i][j] = L[i+1][j-1]+2 # i.e., handling case when corner characters # are same. elif s[i] == s[j]: temp = a[j] a[j] = back_up + 2 back_up = temp # similar to 2D array L[i][j] = max(L[i][j-1], # a[i+1][j]) else: back_up = a[j] a[j] = max(a[j - 1], a[j]) return a[n - 1] # Driver Codestring = "GEEKSFORGEEKS"print(lps(string)) # This code is contributed by Ansu Kumari.
// A Space optimized Dynamic Programming // based C# program for LPS problemusing System; class GFG { // Returns the length of the longest // palindromic subsequence in str static int lps(string s) { int n = s.Length; // a[i] is going to store length // of longest palindromic subsequence // of substring s[0..i] int []a = new int[n]; // Pick starting point for (int i = n - 1; i >= 0; i--) { int back_up = 0; // Pick ending points and see if s[i] // increases length of longest common // subsequence ending with s[j]. for (int j = i; j < n; j++) { // similar to 2D array L[i][j] == 1 // i.e., handling substrings of length // one. if (j == i) a[j] = 1; // Similar to 2D array L[i][j] = L[i+1][j-1]+2 // i.e., handling case when corner characters // are same. else if (s[i] == s[j]) { int temp = a[j]; a[j] = back_up + 2; back_up = temp; } // similar to 2D array L[i][j] = max(L[i][j-1], // a[i+1][j]) else { back_up = a[j]; a[j] = Math.Max(a[j - 1], a[j]); } } } return a[n - 1]; } // Driver program public static void Main() { string str = "GEEKSFORGEEKS"; Console.WriteLine(lps(str)); }} // This code is contributed by vt_m.
<?php// A Space optimized Dynamic// Programming based PHP// program for LPS problem // Returns the length of // the longest palindromic .// subsequence in strfunction lps($s){ $n = strlen($s); // Pick starting point for ($i = $n - 1; $i >= 0; $i--) { $back_up = 0; // Pick ending points and // see if s[i] increases // length of longest common // subsequence ending with s[j]. for ($j = $i; $j < $n; $j++) { // similar to 2D array // L[i][j] == 1 i.e., // handling substrings // of length one. if ($j == $i) $a[$j] = 1; // Similar to 2D array // L[i][j] = L[i+1][j-1]+2 // i.e., handling case when // corner characters are same. else if ($s[$i] == $s[$j]) { // value a[j] is depend // upon previous unupdated // value of a[j-1] but in // previous loop value of // a[j-1] is changed. To // store the unupdated value // of a[j-1] back_up variable // is used. $temp = $a[$j]; $a[$j] = $back_up + 2; $back_up = $temp; } // similar to 2D array // L[i][j] = max(L[i][j-1], // a[i+1][j]) else { $back_up = $a[$j]; $a[$j] = max($a[$j - 1], $a[$j]); } } } return $a[$n - 1];} // Driver Code$str = "GEEKSFORGEEKS";echo lps($str); // This code is contributed// by shiv_bhakt.?>
5
Time Complexity : O(n*n)Auxiliary Space : O(n)YouTubeGeeksforGeeks507K subscribersLongest palindrome subsequence with O(n) space | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 6:08•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=i1o6rlqiSZM" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Vishal_Khoda
palindrome
subsequence
Dynamic Programming
Strings
Strings
Dynamic Programming
palindrome
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum size square sub-matrix with all 1s
Optimal Substructure Property in Dynamic Programming | DP-2
Optimal Binary Search Tree | DP-24
Min Cost Path | DP-6
Maximum Subarray Sum using Divide and Conquer algorithm
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": 419,
"s": 0,
"text": "CoursesFor Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore MoreFor StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore MoreSchool CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore moreAll Courses"
},
{
"code": null,
"e": 600,
"s": 419,
"text": "For Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More"
},
{
"code": null,
"e": 685,
"s": 600,
"text": "LIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore More"
},
{
"code": null,
"e": 702,
"s": 685,
"text": "DSA Live Classes"
},
{
"code": null,
"e": 716,
"s": 702,
"text": "System Design"
},
{
"code": null,
"e": 741,
"s": 716,
"text": "Java Backend Development"
},
{
"code": null,
"e": 757,
"s": 741,
"text": "Full Stack LIVE"
},
{
"code": null,
"e": 770,
"s": 757,
"text": "Explore More"
},
{
"code": null,
"e": 842,
"s": 770,
"text": "Self-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More"
},
{
"code": null,
"e": 858,
"s": 842,
"text": "DSA- Self Paced"
},
{
"code": null,
"e": 869,
"s": 858,
"text": "SDE Theory"
},
{
"code": null,
"e": 894,
"s": 869,
"text": "Must-Do Coding Questions"
},
{
"code": null,
"e": 907,
"s": 894,
"text": "Explore More"
},
{
"code": null,
"e": 1054,
"s": 907,
"text": "For StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More"
},
{
"code": null,
"e": 1130,
"s": 1054,
"text": "LIVECompetitive ProgrammingData Structures with C++Data ScienceExplore More"
},
{
"code": null,
"e": 1154,
"s": 1130,
"text": "Competitive Programming"
},
{
"code": null,
"e": 1179,
"s": 1154,
"text": "Data Structures with C++"
},
{
"code": null,
"e": 1192,
"s": 1179,
"text": "Data Science"
},
{
"code": null,
"e": 1205,
"s": 1192,
"text": "Explore More"
},
{
"code": null,
"e": 1265,
"s": 1205,
"text": "Self-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More"
},
{
"code": null,
"e": 1281,
"s": 1265,
"text": "DSA- Self Paced"
},
{
"code": null,
"e": 1285,
"s": 1281,
"text": "CIP"
},
{
"code": null,
"e": 1305,
"s": 1285,
"text": "JAVA / Python / C++"
},
{
"code": null,
"e": 1318,
"s": 1305,
"text": "Explore More"
},
{
"code": null,
"e": 1393,
"s": 1318,
"text": "School CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore more"
},
{
"code": null,
"e": 1406,
"s": 1393,
"text": "School Guide"
},
{
"code": null,
"e": 1425,
"s": 1406,
"text": "Python Programming"
},
{
"code": null,
"e": 1444,
"s": 1425,
"text": "Learn To Make Apps"
},
{
"code": null,
"e": 1457,
"s": 1444,
"text": "Explore more"
},
{
"code": null,
"e": 1469,
"s": 1457,
"text": "All Courses"
},
{
"code": null,
"e": 3985,
"s": 1469,
"text": "TutorialsAlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll AlgorithmsData StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data StructuresInterview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice QuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlinML & Data ScienceMachine LearningData ScienceCS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware EngineeringGATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CSWeb TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftware DesignsSoftware Design PatternsSystem Design TutorialSchool LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesCS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved PapersStudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers"
},
{
"code": null,
"e": 4566,
"s": 3985,
"text": "AlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll Algorithms"
},
{
"code": null,
"e": 4899,
"s": 4566,
"text": "Analysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity Question"
},
{
"code": null,
"e": 4919,
"s": 4899,
"text": "Asymptotic Analysis"
},
{
"code": null,
"e": 4949,
"s": 4919,
"text": "Worst, Average and Best Cases"
},
{
"code": null,
"e": 4970,
"s": 4949,
"text": "Asymptotic Notations"
},
{
"code": null,
"e": 5006,
"s": 4970,
"text": "Little o and little omega notations"
},
{
"code": null,
"e": 5035,
"s": 5006,
"text": "Lower and Upper Bound Theory"
},
{
"code": null,
"e": 5053,
"s": 5035,
"text": "Analysis of Loops"
},
{
"code": null,
"e": 5073,
"s": 5053,
"text": "Solving Recurrences"
},
{
"code": null,
"e": 5092,
"s": 5073,
"text": "Amortized Analysis"
},
{
"code": null,
"e": 5128,
"s": 5092,
"text": "What does 'Space Complexity' mean ?"
},
{
"code": null,
"e": 5157,
"s": 5128,
"text": "Pseudo-polynomial Algorithms"
},
{
"code": null,
"e": 5194,
"s": 5157,
"text": "Polynomial Time Approximation Scheme"
},
{
"code": null,
"e": 5221,
"s": 5194,
"text": "A Time Complexity Question"
},
{
"code": null,
"e": 5242,
"s": 5221,
"text": "Searching Algorithms"
},
{
"code": null,
"e": 5261,
"s": 5242,
"text": "Sorting Algorithms"
},
{
"code": null,
"e": 5278,
"s": 5261,
"text": "Graph Algorithms"
},
{
"code": null,
"e": 5296,
"s": 5278,
"text": "Pattern Searching"
},
{
"code": null,
"e": 5317,
"s": 5296,
"text": "Geometric Algorithms"
},
{
"code": null,
"e": 5330,
"s": 5317,
"text": "Mathematical"
},
{
"code": null,
"e": 5349,
"s": 5330,
"text": "Bitwise Algorithms"
},
{
"code": null,
"e": 5371,
"s": 5349,
"text": "Randomized Algorithms"
},
{
"code": null,
"e": 5389,
"s": 5371,
"text": "Greedy Algorithms"
},
{
"code": null,
"e": 5409,
"s": 5389,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 5428,
"s": 5409,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 5441,
"s": 5428,
"text": "Backtracking"
},
{
"code": null,
"e": 5458,
"s": 5441,
"text": "Branch and Bound"
},
{
"code": null,
"e": 5473,
"s": 5458,
"text": "All Algorithms"
},
{
"code": null,
"e": 5616,
"s": 5473,
"text": "Data StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data Structures"
},
{
"code": null,
"e": 5623,
"s": 5616,
"text": "Arrays"
},
{
"code": null,
"e": 5635,
"s": 5623,
"text": "Linked List"
},
{
"code": null,
"e": 5641,
"s": 5635,
"text": "Stack"
},
{
"code": null,
"e": 5647,
"s": 5641,
"text": "Queue"
},
{
"code": null,
"e": 5659,
"s": 5647,
"text": "Binary Tree"
},
{
"code": null,
"e": 5678,
"s": 5659,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 5683,
"s": 5678,
"text": "Heap"
},
{
"code": null,
"e": 5691,
"s": 5683,
"text": "Hashing"
},
{
"code": null,
"e": 5697,
"s": 5691,
"text": "Graph"
},
{
"code": null,
"e": 5721,
"s": 5697,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 5728,
"s": 5721,
"text": "Matrix"
},
{
"code": null,
"e": 5736,
"s": 5728,
"text": "Strings"
},
{
"code": null,
"e": 5756,
"s": 5736,
"text": "All Data Structures"
},
{
"code": null,
"e": 5976,
"s": 5756,
"text": "Interview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice Quizzes"
},
{
"code": null,
"e": 5996,
"s": 5976,
"text": "Company Preparation"
},
{
"code": null,
"e": 6007,
"s": 5996,
"text": "Top Topics"
},
{
"code": null,
"e": 6034,
"s": 6007,
"text": "Practice Company Questions"
},
{
"code": null,
"e": 6056,
"s": 6034,
"text": "Interview Experiences"
},
{
"code": null,
"e": 6079,
"s": 6056,
"text": "Experienced Interviews"
},
{
"code": null,
"e": 6101,
"s": 6079,
"text": "Internship Interviews"
},
{
"code": null,
"e": 6126,
"s": 6101,
"text": "Competititve Programming"
},
{
"code": null,
"e": 6142,
"s": 6126,
"text": "Design Patterns"
},
{
"code": null,
"e": 6165,
"s": 6142,
"text": "System Design Tutorial"
},
{
"code": null,
"e": 6189,
"s": 6165,
"text": "Multiple Choice Quizzes"
},
{
"code": null,
"e": 6270,
"s": 6189,
"text": "LanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlin"
},
{
"code": null,
"e": 6272,
"s": 6270,
"text": "C"
},
{
"code": null,
"e": 6276,
"s": 6272,
"text": "C++"
},
{
"code": null,
"e": 6281,
"s": 6276,
"text": "Java"
},
{
"code": null,
"e": 6288,
"s": 6281,
"text": "Python"
},
{
"code": null,
"e": 6291,
"s": 6288,
"text": "C#"
},
{
"code": null,
"e": 6302,
"s": 6291,
"text": "JavaScript"
},
{
"code": null,
"e": 6309,
"s": 6302,
"text": "jQuery"
},
{
"code": null,
"e": 6313,
"s": 6309,
"text": "SQL"
},
{
"code": null,
"e": 6317,
"s": 6313,
"text": "PHP"
},
{
"code": null,
"e": 6323,
"s": 6317,
"text": "Scala"
},
{
"code": null,
"e": 6328,
"s": 6323,
"text": "Perl"
},
{
"code": null,
"e": 6340,
"s": 6328,
"text": "Go Language"
},
{
"code": null,
"e": 6345,
"s": 6340,
"text": "HTML"
},
{
"code": null,
"e": 6349,
"s": 6345,
"text": "CSS"
},
{
"code": null,
"e": 6356,
"s": 6349,
"text": "Kotlin"
},
{
"code": null,
"e": 6402,
"s": 6356,
"text": "ML & Data ScienceMachine LearningData Science"
},
{
"code": null,
"e": 6419,
"s": 6402,
"text": "Machine Learning"
},
{
"code": null,
"e": 6432,
"s": 6419,
"text": "Data Science"
},
{
"code": null,
"e": 6599,
"s": 6432,
"text": "CS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware Engineering"
},
{
"code": null,
"e": 6611,
"s": 6599,
"text": "Mathematics"
},
{
"code": null,
"e": 6628,
"s": 6611,
"text": "Operating System"
},
{
"code": null,
"e": 6633,
"s": 6628,
"text": "DBMS"
},
{
"code": null,
"e": 6651,
"s": 6633,
"text": "Computer Networks"
},
{
"code": null,
"e": 6690,
"s": 6651,
"text": "Computer Organization and Architecture"
},
{
"code": null,
"e": 6712,
"s": 6690,
"text": "Theory of Computation"
},
{
"code": null,
"e": 6728,
"s": 6712,
"text": "Compiler Design"
},
{
"code": null,
"e": 6742,
"s": 6728,
"text": "Digital Logic"
},
{
"code": null,
"e": 6763,
"s": 6742,
"text": "Software Engineering"
},
{
"code": null,
"e": 6938,
"s": 6763,
"text": "GATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CS"
},
{
"code": null,
"e": 6966,
"s": 6938,
"text": "GATE Computer Science Notes"
},
{
"code": null,
"e": 6984,
"s": 6966,
"text": "Last Minute Notes"
},
{
"code": null,
"e": 7006,
"s": 6984,
"text": "GATE CS Solved Papers"
},
{
"code": null,
"e": 7048,
"s": 7006,
"text": "GATE CS Original Papers and Official Keys"
},
{
"code": null,
"e": 7064,
"s": 7048,
"text": "GATE 2021 Dates"
},
{
"code": null,
"e": 7086,
"s": 7064,
"text": "GATE CS 2021 Syllabus"
},
{
"code": null,
"e": 7115,
"s": 7086,
"text": "Important Topics for GATE CS"
},
{
"code": null,
"e": 7189,
"s": 7115,
"text": "Web TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHP"
},
{
"code": null,
"e": 7194,
"s": 7189,
"text": "HTML"
},
{
"code": null,
"e": 7198,
"s": 7194,
"text": "CSS"
},
{
"code": null,
"e": 7209,
"s": 7198,
"text": "JavaScript"
},
{
"code": null,
"e": 7219,
"s": 7209,
"text": "AngularJS"
},
{
"code": null,
"e": 7227,
"s": 7219,
"text": "ReactJS"
},
{
"code": null,
"e": 7234,
"s": 7227,
"text": "NodeJS"
},
{
"code": null,
"e": 7244,
"s": 7234,
"text": "Bootstrap"
},
{
"code": null,
"e": 7251,
"s": 7244,
"text": "jQuery"
},
{
"code": null,
"e": 7255,
"s": 7251,
"text": "PHP"
},
{
"code": null,
"e": 7318,
"s": 7255,
"text": "Software DesignsSoftware Design PatternsSystem Design Tutorial"
},
{
"code": null,
"e": 7343,
"s": 7318,
"text": "Software Design Patterns"
},
{
"code": null,
"e": 7366,
"s": 7343,
"text": "System Design Tutorial"
},
{
"code": null,
"e": 7923,
"s": 7366,
"text": "School LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes"
},
{
"code": null,
"e": 7942,
"s": 7923,
"text": "School Programming"
},
{
"code": null,
"e": 8034,
"s": 7942,
"text": "MathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculus"
},
{
"code": null,
"e": 8048,
"s": 8034,
"text": "Number System"
},
{
"code": null,
"e": 8056,
"s": 8048,
"text": "Algebra"
},
{
"code": null,
"e": 8069,
"s": 8056,
"text": "Trigonometry"
},
{
"code": null,
"e": 8080,
"s": 8069,
"text": "Statistics"
},
{
"code": null,
"e": 8092,
"s": 8080,
"text": "Probability"
},
{
"code": null,
"e": 8101,
"s": 8092,
"text": "Geometry"
},
{
"code": null,
"e": 8113,
"s": 8101,
"text": "Mensuration"
},
{
"code": null,
"e": 8122,
"s": 8113,
"text": "Calculus"
},
{
"code": null,
"e": 8215,
"s": 8122,
"text": "Maths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 Notes"
},
{
"code": null,
"e": 8229,
"s": 8215,
"text": "Class 8 Notes"
},
{
"code": null,
"e": 8243,
"s": 8229,
"text": "Class 9 Notes"
},
{
"code": null,
"e": 8258,
"s": 8243,
"text": "Class 10 Notes"
},
{
"code": null,
"e": 8273,
"s": 8258,
"text": "Class 11 Notes"
},
{
"code": null,
"e": 8288,
"s": 8273,
"text": "Class 12 Notes"
},
{
"code": null,
"e": 8417,
"s": 8288,
"text": "NCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution"
},
{
"code": null,
"e": 8440,
"s": 8417,
"text": "Class 8 Maths Solution"
},
{
"code": null,
"e": 8463,
"s": 8440,
"text": "Class 9 Maths Solution"
},
{
"code": null,
"e": 8487,
"s": 8463,
"text": "Class 10 Maths Solution"
},
{
"code": null,
"e": 8511,
"s": 8487,
"text": "Class 11 Maths Solution"
},
{
"code": null,
"e": 8535,
"s": 8511,
"text": "Class 12 Maths Solution"
},
{
"code": null,
"e": 8668,
"s": 8535,
"text": "RD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution"
},
{
"code": null,
"e": 8691,
"s": 8668,
"text": "Class 8 Maths Solution"
},
{
"code": null,
"e": 8714,
"s": 8691,
"text": "Class 9 Maths Solution"
},
{
"code": null,
"e": 8738,
"s": 8714,
"text": "Class 10 Maths Solution"
},
{
"code": null,
"e": 8762,
"s": 8738,
"text": "Class 11 Maths Solution"
},
{
"code": null,
"e": 8786,
"s": 8762,
"text": "Class 12 Maths Solution"
},
{
"code": null,
"e": 8867,
"s": 8786,
"text": "Physics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes"
},
{
"code": null,
"e": 8881,
"s": 8867,
"text": "Class 8 Notes"
},
{
"code": null,
"e": 8895,
"s": 8881,
"text": "Class 9 Notes"
},
{
"code": null,
"e": 8910,
"s": 8895,
"text": "Class 10 Notes"
},
{
"code": null,
"e": 8925,
"s": 8910,
"text": "Class 11 Notes"
},
{
"code": null,
"e": 9131,
"s": 8925,
"text": "CS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers"
},
{
"code": null,
"e": 9242,
"s": 9131,
"text": "ISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer Exam"
},
{
"code": null,
"e": 9284,
"s": 9242,
"text": "ISRO CS Original Papers and Official Keys"
},
{
"code": null,
"e": 9306,
"s": 9284,
"text": "ISRO CS Solved Papers"
},
{
"code": null,
"e": 9351,
"s": 9306,
"text": "ISRO CS Syllabus for Scientist/Engineer Exam"
},
{
"code": null,
"e": 9434,
"s": 9351,
"text": "UGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers"
},
{
"code": null,
"e": 9460,
"s": 9434,
"text": "UGC NET CS Notes Paper II"
},
{
"code": null,
"e": 9487,
"s": 9460,
"text": "UGC NET CS Notes Paper III"
},
{
"code": null,
"e": 9512,
"s": 9487,
"text": "UGC NET CS Solved Papers"
},
{
"code": null,
"e": 9717,
"s": 9512,
"text": "StudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers"
},
{
"code": null,
"e": 9743,
"s": 9717,
"text": "Campus Ambassador Program"
},
{
"code": null,
"e": 9769,
"s": 9743,
"text": "School Ambassador Program"
},
{
"code": null,
"e": 9777,
"s": 9769,
"text": "Project"
},
{
"code": null,
"e": 9795,
"s": 9777,
"text": "Geek of the Month"
},
{
"code": null,
"e": 9820,
"s": 9795,
"text": "Campus Geek of the Month"
},
{
"code": null,
"e": 9837,
"s": 9820,
"text": "Placement Course"
},
{
"code": null,
"e": 9862,
"s": 9837,
"text": "Competititve Programming"
},
{
"code": null,
"e": 9875,
"s": 9862,
"text": "Testimonials"
},
{
"code": null,
"e": 9891,
"s": 9875,
"text": "Student Chapter"
},
{
"code": null,
"e": 9907,
"s": 9891,
"text": "Geek on the Top"
},
{
"code": null,
"e": 9918,
"s": 9907,
"text": "Internship"
},
{
"code": null,
"e": 9926,
"s": 9918,
"text": "Careers"
},
{
"code": null,
"e": 9965,
"s": 9926,
"text": "JobsApply for JobsPost a JobJOB-A-THON"
},
{
"code": null,
"e": 9980,
"s": 9965,
"text": "Apply for Jobs"
},
{
"code": null,
"e": 9991,
"s": 9980,
"text": "Post a Job"
},
{
"code": null,
"e": 10002,
"s": 9991,
"text": "JOB-A-THON"
},
{
"code": null,
"e": 10267,
"s": 10002,
"text": "PracticeAll DSA ProblemsProblem of the DayInterview Series: Weekly ContestsBi-Wizard Coding: School ContestsContests and EventsPractice SDE SheetCurated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems"
},
{
"code": null,
"e": 10284,
"s": 10267,
"text": "All DSA Problems"
},
{
"code": null,
"e": 10303,
"s": 10284,
"text": "Problem of the Day"
},
{
"code": null,
"e": 10337,
"s": 10303,
"text": "Interview Series: Weekly Contests"
},
{
"code": null,
"e": 10371,
"s": 10337,
"text": "Bi-Wizard Coding: School Contests"
},
{
"code": null,
"e": 10391,
"s": 10371,
"text": "Contests and Events"
},
{
"code": null,
"e": 10410,
"s": 10391,
"text": "Practice SDE Sheet"
},
{
"code": null,
"e": 10530,
"s": 10410,
"text": "Curated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems"
},
{
"code": null,
"e": 10552,
"s": 10530,
"text": "Top 50 Array Problems"
},
{
"code": null,
"e": 10575,
"s": 10552,
"text": "Top 50 String Problems"
},
{
"code": null,
"e": 10596,
"s": 10575,
"text": "Top 50 Tree Problems"
},
{
"code": null,
"e": 10618,
"s": 10596,
"text": "Top 50 Graph Problems"
},
{
"code": null,
"e": 10637,
"s": 10618,
"text": "Top 50 DP Problems"
},
{
"code": null,
"e": 10908,
"s": 10641,
"text": "WriteCome write articles for us and get featuredPracticeLearn and code with the best industry expertsPremiumGet access to ad-free content, doubt assistance and more!JobsCome and find your dream job with usGeeks DigestQuizzesGeeks CampusGblog ArticlesIDECampus Mantri"
},
{
"code": null,
"e": 10921,
"s": 10908,
"text": "Geeks Digest"
},
{
"code": null,
"e": 10929,
"s": 10921,
"text": "Quizzes"
},
{
"code": null,
"e": 10942,
"s": 10929,
"text": "Geeks Campus"
},
{
"code": null,
"e": 10957,
"s": 10942,
"text": "Gblog Articles"
},
{
"code": null,
"e": 10961,
"s": 10957,
"text": "IDE"
},
{
"code": null,
"e": 10975,
"s": 10961,
"text": "Campus Mantri"
},
{
"code": null,
"e": 10983,
"s": 10975,
"text": "Sign In"
},
{
"code": null,
"e": 10991,
"s": 10983,
"text": "Sign In"
},
{
"code": null,
"e": 10996,
"s": 10991,
"text": "Home"
},
{
"code": null,
"e": 11009,
"s": 10996,
"text": "Saved Videos"
},
{
"code": null,
"e": 11017,
"s": 11009,
"text": "Courses"
},
{
"code": null,
"e": 15482,
"s": 11017,
"text": "\n\nFor Working Professionals\n \n\n\n\nLIVE\n \n\n\nDSA Live Classes\n\nSystem Design\n\nJava Backend Development\n\nFull Stack LIVE\n\nExplore More\n\n\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nSDE Theory\n\nMust-Do Coding Questions\n\nExplore More\n\n\nFor Students\n \n\n\n\nLIVE\n \n\n\nCompetitive Programming\n\nData Structures with C++\n\nData Science\n\nExplore More\n\n\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nCIP\n\nJAVA / Python / C++\n\nExplore More\n\n\nSchool Courses\n \n\n\nSchool Guide\n\nPython Programming\n\nLearn To Make Apps\n\nExplore more\n\n\nAlgorithms\n \n\n\nSearching Algorithms\n\nSorting Algorithms\n\nGraph Algorithms\n\nPattern Searching\n\nGeometric Algorithms\n\nMathematical\n\nBitwise Algorithms\n\nRandomized Algorithms\n\nGreedy Algorithms\n\nDynamic Programming\n\nDivide and Conquer\n\nBacktracking\n\nBranch and Bound\n\nAll Algorithms\n\n\nAnalysis of Algorithms\n \n\n\nAsymptotic Analysis\n\nWorst, Average and Best Cases\n\nAsymptotic Notations\n\nLittle o and little omega notations\n\nLower and Upper Bound Theory\n\nAnalysis of Loops\n\nSolving Recurrences\n\nAmortized Analysis\n\nWhat does 'Space Complexity' mean ?\n\nPseudo-polynomial Algorithms\n\nPolynomial Time Approximation Scheme\n\nA Time Complexity Question\n\n\nData Structures\n \n\n\nArrays\n\nLinked List\n\nStack\n\nQueue\n\nBinary Tree\n\nBinary Search Tree\n\nHeap\n\nHashing\n\nGraph\n\nAdvanced Data Structure\n\nMatrix\n\nStrings\n\nAll Data Structures\n\n\nInterview Corner\n \n\n\nCompany Preparation\n\nTop Topics\n\nPractice Company Questions\n\nInterview Experiences\n\nExperienced Interviews\n\nInternship Interviews\n\nCompetititve Programming\n\nDesign Patterns\n\nSystem Design Tutorial\n\nMultiple Choice Quizzes\n\n\nLanguages\n \n\n\nC\n\nC++\n\nJava\n\nPython\n\nC#\n\nJavaScript\n\njQuery\n\nSQL\n\nPHP\n\nScala\n\nPerl\n\nGo Language\n\nHTML\n\nCSS\n\nKotlin\n\n\nML & Data Science\n \n\n\nMachine Learning\n\nData Science\n\n\nCS Subjects\n \n\n\nMathematics\n\nOperating System\n\nDBMS\n\nComputer Networks\n\nComputer Organization and Architecture\n\nTheory of Computation\n\nCompiler Design\n\nDigital Logic\n\nSoftware Engineering\n\n\nGATE\n \n\n\nGATE Computer Science Notes\n\nLast Minute Notes\n\nGATE CS Solved Papers\n\nGATE CS Original Papers and Official Keys\n\nGATE 2021 Dates\n\nGATE CS 2021 Syllabus\n\nImportant Topics for GATE CS\n\n\nWeb Technologies\n \n\n\nHTML\n\nCSS\n\nJavaScript\n\nAngularJS\n\nReactJS\n\nNodeJS\n\nBootstrap\n\njQuery\n\nPHP\n\n\nSoftware Designs\n \n\n\nSoftware Design Patterns\n\nSystem Design Tutorial\n\n\nSchool Learning\n \n\n\nSchool Programming\n\n\nMathematics\n \n\n\nNumber System\n\nAlgebra\n\nTrigonometry\n\nStatistics\n\nProbability\n\nGeometry\n\nMensuration\n\nCalculus\n\n\nMaths Notes (Class 8-12)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n\nClass 12 Notes\n\n\nNCERT Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n\n\nRD Sharma Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n\n\nPhysics Notes (Class 8-11)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n\n\nCS Exams/PSUs\n \n\n\n\nISRO\n \n\n\nISRO CS Original Papers and Official Keys\n\nISRO CS Solved Papers\n\nISRO CS Syllabus for Scientist/Engineer Exam\n\n\nUGC NET\n \n\n\nUGC NET CS Notes Paper II\n\nUGC NET CS Notes Paper III\n\nUGC NET CS Solved Papers\n\n\nStudent\n \n\n\nCampus Ambassador Program\n\nSchool Ambassador Program\n\nProject\n\nGeek of the Month\n\nCampus Geek of the Month\n\nPlacement Course\n\nCompetititve Programming\n\nTestimonials\n\nStudent Chapter\n\nGeek on the Top\n\nInternship\n\nCareers\n\n\nCurated DSA Lists\n \n\n\nTop 50 Array Problems\n\nTop 50 String Problems\n\nTop 50 Tree Problems\n\nTop 50 Graph Problems\n\nTop 50 DP Problems\n\n\nTutorials\n \n\n\n\nJobs\n \n\n\nApply for Jobs\n\nPost a Job\n\nJOB-A-THON\n\n\nPractice\n \n\n\nAll DSA Problems\n\nProblem of the Day\n\nInterview Series: Weekly Contests\n\nBi-Wizard Coding: School Contests\n\nContests and Events\n\nPractice SDE Sheet\n"
},
{
"code": null,
"e": 15536,
"s": 15482,
"text": "\nFor Working Professionals\n \n\n"
},
{
"code": null,
"e": 15659,
"s": 15536,
"text": "\nLIVE\n \n\n\nDSA Live Classes\n\nSystem Design\n\nJava Backend Development\n\nFull Stack LIVE\n\nExplore More\n"
},
{
"code": null,
"e": 15678,
"s": 15659,
"text": "\nDSA Live Classes\n"
},
{
"code": null,
"e": 15694,
"s": 15678,
"text": "\nSystem Design\n"
},
{
"code": null,
"e": 15721,
"s": 15694,
"text": "\nJava Backend Development\n"
},
{
"code": null,
"e": 15739,
"s": 15721,
"text": "\nFull Stack LIVE\n"
},
{
"code": null,
"e": 15754,
"s": 15739,
"text": "\nExplore More\n"
},
{
"code": null,
"e": 15862,
"s": 15754,
"text": "\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nSDE Theory\n\nMust-Do Coding Questions\n\nExplore More\n"
},
{
"code": null,
"e": 15880,
"s": 15862,
"text": "\nDSA- Self Paced\n"
},
{
"code": null,
"e": 15893,
"s": 15880,
"text": "\nSDE Theory\n"
},
{
"code": null,
"e": 15920,
"s": 15893,
"text": "\nMust-Do Coding Questions\n"
},
{
"code": null,
"e": 15935,
"s": 15920,
"text": "\nExplore More\n"
},
{
"code": null,
"e": 15976,
"s": 15935,
"text": "\nFor Students\n \n\n"
},
{
"code": null,
"e": 16088,
"s": 15976,
"text": "\nLIVE\n \n\n\nCompetitive Programming\n\nData Structures with C++\n\nData Science\n\nExplore More\n"
},
{
"code": null,
"e": 16114,
"s": 16088,
"text": "\nCompetitive Programming\n"
},
{
"code": null,
"e": 16141,
"s": 16114,
"text": "\nData Structures with C++\n"
},
{
"code": null,
"e": 16156,
"s": 16141,
"text": "\nData Science\n"
},
{
"code": null,
"e": 16171,
"s": 16156,
"text": "\nExplore More\n"
},
{
"code": null,
"e": 16267,
"s": 16171,
"text": "\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nCIP\n\nJAVA / Python / C++\n\nExplore More\n"
},
{
"code": null,
"e": 16285,
"s": 16267,
"text": "\nDSA- Self Paced\n"
},
{
"code": null,
"e": 16291,
"s": 16285,
"text": "\nCIP\n"
},
{
"code": null,
"e": 16313,
"s": 16291,
"text": "\nJAVA / Python / C++\n"
},
{
"code": null,
"e": 16328,
"s": 16313,
"text": "\nExplore More\n"
},
{
"code": null,
"e": 16439,
"s": 16328,
"text": "\nSchool Courses\n \n\n\nSchool Guide\n\nPython Programming\n\nLearn To Make Apps\n\nExplore more\n"
},
{
"code": null,
"e": 16454,
"s": 16439,
"text": "\nSchool Guide\n"
},
{
"code": null,
"e": 16475,
"s": 16454,
"text": "\nPython Programming\n"
},
{
"code": null,
"e": 16496,
"s": 16475,
"text": "\nLearn To Make Apps\n"
},
{
"code": null,
"e": 16511,
"s": 16496,
"text": "\nExplore more\n"
},
{
"code": null,
"e": 16816,
"s": 16511,
"text": "\nAlgorithms\n \n\n\nSearching Algorithms\n\nSorting Algorithms\n\nGraph Algorithms\n\nPattern Searching\n\nGeometric Algorithms\n\nMathematical\n\nBitwise Algorithms\n\nRandomized Algorithms\n\nGreedy Algorithms\n\nDynamic Programming\n\nDivide and Conquer\n\nBacktracking\n\nBranch and Bound\n\nAll Algorithms\n"
},
{
"code": null,
"e": 16839,
"s": 16816,
"text": "\nSearching Algorithms\n"
},
{
"code": null,
"e": 16860,
"s": 16839,
"text": "\nSorting Algorithms\n"
},
{
"code": null,
"e": 16879,
"s": 16860,
"text": "\nGraph Algorithms\n"
},
{
"code": null,
"e": 16899,
"s": 16879,
"text": "\nPattern Searching\n"
},
{
"code": null,
"e": 16922,
"s": 16899,
"text": "\nGeometric Algorithms\n"
},
{
"code": null,
"e": 16937,
"s": 16922,
"text": "\nMathematical\n"
},
{
"code": null,
"e": 16958,
"s": 16937,
"text": "\nBitwise Algorithms\n"
},
{
"code": null,
"e": 16982,
"s": 16958,
"text": "\nRandomized Algorithms\n"
},
{
"code": null,
"e": 17002,
"s": 16982,
"text": "\nGreedy Algorithms\n"
},
{
"code": null,
"e": 17024,
"s": 17002,
"text": "\nDynamic Programming\n"
},
{
"code": null,
"e": 17045,
"s": 17024,
"text": "\nDivide and Conquer\n"
},
{
"code": null,
"e": 17060,
"s": 17045,
"text": "\nBacktracking\n"
},
{
"code": null,
"e": 17079,
"s": 17060,
"text": "\nBranch and Bound\n"
},
{
"code": null,
"e": 17096,
"s": 17079,
"text": "\nAll Algorithms\n"
},
{
"code": null,
"e": 17481,
"s": 17096,
"text": "\nAnalysis of Algorithms\n \n\n\nAsymptotic Analysis\n\nWorst, Average and Best Cases\n\nAsymptotic Notations\n\nLittle o and little omega notations\n\nLower and Upper Bound Theory\n\nAnalysis of Loops\n\nSolving Recurrences\n\nAmortized Analysis\n\nWhat does 'Space Complexity' mean ?\n\nPseudo-polynomial Algorithms\n\nPolynomial Time Approximation Scheme\n\nA Time Complexity Question\n"
},
{
"code": null,
"e": 17503,
"s": 17481,
"text": "\nAsymptotic Analysis\n"
},
{
"code": null,
"e": 17535,
"s": 17503,
"text": "\nWorst, Average and Best Cases\n"
},
{
"code": null,
"e": 17558,
"s": 17535,
"text": "\nAsymptotic Notations\n"
},
{
"code": null,
"e": 17596,
"s": 17558,
"text": "\nLittle o and little omega notations\n"
},
{
"code": null,
"e": 17627,
"s": 17596,
"text": "\nLower and Upper Bound Theory\n"
},
{
"code": null,
"e": 17647,
"s": 17627,
"text": "\nAnalysis of Loops\n"
},
{
"code": null,
"e": 17669,
"s": 17647,
"text": "\nSolving Recurrences\n"
},
{
"code": null,
"e": 17690,
"s": 17669,
"text": "\nAmortized Analysis\n"
},
{
"code": null,
"e": 17728,
"s": 17690,
"text": "\nWhat does 'Space Complexity' mean ?\n"
},
{
"code": null,
"e": 17759,
"s": 17728,
"text": "\nPseudo-polynomial Algorithms\n"
},
{
"code": null,
"e": 17798,
"s": 17759,
"text": "\nPolynomial Time Approximation Scheme\n"
},
{
"code": null,
"e": 17827,
"s": 17798,
"text": "\nA Time Complexity Question\n"
},
{
"code": null,
"e": 18024,
"s": 17827,
"text": "\nData Structures\n \n\n\nArrays\n\nLinked List\n\nStack\n\nQueue\n\nBinary Tree\n\nBinary Search Tree\n\nHeap\n\nHashing\n\nGraph\n\nAdvanced Data Structure\n\nMatrix\n\nStrings\n\nAll Data Structures\n"
},
{
"code": null,
"e": 18033,
"s": 18024,
"text": "\nArrays\n"
},
{
"code": null,
"e": 18047,
"s": 18033,
"text": "\nLinked List\n"
},
{
"code": null,
"e": 18055,
"s": 18047,
"text": "\nStack\n"
},
{
"code": null,
"e": 18063,
"s": 18055,
"text": "\nQueue\n"
},
{
"code": null,
"e": 18077,
"s": 18063,
"text": "\nBinary Tree\n"
},
{
"code": null,
"e": 18098,
"s": 18077,
"text": "\nBinary Search Tree\n"
},
{
"code": null,
"e": 18105,
"s": 18098,
"text": "\nHeap\n"
},
{
"code": null,
"e": 18115,
"s": 18105,
"text": "\nHashing\n"
},
{
"code": null,
"e": 18123,
"s": 18115,
"text": "\nGraph\n"
},
{
"code": null,
"e": 18149,
"s": 18123,
"text": "\nAdvanced Data Structure\n"
},
{
"code": null,
"e": 18158,
"s": 18149,
"text": "\nMatrix\n"
},
{
"code": null,
"e": 18168,
"s": 18158,
"text": "\nStrings\n"
},
{
"code": null,
"e": 18190,
"s": 18168,
"text": "\nAll Data Structures\n"
},
{
"code": null,
"e": 18458,
"s": 18190,
"text": "\nInterview Corner\n \n\n\nCompany Preparation\n\nTop Topics\n\nPractice Company Questions\n\nInterview Experiences\n\nExperienced Interviews\n\nInternship Interviews\n\nCompetititve Programming\n\nDesign Patterns\n\nSystem Design Tutorial\n\nMultiple Choice Quizzes\n"
},
{
"code": null,
"e": 18480,
"s": 18458,
"text": "\nCompany Preparation\n"
},
{
"code": null,
"e": 18493,
"s": 18480,
"text": "\nTop Topics\n"
},
{
"code": null,
"e": 18522,
"s": 18493,
"text": "\nPractice Company Questions\n"
},
{
"code": null,
"e": 18546,
"s": 18522,
"text": "\nInterview Experiences\n"
},
{
"code": null,
"e": 18571,
"s": 18546,
"text": "\nExperienced Interviews\n"
},
{
"code": null,
"e": 18595,
"s": 18571,
"text": "\nInternship Interviews\n"
},
{
"code": null,
"e": 18622,
"s": 18595,
"text": "\nCompetititve Programming\n"
},
{
"code": null,
"e": 18640,
"s": 18622,
"text": "\nDesign Patterns\n"
},
{
"code": null,
"e": 18665,
"s": 18640,
"text": "\nSystem Design Tutorial\n"
},
{
"code": null,
"e": 18691,
"s": 18665,
"text": "\nMultiple Choice Quizzes\n"
},
{
"code": null,
"e": 18830,
"s": 18691,
"text": "\nLanguages\n \n\n\nC\n\nC++\n\nJava\n\nPython\n\nC#\n\nJavaScript\n\njQuery\n\nSQL\n\nPHP\n\nScala\n\nPerl\n\nGo Language\n\nHTML\n\nCSS\n\nKotlin\n"
},
{
"code": null,
"e": 18834,
"s": 18830,
"text": "\nC\n"
},
{
"code": null,
"e": 18840,
"s": 18834,
"text": "\nC++\n"
},
{
"code": null,
"e": 18847,
"s": 18840,
"text": "\nJava\n"
},
{
"code": null,
"e": 18856,
"s": 18847,
"text": "\nPython\n"
},
{
"code": null,
"e": 18861,
"s": 18856,
"text": "\nC#\n"
},
{
"code": null,
"e": 18874,
"s": 18861,
"text": "\nJavaScript\n"
},
{
"code": null,
"e": 18883,
"s": 18874,
"text": "\njQuery\n"
},
{
"code": null,
"e": 18889,
"s": 18883,
"text": "\nSQL\n"
},
{
"code": null,
"e": 18895,
"s": 18889,
"text": "\nPHP\n"
},
{
"code": null,
"e": 18903,
"s": 18895,
"text": "\nScala\n"
},
{
"code": null,
"e": 18910,
"s": 18903,
"text": "\nPerl\n"
},
{
"code": null,
"e": 18924,
"s": 18910,
"text": "\nGo Language\n"
},
{
"code": null,
"e": 18931,
"s": 18924,
"text": "\nHTML\n"
},
{
"code": null,
"e": 18937,
"s": 18931,
"text": "\nCSS\n"
},
{
"code": null,
"e": 18946,
"s": 18937,
"text": "\nKotlin\n"
},
{
"code": null,
"e": 19024,
"s": 18946,
"text": "\nML & Data Science\n \n\n\nMachine Learning\n\nData Science\n"
},
{
"code": null,
"e": 19043,
"s": 19024,
"text": "\nMachine Learning\n"
},
{
"code": null,
"e": 19058,
"s": 19043,
"text": "\nData Science\n"
},
{
"code": null,
"e": 19271,
"s": 19058,
"text": "\nCS Subjects\n \n\n\nMathematics\n\nOperating System\n\nDBMS\n\nComputer Networks\n\nComputer Organization and Architecture\n\nTheory of Computation\n\nCompiler Design\n\nDigital Logic\n\nSoftware Engineering\n"
},
{
"code": null,
"e": 19285,
"s": 19271,
"text": "\nMathematics\n"
},
{
"code": null,
"e": 19304,
"s": 19285,
"text": "\nOperating System\n"
},
{
"code": null,
"e": 19311,
"s": 19304,
"text": "\nDBMS\n"
},
{
"code": null,
"e": 19331,
"s": 19311,
"text": "\nComputer Networks\n"
},
{
"code": null,
"e": 19372,
"s": 19331,
"text": "\nComputer Organization and Architecture\n"
},
{
"code": null,
"e": 19396,
"s": 19372,
"text": "\nTheory of Computation\n"
},
{
"code": null,
"e": 19414,
"s": 19396,
"text": "\nCompiler Design\n"
},
{
"code": null,
"e": 19430,
"s": 19414,
"text": "\nDigital Logic\n"
},
{
"code": null,
"e": 19453,
"s": 19430,
"text": "\nSoftware Engineering\n"
},
{
"code": null,
"e": 19670,
"s": 19453,
"text": "\nGATE\n \n\n\nGATE Computer Science Notes\n\nLast Minute Notes\n\nGATE CS Solved Papers\n\nGATE CS Original Papers and Official Keys\n\nGATE 2021 Dates\n\nGATE CS 2021 Syllabus\n\nImportant Topics for GATE CS\n"
},
{
"code": null,
"e": 19700,
"s": 19670,
"text": "\nGATE Computer Science Notes\n"
},
{
"code": null,
"e": 19720,
"s": 19700,
"text": "\nLast Minute Notes\n"
},
{
"code": null,
"e": 19744,
"s": 19720,
"text": "\nGATE CS Solved Papers\n"
},
{
"code": null,
"e": 19788,
"s": 19744,
"text": "\nGATE CS Original Papers and Official Keys\n"
},
{
"code": null,
"e": 19806,
"s": 19788,
"text": "\nGATE 2021 Dates\n"
},
{
"code": null,
"e": 19830,
"s": 19806,
"text": "\nGATE CS 2021 Syllabus\n"
},
{
"code": null,
"e": 19861,
"s": 19830,
"text": "\nImportant Topics for GATE CS\n"
},
{
"code": null,
"e": 19981,
"s": 19861,
"text": "\nWeb Technologies\n \n\n\nHTML\n\nCSS\n\nJavaScript\n\nAngularJS\n\nReactJS\n\nNodeJS\n\nBootstrap\n\njQuery\n\nPHP\n"
},
{
"code": null,
"e": 19988,
"s": 19981,
"text": "\nHTML\n"
},
{
"code": null,
"e": 19994,
"s": 19988,
"text": "\nCSS\n"
},
{
"code": null,
"e": 20007,
"s": 19994,
"text": "\nJavaScript\n"
},
{
"code": null,
"e": 20019,
"s": 20007,
"text": "\nAngularJS\n"
},
{
"code": null,
"e": 20029,
"s": 20019,
"text": "\nReactJS\n"
},
{
"code": null,
"e": 20038,
"s": 20029,
"text": "\nNodeJS\n"
},
{
"code": null,
"e": 20050,
"s": 20038,
"text": "\nBootstrap\n"
},
{
"code": null,
"e": 20059,
"s": 20050,
"text": "\njQuery\n"
},
{
"code": null,
"e": 20065,
"s": 20059,
"text": "\nPHP\n"
},
{
"code": null,
"e": 20160,
"s": 20065,
"text": "\nSoftware Designs\n \n\n\nSoftware Design Patterns\n\nSystem Design Tutorial\n"
},
{
"code": null,
"e": 20187,
"s": 20160,
"text": "\nSoftware Design Patterns\n"
},
{
"code": null,
"e": 20212,
"s": 20187,
"text": "\nSystem Design Tutorial\n"
},
{
"code": null,
"e": 20276,
"s": 20212,
"text": "\nSchool Learning\n \n\n\nSchool Programming\n"
},
{
"code": null,
"e": 20297,
"s": 20276,
"text": "\nSchool Programming\n"
},
{
"code": null,
"e": 20433,
"s": 20297,
"text": "\nMathematics\n \n\n\nNumber System\n\nAlgebra\n\nTrigonometry\n\nStatistics\n\nProbability\n\nGeometry\n\nMensuration\n\nCalculus\n"
},
{
"code": null,
"e": 20449,
"s": 20433,
"text": "\nNumber System\n"
},
{
"code": null,
"e": 20459,
"s": 20449,
"text": "\nAlgebra\n"
},
{
"code": null,
"e": 20474,
"s": 20459,
"text": "\nTrigonometry\n"
},
{
"code": null,
"e": 20487,
"s": 20474,
"text": "\nStatistics\n"
},
{
"code": null,
"e": 20501,
"s": 20487,
"text": "\nProbability\n"
},
{
"code": null,
"e": 20512,
"s": 20501,
"text": "\nGeometry\n"
},
{
"code": null,
"e": 20526,
"s": 20512,
"text": "\nMensuration\n"
},
{
"code": null,
"e": 20537,
"s": 20526,
"text": "\nCalculus\n"
},
{
"code": null,
"e": 20668,
"s": 20537,
"text": "\nMaths Notes (Class 8-12)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n\nClass 12 Notes\n"
},
{
"code": null,
"e": 20684,
"s": 20668,
"text": "\nClass 8 Notes\n"
},
{
"code": null,
"e": 20700,
"s": 20684,
"text": "\nClass 9 Notes\n"
},
{
"code": null,
"e": 20717,
"s": 20700,
"text": "\nClass 10 Notes\n"
},
{
"code": null,
"e": 20734,
"s": 20717,
"text": "\nClass 11 Notes\n"
},
{
"code": null,
"e": 20751,
"s": 20734,
"text": "\nClass 12 Notes\n"
},
{
"code": null,
"e": 20918,
"s": 20751,
"text": "\nNCERT Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n"
},
{
"code": null,
"e": 20943,
"s": 20918,
"text": "\nClass 8 Maths Solution\n"
},
{
"code": null,
"e": 20968,
"s": 20943,
"text": "\nClass 9 Maths Solution\n"
},
{
"code": null,
"e": 20994,
"s": 20968,
"text": "\nClass 10 Maths Solution\n"
},
{
"code": null,
"e": 21020,
"s": 20994,
"text": "\nClass 11 Maths Solution\n"
},
{
"code": null,
"e": 21046,
"s": 21020,
"text": "\nClass 12 Maths Solution\n"
},
{
"code": null,
"e": 21217,
"s": 21046,
"text": "\nRD Sharma Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n"
},
{
"code": null,
"e": 21242,
"s": 21217,
"text": "\nClass 8 Maths Solution\n"
},
{
"code": null,
"e": 21267,
"s": 21242,
"text": "\nClass 9 Maths Solution\n"
},
{
"code": null,
"e": 21293,
"s": 21267,
"text": "\nClass 10 Maths Solution\n"
},
{
"code": null,
"e": 21319,
"s": 21293,
"text": "\nClass 11 Maths Solution\n"
},
{
"code": null,
"e": 21345,
"s": 21319,
"text": "\nClass 12 Maths Solution\n"
},
{
"code": null,
"e": 21462,
"s": 21345,
"text": "\nPhysics Notes (Class 8-11)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n"
},
{
"code": null,
"e": 21478,
"s": 21462,
"text": "\nClass 8 Notes\n"
},
{
"code": null,
"e": 21494,
"s": 21478,
"text": "\nClass 9 Notes\n"
},
{
"code": null,
"e": 21511,
"s": 21494,
"text": "\nClass 10 Notes\n"
},
{
"code": null,
"e": 21528,
"s": 21511,
"text": "\nClass 11 Notes\n"
},
{
"code": null,
"e": 21570,
"s": 21528,
"text": "\nCS Exams/PSUs\n \n\n"
},
{
"code": null,
"e": 21715,
"s": 21570,
"text": "\nISRO\n \n\n\nISRO CS Original Papers and Official Keys\n\nISRO CS Solved Papers\n\nISRO CS Syllabus for Scientist/Engineer Exam\n"
},
{
"code": null,
"e": 21759,
"s": 21715,
"text": "\nISRO CS Original Papers and Official Keys\n"
},
{
"code": null,
"e": 21783,
"s": 21759,
"text": "\nISRO CS Solved Papers\n"
},
{
"code": null,
"e": 21830,
"s": 21783,
"text": "\nISRO CS Syllabus for Scientist/Engineer Exam\n"
},
{
"code": null,
"e": 21947,
"s": 21830,
"text": "\nUGC NET\n \n\n\nUGC NET CS Notes Paper II\n\nUGC NET CS Notes Paper III\n\nUGC NET CS Solved Papers\n"
},
{
"code": null,
"e": 21975,
"s": 21947,
"text": "\nUGC NET CS Notes Paper II\n"
},
{
"code": null,
"e": 22004,
"s": 21975,
"text": "\nUGC NET CS Notes Paper III\n"
},
{
"code": null,
"e": 22031,
"s": 22004,
"text": "\nUGC NET CS Solved Papers\n"
},
{
"code": null,
"e": 22288,
"s": 22031,
"text": "\nStudent\n \n\n\nCampus Ambassador Program\n\nSchool Ambassador Program\n\nProject\n\nGeek of the Month\n\nCampus Geek of the Month\n\nPlacement Course\n\nCompetititve Programming\n\nTestimonials\n\nStudent Chapter\n\nGeek on the Top\n\nInternship\n\nCareers\n"
},
{
"code": null,
"e": 22316,
"s": 22288,
"text": "\nCampus Ambassador Program\n"
},
{
"code": null,
"e": 22344,
"s": 22316,
"text": "\nSchool Ambassador Program\n"
},
{
"code": null,
"e": 22354,
"s": 22344,
"text": "\nProject\n"
},
{
"code": null,
"e": 22374,
"s": 22354,
"text": "\nGeek of the Month\n"
},
{
"code": null,
"e": 22401,
"s": 22374,
"text": "\nCampus Geek of the Month\n"
},
{
"code": null,
"e": 22420,
"s": 22401,
"text": "\nPlacement Course\n"
},
{
"code": null,
"e": 22447,
"s": 22420,
"text": "\nCompetititve Programming\n"
},
{
"code": null,
"e": 22462,
"s": 22447,
"text": "\nTestimonials\n"
},
{
"code": null,
"e": 22480,
"s": 22462,
"text": "\nStudent Chapter\n"
},
{
"code": null,
"e": 22498,
"s": 22480,
"text": "\nGeek on the Top\n"
},
{
"code": null,
"e": 22511,
"s": 22498,
"text": "\nInternship\n"
},
{
"code": null,
"e": 22521,
"s": 22511,
"text": "\nCareers\n"
},
{
"code": null,
"e": 22679,
"s": 22521,
"text": "\nCurated DSA Lists\n \n\n\nTop 50 Array Problems\n\nTop 50 String Problems\n\nTop 50 Tree Problems\n\nTop 50 Graph Problems\n\nTop 50 DP Problems\n"
},
{
"code": null,
"e": 22703,
"s": 22679,
"text": "\nTop 50 Array Problems\n"
},
{
"code": null,
"e": 22728,
"s": 22703,
"text": "\nTop 50 String Problems\n"
},
{
"code": null,
"e": 22751,
"s": 22728,
"text": "\nTop 50 Tree Problems\n"
},
{
"code": null,
"e": 22775,
"s": 22751,
"text": "\nTop 50 Graph Problems\n"
},
{
"code": null,
"e": 22796,
"s": 22775,
"text": "\nTop 50 DP Problems\n"
},
{
"code": null,
"e": 22834,
"s": 22796,
"text": "\nTutorials\n \n\n"
},
{
"code": null,
"e": 22907,
"s": 22834,
"text": "\nJobs\n \n\n\nApply for Jobs\n\nPost a Job\n\nJOB-A-THON\n"
},
{
"code": null,
"e": 22924,
"s": 22907,
"text": "\nApply for Jobs\n"
},
{
"code": null,
"e": 22937,
"s": 22924,
"text": "\nPost a Job\n"
},
{
"code": null,
"e": 22950,
"s": 22937,
"text": "\nJOB-A-THON\n"
},
{
"code": null,
"e": 23136,
"s": 22950,
"text": "\nPractice\n \n\n\nAll DSA Problems\n\nProblem of the Day\n\nInterview Series: Weekly Contests\n\nBi-Wizard Coding: School Contests\n\nContests and Events\n\nPractice SDE Sheet\n"
},
{
"code": null,
"e": 23155,
"s": 23136,
"text": "\nAll DSA Problems\n"
},
{
"code": null,
"e": 23176,
"s": 23155,
"text": "\nProblem of the Day\n"
},
{
"code": null,
"e": 23212,
"s": 23176,
"text": "\nInterview Series: Weekly Contests\n"
},
{
"code": null,
"e": 23248,
"s": 23212,
"text": "\nBi-Wizard Coding: School Contests\n"
},
{
"code": null,
"e": 23270,
"s": 23248,
"text": "\nContests and Events\n"
},
{
"code": null,
"e": 23291,
"s": 23270,
"text": "\nPractice SDE Sheet\n"
},
{
"code": null,
"e": 23297,
"s": 23291,
"text": "GBlog"
},
{
"code": null,
"e": 23305,
"s": 23297,
"text": "Puzzles"
},
{
"code": null,
"e": 23318,
"s": 23305,
"text": "What's New ?"
},
{
"code": null,
"e": 23324,
"s": 23318,
"text": "Array"
},
{
"code": null,
"e": 23331,
"s": 23324,
"text": "Matrix"
},
{
"code": null,
"e": 23339,
"s": 23331,
"text": "Strings"
},
{
"code": null,
"e": 23347,
"s": 23339,
"text": "Hashing"
},
{
"code": null,
"e": 23359,
"s": 23347,
"text": "Linked List"
},
{
"code": null,
"e": 23365,
"s": 23359,
"text": "Stack"
},
{
"code": null,
"e": 23371,
"s": 23365,
"text": "Queue"
},
{
"code": null,
"e": 23383,
"s": 23371,
"text": "Binary Tree"
},
{
"code": null,
"e": 23402,
"s": 23383,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 23407,
"s": 23402,
"text": "Heap"
},
{
"code": null,
"e": 23413,
"s": 23407,
"text": "Graph"
},
{
"code": null,
"e": 23423,
"s": 23413,
"text": "Searching"
},
{
"code": null,
"e": 23431,
"s": 23423,
"text": "Sorting"
},
{
"code": null,
"e": 23448,
"s": 23431,
"text": "Divide & Conquer"
},
{
"code": null,
"e": 23461,
"s": 23448,
"text": "Mathematical"
},
{
"code": null,
"e": 23471,
"s": 23461,
"text": "Geometric"
},
{
"code": null,
"e": 23479,
"s": 23471,
"text": "Bitwise"
},
{
"code": null,
"e": 23486,
"s": 23479,
"text": "Greedy"
},
{
"code": null,
"e": 23499,
"s": 23486,
"text": "Backtracking"
},
{
"code": null,
"e": 23516,
"s": 23499,
"text": "Branch and Bound"
},
{
"code": null,
"e": 23536,
"s": 23516,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 23554,
"s": 23536,
"text": "Pattern Searching"
},
{
"code": null,
"e": 23565,
"s": 23554,
"text": "Randomized"
},
{
"code": null,
"e": 23595,
"s": 23565,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 23624,
"s": 23595,
"text": "0-1 Knapsack Problem | DP-10"
},
{
"code": null,
"e": 23656,
"s": 23624,
"text": "Largest Sum Contiguous Subarray"
},
{
"code": null,
"e": 23690,
"s": 23656,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 23728,
"s": 23690,
"text": "Longest Increasing Subsequence | DP-3"
},
{
"code": null,
"e": 23747,
"s": 23728,
"text": "Coin Change | DP-7"
},
{
"code": null,
"e": 23774,
"s": 23747,
"text": "Subset Sum Problem | DP-25"
},
{
"code": null,
"e": 23812,
"s": 23774,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 23834,
"s": 23812,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 23865,
"s": 23834,
"text": "Bellman–Ford Algorithm | DP-23"
},
{
"code": null,
"e": 23900,
"s": 23865,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 23933,
"s": 23900,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 23970,
"s": 23933,
"text": "Minimum number of jumps to reach end"
},
{
"code": null,
"e": 24033,
"s": 23970,
"text": "Efficient program to print all prime factors of a given number"
},
{
"code": null,
"e": 24054,
"s": 24033,
"text": "Edit Distance | DP-5"
},
{
"code": null,
"e": 24122,
"s": 24054,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 24175,
"s": 24122,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 24222,
"s": 24175,
"text": "Top 20 Dynamic Programming Interview Questions"
},
{
"code": null,
"e": 24285,
"s": 24222,
"text": "Overlapping Subproblems Property in Dynamic Programming | DP-1"
},
{
"code": null,
"e": 24307,
"s": 24285,
"text": "Cutting a Rod | DP-13"
},
{
"code": null,
"e": 24340,
"s": 24307,
"text": "Longest Common Substring | DP-29"
},
{
"code": null,
"e": 24366,
"s": 24340,
"text": "Tabulation vs Memoization"
},
{
"code": null,
"e": 24406,
"s": 24366,
"text": "Longest Palindromic Subsequence | DP-12"
},
{
"code": null,
"e": 24437,
"s": 24406,
"text": "Program for nth Catalan Number"
},
{
"code": null,
"e": 24521,
"s": 24437,
"text": "Partition a set into two subsets such that the difference of subset sums is minimum"
},
{
"code": null,
"e": 24549,
"s": 24521,
"text": "Egg Dropping Puzzle | DP-11"
},
{
"code": null,
"e": 24620,
"s": 24549,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
},
{
"code": null,
"e": 24655,
"s": 24620,
"text": "Count ways to reach the n'th stair"
},
{
"code": null,
"e": 24701,
"s": 24655,
"text": "Longest Increasing Subsequence Size (N log N)"
},
{
"code": null,
"e": 24727,
"s": 24701,
"text": "Partition problem | DP-18"
},
{
"code": null,
"e": 24757,
"s": 24727,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 24786,
"s": 24757,
"text": "0-1 Knapsack Problem | DP-10"
},
{
"code": null,
"e": 24818,
"s": 24786,
"text": "Largest Sum Contiguous Subarray"
},
{
"code": null,
"e": 24852,
"s": 24818,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 24890,
"s": 24852,
"text": "Longest Increasing Subsequence | DP-3"
},
{
"code": null,
"e": 24909,
"s": 24890,
"text": "Coin Change | DP-7"
},
{
"code": null,
"e": 24936,
"s": 24909,
"text": "Subset Sum Problem | DP-25"
},
{
"code": null,
"e": 24974,
"s": 24936,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 24996,
"s": 24974,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 25027,
"s": 24996,
"text": "Bellman–Ford Algorithm | DP-23"
},
{
"code": null,
"e": 25062,
"s": 25027,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 25095,
"s": 25062,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 25132,
"s": 25095,
"text": "Minimum number of jumps to reach end"
},
{
"code": null,
"e": 25195,
"s": 25132,
"text": "Efficient program to print all prime factors of a given number"
},
{
"code": null,
"e": 25216,
"s": 25195,
"text": "Edit Distance | DP-5"
},
{
"code": null,
"e": 25284,
"s": 25216,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 25337,
"s": 25284,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 25384,
"s": 25337,
"text": "Top 20 Dynamic Programming Interview Questions"
},
{
"code": null,
"e": 25447,
"s": 25384,
"text": "Overlapping Subproblems Property in Dynamic Programming | DP-1"
},
{
"code": null,
"e": 25469,
"s": 25447,
"text": "Cutting a Rod | DP-13"
},
{
"code": null,
"e": 25502,
"s": 25469,
"text": "Longest Common Substring | DP-29"
},
{
"code": null,
"e": 25528,
"s": 25502,
"text": "Tabulation vs Memoization"
},
{
"code": null,
"e": 25568,
"s": 25528,
"text": "Longest Palindromic Subsequence | DP-12"
},
{
"code": null,
"e": 25599,
"s": 25568,
"text": "Program for nth Catalan Number"
},
{
"code": null,
"e": 25683,
"s": 25599,
"text": "Partition a set into two subsets such that the difference of subset sums is minimum"
},
{
"code": null,
"e": 25711,
"s": 25683,
"text": "Egg Dropping Puzzle | DP-11"
},
{
"code": null,
"e": 25782,
"s": 25711,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
},
{
"code": null,
"e": 25817,
"s": 25782,
"text": "Count ways to reach the n'th stair"
},
{
"code": null,
"e": 25863,
"s": 25817,
"text": "Longest Increasing Subsequence Size (N log N)"
},
{
"code": null,
"e": 25889,
"s": 25863,
"text": "Partition problem | DP-18"
},
{
"code": null,
"e": 25913,
"s": 25889,
"text": "Difficulty Level :\nHard"
},
{
"code": null,
"e": 25993,
"s": 25913,
"text": "Given a sequence, find the length of the longest palindromic subsequence in it."
},
{
"code": null,
"e": 26003,
"s": 25993,
"text": "Examples:"
},
{
"code": null,
"e": 26064,
"s": 26003,
"text": "Input : abbaab\nOutput : 4\n\nInput : geeksforgeeks\nOutput : 5\n"
},
{
"code": null,
"e": 26192,
"s": 26064,
"text": "We have discussed a Dynamic Programming solution for Longest Palindromic Subsequence which is based on below recursive formula."
},
{
"code": null,
"e": 26293,
"s": 26192,
"text": "// Every single character is a palindrome of length 1L(i, i) = 1 for all indexes i in given sequence"
},
{
"code": null,
"e": 26395,
"s": 26293,
"text": "// IF first and last characters are not sameIf (X[i] != X[j]) L(i, j) = max{L(i + 1, j), L(i, j – 1)}"
},
{
"code": null,
"e": 26479,
"s": 26395,
"text": "// If there are only 2 characters and both are sameElse if (j == i + 1) L(i, j) = 2"
},
{
"code": null,
"e": 26596,
"s": 26479,
"text": "// If there are more than two characters, and first// and last characters are sameElse L(i, j) = L(i + 1, j – 1) + 2"
},
{
"code": null,
"e": 26935,
"s": 26596,
"text": "The solution discussed above takes O(n2) extra space. In this post a space optimized solution is discussed that requires O(n) extra space. The idea is to create a one dimensional array a[] of same size as given string. We make sure that a[i] stores length of longest palindromic subsequence of prefix ending with i (or substring s[0..i])."
},
{
"code": null,
"e": 26939,
"s": 26935,
"text": "C++"
},
{
"code": null,
"e": 26944,
"s": 26939,
"text": "Java"
},
{
"code": null,
"e": 26952,
"s": 26944,
"text": "Python3"
},
{
"code": null,
"e": 26955,
"s": 26952,
"text": "C#"
},
{
"code": null,
"e": 26959,
"s": 26955,
"text": "PHP"
},
{
"code": "// A Space optimized Dynamic Programming based C++// program for LPS problem#include <bits/stdc++.h>using namespace std; // Returns the length of the longest palindromic// subsequence in strint lps(string &s){ int n = s.length(); // a[i] is going to store length of longest // palindromic subsequence of substring s[0..i] int a[n]; // Pick starting point for (int i = n - 1; i >= 0; i--) { int back_up = 0; // Pick ending points and see if s[i] // increases length of longest common // subsequence ending with s[j]. for (int j = i; j < n; j++) { // similar to 2D array L[i][j] == 1 // i.e., handling substrings of length // one. if (j == i) a[j] = 1; // Similar to 2D array L[i][j] = L[i+1][j-1]+2 // i.e., handling case when corner characters // are same. else if (s[i] == s[j]) { // value a[j] is depend upon previous // unupdated value of a[j-1] but in // previous loop value of a[j-1] is // changed. To store the unupdated // value of a[j-1] back_up variable // is used. int temp = a[j]; a[j] = back_up + 2; back_up = temp; } // similar to 2D array L[i][j] = max(L[i][j-1], // a[i+1][j]) else { back_up = a[j]; a[j] = max(a[j - 1], a[j]); } } } return a[n - 1];} /* Driver program to test above functions */int main(){ string str = \"GEEKSFORGEEKS\"; cout << lps(str); return 0;}",
"e": 28718,
"s": 26959,
"text": null
},
{
"code": "// A Space optimized Dynamic Programming // based Java program for LPS problem class GFG { // Returns the length of the longest // palindromic subsequence in str static int lps(String s) { int n = s.length(); // a[i] is going to store length // of longest palindromic subsequence // of substring s[0..i] int a[] = new int[n]; // Pick starting point for (int i = n - 1; i >= 0; i--) { int back_up = 0; // Pick ending points and see if s[i] // increases length of longest common // subsequence ending with s[j]. for (int j = i; j < n; j++) { // similar to 2D array L[i][j] == 1 // i.e., handling substrings of length // one. if (j == i) a[j] = 1; // Similar to 2D array L[i][j] = L[i+1][j-1]+2 // i.e., handling case when corner characters // are same. else if (s.charAt(i) == s.charAt(j)) { int temp = a[j]; a[j] = back_up + 2; back_up = temp; } // similar to 2D array L[i][j] = max(L[i][j-1], // a[i+1][j]) else { back_up = a[j]; a[j] = Math.max(a[j - 1], a[j]); } } } return a[n - 1]; } /* Driver program to test above functions */ public static void main(String[] args) { String str = \"GEEKSFORGEEKS\"; System.out.println(lps(str)); }} //This article is contributed by prerna saini.",
"e": 30182,
"s": 28718,
"text": null
},
{
"code": "# A Space optimized Dynamic Programming # based Python3 program for LPS problem # Returns the length of the longest # palindromic subsequence in strdef lps(s): n = len(s) # a[i] is going to store length # of longest palindromic subsequence # of substring s[0..i] a = [0] * n # Pick starting point for i in range(n-1, -1, -1): back_up = 0 # Pick ending points and see if s[i] # increases length of longest common # subsequence ending with s[j]. for j in range(i, n): # similar to 2D array L[i][j] == 1 # i.e., handling substrings of length # one. if j == i: a[j] = 1 # Similar to 2D array L[i][j] = L[i+1][j-1]+2 # i.e., handling case when corner characters # are same. elif s[i] == s[j]: temp = a[j] a[j] = back_up + 2 back_up = temp # similar to 2D array L[i][j] = max(L[i][j-1], # a[i+1][j]) else: back_up = a[j] a[j] = max(a[j - 1], a[j]) return a[n - 1] # Driver Codestring = \"GEEKSFORGEEKS\"print(lps(string)) # This code is contributed by Ansu Kumari.",
"e": 31365,
"s": 30182,
"text": null
},
{
"code": "// A Space optimized Dynamic Programming // based C# program for LPS problemusing System; class GFG { // Returns the length of the longest // palindromic subsequence in str static int lps(string s) { int n = s.Length; // a[i] is going to store length // of longest palindromic subsequence // of substring s[0..i] int []a = new int[n]; // Pick starting point for (int i = n - 1; i >= 0; i--) { int back_up = 0; // Pick ending points and see if s[i] // increases length of longest common // subsequence ending with s[j]. for (int j = i; j < n; j++) { // similar to 2D array L[i][j] == 1 // i.e., handling substrings of length // one. if (j == i) a[j] = 1; // Similar to 2D array L[i][j] = L[i+1][j-1]+2 // i.e., handling case when corner characters // are same. else if (s[i] == s[j]) { int temp = a[j]; a[j] = back_up + 2; back_up = temp; } // similar to 2D array L[i][j] = max(L[i][j-1], // a[i+1][j]) else { back_up = a[j]; a[j] = Math.Max(a[j - 1], a[j]); } } } return a[n - 1]; } // Driver program public static void Main() { string str = \"GEEKSFORGEEKS\"; Console.WriteLine(lps(str)); }} // This code is contributed by vt_m.",
"e": 32771,
"s": 31365,
"text": null
},
{
"code": "<?php// A Space optimized Dynamic// Programming based PHP// program for LPS problem // Returns the length of // the longest palindromic .// subsequence in strfunction lps($s){ $n = strlen($s); // Pick starting point for ($i = $n - 1; $i >= 0; $i--) { $back_up = 0; // Pick ending points and // see if s[i] increases // length of longest common // subsequence ending with s[j]. for ($j = $i; $j < $n; $j++) { // similar to 2D array // L[i][j] == 1 i.e., // handling substrings // of length one. if ($j == $i) $a[$j] = 1; // Similar to 2D array // L[i][j] = L[i+1][j-1]+2 // i.e., handling case when // corner characters are same. else if ($s[$i] == $s[$j]) { // value a[j] is depend // upon previous unupdated // value of a[j-1] but in // previous loop value of // a[j-1] is changed. To // store the unupdated value // of a[j-1] back_up variable // is used. $temp = $a[$j]; $a[$j] = $back_up + 2; $back_up = $temp; } // similar to 2D array // L[i][j] = max(L[i][j-1], // a[i+1][j]) else { $back_up = $a[$j]; $a[$j] = max($a[$j - 1], $a[$j]); } } } return $a[$n - 1];} // Driver Code$str = \"GEEKSFORGEEKS\";echo lps($str); // This code is contributed// by shiv_bhakt.?>",
"e": 34519,
"s": 32771,
"text": null
},
{
"code": null,
"e": 34522,
"s": 34519,
"text": "5\n"
},
{
"code": null,
"e": 35413,
"s": 34522,
"text": "Time Complexity : O(n*n)Auxiliary Space : O(n)YouTubeGeeksforGeeks507K subscribersLongest palindrome subsequence with O(n) space | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 6:08•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=i1o6rlqiSZM\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 35426,
"s": 35413,
"text": "Vishal_Khoda"
},
{
"code": null,
"e": 35437,
"s": 35426,
"text": "palindrome"
},
{
"code": null,
"e": 35449,
"s": 35437,
"text": "subsequence"
},
{
"code": null,
"e": 35469,
"s": 35449,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 35477,
"s": 35469,
"text": "Strings"
},
{
"code": null,
"e": 35485,
"s": 35477,
"text": "Strings"
},
{
"code": null,
"e": 35505,
"s": 35485,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 35516,
"s": 35505,
"text": "palindrome"
},
{
"code": null,
"e": 35614,
"s": 35516,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35657,
"s": 35614,
"text": "Maximum size square sub-matrix with all 1s"
},
{
"code": null,
"e": 35717,
"s": 35657,
"text": "Optimal Substructure Property in Dynamic Programming | DP-2"
},
{
"code": null,
"e": 35752,
"s": 35717,
"text": "Optimal Binary Search Tree | DP-24"
},
{
"code": null,
"e": 35773,
"s": 35752,
"text": "Min Cost Path | DP-6"
},
{
"code": null,
"e": 35829,
"s": 35773,
"text": "Maximum Subarray Sum using Divide and Conquer algorithm"
},
{
"code": null,
"e": 35875,
"s": 35829,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 35900,
"s": 35875,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 35960,
"s": 35900,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 35975,
"s": 35960,
"text": "C++ Data Types"
}
]
|
Terra - OSINT Tool On Instagram - GeeksforGeeks | 28 Nov, 2021
Terra is an Open Source Intelligence Tool. Terra can give you so much information about an Instagram account that is not easily visible to a normal user. Using Terra you can get various information such as location, timestamp, caption, picture, URL of the account. Terra is a free and open-source tool available on GitHub which can be used to perform reconnaissance on Instagram account/profiles. The location parameter of the terra will give you a complete list of all the locations over where the user has tagged the location on pictures, posts, etc. Timestamp will give you the actual timestamp of all the posts of the user. Terra even gives the email address of the user if an email is used anywhere it’ll be displayed. Terra is written in python language. You must have python language installed in your kali Linux operating system. As this tool is open source so you can contribute in this tool. This tool is very useful when you want to get information about Instagram that you normally wouldn’t be able to get from just looking at the profile of the user.
Step 1: Open your kali linux operating system and use the following command to install the tool from GitHub.
git clone https://github.com/xadhrit/terra.git
Step 2: Use the following command to move in to the directory of the tool.
cd terra
Step 3: Now install the dependences of the tool.
python3 -m pip install -r requirements.txt
Step 4: Now use the following command to run the tool.
python3 terra.py
Now we will see example to use the tool.
Example: use the terra tool to find information about a username of a Instagram account.
python3 terra.py <username of target>
The tool found the details of given username.
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
Docker - COPY Instruction
mv command in Linux with examples
SED command in Linux | Set 2
chown command in Linux with Examples
nohup Command in Linux with Examples
Named Pipe or FIFO with example C program
Thread functions in C/C++
uniq Command in LINUX with examples
Start/Stop/Restart Services Using Systemctl in Linux | [
{
"code": null,
"e": 25651,
"s": 25623,
"text": "\n28 Nov, 2021"
},
{
"code": null,
"e": 26717,
"s": 25651,
"text": "Terra is an Open Source Intelligence Tool. Terra can give you so much information about an Instagram account that is not easily visible to a normal user. Using Terra you can get various information such as location, timestamp, caption, picture, URL of the account. Terra is a free and open-source tool available on GitHub which can be used to perform reconnaissance on Instagram account/profiles. The location parameter of the terra will give you a complete list of all the locations over where the user has tagged the location on pictures, posts, etc. Timestamp will give you the actual timestamp of all the posts of the user. Terra even gives the email address of the user if an email is used anywhere it’ll be displayed. Terra is written in python language. You must have python language installed in your kali Linux operating system. As this tool is open source so you can contribute in this tool. This tool is very useful when you want to get information about Instagram that you normally wouldn’t be able to get from just looking at the profile of the user. "
},
{
"code": null,
"e": 26826,
"s": 26717,
"text": "Step 1: Open your kali linux operating system and use the following command to install the tool from GitHub."
},
{
"code": null,
"e": 26873,
"s": 26826,
"text": "git clone https://github.com/xadhrit/terra.git"
},
{
"code": null,
"e": 26948,
"s": 26873,
"text": "Step 2: Use the following command to move in to the directory of the tool."
},
{
"code": null,
"e": 26957,
"s": 26948,
"text": "cd terra"
},
{
"code": null,
"e": 27006,
"s": 26957,
"text": "Step 3: Now install the dependences of the tool."
},
{
"code": null,
"e": 27049,
"s": 27006,
"text": "python3 -m pip install -r requirements.txt"
},
{
"code": null,
"e": 27104,
"s": 27049,
"text": "Step 4: Now use the following command to run the tool."
},
{
"code": null,
"e": 27121,
"s": 27104,
"text": "python3 terra.py"
},
{
"code": null,
"e": 27162,
"s": 27121,
"text": "Now we will see example to use the tool."
},
{
"code": null,
"e": 27251,
"s": 27162,
"text": "Example: use the terra tool to find information about a username of a Instagram account."
},
{
"code": null,
"e": 27290,
"s": 27251,
"text": "python3 terra.py <username of target> "
},
{
"code": null,
"e": 27336,
"s": 27290,
"text": "The tool found the details of given username."
},
{
"code": null,
"e": 27347,
"s": 27336,
"text": "Kali-Linux"
},
{
"code": null,
"e": 27359,
"s": 27347,
"text": "Linux-Tools"
},
{
"code": null,
"e": 27370,
"s": 27359,
"text": "Linux-Unix"
},
{
"code": null,
"e": 27468,
"s": 27370,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27503,
"s": 27468,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 27529,
"s": 27503,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 27563,
"s": 27529,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 27592,
"s": 27563,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 27629,
"s": 27592,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 27666,
"s": 27629,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 27708,
"s": 27666,
"text": "Named Pipe or FIFO with example C program"
},
{
"code": null,
"e": 27734,
"s": 27708,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 27770,
"s": 27734,
"text": "uniq Command in LINUX with examples"
}
]
|
Program to draw circles using mouse moves in OpenGL - GeeksforGeeks | 16 Jul, 2021
In this article, the task is to draw circles using a single mouse click in OpenGL.
OpenGL: OpenGL is a cross-language, cross-platform API for rendering 2D and 3D Vector Graphics. It will make a lot of design as well as animations using this.
Create a circle anywhere on the console using a single left mouse click and the coordinates of the center of the circle created depends on the position of your click.
To change the color of the circle, simply right-click on the mouse.
After performing all operations jump out of the program by simply pressing the Esc key on the keyboard.
Approach: The idea is to use the below inbuilt function to draw the circle using single click in OpenGL:
glMatrixMode(GL_PROJECTION): This function sets the current matrix to projection.
glLoadIdentity(): The function is used to multiply the current matrix by identity matrix.
gluOrtho2D(0.0, 800.0, 0.0, 600.0): It sets the parallel(orthographic) projection of the full frame buffer.
glutCreateWindow(“Circle Creation on mouse click”): Creates the window as specified by the user as above.
glClearColor(0, 0, 0, 0): It sets the background color.
glClear(GL_COLOR_BUFFER_BIT): It clears the frame buffer and set values defined in glClearColor() function call.
glutDisplayFunc(display): It links the display event with the display event handler(display).
glutMouseFunc(mouse): Mouse event handler.
glutKeyboardFunc(keyboard): Keyboard event handler.
glutMainLoop(): This function loops the current event.
Below is a C++ program that implements onClick functionality in OpenGL:
C++
// C++ program to implement onClick// functionality in OpenGL to draw// a circle#include <GL/glut.h>#include <iostream>#include <math.h>#include <stdlib.h>#define xpix 500#include <cstring>using namespace std; float r, g, b, x, y;bool flag = true;int counter = 0; // Function works on mouse clickvoid mouse(int button, int state, int mousex, int mousey){ if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) { flag = true; x = mousex; y = 600 - mousey; } // Change color of circle else if (button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN) { if (counter > 4) { counter = 0; } counter++; // Redisplay glutPostRedisplay(); }} // Function that exits from programvoid keyboard(unsigned char key, int x, int y){ switch (key) { case 27: glutHideWindow(); }} // Function to draw the circlevoid display(void){ float angle_theta; if (counter == 1) { glColor3f(1, 0, 0); } else if (counter == 2) { glColor3f(0, 1, 0); } else if (counter == 3) { glColor3f(0, 1, 1); } else if (counter == 4) { glColor3f(0.5, 0, 1); } else if (counter == 5) { glColor3f(0, 0.5, 1); } // Matrix mode glMatrixMode(GL_PROJECTION); glLoadIdentity(); // Given the coordinates gluOrtho2D(0.0, 800.0, 0.0, 600.0); // If the flag is true if (flag) { // Begin the pointer glBegin(GL_POLYGON); // Iterate through all the // 360 degrees for (int i = 0; i < 360; i++) { // Find the angle angle_theta = i * 3.142 / 180; glVertex2f(x + 50 * cos(angle_theta), y + 50 * sin(angle_theta)); } // Sets vertex glEnd(); } // Flushes the frame buffer // to the screen glFlush();} // Driver Codeint main(int argc, char** argv){ glutInit(&argc, argv); glutInitWindowSize(800, 600); glutInitWindowPosition(100, 100); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); // Creates the window as // specified by the user glutCreateWindow("Circle Creation " "on mouse click"); // Sets the background color glClearColor(0, 0, 0, 0); // Clears the frame buffer glClear(GL_COLOR_BUFFER_BIT); // Links display event with the // display event handler(display) glutDisplayFunc(display); // Mouse event handler glutMouseFunc(mouse); // Keyboard event handler glutKeyboardFunc(keyboard); // Loops the current event glutMainLoop();}
Output:
akshaysingh98088
OpenGL
C++
C++ Programs
Geometric
Geometric
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
std::string class in C++
Header files in C/C++ and its uses
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
C++ Program for QuickSort
Sorting a Map by value in C++ STL | [
{
"code": null,
"e": 25343,
"s": 25315,
"text": "\n16 Jul, 2021"
},
{
"code": null,
"e": 25426,
"s": 25343,
"text": "In this article, the task is to draw circles using a single mouse click in OpenGL."
},
{
"code": null,
"e": 25585,
"s": 25426,
"text": "OpenGL: OpenGL is a cross-language, cross-platform API for rendering 2D and 3D Vector Graphics. It will make a lot of design as well as animations using this."
},
{
"code": null,
"e": 25752,
"s": 25585,
"text": "Create a circle anywhere on the console using a single left mouse click and the coordinates of the center of the circle created depends on the position of your click."
},
{
"code": null,
"e": 25820,
"s": 25752,
"text": "To change the color of the circle, simply right-click on the mouse."
},
{
"code": null,
"e": 25924,
"s": 25820,
"text": "After performing all operations jump out of the program by simply pressing the Esc key on the keyboard."
},
{
"code": null,
"e": 26029,
"s": 25924,
"text": "Approach: The idea is to use the below inbuilt function to draw the circle using single click in OpenGL:"
},
{
"code": null,
"e": 26111,
"s": 26029,
"text": "glMatrixMode(GL_PROJECTION): This function sets the current matrix to projection."
},
{
"code": null,
"e": 26201,
"s": 26111,
"text": "glLoadIdentity(): The function is used to multiply the current matrix by identity matrix."
},
{
"code": null,
"e": 26309,
"s": 26201,
"text": "gluOrtho2D(0.0, 800.0, 0.0, 600.0): It sets the parallel(orthographic) projection of the full frame buffer."
},
{
"code": null,
"e": 26415,
"s": 26309,
"text": "glutCreateWindow(“Circle Creation on mouse click”): Creates the window as specified by the user as above."
},
{
"code": null,
"e": 26471,
"s": 26415,
"text": "glClearColor(0, 0, 0, 0): It sets the background color."
},
{
"code": null,
"e": 26584,
"s": 26471,
"text": "glClear(GL_COLOR_BUFFER_BIT): It clears the frame buffer and set values defined in glClearColor() function call."
},
{
"code": null,
"e": 26678,
"s": 26584,
"text": "glutDisplayFunc(display): It links the display event with the display event handler(display)."
},
{
"code": null,
"e": 26721,
"s": 26678,
"text": "glutMouseFunc(mouse): Mouse event handler."
},
{
"code": null,
"e": 26773,
"s": 26721,
"text": "glutKeyboardFunc(keyboard): Keyboard event handler."
},
{
"code": null,
"e": 26828,
"s": 26773,
"text": "glutMainLoop(): This function loops the current event."
},
{
"code": null,
"e": 26900,
"s": 26828,
"text": "Below is a C++ program that implements onClick functionality in OpenGL:"
},
{
"code": null,
"e": 26904,
"s": 26900,
"text": "C++"
},
{
"code": "// C++ program to implement onClick// functionality in OpenGL to draw// a circle#include <GL/glut.h>#include <iostream>#include <math.h>#include <stdlib.h>#define xpix 500#include <cstring>using namespace std; float r, g, b, x, y;bool flag = true;int counter = 0; // Function works on mouse clickvoid mouse(int button, int state, int mousex, int mousey){ if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) { flag = true; x = mousex; y = 600 - mousey; } // Change color of circle else if (button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN) { if (counter > 4) { counter = 0; } counter++; // Redisplay glutPostRedisplay(); }} // Function that exits from programvoid keyboard(unsigned char key, int x, int y){ switch (key) { case 27: glutHideWindow(); }} // Function to draw the circlevoid display(void){ float angle_theta; if (counter == 1) { glColor3f(1, 0, 0); } else if (counter == 2) { glColor3f(0, 1, 0); } else if (counter == 3) { glColor3f(0, 1, 1); } else if (counter == 4) { glColor3f(0.5, 0, 1); } else if (counter == 5) { glColor3f(0, 0.5, 1); } // Matrix mode glMatrixMode(GL_PROJECTION); glLoadIdentity(); // Given the coordinates gluOrtho2D(0.0, 800.0, 0.0, 600.0); // If the flag is true if (flag) { // Begin the pointer glBegin(GL_POLYGON); // Iterate through all the // 360 degrees for (int i = 0; i < 360; i++) { // Find the angle angle_theta = i * 3.142 / 180; glVertex2f(x + 50 * cos(angle_theta), y + 50 * sin(angle_theta)); } // Sets vertex glEnd(); } // Flushes the frame buffer // to the screen glFlush();} // Driver Codeint main(int argc, char** argv){ glutInit(&argc, argv); glutInitWindowSize(800, 600); glutInitWindowPosition(100, 100); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); // Creates the window as // specified by the user glutCreateWindow(\"Circle Creation \" \"on mouse click\"); // Sets the background color glClearColor(0, 0, 0, 0); // Clears the frame buffer glClear(GL_COLOR_BUFFER_BIT); // Links display event with the // display event handler(display) glutDisplayFunc(display); // Mouse event handler glutMouseFunc(mouse); // Keyboard event handler glutKeyboardFunc(keyboard); // Loops the current event glutMainLoop();}",
"e": 29532,
"s": 26904,
"text": null
},
{
"code": null,
"e": 29542,
"s": 29532,
"text": "Output: "
},
{
"code": null,
"e": 29561,
"s": 29544,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 29568,
"s": 29561,
"text": "OpenGL"
},
{
"code": null,
"e": 29572,
"s": 29568,
"text": "C++"
},
{
"code": null,
"e": 29585,
"s": 29572,
"text": "C++ Programs"
},
{
"code": null,
"e": 29595,
"s": 29585,
"text": "Geometric"
},
{
"code": null,
"e": 29605,
"s": 29595,
"text": "Geometric"
},
{
"code": null,
"e": 29609,
"s": 29605,
"text": "CPP"
},
{
"code": null,
"e": 29707,
"s": 29609,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29735,
"s": 29707,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 29755,
"s": 29735,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 29788,
"s": 29755,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 29812,
"s": 29788,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 29837,
"s": 29812,
"text": "std::string class in C++"
},
{
"code": null,
"e": 29872,
"s": 29837,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 29916,
"s": 29872,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 29975,
"s": 29916,
"text": "How to return multiple values from a function in C or C++?"
},
{
"code": null,
"e": 30001,
"s": 29975,
"text": "C++ Program for QuickSort"
}
]
|
Python program to implement Half Adder | 21 Aug, 2021
Prerequisite: Half Adder in Digital Logic
Given two inputs of Half Adder A, B. The task is to implement the Half Adder circuit and Print output i.e sum and carry of two inputs.
Half Adder: A half adder is a type of adder, an electronic circuit that performs the addition of numbers. The half adder is able to add two single binary digits and provide the output plus a carrying value. It has two inputs, called A and B, and two outputs S (sum) and C (carry).
Logical Expression:
Sum = A XOR B
Carry = A AND B
Truth Table:
Examples:
Input : 0 1
Output: Sum=1, Carry=0
Explanation: According to logical expression Sum=A XOR B i.e 0 XOR 1 =1 , Carry=A AND B i.e 0 AND 1 =0
Input : 1 1
Output: Sum=0, Carry=1
Explanation: According to logical expression Sum=A XOR B i.e 1 XOR 1 =0 , Carry=A AND B i.e 1 AND 1 =1
Approach:
We take two inputs A and B.
XOR operation on A and B gives the value of the sum.
AND operation on A and B gives the value of Carry.
Below is the implementation.
Python3
# Function to print sum and carrydef getResult(A, B): # Calculating value of sum Sum = A ^ B # Calculating value of Carry Carry = A & B # printing the values print("Sum ", Sum) print("Carry", Carry) # Driver codeA = 0B = 1 # passing two inputs of halfadder as arguments to get result functiongetResult(A, B)
Output:
Sum 1
Carry 0
simranarora5sos
anudeep23042002
Technical Scripter 2020
Digital Electronics & Logic Design
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to memory and memory units
Analog to Digital Conversion
Latches in Digital Logic
Introduction of Sequential Circuits
Half Subtractor in Digital Logic
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
Python Dictionary
How to get column names in Pandas dataframe | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Aug, 2021"
},
{
"code": null,
"e": 70,
"s": 28,
"text": "Prerequisite: Half Adder in Digital Logic"
},
{
"code": null,
"e": 205,
"s": 70,
"text": "Given two inputs of Half Adder A, B. The task is to implement the Half Adder circuit and Print output i.e sum and carry of two inputs."
},
{
"code": null,
"e": 486,
"s": 205,
"text": "Half Adder: A half adder is a type of adder, an electronic circuit that performs the addition of numbers. The half adder is able to add two single binary digits and provide the output plus a carrying value. It has two inputs, called A and B, and two outputs S (sum) and C (carry)."
},
{
"code": null,
"e": 508,
"s": 486,
"text": "Logical Expression: "
},
{
"code": null,
"e": 541,
"s": 508,
"text": "Sum = A XOR B \nCarry = A AND B "
},
{
"code": null,
"e": 554,
"s": 541,
"text": "Truth Table:"
},
{
"code": null,
"e": 564,
"s": 554,
"text": "Examples:"
},
{
"code": null,
"e": 576,
"s": 564,
"text": "Input : 0 1"
},
{
"code": null,
"e": 599,
"s": 576,
"text": "Output: Sum=1, Carry=0"
},
{
"code": null,
"e": 704,
"s": 599,
"text": "Explanation: According to logical expression Sum=A XOR B i.e 0 XOR 1 =1 , Carry=A AND B i.e 0 AND 1 =0"
},
{
"code": null,
"e": 716,
"s": 704,
"text": "Input : 1 1"
},
{
"code": null,
"e": 739,
"s": 716,
"text": "Output: Sum=0, Carry=1"
},
{
"code": null,
"e": 844,
"s": 739,
"text": "Explanation: According to logical expression Sum=A XOR B i.e 1 XOR 1 =0 , Carry=A AND B i.e 1 AND 1 =1"
},
{
"code": null,
"e": 854,
"s": 844,
"text": "Approach:"
},
{
"code": null,
"e": 882,
"s": 854,
"text": "We take two inputs A and B."
},
{
"code": null,
"e": 935,
"s": 882,
"text": "XOR operation on A and B gives the value of the sum."
},
{
"code": null,
"e": 986,
"s": 935,
"text": "AND operation on A and B gives the value of Carry."
},
{
"code": null,
"e": 1015,
"s": 986,
"text": "Below is the implementation."
},
{
"code": null,
"e": 1023,
"s": 1015,
"text": "Python3"
},
{
"code": "# Function to print sum and carrydef getResult(A, B): # Calculating value of sum Sum = A ^ B # Calculating value of Carry Carry = A & B # printing the values print(\"Sum \", Sum) print(\"Carry\", Carry) # Driver codeA = 0B = 1 # passing two inputs of halfadder as arguments to get result functiongetResult(A, B)",
"e": 1366,
"s": 1023,
"text": null
},
{
"code": null,
"e": 1374,
"s": 1366,
"text": "Output:"
},
{
"code": null,
"e": 1389,
"s": 1374,
"text": "Sum 1\nCarry 0"
},
{
"code": null,
"e": 1405,
"s": 1389,
"text": "simranarora5sos"
},
{
"code": null,
"e": 1421,
"s": 1405,
"text": "anudeep23042002"
},
{
"code": null,
"e": 1445,
"s": 1421,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 1480,
"s": 1445,
"text": "Digital Electronics & Logic Design"
},
{
"code": null,
"e": 1487,
"s": 1480,
"text": "Python"
},
{
"code": null,
"e": 1506,
"s": 1487,
"text": "Technical Scripter"
},
{
"code": null,
"e": 1604,
"s": 1506,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1644,
"s": 1604,
"text": "Introduction to memory and memory units"
},
{
"code": null,
"e": 1673,
"s": 1644,
"text": "Analog to Digital Conversion"
},
{
"code": null,
"e": 1698,
"s": 1673,
"text": "Latches in Digital Logic"
},
{
"code": null,
"e": 1734,
"s": 1698,
"text": "Introduction of Sequential Circuits"
},
{
"code": null,
"e": 1767,
"s": 1734,
"text": "Half Subtractor in Digital Logic"
},
{
"code": null,
"e": 1795,
"s": 1767,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 1845,
"s": 1795,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 1867,
"s": 1845,
"text": "Python map() function"
},
{
"code": null,
"e": 1885,
"s": 1867,
"text": "Python Dictionary"
}
]
|
Check whether a point lies inside a sphere or not | 24 Mar, 2021
Given co-ordinates of the center of a sphere (cx, cy, cz) and its radius r. Our task is to check whether a point (x, y, z) lies inside, outside or on this sphere.Examples:
Input : Centre(0, 0, 0) Radius 3
Point(1, 1, 1)
Output :Point is inside the sphere
Input :Centre(0, 0, 0) Radius 3
Point(2, 1, 2)
Output :Point lies on the sphere
Input :Centre(0, 0, 0) Radius 3
Point(10, 10, 10)
Output :Point is outside the sphere
Approach: Whether a point lies inside a sphere or not, depends upon its distance from the centre. A point (x, y, z) is inside the sphere with center (cx, cy, cz) and radius r if
( x-cx ) ^2 + (y-cy) ^2 + (z-cz) ^ 2 < r^2
A point (x, y, z) lies on the sphere with center (cx, cy, cz) and radius r if
( x-cx ) ^2 + (y-cy) ^2 + (z-cz) ^ 2 = r^2
A point (x, y, z) is outside the sphere with center (cx, cy, cz) and radius r if
( x-cx ) ^2 + (y-cy) ^2 + (z-cz) ^ 2 > r^2
C++
Java
Python
C#
PHP
Javascript
// CPP code to illustrate above approach#include <bits/stdc++.h>using namespace std;// function to calculate the distance between centre and the pointint check(int cx, int cy, int cz, int x, int y, int z){ int x1 = pow((x - cx), 2); int y1 = pow((y - cy), 2); int z1 = pow((z - cz), 2); // distance between the centre // and given point return (x1 + y1 + z1);} // Driver program to test above functionint main(){ // coordinates of centre int cx = 1, cy = 2, cz = 3; int r = 5; // radius of the sphere int x = 4, y = 5, z = 2; // coordinates of point int ans = check(cx, cy, cz, x, y, z); // distance btw centre and point is less // than radius if (ans < (r * r)) cout << "Point is inside the sphere"; // distance btw centre and point is // equal to radius else if (ans == (r * r)) cout << "Point lies on the sphere"; // distance btw center and point is // greater than radius else cout << "Point is outside the sphere"; return 0;}
// Java code to illustrate above approachimport java.io.*;import java.util.*;import java.lang.*; class GfG { // function to calculate the distance // between centre and the point public static int check(int cx, int cy, int cz, int x, int y, int z) { int x1 = (int)Math.pow((x - cx), 2); int y1 = (int)Math.pow((y - cy), 2); int z1 = (int)Math.pow((z - cz), 2); // distance between the centre // and given point return (x1 + y1 + z1); } // Driver program to test above function public static void main(String[] args) { // coordinates of centre int cx = 1, cy = 2, cz = 3; int r = 5; // radius of the sphere // coordinates of point int x = 4, y = 5, z = 2; int ans = check(cx, cy, cz, x, y, z); // distance btw centre and point is less // than radius if (ans < (r * r)) System.out.println("Point is inside" + " the sphere"); // distance btw centre and point is // equal to radius else if (ans == (r * r)) System.out.println("Point lies on" + " the sphere"); // distance btw center and point is // greater than radius else System.out.println("Point is outside" + " the sphere"); }} // This code is contributed by Sagar Shukla.
# Python3 code to illustrate above approach import math# function to calculate distance btw center and given pointdef check(cx, cy, cz, x, y, z, ): x1 = math.pow((x-cx), 2) y1 = math.pow((y-cy), 2) z1 = math.pow((z-cz), 2) return (x1 + y1 + z1) # distance between the centre and given point # driver code cx = 1cy = 2 # coordinates of centrecz = 3 r = 5 # radius of sphere x = 4y = 5 # coordinates of the given pointz = 2# function call to calculate distance btw centre and given pointans = check(cx, cy, cz, x, y, z); # distance btw centre and point is less than radiusif ans<(r**2): print("Point is inside the sphere") # distance btw centre and point is equal to radiuselif ans ==(r**2): print("Point lies on the sphere") # distance btw centre and point is greater than radiuselse: print("Point is outside the sphere")
// C# code to illustrate// above approachusing System; class GFG{ // function to calculate // the distance between // centre and the point public static int check(int cx, int cy, int cz, int x, int y, int z) { int x1 = (int)Math.Pow((x - cx), 2); int y1 = (int)Math.Pow((y - cy), 2); int z1 = (int)Math.Pow((z - cz), 2); // distance between the // centre and given point return (x1 + y1 + z1); } // Driver Code public static void Main() { // coordinates of centre int cx = 1, cy = 2, cz = 3; int r = 5; // radius of the sphere // coordinates of point int x = 4, y = 5, z = 2; int ans = check(cx, cy, cz, x, y, z); // distance btw centre // and point is less // than radius if (ans < (r * r)) Console.WriteLine("Point is inside" + " the sphere"); // distance btw centre // and point is // equal to radius else if (ans == (r * r)) Console.WriteLine("Point lies on" + " the sphere"); // distance btw center // and point is greater // than radius else Console.WriteLine("Point is outside" + " the sphere"); }} // This code is contributed by anuj_67.
<?php// function to calculate // the distance between// centre and the pointfunction check($cx, $cy, $cz, $x, $y, $z){ $x1 = pow(($x - $cx), 2); $y1 = pow(($y - $cy), 2); $z1 = pow(($z - $cz), 2); // distance between the // centre and given point return ($x1 + $y1 + $z1);} // Driver Code // coordinates of centre$cx = 1;$cy = 2;$cz = 3; $r = 5; // radius of the sphere$x = 4;$y = 5;$z = 2; // coordinates of point $ans = check($cx, $cy, $cz, $x, $y, $z); // distance btw centre and// point is less than radiusif ($ans < ($r * $r)) echo "Point is inside " . "the sphere"; // distance btw centre and// point is equal to radiuselse if ($ans == ($r * $r)) echo "Point lies on the sphere"; // distance btw center and point// is greater than radiuselse echo "Point is outside " . "the sphere"; // This code is contributed// by shiv_bhakt?>
<script> // Javascript code to illustrate above approach // function to calculate the distance between centre and the pointfunction check(cx, cy, cz, x, y, z){ let x1 = Math.pow((x - cx), 2); let y1 = Math.pow((y - cy), 2); let z1 = Math.pow((z - cz), 2); // distance between the centre // and given point return (x1 + y1 + z1);} // Driver program to test above function // coordinates of centre let cx = 1, cy = 2, cz = 3; let r = 5; // radius of the sphere let x = 4, y = 5, z = 2; // coordinates of point let ans = check(cx, cy, cz, x, y, z); // distance btw centre and point is less // than radius if (ans < (r * r)) document.write("Point is inside the sphere"); // distance btw centre and point is // equal to radius else if (ans == (r * r)) document.write("Point lies on the sphere"); // distance btw center and point is // greater than radius else document.write("Point is outside the sphere"); // This code is contributed by Mayank Tyagi </script>
Output:
Point is inside the sphere
Time Complexity:O(1)
vt_m
Vishal_Khoda
mayanktyagi1709
Geometric
School Programming
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n24 Mar, 2021"
},
{
"code": null,
"e": 227,
"s": 53,
"text": "Given co-ordinates of the center of a sphere (cx, cy, cz) and its radius r. Our task is to check whether a point (x, y, z) lies inside, outside or on this sphere.Examples: "
},
{
"code": null,
"e": 500,
"s": 227,
"text": "Input : Centre(0, 0, 0) Radius 3\n Point(1, 1, 1)\nOutput :Point is inside the sphere\n\nInput :Centre(0, 0, 0) Radius 3\n Point(2, 1, 2)\nOutput :Point lies on the sphere\n\nInput :Centre(0, 0, 0) Radius 3\n Point(10, 10, 10)\nOutput :Point is outside the sphere"
},
{
"code": null,
"e": 682,
"s": 502,
"text": "Approach: Whether a point lies inside a sphere or not, depends upon its distance from the centre. A point (x, y, z) is inside the sphere with center (cx, cy, cz) and radius r if "
},
{
"code": null,
"e": 726,
"s": 682,
"text": "( x-cx ) ^2 + (y-cy) ^2 + (z-cz) ^ 2 < r^2 "
},
{
"code": null,
"e": 806,
"s": 726,
"text": "A point (x, y, z) lies on the sphere with center (cx, cy, cz) and radius r if "
},
{
"code": null,
"e": 850,
"s": 806,
"text": "( x-cx ) ^2 + (y-cy) ^2 + (z-cz) ^ 2 = r^2 "
},
{
"code": null,
"e": 933,
"s": 850,
"text": "A point (x, y, z) is outside the sphere with center (cx, cy, cz) and radius r if "
},
{
"code": null,
"e": 977,
"s": 933,
"text": "( x-cx ) ^2 + (y-cy) ^2 + (z-cz) ^ 2 > r^2 "
},
{
"code": null,
"e": 983,
"s": 979,
"text": "C++"
},
{
"code": null,
"e": 988,
"s": 983,
"text": "Java"
},
{
"code": null,
"e": 995,
"s": 988,
"text": "Python"
},
{
"code": null,
"e": 998,
"s": 995,
"text": "C#"
},
{
"code": null,
"e": 1002,
"s": 998,
"text": "PHP"
},
{
"code": null,
"e": 1013,
"s": 1002,
"text": "Javascript"
},
{
"code": "// CPP code to illustrate above approach#include <bits/stdc++.h>using namespace std;// function to calculate the distance between centre and the pointint check(int cx, int cy, int cz, int x, int y, int z){ int x1 = pow((x - cx), 2); int y1 = pow((y - cy), 2); int z1 = pow((z - cz), 2); // distance between the centre // and given point return (x1 + y1 + z1);} // Driver program to test above functionint main(){ // coordinates of centre int cx = 1, cy = 2, cz = 3; int r = 5; // radius of the sphere int x = 4, y = 5, z = 2; // coordinates of point int ans = check(cx, cy, cz, x, y, z); // distance btw centre and point is less // than radius if (ans < (r * r)) cout << \"Point is inside the sphere\"; // distance btw centre and point is // equal to radius else if (ans == (r * r)) cout << \"Point lies on the sphere\"; // distance btw center and point is // greater than radius else cout << \"Point is outside the sphere\"; return 0;}",
"e": 2034,
"s": 1013,
"text": null
},
{
"code": "// Java code to illustrate above approachimport java.io.*;import java.util.*;import java.lang.*; class GfG { // function to calculate the distance // between centre and the point public static int check(int cx, int cy, int cz, int x, int y, int z) { int x1 = (int)Math.pow((x - cx), 2); int y1 = (int)Math.pow((y - cy), 2); int z1 = (int)Math.pow((z - cz), 2); // distance between the centre // and given point return (x1 + y1 + z1); } // Driver program to test above function public static void main(String[] args) { // coordinates of centre int cx = 1, cy = 2, cz = 3; int r = 5; // radius of the sphere // coordinates of point int x = 4, y = 5, z = 2; int ans = check(cx, cy, cz, x, y, z); // distance btw centre and point is less // than radius if (ans < (r * r)) System.out.println(\"Point is inside\" + \" the sphere\"); // distance btw centre and point is // equal to radius else if (ans == (r * r)) System.out.println(\"Point lies on\" + \" the sphere\"); // distance btw center and point is // greater than radius else System.out.println(\"Point is outside\" + \" the sphere\"); }} // This code is contributed by Sagar Shukla.",
"e": 3503,
"s": 2034,
"text": null
},
{
"code": "# Python3 code to illustrate above approach import math# function to calculate distance btw center and given pointdef check(cx, cy, cz, x, y, z, ): x1 = math.pow((x-cx), 2) y1 = math.pow((y-cy), 2) z1 = math.pow((z-cz), 2) return (x1 + y1 + z1) # distance between the centre and given point # driver code cx = 1cy = 2 # coordinates of centrecz = 3 r = 5 # radius of sphere x = 4y = 5 # coordinates of the given pointz = 2# function call to calculate distance btw centre and given pointans = check(cx, cy, cz, x, y, z); # distance btw centre and point is less than radiusif ans<(r**2): print(\"Point is inside the sphere\") # distance btw centre and point is equal to radiuselif ans ==(r**2): print(\"Point lies on the sphere\") # distance btw centre and point is greater than radiuselse: print(\"Point is outside the sphere\")",
"e": 4356,
"s": 3503,
"text": null
},
{
"code": "// C# code to illustrate// above approachusing System; class GFG{ // function to calculate // the distance between // centre and the point public static int check(int cx, int cy, int cz, int x, int y, int z) { int x1 = (int)Math.Pow((x - cx), 2); int y1 = (int)Math.Pow((y - cy), 2); int z1 = (int)Math.Pow((z - cz), 2); // distance between the // centre and given point return (x1 + y1 + z1); } // Driver Code public static void Main() { // coordinates of centre int cx = 1, cy = 2, cz = 3; int r = 5; // radius of the sphere // coordinates of point int x = 4, y = 5, z = 2; int ans = check(cx, cy, cz, x, y, z); // distance btw centre // and point is less // than radius if (ans < (r * r)) Console.WriteLine(\"Point is inside\" + \" the sphere\"); // distance btw centre // and point is // equal to radius else if (ans == (r * r)) Console.WriteLine(\"Point lies on\" + \" the sphere\"); // distance btw center // and point is greater // than radius else Console.WriteLine(\"Point is outside\" + \" the sphere\"); }} // This code is contributed by anuj_67.",
"e": 5857,
"s": 4356,
"text": null
},
{
"code": "<?php// function to calculate // the distance between// centre and the pointfunction check($cx, $cy, $cz, $x, $y, $z){ $x1 = pow(($x - $cx), 2); $y1 = pow(($y - $cy), 2); $z1 = pow(($z - $cz), 2); // distance between the // centre and given point return ($x1 + $y1 + $z1);} // Driver Code // coordinates of centre$cx = 1;$cy = 2;$cz = 3; $r = 5; // radius of the sphere$x = 4;$y = 5;$z = 2; // coordinates of point $ans = check($cx, $cy, $cz, $x, $y, $z); // distance btw centre and// point is less than radiusif ($ans < ($r * $r)) echo \"Point is inside \" . \"the sphere\"; // distance btw centre and// point is equal to radiuselse if ($ans == ($r * $r)) echo \"Point lies on the sphere\"; // distance btw center and point// is greater than radiuselse echo \"Point is outside \" . \"the sphere\"; // This code is contributed// by shiv_bhakt?>",
"e": 6783,
"s": 5857,
"text": null
},
{
"code": "<script> // Javascript code to illustrate above approach // function to calculate the distance between centre and the pointfunction check(cx, cy, cz, x, y, z){ let x1 = Math.pow((x - cx), 2); let y1 = Math.pow((y - cy), 2); let z1 = Math.pow((z - cz), 2); // distance between the centre // and given point return (x1 + y1 + z1);} // Driver program to test above function // coordinates of centre let cx = 1, cy = 2, cz = 3; let r = 5; // radius of the sphere let x = 4, y = 5, z = 2; // coordinates of point let ans = check(cx, cy, cz, x, y, z); // distance btw centre and point is less // than radius if (ans < (r * r)) document.write(\"Point is inside the sphere\"); // distance btw centre and point is // equal to radius else if (ans == (r * r)) document.write(\"Point lies on the sphere\"); // distance btw center and point is // greater than radius else document.write(\"Point is outside the sphere\"); // This code is contributed by Mayank Tyagi </script>",
"e": 7832,
"s": 6783,
"text": null
},
{
"code": null,
"e": 7841,
"s": 7832,
"text": "Output: "
},
{
"code": null,
"e": 7868,
"s": 7841,
"text": "Point is inside the sphere"
},
{
"code": null,
"e": 7890,
"s": 7868,
"text": "Time Complexity:O(1) "
},
{
"code": null,
"e": 7895,
"s": 7890,
"text": "vt_m"
},
{
"code": null,
"e": 7908,
"s": 7895,
"text": "Vishal_Khoda"
},
{
"code": null,
"e": 7924,
"s": 7908,
"text": "mayanktyagi1709"
},
{
"code": null,
"e": 7934,
"s": 7924,
"text": "Geometric"
},
{
"code": null,
"e": 7953,
"s": 7934,
"text": "School Programming"
},
{
"code": null,
"e": 7963,
"s": 7953,
"text": "Geometric"
}
]
|
Find most significant set bit of a number | 27 May, 2022
Given a number, find the greatest number less than the given a number which is the power of two or find the most significant bit number .
Examples:
Input : 10
Output : 8
Greatest number which is a Power of 2 less than 10 is 8
Binary representation of 10 is 1010
The most significant bit corresponds
to decimal number 8.
Input : 18
Output : 16
A simple solution is to one by one divide n by 2 until it becomes 0 and increment a count while doing this. This count actually represents the position of MSB.
C++
C
Java
Python3
C#
PHP
Javascript
// Simple CPP program to find MSB number// for given POSITIVE n.#include <iostream>using namespace std; int setBitNumber(int n){ if (n == 0) return 0; int msb = 0; n = n / 2; while (n != 0) { n = n / 2; msb++; } return (1 << msb);} // Driver codeint main(){ int n = 0; cout << setBitNumber(n); n = ~(int)0; // test for possible overflow cout << "\n" << (unsigned int)setBitNumber(n); return 0;}
#include <stdio.h> int setBitNumber(int n){ if (n == 0) return 0; int msb = 0; n = n / 2; while (n != 0) { n = n / 2; msb++; } return (1 << msb);}int main() { int n = 0; printf("%d \n",setBitNumber(n)); n = ~(int)0; // test for possible overflow int ns = (unsigned int)setBitNumber(n); printf("%d",ns); return 0;}
// Simple Java program to find// MSB number for given n.import java.io.*; class GFG { static int setBitNumber(int n) { if (n == 0) return 0; int msb = 0; n = n / 2; while (n != 0) { n = n / 2; msb++; } return (1 << msb); } // Driver code public static void main(String[] args) { int n = 0; System.out.println(setBitNumber(n)); }} // This code is contributed by ajit
# Simple Python3 program# to find MSB number# for given n.def setBitNumber(n): if (n == 0): return 0; msb = 0; n = int(n / 2); while (n > 0): n = int(n / 2); msb += 1; return (1 << msb); # Driver coden = 0;print(setBitNumber(n)); # This code is contributed# by mits
// Simple C# program to find// MSB number for given n.using System; class GFG { static int setBitNumber(int n) { if (n == 0) return 0; int msb = 0; n = n / 2; while (n != 0) { n = n / 2; msb++; } return (1 << msb); } // Driver code static public void Main() { int n = 0; Console.WriteLine(setBitNumber(n)); }} // This code is contributed// by akt_mit
<?php// Simple PhP program// to find MSB number// for given n. function setBitNumber($n){ if ($n == 0) return 0; $msb = 0; $n = $n / 2; while ($n != 0) { $n = $n / 2; $msb++; } return (1 << $msb);} // Driver code$n = 0;echo setBitNumber($n); // This code is contributed// by akt_mit?>
<script> // Javascript program// to find MSB number// for given n. function setBitNumber(n){ if (n == 0) return 0; let msb = 0; n = n / 2; while (n != 0) { n = $n / 2; msb++; } return (1 << msb);} // Driver codelet n = 0;document.write (setBitNumber(n)); // This code is contributed by Bobby </script>
0
An efficient solution for a fixed size integer (say 32 bits) is to one by one set bits, then add 1 so that only the bit after MSB is set. Finally right shift by 1 and return the answer. This solution does not require any condition checking.
C++
C
Java
Python3
C#
PHP
Javascript
// CPP program to find MSB number for ANY given n.#include <iostream>#include <limits.h>using namespace std; int setBitNumber(int n){ // Below steps set bits after // MSB (including MSB) // Suppose n is 273 (binary // is 100010001). It does following // 100010001 | 010001000 = 110011001 n |= n >> 1; // This makes sure 4 bits // (From MSB and including MSB) // are set. It does following // 110011001 | 001100110 = 111111111 n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // The naive approach would increment n by 1, // so only the MSB+1 bit will be set, // So now n theoretically becomes 1000000000. // All the would remain is a single bit right shift: // n = n + 1; // return (n >> 1); // // ... however, this could overflow the type. // To avoid overflow, we must retain the value // of the bit that could overflow: // n & (1 << ((sizeof(n) * CHAR_BIT)-1)) // and OR its value with the naive approach: // ((n + 1) >> 1) n = ((n + 1) >> 1) | (n & (1 << ((sizeof(n) * CHAR_BIT)-1))); return n;} // Driver codeint main(){ int n = 273; cout << setBitNumber(n); n = ~(int)0; // test for possible overflow cout << "\n" << (unsigned int)setBitNumber(n); return 0;}
#include <stdio.h>#include <limits.h>int setBitNumber(int n){ // Below steps set bits after // MSB (including MSB) // Suppose n is 273 (binary // is 100010001). It does following // 100010001 | 010001000 = 110011001 n |= n >> 1; // This makes sure 4 bits // (From MSB and including MSB) // are set. It does following // 110011001 | 001100110 = 111111111 n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // The naive approach would increment n by 1, // so only the MSB+1 bit will be set, // So now n theoretically becomes 1000000000. // All the would remain is a single bit right shift: // n = n + 1; // return (n >> 1); // // ... however, this could overflow the type. // To avoid overflow, we must retain the value // of the bit that could overflow: // n & (1 << ((sizeof(n) * CHAR_BIT)-1)) // and OR its value with the naive approach: // ((n + 1) >> 1) n = ((n + 1) >> 1) | (n & (1 << ((sizeof(n) * CHAR_BIT)-1))); return n;} int main() { int n = 273; printf("%d\n",setBitNumber(n)); return 0;}
// Java program to find MSB// number for given n. class GFG { static int setBitNumber(int n) { // Below steps set bits after // MSB (including MSB) // Suppose n is 273 (binary // is 100010001). It does following // 100010001 | 010001000 = 110011001 n |= n >> 1; // This makes sure 4 bits // (From MSB and including MSB) // are set. It does following // 110011001 | 001100110 = 111111111 n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // Increment n by 1 so that // there is only one set bit // which is just before original // MSB. n now becomes 1000000000 n = n + 1; // Return original MSB after shifting. // n now becomes 100000000 return (n >> 1); } // Driver code public static void main(String arg[]) { int n = 273; System.out.print(setBitNumber(n)); }} // This code is contributed by Anant Agarwal.
# Python program to find# MSB number for given n. def setBitNumber(n): # Below steps set bits after # MSB (including MSB) # Suppose n is 273 (binary # is 100010001). It does following # 100010001 | 010001000 = 110011001 n |= n>>1 # This makes sure 4 bits # (From MSB and including MSB) # are set. It does following # 110011001 | 001100110 = 111111111 n |= n>>2 n |= n>>4 n |= n>>8 n |= n>>16 # Increment n by 1 so that # there is only one set bit # which is just before original # MSB. n now becomes 1000000000 n = n + 1 # Return original MSB after shifting. # n now becomes 100000000 return (n >> 1) # Driver code n = 273 print(setBitNumber(n)) # This code is contributed# by Anant Agarwal.
// C# program to find MSB number for given n.using System; class GFG { static int setBitNumber(int n) { // Below steps set bits after // MSB (including MSB) // Suppose n is 273 (binary // is 100010001). It does following // 100010001 | 010001000 = 110011001 n |= n >> 1; // This makes sure 4 bits // (From MSB and including MSB) // are set. It does following // 110011001 | 001100110 = 111111111 n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // Increment n by 1 so that // there is only one set bit // which is just before original // MSB. n now becomes 1000000000 n = n + 1; // Return original MSB after shifting. // n now becomes 100000000 return (n >> 1); } // Driver code public static void Main() { int n = 273; Console.WriteLine(setBitNumber(n)); }} // This code is contributed by Sam007.
<?php// PHP program to find// MSB number for given n. function setBitNumber($n){ // Below steps set bits // after MSB (including MSB) // Suppose n is 273 (binary // is 100010001). It does // following 100010001 | // 010001000 = 110011001 $n |= $n >> 1; // This makes sure 4 bits // (From MSB and including // MSB) are set. It does // following 110011001 | // 001100110 = 111111111 $n |= $n >> 2; $n |= $n >> 4; $n |= $n >> 8; $n |= $n >> 16; // Increment n by 1 so // that there is only // one set bit which is // just before original // MSB. n now becomes // 1000000000 $n = $n + 1; // Return original MSB // after shifting. n // now becomes 100000000 return ($n >> 1);} // Driver code$n = 273;echo setBitNumber($n); // This code is contributed// by akt_mit?>
<script> // Javascript program to find MSB// number for given n.function setBitNumber(n){ // Below steps set bits after // MSB (including MSB) // Suppose n is 273 (binary // is 100010001). It does following // 100010001 | 010001000 = 110011001 n |= n >> 1; // This makes sure 4 bits // (From MSB and including MSB) // are set. It does following // 110011001 | 001100110 = 111111111 n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // Increment n by 1 so that // there is only one set bit // which is just before original // MSB. n now becomes 1000000000 n = n + 1; // Return original MSB after shifting. // n now becomes 100000000 return (n >> 1);} // Driver codelet n = 273;document.write(setBitNumber(n)); // This code is contributed by suresh07 </script>
256
Time complexity is O(1).
Another Approach: Given a number n. First, find the position of the most significant set bit and then compute the value of the number with a set bit at k-th position.
Thanks Rohit Narayan for suggesting this method.
C++
C
Java
Python3
C#
PHP
Javascript
// CPP program to find MSB// number for given POSITIVE n.#include <bits/stdc++.h>using namespace std; int setBitNumber(int n){ // To find the position // of the most significant // set bit int k = (int)(log2(n)); // To return the value // of the number with set // bit at k-th position return 1 << k;} // Driver codeint main(){ int n = 273; cout << setBitNumber(n); n = ~(int)0; // test for possible overflow cout << "\n" << (unsigned int)setBitNumber(n); return 0;}
#include <stdio.h>#include <math.h> int setBitNumber(int n){ // To find the position // of the most significant // set bit int k = (int)(log2(n)); // To return the value // of the number with set // bit at k-th position return 1 << k;}int main() { int n = 273; printf("%d",setBitNumber(n)); return 0;}
// Java program to find MSB// number for given n. class GFG { static int setBitNumber(int n) { // To find the position of the // most significant set bit int k = (int)(Math.log(n) / Math.log(2)); // To return the value of the number // with set bit at k-th position return 1 << k; } // Driver code public static void main(String arg[]) { int n = 273; System.out.print(setBitNumber(n)); }}
# Python program to find# MSB number for given n.import math def setBitNumber(n): # To find the position of # the most significant # set bit k = int(math.log(n, 2)) # To return the value # of the number with set # bit at k-th position return 1 << k # Driver coden = 273 print(setBitNumber(n))
// C# program to find MSB// number for given n.using System; public class GFG { static int setBitNumber(int n) { // To find the position of the // most significant set bit int k = (int)(Math.Log(n) / Math.Log(2)); // To return the value of the number // with set bit at k-th position return 1 << k; } // Driver code static public void Main() { int n = 273; Console.WriteLine(setBitNumber(n)); }}
<?php// PHP program to find MSB// number for given n. function setBitNumber($n){ // To find the position // of the most significant // set bit $k =(int)(log($n, 2)); // To return the value // of the number with set // bit at k-th position return 1 << $k;} // Driver code $n = 273; echo setBitNumber($n); // This code is contributed// by jit_t.?>
<script> // Javascript program to find // MSB number for given n. function setBitNumber(n) { // To find the position of the // most significant set bit let k = parseInt(Math.log(n) / Math.log(2), 10); // To return the value of the number // with set bit at k-th position return 1 << k; } let n = 273; document.write(setBitNumber(n)); </script>
256
Another Approach :
This article is contributed by Devanshu Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. 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.
Sam007
rohitnarayan
jit_t
Mithun Kumar
Akanksha_Rai
surjyaroy2001
pragup
probablyamogh
gottumukkalabobby
divyeshrabadiya07
suresh07
simranarora5sos
bo9
sweetyty
devendrasalunke
Bit Magic
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n27 May, 2022"
},
{
"code": null,
"e": 192,
"s": 54,
"text": "Given a number, find the greatest number less than the given a number which is the power of two or find the most significant bit number ."
},
{
"code": null,
"e": 203,
"s": 192,
"text": "Examples: "
},
{
"code": null,
"e": 400,
"s": 203,
"text": "Input : 10\nOutput : 8\nGreatest number which is a Power of 2 less than 10 is 8\nBinary representation of 10 is 1010\nThe most significant bit corresponds\nto decimal number 8.\n\nInput : 18\nOutput : 16 "
},
{
"code": null,
"e": 561,
"s": 400,
"text": "A simple solution is to one by one divide n by 2 until it becomes 0 and increment a count while doing this. This count actually represents the position of MSB. "
},
{
"code": null,
"e": 565,
"s": 561,
"text": "C++"
},
{
"code": null,
"e": 567,
"s": 565,
"text": "C"
},
{
"code": null,
"e": 572,
"s": 567,
"text": "Java"
},
{
"code": null,
"e": 580,
"s": 572,
"text": "Python3"
},
{
"code": null,
"e": 583,
"s": 580,
"text": "C#"
},
{
"code": null,
"e": 587,
"s": 583,
"text": "PHP"
},
{
"code": null,
"e": 598,
"s": 587,
"text": "Javascript"
},
{
"code": "// Simple CPP program to find MSB number// for given POSITIVE n.#include <iostream>using namespace std; int setBitNumber(int n){ if (n == 0) return 0; int msb = 0; n = n / 2; while (n != 0) { n = n / 2; msb++; } return (1 << msb);} // Driver codeint main(){ int n = 0; cout << setBitNumber(n); n = ~(int)0; // test for possible overflow cout << \"\\n\" << (unsigned int)setBitNumber(n); return 0;}",
"e": 1050,
"s": 598,
"text": null
},
{
"code": "#include <stdio.h> int setBitNumber(int n){ if (n == 0) return 0; int msb = 0; n = n / 2; while (n != 0) { n = n / 2; msb++; } return (1 << msb);}int main() { int n = 0; printf(\"%d \\n\",setBitNumber(n)); n = ~(int)0; // test for possible overflow int ns = (unsigned int)setBitNumber(n); printf(\"%d\",ns); return 0;}",
"e": 1425,
"s": 1050,
"text": null
},
{
"code": "// Simple Java program to find// MSB number for given n.import java.io.*; class GFG { static int setBitNumber(int n) { if (n == 0) return 0; int msb = 0; n = n / 2; while (n != 0) { n = n / 2; msb++; } return (1 << msb); } // Driver code public static void main(String[] args) { int n = 0; System.out.println(setBitNumber(n)); }} // This code is contributed by ajit",
"e": 1905,
"s": 1425,
"text": null
},
{
"code": "# Simple Python3 program# to find MSB number# for given n.def setBitNumber(n): if (n == 0): return 0; msb = 0; n = int(n / 2); while (n > 0): n = int(n / 2); msb += 1; return (1 << msb); # Driver coden = 0;print(setBitNumber(n)); # This code is contributed# by mits",
"e": 2214,
"s": 1905,
"text": null
},
{
"code": "// Simple C# program to find// MSB number for given n.using System; class GFG { static int setBitNumber(int n) { if (n == 0) return 0; int msb = 0; n = n / 2; while (n != 0) { n = n / 2; msb++; } return (1 << msb); } // Driver code static public void Main() { int n = 0; Console.WriteLine(setBitNumber(n)); }} // This code is contributed// by akt_mit",
"e": 2679,
"s": 2214,
"text": null
},
{
"code": "<?php// Simple PhP program// to find MSB number// for given n. function setBitNumber($n){ if ($n == 0) return 0; $msb = 0; $n = $n / 2; while ($n != 0) { $n = $n / 2; $msb++; } return (1 << $msb);} // Driver code$n = 0;echo setBitNumber($n); // This code is contributed// by akt_mit?>",
"e": 3017,
"s": 2679,
"text": null
},
{
"code": "<script> // Javascript program// to find MSB number// for given n. function setBitNumber(n){ if (n == 0) return 0; let msb = 0; n = n / 2; while (n != 0) { n = $n / 2; msb++; } return (1 << msb);} // Driver codelet n = 0;document.write (setBitNumber(n)); // This code is contributed by Bobby </script>",
"e": 3373,
"s": 3017,
"text": null
},
{
"code": null,
"e": 3375,
"s": 3373,
"text": "0"
},
{
"code": null,
"e": 3618,
"s": 3377,
"text": "An efficient solution for a fixed size integer (say 32 bits) is to one by one set bits, then add 1 so that only the bit after MSB is set. Finally right shift by 1 and return the answer. This solution does not require any condition checking."
},
{
"code": null,
"e": 3622,
"s": 3618,
"text": "C++"
},
{
"code": null,
"e": 3624,
"s": 3622,
"text": "C"
},
{
"code": null,
"e": 3629,
"s": 3624,
"text": "Java"
},
{
"code": null,
"e": 3637,
"s": 3629,
"text": "Python3"
},
{
"code": null,
"e": 3640,
"s": 3637,
"text": "C#"
},
{
"code": null,
"e": 3644,
"s": 3640,
"text": "PHP"
},
{
"code": null,
"e": 3655,
"s": 3644,
"text": "Javascript"
},
{
"code": "// CPP program to find MSB number for ANY given n.#include <iostream>#include <limits.h>using namespace std; int setBitNumber(int n){ // Below steps set bits after // MSB (including MSB) // Suppose n is 273 (binary // is 100010001). It does following // 100010001 | 010001000 = 110011001 n |= n >> 1; // This makes sure 4 bits // (From MSB and including MSB) // are set. It does following // 110011001 | 001100110 = 111111111 n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // The naive approach would increment n by 1, // so only the MSB+1 bit will be set, // So now n theoretically becomes 1000000000. // All the would remain is a single bit right shift: // n = n + 1; // return (n >> 1); // // ... however, this could overflow the type. // To avoid overflow, we must retain the value // of the bit that could overflow: // n & (1 << ((sizeof(n) * CHAR_BIT)-1)) // and OR its value with the naive approach: // ((n + 1) >> 1) n = ((n + 1) >> 1) | (n & (1 << ((sizeof(n) * CHAR_BIT)-1))); return n;} // Driver codeint main(){ int n = 273; cout << setBitNumber(n); n = ~(int)0; // test for possible overflow cout << \"\\n\" << (unsigned int)setBitNumber(n); return 0;}",
"e": 4950,
"s": 3655,
"text": null
},
{
"code": "#include <stdio.h>#include <limits.h>int setBitNumber(int n){ // Below steps set bits after // MSB (including MSB) // Suppose n is 273 (binary // is 100010001). It does following // 100010001 | 010001000 = 110011001 n |= n >> 1; // This makes sure 4 bits // (From MSB and including MSB) // are set. It does following // 110011001 | 001100110 = 111111111 n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // The naive approach would increment n by 1, // so only the MSB+1 bit will be set, // So now n theoretically becomes 1000000000. // All the would remain is a single bit right shift: // n = n + 1; // return (n >> 1); // // ... however, this could overflow the type. // To avoid overflow, we must retain the value // of the bit that could overflow: // n & (1 << ((sizeof(n) * CHAR_BIT)-1)) // and OR its value with the naive approach: // ((n + 1) >> 1) n = ((n + 1) >> 1) | (n & (1 << ((sizeof(n) * CHAR_BIT)-1))); return n;} int main() { int n = 273; printf(\"%d\\n\",setBitNumber(n)); return 0;}",
"e": 6070,
"s": 4950,
"text": null
},
{
"code": "// Java program to find MSB// number for given n. class GFG { static int setBitNumber(int n) { // Below steps set bits after // MSB (including MSB) // Suppose n is 273 (binary // is 100010001). It does following // 100010001 | 010001000 = 110011001 n |= n >> 1; // This makes sure 4 bits // (From MSB and including MSB) // are set. It does following // 110011001 | 001100110 = 111111111 n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // Increment n by 1 so that // there is only one set bit // which is just before original // MSB. n now becomes 1000000000 n = n + 1; // Return original MSB after shifting. // n now becomes 100000000 return (n >> 1); } // Driver code public static void main(String arg[]) { int n = 273; System.out.print(setBitNumber(n)); }} // This code is contributed by Anant Agarwal.",
"e": 7078,
"s": 6070,
"text": null
},
{
"code": "# Python program to find# MSB number for given n. def setBitNumber(n): # Below steps set bits after # MSB (including MSB) # Suppose n is 273 (binary # is 100010001). It does following # 100010001 | 010001000 = 110011001 n |= n>>1 # This makes sure 4 bits # (From MSB and including MSB) # are set. It does following # 110011001 | 001100110 = 111111111 n |= n>>2 n |= n>>4 n |= n>>8 n |= n>>16 # Increment n by 1 so that # there is only one set bit # which is just before original # MSB. n now becomes 1000000000 n = n + 1 # Return original MSB after shifting. # n now becomes 100000000 return (n >> 1) # Driver code n = 273 print(setBitNumber(n)) # This code is contributed# by Anant Agarwal.",
"e": 7864,
"s": 7078,
"text": null
},
{
"code": "// C# program to find MSB number for given n.using System; class GFG { static int setBitNumber(int n) { // Below steps set bits after // MSB (including MSB) // Suppose n is 273 (binary // is 100010001). It does following // 100010001 | 010001000 = 110011001 n |= n >> 1; // This makes sure 4 bits // (From MSB and including MSB) // are set. It does following // 110011001 | 001100110 = 111111111 n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // Increment n by 1 so that // there is only one set bit // which is just before original // MSB. n now becomes 1000000000 n = n + 1; // Return original MSB after shifting. // n now becomes 100000000 return (n >> 1); } // Driver code public static void Main() { int n = 273; Console.WriteLine(setBitNumber(n)); }} // This code is contributed by Sam007.",
"e": 8863,
"s": 7864,
"text": null
},
{
"code": "<?php// PHP program to find// MSB number for given n. function setBitNumber($n){ // Below steps set bits // after MSB (including MSB) // Suppose n is 273 (binary // is 100010001). It does // following 100010001 | // 010001000 = 110011001 $n |= $n >> 1; // This makes sure 4 bits // (From MSB and including // MSB) are set. It does // following 110011001 | // 001100110 = 111111111 $n |= $n >> 2; $n |= $n >> 4; $n |= $n >> 8; $n |= $n >> 16; // Increment n by 1 so // that there is only // one set bit which is // just before original // MSB. n now becomes // 1000000000 $n = $n + 1; // Return original MSB // after shifting. n // now becomes 100000000 return ($n >> 1);} // Driver code$n = 273;echo setBitNumber($n); // This code is contributed// by akt_mit?>",
"e": 9710,
"s": 8863,
"text": null
},
{
"code": "<script> // Javascript program to find MSB// number for given n.function setBitNumber(n){ // Below steps set bits after // MSB (including MSB) // Suppose n is 273 (binary // is 100010001). It does following // 100010001 | 010001000 = 110011001 n |= n >> 1; // This makes sure 4 bits // (From MSB and including MSB) // are set. It does following // 110011001 | 001100110 = 111111111 n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // Increment n by 1 so that // there is only one set bit // which is just before original // MSB. n now becomes 1000000000 n = n + 1; // Return original MSB after shifting. // n now becomes 100000000 return (n >> 1);} // Driver codelet n = 273;document.write(setBitNumber(n)); // This code is contributed by suresh07 </script>",
"e": 10548,
"s": 9710,
"text": null
},
{
"code": null,
"e": 10552,
"s": 10548,
"text": "256"
},
{
"code": null,
"e": 10579,
"s": 10554,
"text": "Time complexity is O(1)."
},
{
"code": null,
"e": 10747,
"s": 10579,
"text": "Another Approach: Given a number n. First, find the position of the most significant set bit and then compute the value of the number with a set bit at k-th position. "
},
{
"code": null,
"e": 10797,
"s": 10747,
"text": "Thanks Rohit Narayan for suggesting this method. "
},
{
"code": null,
"e": 10801,
"s": 10797,
"text": "C++"
},
{
"code": null,
"e": 10803,
"s": 10801,
"text": "C"
},
{
"code": null,
"e": 10808,
"s": 10803,
"text": "Java"
},
{
"code": null,
"e": 10816,
"s": 10808,
"text": "Python3"
},
{
"code": null,
"e": 10819,
"s": 10816,
"text": "C#"
},
{
"code": null,
"e": 10823,
"s": 10819,
"text": "PHP"
},
{
"code": null,
"e": 10834,
"s": 10823,
"text": "Javascript"
},
{
"code": "// CPP program to find MSB// number for given POSITIVE n.#include <bits/stdc++.h>using namespace std; int setBitNumber(int n){ // To find the position // of the most significant // set bit int k = (int)(log2(n)); // To return the value // of the number with set // bit at k-th position return 1 << k;} // Driver codeint main(){ int n = 273; cout << setBitNumber(n); n = ~(int)0; // test for possible overflow cout << \"\\n\" << (unsigned int)setBitNumber(n); return 0;}",
"e": 11342,
"s": 10834,
"text": null
},
{
"code": "#include <stdio.h>#include <math.h> int setBitNumber(int n){ // To find the position // of the most significant // set bit int k = (int)(log2(n)); // To return the value // of the number with set // bit at k-th position return 1 << k;}int main() { int n = 273; printf(\"%d\",setBitNumber(n)); return 0;}",
"e": 11679,
"s": 11342,
"text": null
},
{
"code": "// Java program to find MSB// number for given n. class GFG { static int setBitNumber(int n) { // To find the position of the // most significant set bit int k = (int)(Math.log(n) / Math.log(2)); // To return the value of the number // with set bit at k-th position return 1 << k; } // Driver code public static void main(String arg[]) { int n = 273; System.out.print(setBitNumber(n)); }}",
"e": 12149,
"s": 11679,
"text": null
},
{
"code": "# Python program to find# MSB number for given n.import math def setBitNumber(n): # To find the position of # the most significant # set bit k = int(math.log(n, 2)) # To return the value # of the number with set # bit at k-th position return 1 << k # Driver coden = 273 print(setBitNumber(n))",
"e": 12482,
"s": 12149,
"text": null
},
{
"code": "// C# program to find MSB// number for given n.using System; public class GFG { static int setBitNumber(int n) { // To find the position of the // most significant set bit int k = (int)(Math.Log(n) / Math.Log(2)); // To return the value of the number // with set bit at k-th position return 1 << k; } // Driver code static public void Main() { int n = 273; Console.WriteLine(setBitNumber(n)); }}",
"e": 12960,
"s": 12482,
"text": null
},
{
"code": "<?php// PHP program to find MSB// number for given n. function setBitNumber($n){ // To find the position // of the most significant // set bit $k =(int)(log($n, 2)); // To return the value // of the number with set // bit at k-th position return 1 << $k;} // Driver code $n = 273; echo setBitNumber($n); // This code is contributed// by jit_t.?>",
"e": 13338,
"s": 12960,
"text": null
},
{
"code": "<script> // Javascript program to find // MSB number for given n. function setBitNumber(n) { // To find the position of the // most significant set bit let k = parseInt(Math.log(n) / Math.log(2), 10); // To return the value of the number // with set bit at k-th position return 1 << k; } let n = 273; document.write(setBitNumber(n)); </script>",
"e": 13766,
"s": 13338,
"text": null
},
{
"code": null,
"e": 13770,
"s": 13766,
"text": "256"
},
{
"code": null,
"e": 13792,
"s": 13772,
"text": "Another Approach : "
},
{
"code": null,
"e": 14216,
"s": 13792,
"text": "This article is contributed by Devanshu Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. 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": 14223,
"s": 14216,
"text": "Sam007"
},
{
"code": null,
"e": 14236,
"s": 14223,
"text": "rohitnarayan"
},
{
"code": null,
"e": 14242,
"s": 14236,
"text": "jit_t"
},
{
"code": null,
"e": 14255,
"s": 14242,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 14268,
"s": 14255,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 14282,
"s": 14268,
"text": "surjyaroy2001"
},
{
"code": null,
"e": 14289,
"s": 14282,
"text": "pragup"
},
{
"code": null,
"e": 14303,
"s": 14289,
"text": "probablyamogh"
},
{
"code": null,
"e": 14321,
"s": 14303,
"text": "gottumukkalabobby"
},
{
"code": null,
"e": 14339,
"s": 14321,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 14348,
"s": 14339,
"text": "suresh07"
},
{
"code": null,
"e": 14364,
"s": 14348,
"text": "simranarora5sos"
},
{
"code": null,
"e": 14368,
"s": 14364,
"text": "bo9"
},
{
"code": null,
"e": 14377,
"s": 14368,
"text": "sweetyty"
},
{
"code": null,
"e": 14393,
"s": 14377,
"text": "devendrasalunke"
},
{
"code": null,
"e": 14403,
"s": 14393,
"text": "Bit Magic"
},
{
"code": null,
"e": 14413,
"s": 14403,
"text": "Bit Magic"
}
]
|
SQL | WITH clause | 13 Aug, 2021
The SQL WITH clause was introduced by Oracle in the Oracle 9i release 2 database. The SQL WITH clause allows you to give a sub-query block a name (a process also called sub-query refactoring), which can be referenced in several places within the main SQL query.
The clause is used for defining a temporary relation such that the output of this temporary relation is available and is used by the query that is associated with the WITH clause.
Queries that have an associated WITH clause can also be written using nested sub-queries but doing so add more complexity to read/debug the SQL query.
WITH clause is not supported by all database system.
The name assigned to the sub-query is treated as though it was an inline view or table
The SQL WITH clause was introduced by Oracle in the Oracle 9i release 2 database.
Syntax:
WITH temporaryTable (averageValue) as
(SELECT avg(Attr1)
FROM Table)
SELECT Attr1
FROM Table, temporaryTable
WHERE Table.Attr1 > temporaryTable.averageValue;
In this query, WITH clause is used to define a temporary relation temporaryTable that has only 1 attribute averageValue. averageValue holds the average value of column Attr1 described in relation Table. The SELECT statement that follows the WITH clause will produce only those tuples where the value of Attr1 in relation Table is greater than the average value obtained from the WITH clause statement.
Note: When a query with a WITH clause is executed, first the query mentioned within the clause is evaluated and the output of this evaluation is stored in a temporary relation. Following this, the main query associated with the WITH clause is finally executed that would use the temporary relation produced.
Queries
Example 1: Find all the employee whose salary is more than the average salary of all employees. Name of the relation: Employee
SQL Query:
WITH temporaryTable(averageValue) as
(SELECT avg(Salary)
from Employee)
SELECT EmployeeID,Name, Salary
FROM Employee, temporaryTable
WHERE Employee.Salary > temporaryTable.averageValue;
Output:
Explanation: The average salary of all employees is 70591. Therefore, all employees whose salary is more than the obtained average lies in the output relation.
Example 2: Find all the airlines where the total salary of all pilots in that airline is more than the average of total salary of all pilots in the database.
Name of the relation: Pilot
SQL Query:
WITH totalSalary(Airline, total) as
(SELECT Airline, sum(Salary)
FROM Pilot
GROUP BY Airline),
airlineAverage(avgSalary) as
(SELECT avg(Salary)
FROM Pilot )
SELECT Airline
FROM totalSalary, airlineAverage
WHERE totalSalary.total > airlineAverage.avgSalary;
Output:
Explanation: The total salary of all pilots of Airbus 380 = 298,830 and that of Boeing = 45000. Average salary of all pilots in the table Pilot = 57305. Since only the total salary of all pilots of Airbus 380 is greater than the average salary obtained, so Airbus 380 lies in the output relation.
Important Points:
The SQL WITH clause is good when used with complex SQL statements rather than simple ones
It also allows you to break down complex SQL queries into smaller ones which make it easy for debugging and processing the complex queries.
The SQL WITH clause is basically a drop-in replacement to the normal sub-query.
This article is contributed by Mayank Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. 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.
lonewolf_ab
SaranshSharma
amanpandey12
narcis
DBMS-SQL
SQL-basics
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n13 Aug, 2021"
},
{
"code": null,
"e": 318,
"s": 54,
"text": "The SQL WITH clause was introduced by Oracle in the Oracle 9i release 2 database. The SQL WITH clause allows you to give a sub-query block a name (a process also called sub-query refactoring), which can be referenced in several places within the main SQL query. "
},
{
"code": null,
"e": 498,
"s": 318,
"text": "The clause is used for defining a temporary relation such that the output of this temporary relation is available and is used by the query that is associated with the WITH clause."
},
{
"code": null,
"e": 649,
"s": 498,
"text": "Queries that have an associated WITH clause can also be written using nested sub-queries but doing so add more complexity to read/debug the SQL query."
},
{
"code": null,
"e": 702,
"s": 649,
"text": "WITH clause is not supported by all database system."
},
{
"code": null,
"e": 789,
"s": 702,
"text": "The name assigned to the sub-query is treated as though it was an inline view or table"
},
{
"code": null,
"e": 871,
"s": 789,
"text": "The SQL WITH clause was introduced by Oracle in the Oracle 9i release 2 database."
},
{
"code": null,
"e": 880,
"s": 871,
"text": "Syntax: "
},
{
"code": null,
"e": 1060,
"s": 880,
"text": "WITH temporaryTable (averageValue) as\n (SELECT avg(Attr1)\n FROM Table)\n SELECT Attr1\n FROM Table, temporaryTable\n WHERE Table.Attr1 > temporaryTable.averageValue;\n "
},
{
"code": null,
"e": 1463,
"s": 1060,
"text": "In this query, WITH clause is used to define a temporary relation temporaryTable that has only 1 attribute averageValue. averageValue holds the average value of column Attr1 described in relation Table. The SELECT statement that follows the WITH clause will produce only those tuples where the value of Attr1 in relation Table is greater than the average value obtained from the WITH clause statement. "
},
{
"code": null,
"e": 1774,
"s": 1463,
"text": "Note: When a query with a WITH clause is executed, first the query mentioned within the clause is evaluated and the output of this evaluation is stored in a temporary relation. Following this, the main query associated with the WITH clause is finally executed that would use the temporary relation produced. "
},
{
"code": null,
"e": 1782,
"s": 1774,
"text": "Queries"
},
{
"code": null,
"e": 1912,
"s": 1782,
"text": "Example 1: Find all the employee whose salary is more than the average salary of all employees. Name of the relation: Employee "
},
{
"code": null,
"e": 1924,
"s": 1912,
"text": "SQL Query: "
},
{
"code": null,
"e": 2144,
"s": 1924,
"text": "WITH temporaryTable(averageValue) as\n (SELECT avg(Salary)\n from Employee)\n SELECT EmployeeID,Name, Salary \n FROM Employee, temporaryTable \n WHERE Employee.Salary > temporaryTable.averageValue;"
},
{
"code": null,
"e": 2154,
"s": 2144,
"text": "Output: "
},
{
"code": null,
"e": 2316,
"s": 2154,
"text": "Explanation: The average salary of all employees is 70591. Therefore, all employees whose salary is more than the obtained average lies in the output relation. "
},
{
"code": null,
"e": 2475,
"s": 2316,
"text": "Example 2: Find all the airlines where the total salary of all pilots in that airline is more than the average of total salary of all pilots in the database. "
},
{
"code": null,
"e": 2505,
"s": 2475,
"text": "Name of the relation: Pilot "
},
{
"code": null,
"e": 2517,
"s": 2505,
"text": "SQL Query: "
},
{
"code": null,
"e": 2811,
"s": 2517,
"text": "WITH totalSalary(Airline, total) as\n (SELECT Airline, sum(Salary)\n FROM Pilot\n GROUP BY Airline),\n airlineAverage(avgSalary) as \n (SELECT avg(Salary)\n FROM Pilot )\n SELECT Airline\n FROM totalSalary, airlineAverage\n WHERE totalSalary.total > airlineAverage.avgSalary;"
},
{
"code": null,
"e": 2821,
"s": 2811,
"text": "Output: "
},
{
"code": null,
"e": 3119,
"s": 2821,
"text": "Explanation: The total salary of all pilots of Airbus 380 = 298,830 and that of Boeing = 45000. Average salary of all pilots in the table Pilot = 57305. Since only the total salary of all pilots of Airbus 380 is greater than the average salary obtained, so Airbus 380 lies in the output relation. "
},
{
"code": null,
"e": 3138,
"s": 3119,
"text": "Important Points: "
},
{
"code": null,
"e": 3228,
"s": 3138,
"text": "The SQL WITH clause is good when used with complex SQL statements rather than simple ones"
},
{
"code": null,
"e": 3368,
"s": 3228,
"text": "It also allows you to break down complex SQL queries into smaller ones which make it easy for debugging and processing the complex queries."
},
{
"code": null,
"e": 3448,
"s": 3368,
"text": "The SQL WITH clause is basically a drop-in replacement to the normal sub-query."
},
{
"code": null,
"e": 3745,
"s": 3448,
"text": "This article is contributed by Mayank Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. "
},
{
"code": null,
"e": 3870,
"s": 3745,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 3882,
"s": 3870,
"text": "lonewolf_ab"
},
{
"code": null,
"e": 3896,
"s": 3882,
"text": "SaranshSharma"
},
{
"code": null,
"e": 3909,
"s": 3896,
"text": "amanpandey12"
},
{
"code": null,
"e": 3916,
"s": 3909,
"text": "narcis"
},
{
"code": null,
"e": 3925,
"s": 3916,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 3936,
"s": 3925,
"text": "SQL-basics"
},
{
"code": null,
"e": 3941,
"s": 3936,
"text": "DBMS"
},
{
"code": null,
"e": 3945,
"s": 3941,
"text": "SQL"
},
{
"code": null,
"e": 3950,
"s": 3945,
"text": "DBMS"
},
{
"code": null,
"e": 3954,
"s": 3950,
"text": "SQL"
}
]
|
How to include HTML code snippets in HTML ? | 11 Nov, 2021
In this article, we will learn how to include HTML snippets in HTML code. We will include the HTML code snippet of “gfg.html” into “index.html“. To achieve this task, we are going to write a JavaScript function in “index.html” which traverses the collection of all HTML elements in “gfg.html” and searches for elements with specific attributes. It creates an HTTP request with the attribute value as the file name. In the end, we will differentiate between the main “index.html” file and included the “gfg.html” snippet.
Approach:
Create two HTML files “index.html” and “gfg.html“.
Create another HTML file for including the “index.html” file.
Create a JavaScript function in the main HTML file for including the HTML Snippet.
Call the function in the main ( “index.html“) file to include the snippet of “gfg.html“.
Step 1: Create the main HTML file named “index.html” file. This file will display a heading text ‘This is index.html’.
HTML
<!DOCTYPE html><html> <body> <h1 align='center'> <font color='Red'> This is index.html </font> </h1></body> </html>
Output:
Step 2: Create another HTML file of your choice for including in the “index.html” file and save this file in the same directory in which “index.html” is present. In this article, create an HTML file named “gfg.html” which displays ” GeeksforGeeks A Computer Science Portal For Geeks “.
HTML
<!DOCTYPE html><html> <style> body { text-align: center; } .gfg { font-size: 180px; font-weight: bold; color: green; } .geeks { font-size: 50px; font-weight: bold; font-family: Arial; }</style> <body> <div class="gfg">GeeksforGeeks</div> <div class="geeks"> A computer science portal for geeks </div> <h1> <font color='Blue'> This is gfg.html </font> </h1></body> </html>
Output:
Step 3: We are going to include the “gfg.html” snippet in the “index.html” file. Including HTML is done by using a GFG-include-html-snippet attribute.
<div GFG-include-html-snippet="gfg.html"></div>
Add the JavaScript
Traverse the collection of all HTML elements.
Search for elements with specific attributes.
Create an HTTP request with the attribute value as the file name.
Delete the attribute and call this function again.
Exit function.
JavaScript code snippet:
Javascript
<script> function includeHTMLSnippet() { // Traverse the collection of all // HTML elements id = document.getElementsByTagName("*"); for (i = 0; i < id.length; i++) { element = id[i]; // Search for elements with // specific attributes file = element.getAttribute( "GFG-include-html-snippet"); if (file) { // Create an HTTP request with // the attribute value as the // file name xmlRequest = new XMLHttpRequest(); xmlRequest.onreadystatechange = function () { if (this.readyState == 4) { if (this.status == 200) { element.innerHTML = this.responseText; } if (this.status == 404) { element.innerHTML = "Page not found."; } // Delete the attribute and // call this function again. element.removeAttribute( "GFG-include-html-snippet"); includeHTMLSnippet(); } } xmlRequest.open("GET", file, true); xmlRequest.send(); return; // Exit function. } } };</script>
Step 4: Call includeHTMLSnippet() at the bottom of the page.
<script>
includeHTMLSnippet();
</script>
Final code: The following code demonstrates the combination of all the above steps.
index.html
<!DOCTYPE html><html> <head> <script> function includeHTMLSnippet() { // Traverse the collection of // all HTML elements id = document.getElementsByTagName("*"); for (i = 0; i < id.length; i++) { element = id[i]; // Search for elements with // specific attributes file = element.getAttribute( "GFG-include-html-snippet"); if (file) { // Create an HTTP request with the // attribute value as the file name xmlRequest = new XMLHttpRequest(); xmlRequest.onreadystatechange = function () { if (this.readyState == 4) { if (this.status == 200) { element.innerHTML = this.responseText; } if (this.status == 404) { element.innerHTML = "Page not found."; } // Delete the attribute and // call this function again element.removeAttribute( "GFG-include-html-snippet"); includeHTMLSnippet(); } } xmlRequest.open("GET", file, true); xmlRequest.send(); return; // Exit function. } } }; </script></head> <body> <h1 align='center'> <font color='Red'> This is index.html </font> </h1> <div GFG-include-html-snippet="gfg.html"></div> <script> includeHTMLSnippet(); </script></body> </html>
gfg.html
<!DOCTYPE html><html> <head> <style> body { text-align: center; } .gfg { font-size: 140px; font-weight: bold; color: green; } .geeks { font-size: 50px; font-weight: bold; font-family: Arial; } </style></head> <body> <div class="gfg"> GeeksforGeeks </div> <div class="geeks"> A computer science portal for geeks </div> <h1> <font color='Blue'> This is gfg.html </font> </h1></body> </html>
Output:
Differentiating included gfg.html snippet in index.html: The red border indicates the output of the main index.html and the blue border indicates the output of included HTML snippet.
CSS-Properties
CSS-Questions
HTML-Questions
JavaScript-Questions
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": 54,
"s": 26,
"text": "\n11 Nov, 2021"
},
{
"code": null,
"e": 575,
"s": 54,
"text": "In this article, we will learn how to include HTML snippets in HTML code. We will include the HTML code snippet of “gfg.html” into “index.html“. To achieve this task, we are going to write a JavaScript function in “index.html” which traverses the collection of all HTML elements in “gfg.html” and searches for elements with specific attributes. It creates an HTTP request with the attribute value as the file name. In the end, we will differentiate between the main “index.html” file and included the “gfg.html” snippet."
},
{
"code": null,
"e": 585,
"s": 575,
"text": "Approach:"
},
{
"code": null,
"e": 636,
"s": 585,
"text": "Create two HTML files “index.html” and “gfg.html“."
},
{
"code": null,
"e": 698,
"s": 636,
"text": "Create another HTML file for including the “index.html” file."
},
{
"code": null,
"e": 781,
"s": 698,
"text": "Create a JavaScript function in the main HTML file for including the HTML Snippet."
},
{
"code": null,
"e": 870,
"s": 781,
"text": "Call the function in the main ( “index.html“) file to include the snippet of “gfg.html“."
},
{
"code": null,
"e": 989,
"s": 870,
"text": "Step 1: Create the main HTML file named “index.html” file. This file will display a heading text ‘This is index.html’."
},
{
"code": null,
"e": 996,
"s": 991,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <h1 align='center'> <font color='Red'> This is index.html </font> </h1></body> </html>",
"e": 1146,
"s": 996,
"text": null
},
{
"code": null,
"e": 1154,
"s": 1146,
"text": "Output:"
},
{
"code": null,
"e": 1440,
"s": 1154,
"text": "Step 2: Create another HTML file of your choice for including in the “index.html” file and save this file in the same directory in which “index.html” is present. In this article, create an HTML file named “gfg.html” which displays ” GeeksforGeeks A Computer Science Portal For Geeks “."
},
{
"code": null,
"e": 1445,
"s": 1440,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <style> body { text-align: center; } .gfg { font-size: 180px; font-weight: bold; color: green; } .geeks { font-size: 50px; font-weight: bold; font-family: Arial; }</style> <body> <div class=\"gfg\">GeeksforGeeks</div> <div class=\"geeks\"> A computer science portal for geeks </div> <h1> <font color='Blue'> This is gfg.html </font> </h1></body> </html>",
"e": 1941,
"s": 1445,
"text": null
},
{
"code": null,
"e": 1949,
"s": 1941,
"text": "Output:"
},
{
"code": null,
"e": 2100,
"s": 1949,
"text": "Step 3: We are going to include the “gfg.html” snippet in the “index.html” file. Including HTML is done by using a GFG-include-html-snippet attribute."
},
{
"code": null,
"e": 2148,
"s": 2100,
"text": "<div GFG-include-html-snippet=\"gfg.html\"></div>"
},
{
"code": null,
"e": 2167,
"s": 2148,
"text": "Add the JavaScript"
},
{
"code": null,
"e": 2213,
"s": 2167,
"text": "Traverse the collection of all HTML elements."
},
{
"code": null,
"e": 2259,
"s": 2213,
"text": "Search for elements with specific attributes."
},
{
"code": null,
"e": 2325,
"s": 2259,
"text": "Create an HTTP request with the attribute value as the file name."
},
{
"code": null,
"e": 2376,
"s": 2325,
"text": "Delete the attribute and call this function again."
},
{
"code": null,
"e": 2391,
"s": 2376,
"text": "Exit function."
},
{
"code": null,
"e": 2416,
"s": 2391,
"text": "JavaScript code snippet:"
},
{
"code": null,
"e": 2427,
"s": 2416,
"text": "Javascript"
},
{
"code": "<script> function includeHTMLSnippet() { // Traverse the collection of all // HTML elements id = document.getElementsByTagName(\"*\"); for (i = 0; i < id.length; i++) { element = id[i]; // Search for elements with // specific attributes file = element.getAttribute( \"GFG-include-html-snippet\"); if (file) { // Create an HTTP request with // the attribute value as the // file name xmlRequest = new XMLHttpRequest(); xmlRequest.onreadystatechange = function () { if (this.readyState == 4) { if (this.status == 200) { element.innerHTML = this.responseText; } if (this.status == 404) { element.innerHTML = \"Page not found.\"; } // Delete the attribute and // call this function again. element.removeAttribute( \"GFG-include-html-snippet\"); includeHTMLSnippet(); } } xmlRequest.open(\"GET\", file, true); xmlRequest.send(); return; // Exit function. } } };</script>",
"e": 3926,
"s": 2427,
"text": null
},
{
"code": null,
"e": 3987,
"s": 3926,
"text": "Step 4: Call includeHTMLSnippet() at the bottom of the page."
},
{
"code": null,
"e": 4032,
"s": 3987,
"text": "<script>\n includeHTMLSnippet();\n</script>"
},
{
"code": null,
"e": 4116,
"s": 4032,
"text": "Final code: The following code demonstrates the combination of all the above steps."
},
{
"code": null,
"e": 4127,
"s": 4116,
"text": "index.html"
},
{
"code": "<!DOCTYPE html><html> <head> <script> function includeHTMLSnippet() { // Traverse the collection of // all HTML elements id = document.getElementsByTagName(\"*\"); for (i = 0; i < id.length; i++) { element = id[i]; // Search for elements with // specific attributes file = element.getAttribute( \"GFG-include-html-snippet\"); if (file) { // Create an HTTP request with the // attribute value as the file name xmlRequest = new XMLHttpRequest(); xmlRequest.onreadystatechange = function () { if (this.readyState == 4) { if (this.status == 200) { element.innerHTML = this.responseText; } if (this.status == 404) { element.innerHTML = \"Page not found.\"; } // Delete the attribute and // call this function again element.removeAttribute( \"GFG-include-html-snippet\"); includeHTMLSnippet(); } } xmlRequest.open(\"GET\", file, true); xmlRequest.send(); return; // Exit function. } } }; </script></head> <body> <h1 align='center'> <font color='Red'> This is index.html </font> </h1> <div GFG-include-html-snippet=\"gfg.html\"></div> <script> includeHTMLSnippet(); </script></body> </html>",
"e": 6023,
"s": 4127,
"text": null
},
{
"code": null,
"e": 6032,
"s": 6023,
"text": "gfg.html"
},
{
"code": "<!DOCTYPE html><html> <head> <style> body { text-align: center; } .gfg { font-size: 140px; font-weight: bold; color: green; } .geeks { font-size: 50px; font-weight: bold; font-family: Arial; } </style></head> <body> <div class=\"gfg\"> GeeksforGeeks </div> <div class=\"geeks\"> A computer science portal for geeks </div> <h1> <font color='Blue'> This is gfg.html </font> </h1></body> </html>",
"e": 6622,
"s": 6032,
"text": null
},
{
"code": null,
"e": 6630,
"s": 6622,
"text": "Output:"
},
{
"code": null,
"e": 6813,
"s": 6630,
"text": "Differentiating included gfg.html snippet in index.html: The red border indicates the output of the main index.html and the blue border indicates the output of included HTML snippet."
},
{
"code": null,
"e": 6828,
"s": 6813,
"text": "CSS-Properties"
},
{
"code": null,
"e": 6842,
"s": 6828,
"text": "CSS-Questions"
},
{
"code": null,
"e": 6857,
"s": 6842,
"text": "HTML-Questions"
},
{
"code": null,
"e": 6878,
"s": 6857,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 6885,
"s": 6878,
"text": "Picked"
},
{
"code": null,
"e": 6889,
"s": 6885,
"text": "CSS"
},
{
"code": null,
"e": 6894,
"s": 6889,
"text": "HTML"
},
{
"code": null,
"e": 6905,
"s": 6894,
"text": "JavaScript"
},
{
"code": null,
"e": 6922,
"s": 6905,
"text": "Web Technologies"
},
{
"code": null,
"e": 6927,
"s": 6922,
"text": "HTML"
}
]
|
SQL Query to List All Databases | 15 May, 2021
SQL language is a DML in DBMS. This is used to manipulate databases and the records kept in them. A database is a collection of structured information or data stored in any computer system. So to modify these databases or to update any data contained by them, we are using DML languages like SQL, etc. We will mainly be using MS SQL SERVER for this topic.
So first let us create some of the databases which we will be using in this article to query up using SQL.
To create a database in SQL we have to use the following command:
CREATE DATABASE database_name;
This command creates a database of the given names in the SQL server and then we can add tables to this database also through SQL. We can also add tuples or rows in these tables, or we can delete the tables or update or modify them according to our needs using SQL.
To use any particular database we should select between them which we can do as shown below:
USE database_name;
So let’s add two tables to this database using SQL.
To do that we will be using the below given commands:
CREATE TABLE [database_name.]table_name (
pk_column data_type PRIMARY KEY,
column_1 data_type NOT NULL,
column_2 data_type,
...,
table_constraints
);
If we do not mention the name of the database then the default USE database is selected for the creation of tables.
Below are some commands which shows how we created databases and then how we listed them and run queries on them.
There are default databases present on SQL server initially, which are of two types :
The command to see system databases are :
SELECT name, database_id, create_date
FROM sys.databases ;
Output:
There are mainly four types of system databases :
mastermodelmsdbtmpdb
master
model
msdb
tmpdb
Some other databases are also present in the server other than the above ones. Those can be displayed as shown below:
SELECT name FROM master.dbo.sysdatabases
Output:
Now in order to select the user-defined databases first let’s create some databases in the server.
We will be using the below-mentioned commands to add some databases to SQL server:
create database GFG;
create database GFG1;
create database GFG2;
Output:
These are the query to list the user-defined database present in the server (while we had done above):
select name
from sys.Databases
WHERE name NOT IN ('master', 'tempdb', 'model', 'msdb'); /* removing the name of sys db*/
Output:
Hence in this way we are able to select and list all the user-defined and non-user-defined databases in the SQL server.
Picked
SQL-Query
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n15 May, 2021"
},
{
"code": null,
"e": 408,
"s": 52,
"text": "SQL language is a DML in DBMS. This is used to manipulate databases and the records kept in them. A database is a collection of structured information or data stored in any computer system. So to modify these databases or to update any data contained by them, we are using DML languages like SQL, etc. We will mainly be using MS SQL SERVER for this topic."
},
{
"code": null,
"e": 515,
"s": 408,
"text": "So first let us create some of the databases which we will be using in this article to query up using SQL."
},
{
"code": null,
"e": 581,
"s": 515,
"text": "To create a database in SQL we have to use the following command:"
},
{
"code": null,
"e": 612,
"s": 581,
"text": "CREATE DATABASE database_name;"
},
{
"code": null,
"e": 879,
"s": 612,
"text": "This command creates a database of the given names in the SQL server and then we can add tables to this database also through SQL. We can also add tuples or rows in these tables, or we can delete the tables or update or modify them according to our needs using SQL. "
},
{
"code": null,
"e": 972,
"s": 879,
"text": "To use any particular database we should select between them which we can do as shown below:"
},
{
"code": null,
"e": 991,
"s": 972,
"text": "USE database_name;"
},
{
"code": null,
"e": 1043,
"s": 991,
"text": "So let’s add two tables to this database using SQL."
},
{
"code": null,
"e": 1097,
"s": 1043,
"text": "To do that we will be using the below given commands:"
},
{
"code": null,
"e": 1262,
"s": 1097,
"text": "CREATE TABLE [database_name.]table_name (\n pk_column data_type PRIMARY KEY,\n column_1 data_type NOT NULL,\n column_2 data_type,\n ...,\n table_constraints\n);"
},
{
"code": null,
"e": 1378,
"s": 1262,
"text": "If we do not mention the name of the database then the default USE database is selected for the creation of tables."
},
{
"code": null,
"e": 1492,
"s": 1378,
"text": "Below are some commands which shows how we created databases and then how we listed them and run queries on them."
},
{
"code": null,
"e": 1578,
"s": 1492,
"text": "There are default databases present on SQL server initially, which are of two types :"
},
{
"code": null,
"e": 1683,
"s": 1578,
"text": "The command to see system databases are :\nSELECT name, database_id, create_date \nFROM sys.databases ; "
},
{
"code": null,
"e": 1691,
"s": 1683,
"text": "Output:"
},
{
"code": null,
"e": 1741,
"s": 1691,
"text": "There are mainly four types of system databases :"
},
{
"code": null,
"e": 1762,
"s": 1741,
"text": "mastermodelmsdbtmpdb"
},
{
"code": null,
"e": 1769,
"s": 1762,
"text": "master"
},
{
"code": null,
"e": 1775,
"s": 1769,
"text": "model"
},
{
"code": null,
"e": 1780,
"s": 1775,
"text": "msdb"
},
{
"code": null,
"e": 1786,
"s": 1780,
"text": "tmpdb"
},
{
"code": null,
"e": 1904,
"s": 1786,
"text": "Some other databases are also present in the server other than the above ones. Those can be displayed as shown below:"
},
{
"code": null,
"e": 1945,
"s": 1904,
"text": "SELECT name FROM master.dbo.sysdatabases"
},
{
"code": null,
"e": 1953,
"s": 1945,
"text": "Output:"
},
{
"code": null,
"e": 2052,
"s": 1953,
"text": "Now in order to select the user-defined databases first let’s create some databases in the server."
},
{
"code": null,
"e": 2135,
"s": 2052,
"text": "We will be using the below-mentioned commands to add some databases to SQL server:"
},
{
"code": null,
"e": 2200,
"s": 2135,
"text": "create database GFG;\ncreate database GFG1;\ncreate database GFG2;"
},
{
"code": null,
"e": 2208,
"s": 2200,
"text": "Output:"
},
{
"code": null,
"e": 2311,
"s": 2208,
"text": "These are the query to list the user-defined database present in the server (while we had done above):"
},
{
"code": null,
"e": 2435,
"s": 2311,
"text": "select name \nfrom sys.Databases\nWHERE name NOT IN ('master', 'tempdb', 'model', 'msdb'); /* removing the name of sys db*/"
},
{
"code": null,
"e": 2443,
"s": 2435,
"text": "Output:"
},
{
"code": null,
"e": 2563,
"s": 2443,
"text": "Hence in this way we are able to select and list all the user-defined and non-user-defined databases in the SQL server."
},
{
"code": null,
"e": 2570,
"s": 2563,
"text": "Picked"
},
{
"code": null,
"e": 2580,
"s": 2570,
"text": "SQL-Query"
},
{
"code": null,
"e": 2584,
"s": 2580,
"text": "SQL"
},
{
"code": null,
"e": 2588,
"s": 2584,
"text": "SQL"
}
]
|
Minimum number of given operations required to make two strings equal | 17 Feb, 2020
Given two strings A and B, both strings contain characters a and b and are of equal lengths. There is one _ (empty space) in both the strings. The task is to convert first string into second string by doing the minimum number of the following operations:
If _ is at position i then _ can be swapped with a character at position i+1 or i-1.If characters at positions i+1 and i+2 are different then _ can be swapped with a character at position i+1 or i+2.Similarly, if characters at positions i-1 and i-2 are different then _ can be swapped with a character at position i-1 or i-2.
If _ is at position i then _ can be swapped with a character at position i+1 or i-1.
If characters at positions i+1 and i+2 are different then _ can be swapped with a character at position i+1 or i+2.
Similarly, if characters at positions i-1 and i-2 are different then _ can be swapped with a character at position i-1 or i-2.
Examples:
Input: A = “aba_a”, B = “_baaa”Output: 2Move 1 : A = “ab_aa” (Swapped A[2] with A[3])Move 2 : A = “_baaa” (Swapped A[0] with A[2])
Input: A = “a_b”, B = “ab_”Output: 1
Source: Directi Interview Set 7
Approach:
Apply a simple Breadth First Search over the string and an element of the queue used for BFS will contain the pair str, pos where pos is the position of _ in the string str.
Also maintain a map vis which will store the string as key and the minimum moves to get to the string as value.
For every string str from the queue, generate a new string tmp based on the four conditions given and update the vis map as vis[tmp] = vis[str] + 1.
Repeat the above steps until the queue is empty or the required string is generated i.e. tmp == B
If the required string is generated then return vis[str] + 1 which is the minimum number of operations required to change A to B.
Below is the implementation of the above approach:
C++
Python3
// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to return the minimum number of// operations to convert string A to Bint minOperations(string s, string f){ // If both the strings are equal then // no operation needs to be performed if (s == f) return 0; unordered_map<string, int> vis; int n; n = s.length(); int pos = 0; for (int i = 0; i < s.length(); i++) { if (s[i] == '_') { // store the position of '_' pos = i; break; } } // to store the generated string at every // move and the position of '_' within it queue<pair<string, int> > q; q.push({ s, pos }); // vis will store the minimum operations // to reach that particular string vis[s] = 0; while (!q.empty()) { string ss = q.front().first; int pp = q.front().second; // minimum moves to reach the string ss int dist = vis[ss]; q.pop(); // try all 4 possible operations // if '_' can be swapped with // the character on it's left if (pp > 0) { // swap with the left character swap(ss[pp], ss[pp - 1]); // if the string is generated // for the first time if (!vis.count(ss)) { // if generated string is // the required string if (ss == f) { return dist + 1; break; } // update the distance for the // currently generated string vis[ss] = dist + 1; q.push({ ss, pp - 1 }); } // restore the string before it was // swapped to check other cases swap(ss[pp], ss[pp - 1]); } // swap '_' with the character // on it's right this time if (pp < n - 1) { swap(ss[pp], ss[pp + 1]); if (!vis.count(ss)) { if (ss == f) { return dist + 1; break; } vis[ss] = dist + 1; q.push({ ss, pp + 1 }); } swap(ss[pp], ss[pp + 1]); } // if '_' can be swapped // with the character 'i+2' if (pp > 1 && ss[pp - 1] != ss[pp - 2]) { swap(ss[pp], ss[pp - 2]); if (!vis.count(ss)) { if (ss == f) { return dist + 1; break; } vis[ss] = dist + 1; q.push({ ss, pp - 2 }); } swap(ss[pp], ss[pp - 2]); } // if '_' can be swapped // with the character at 'i+2' if (pp < n - 2 && ss[pp + 1] != ss[pp + 2]) { swap(ss[pp], ss[pp + 2]); if (!vis.count(ss)) { if (ss == f) { return dist + 1; break; } vis[ss] = dist + 1; q.push({ ss, pp + 2 }); } swap(ss[pp], ss[pp + 2]); } }} // Driver codeint main(){ string A = "aba_a"; string B = "_baaa"; cout << minOperations(A, B); return 0;}
# Python3 implementation of the approachfrom collections import deque # Function to return the minimum number of# operations to convert string A to Bdef minOperations(s: str, f: str) -> int: # If both the strings are equal then # no operation needs to be performed if s == f: return 0 vis = dict() n = len(s) pos = 0 for i in range(n): if s[i] == '_': # store the position of '_' pos = i break # to store the generated string at every # move and the position of '_' within it q = deque() q.append((s, pos)) # vis will store the minimum operations # to reach that particular string vis[s] = 0 while q: ss = q[0][0] pp = q[0][1] # minimum moves to reach the string ss dist = vis[ss] q.popleft() ss = list(ss) # try all 4 possible operations # if '_' can be swapped with # the character on it's left if pp > 0: # swap with the left character ss[pp], ss[pp - 1] = ss[pp - 1], ss[pp] ss = ''.join(ss) # if the string is generated # for the first time if ss not in vis: # if generated string is # the required string if ss == f: return dist + 1 # update the distance for the # currently generated string vis[ss] = dist + 1 q.append((ss, pp - 1)) ss = list(ss) # restore the string before it was # swapped to check other cases ss[pp], ss[pp - 1] = ss[pp - 1], ss[pp] ss = ''.join(ss) # swap '_' with the character # on it's right this time if pp < n - 1: ss = list(ss) ss[pp], ss[pp + 1] = ss[pp + 1], ss[pp] ss = ''.join(ss) if ss not in vis: if ss == f: return dist + 1 vis[ss] = dist + 1 q.append((ss, pp + 1)) ss = list(ss) ss[pp], ss[pp + 1] = ss[pp + 1], ss[pp] ss = ''.join(ss) # if '_' can be swapped # with the character 'i+2' if pp > 1 and ss[pp - 1] != ss[pp - 2]: ss = list(ss) ss[pp], ss[pp - 2] = ss[pp - 2], ss[pp] ss = ''.join(ss) if ss not in vis: if ss == f: return dist + 1 vis[ss] = dist + 1 q.append((ss, pp - 2)) ss = list(ss) ss[pp], ss[pp - 2] = ss[pp - 2], ss[pp] ss = ''.join(ss) # if '_' can be swapped # with the character at 'i+2' if pp < n - 2 and ss[pp + 1] != ss[pp + 2]: ss = list(ss) ss[pp], ss[pp + 2] = ss[pp + 2], ss[pp] ss = ''.join(ss) if ss not in vis: if ss == f: return dist + 1 vis[ss] = dist + 1 q.append((ss, pp + 2)) ss = list(ss) ss[pp], ss[pp + 2] = ss[pp + 2], ss[pp] ss = ''.join(ss) # Driver Codeif __name__ == "__main__": A = "aba_a" B = "_baaa" print(minOperations(A, B)) # This code is contributed by# sanjeev2552
2
sanjeev2552
BFS
Directi
Technical Scripter 2018
Queue
Strings
Directi
Strings
Queue
BFS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
What is Priority Queue | Introduction to Priority Queue
Sliding Window Maximum (Maximum of all subarrays of size k)
Queue | Set 1 (Introduction and Array Implementation)
LRU Cache Implementation
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
Different Methods to Reverse a String in C++ | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n17 Feb, 2020"
},
{
"code": null,
"e": 307,
"s": 52,
"text": "Given two strings A and B, both strings contain characters a and b and are of equal lengths. There is one _ (empty space) in both the strings. The task is to convert first string into second string by doing the minimum number of the following operations:"
},
{
"code": null,
"e": 633,
"s": 307,
"text": "If _ is at position i then _ can be swapped with a character at position i+1 or i-1.If characters at positions i+1 and i+2 are different then _ can be swapped with a character at position i+1 or i+2.Similarly, if characters at positions i-1 and i-2 are different then _ can be swapped with a character at position i-1 or i-2."
},
{
"code": null,
"e": 718,
"s": 633,
"text": "If _ is at position i then _ can be swapped with a character at position i+1 or i-1."
},
{
"code": null,
"e": 834,
"s": 718,
"text": "If characters at positions i+1 and i+2 are different then _ can be swapped with a character at position i+1 or i+2."
},
{
"code": null,
"e": 961,
"s": 834,
"text": "Similarly, if characters at positions i-1 and i-2 are different then _ can be swapped with a character at position i-1 or i-2."
},
{
"code": null,
"e": 971,
"s": 961,
"text": "Examples:"
},
{
"code": null,
"e": 1102,
"s": 971,
"text": "Input: A = “aba_a”, B = “_baaa”Output: 2Move 1 : A = “ab_aa” (Swapped A[2] with A[3])Move 2 : A = “_baaa” (Swapped A[0] with A[2])"
},
{
"code": null,
"e": 1139,
"s": 1102,
"text": "Input: A = “a_b”, B = “ab_”Output: 1"
},
{
"code": null,
"e": 1171,
"s": 1139,
"text": "Source: Directi Interview Set 7"
},
{
"code": null,
"e": 1181,
"s": 1171,
"text": "Approach:"
},
{
"code": null,
"e": 1355,
"s": 1181,
"text": "Apply a simple Breadth First Search over the string and an element of the queue used for BFS will contain the pair str, pos where pos is the position of _ in the string str."
},
{
"code": null,
"e": 1467,
"s": 1355,
"text": "Also maintain a map vis which will store the string as key and the minimum moves to get to the string as value."
},
{
"code": null,
"e": 1616,
"s": 1467,
"text": "For every string str from the queue, generate a new string tmp based on the four conditions given and update the vis map as vis[tmp] = vis[str] + 1."
},
{
"code": null,
"e": 1714,
"s": 1616,
"text": "Repeat the above steps until the queue is empty or the required string is generated i.e. tmp == B"
},
{
"code": null,
"e": 1844,
"s": 1714,
"text": "If the required string is generated then return vis[str] + 1 which is the minimum number of operations required to change A to B."
},
{
"code": null,
"e": 1895,
"s": 1844,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1899,
"s": 1895,
"text": "C++"
},
{
"code": null,
"e": 1907,
"s": 1899,
"text": "Python3"
},
{
"code": "// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to return the minimum number of// operations to convert string A to Bint minOperations(string s, string f){ // If both the strings are equal then // no operation needs to be performed if (s == f) return 0; unordered_map<string, int> vis; int n; n = s.length(); int pos = 0; for (int i = 0; i < s.length(); i++) { if (s[i] == '_') { // store the position of '_' pos = i; break; } } // to store the generated string at every // move and the position of '_' within it queue<pair<string, int> > q; q.push({ s, pos }); // vis will store the minimum operations // to reach that particular string vis[s] = 0; while (!q.empty()) { string ss = q.front().first; int pp = q.front().second; // minimum moves to reach the string ss int dist = vis[ss]; q.pop(); // try all 4 possible operations // if '_' can be swapped with // the character on it's left if (pp > 0) { // swap with the left character swap(ss[pp], ss[pp - 1]); // if the string is generated // for the first time if (!vis.count(ss)) { // if generated string is // the required string if (ss == f) { return dist + 1; break; } // update the distance for the // currently generated string vis[ss] = dist + 1; q.push({ ss, pp - 1 }); } // restore the string before it was // swapped to check other cases swap(ss[pp], ss[pp - 1]); } // swap '_' with the character // on it's right this time if (pp < n - 1) { swap(ss[pp], ss[pp + 1]); if (!vis.count(ss)) { if (ss == f) { return dist + 1; break; } vis[ss] = dist + 1; q.push({ ss, pp + 1 }); } swap(ss[pp], ss[pp + 1]); } // if '_' can be swapped // with the character 'i+2' if (pp > 1 && ss[pp - 1] != ss[pp - 2]) { swap(ss[pp], ss[pp - 2]); if (!vis.count(ss)) { if (ss == f) { return dist + 1; break; } vis[ss] = dist + 1; q.push({ ss, pp - 2 }); } swap(ss[pp], ss[pp - 2]); } // if '_' can be swapped // with the character at 'i+2' if (pp < n - 2 && ss[pp + 1] != ss[pp + 2]) { swap(ss[pp], ss[pp + 2]); if (!vis.count(ss)) { if (ss == f) { return dist + 1; break; } vis[ss] = dist + 1; q.push({ ss, pp + 2 }); } swap(ss[pp], ss[pp + 2]); } }} // Driver codeint main(){ string A = \"aba_a\"; string B = \"_baaa\"; cout << minOperations(A, B); return 0;}",
"e": 5163,
"s": 1907,
"text": null
},
{
"code": "# Python3 implementation of the approachfrom collections import deque # Function to return the minimum number of# operations to convert string A to Bdef minOperations(s: str, f: str) -> int: # If both the strings are equal then # no operation needs to be performed if s == f: return 0 vis = dict() n = len(s) pos = 0 for i in range(n): if s[i] == '_': # store the position of '_' pos = i break # to store the generated string at every # move and the position of '_' within it q = deque() q.append((s, pos)) # vis will store the minimum operations # to reach that particular string vis[s] = 0 while q: ss = q[0][0] pp = q[0][1] # minimum moves to reach the string ss dist = vis[ss] q.popleft() ss = list(ss) # try all 4 possible operations # if '_' can be swapped with # the character on it's left if pp > 0: # swap with the left character ss[pp], ss[pp - 1] = ss[pp - 1], ss[pp] ss = ''.join(ss) # if the string is generated # for the first time if ss not in vis: # if generated string is # the required string if ss == f: return dist + 1 # update the distance for the # currently generated string vis[ss] = dist + 1 q.append((ss, pp - 1)) ss = list(ss) # restore the string before it was # swapped to check other cases ss[pp], ss[pp - 1] = ss[pp - 1], ss[pp] ss = ''.join(ss) # swap '_' with the character # on it's right this time if pp < n - 1: ss = list(ss) ss[pp], ss[pp + 1] = ss[pp + 1], ss[pp] ss = ''.join(ss) if ss not in vis: if ss == f: return dist + 1 vis[ss] = dist + 1 q.append((ss, pp + 1)) ss = list(ss) ss[pp], ss[pp + 1] = ss[pp + 1], ss[pp] ss = ''.join(ss) # if '_' can be swapped # with the character 'i+2' if pp > 1 and ss[pp - 1] != ss[pp - 2]: ss = list(ss) ss[pp], ss[pp - 2] = ss[pp - 2], ss[pp] ss = ''.join(ss) if ss not in vis: if ss == f: return dist + 1 vis[ss] = dist + 1 q.append((ss, pp - 2)) ss = list(ss) ss[pp], ss[pp - 2] = ss[pp - 2], ss[pp] ss = ''.join(ss) # if '_' can be swapped # with the character at 'i+2' if pp < n - 2 and ss[pp + 1] != ss[pp + 2]: ss = list(ss) ss[pp], ss[pp + 2] = ss[pp + 2], ss[pp] ss = ''.join(ss) if ss not in vis: if ss == f: return dist + 1 vis[ss] = dist + 1 q.append((ss, pp + 2)) ss = list(ss) ss[pp], ss[pp + 2] = ss[pp + 2], ss[pp] ss = ''.join(ss) # Driver Codeif __name__ == \"__main__\": A = \"aba_a\" B = \"_baaa\" print(minOperations(A, B)) # This code is contributed by# sanjeev2552",
"e": 8489,
"s": 5163,
"text": null
},
{
"code": null,
"e": 8492,
"s": 8489,
"text": "2\n"
},
{
"code": null,
"e": 8504,
"s": 8492,
"text": "sanjeev2552"
},
{
"code": null,
"e": 8508,
"s": 8504,
"text": "BFS"
},
{
"code": null,
"e": 8516,
"s": 8508,
"text": "Directi"
},
{
"code": null,
"e": 8540,
"s": 8516,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 8546,
"s": 8540,
"text": "Queue"
},
{
"code": null,
"e": 8554,
"s": 8546,
"text": "Strings"
},
{
"code": null,
"e": 8562,
"s": 8554,
"text": "Directi"
},
{
"code": null,
"e": 8570,
"s": 8562,
"text": "Strings"
},
{
"code": null,
"e": 8576,
"s": 8570,
"text": "Queue"
},
{
"code": null,
"e": 8580,
"s": 8576,
"text": "BFS"
},
{
"code": null,
"e": 8678,
"s": 8580,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8710,
"s": 8678,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 8766,
"s": 8710,
"text": "What is Priority Queue | Introduction to Priority Queue"
},
{
"code": null,
"e": 8826,
"s": 8766,
"text": "Sliding Window Maximum (Maximum of all subarrays of size k)"
},
{
"code": null,
"e": 8880,
"s": 8826,
"text": "Queue | Set 1 (Introduction and Array Implementation)"
},
{
"code": null,
"e": 8905,
"s": 8880,
"text": "LRU Cache Implementation"
},
{
"code": null,
"e": 8951,
"s": 8905,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 8976,
"s": 8951,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 9036,
"s": 8976,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 9051,
"s": 9036,
"text": "C++ Data Types"
}
]
|
Replacing missing values using Pandas in Python | 16 Nov, 2020
Dataset is a collection of attributes and rows. Data set can have missing data that are represented by NA in Python and in this article, we are going to replace missing values in this article
We consider this data set: Dataset
data set
In our data contains missing values in quantity, price, bought, forenoon and afternoon columns,
So, We can replace missing values in the quantity column with mean, price column with a median, Bought column with standard deviation. Forenoon column with the minimum value in that column. Afternoon column with maximum value in that column.
Approach:
Import the module
Load data set
Fill in the missing values
Verify data set
Syntax:
Mean: data=data.fillna(data.mean())
Median: data=data.fillna(data.median())
Standard Deviation: data=data.fillna(data.std())
Min: data=data.fillna(data.min())
Max: data=data.fillna(data.max())
Below is the Implementation:
Python3
# importing pandas moduleimport pandas as pd # loading data setdata = pd.read_csv('item.csv') # display the dataprint(data)
Output:
Then after we will proceed with Replacing missing values with mean, median, mode, standard deviation, min & max
Python3
# replacing missing values in quantity# column with mean of that columndata['quantity'] = data['quantity'].fillna(data['quantity'].mean()) # replacing missing values in price column# with median of that columndata['price'] = data['price'].fillna(data['price'].median()) # replacing missing values in bought column with# standard deviation of that columndata['bought'] = data['bought'].fillna(data['bought'].std()) # replacing missing values in forenoon column with# minimum number of that columndata['forenoon'] = data['forenoon'].fillna(data['forenoon'].min()) # replacing missing values in afternoon column with # maximum number of that columndata['afternoon'] = data['afternoon'].fillna(data['afternoon'].max()) print(Data)
Output:
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n16 Nov, 2020"
},
{
"code": null,
"e": 245,
"s": 53,
"text": "Dataset is a collection of attributes and rows. Data set can have missing data that are represented by NA in Python and in this article, we are going to replace missing values in this article"
},
{
"code": null,
"e": 280,
"s": 245,
"text": "We consider this data set: Dataset"
},
{
"code": null,
"e": 289,
"s": 280,
"text": "data set"
},
{
"code": null,
"e": 385,
"s": 289,
"text": "In our data contains missing values in quantity, price, bought, forenoon and afternoon columns,"
},
{
"code": null,
"e": 627,
"s": 385,
"text": "So, We can replace missing values in the quantity column with mean, price column with a median, Bought column with standard deviation. Forenoon column with the minimum value in that column. Afternoon column with maximum value in that column."
},
{
"code": null,
"e": 637,
"s": 627,
"text": "Approach:"
},
{
"code": null,
"e": 655,
"s": 637,
"text": "Import the module"
},
{
"code": null,
"e": 669,
"s": 655,
"text": "Load data set"
},
{
"code": null,
"e": 696,
"s": 669,
"text": "Fill in the missing values"
},
{
"code": null,
"e": 712,
"s": 696,
"text": "Verify data set"
},
{
"code": null,
"e": 720,
"s": 712,
"text": "Syntax:"
},
{
"code": null,
"e": 756,
"s": 720,
"text": "Mean: data=data.fillna(data.mean())"
},
{
"code": null,
"e": 796,
"s": 756,
"text": "Median: data=data.fillna(data.median())"
},
{
"code": null,
"e": 845,
"s": 796,
"text": "Standard Deviation: data=data.fillna(data.std())"
},
{
"code": null,
"e": 879,
"s": 845,
"text": "Min: data=data.fillna(data.min())"
},
{
"code": null,
"e": 913,
"s": 879,
"text": "Max: data=data.fillna(data.max())"
},
{
"code": null,
"e": 942,
"s": 913,
"text": "Below is the Implementation:"
},
{
"code": null,
"e": 950,
"s": 942,
"text": "Python3"
},
{
"code": "# importing pandas moduleimport pandas as pd # loading data setdata = pd.read_csv('item.csv') # display the dataprint(data)",
"e": 1076,
"s": 950,
"text": null
},
{
"code": null,
"e": 1084,
"s": 1076,
"text": "Output:"
},
{
"code": null,
"e": 1196,
"s": 1084,
"text": "Then after we will proceed with Replacing missing values with mean, median, mode, standard deviation, min & max"
},
{
"code": null,
"e": 1204,
"s": 1196,
"text": "Python3"
},
{
"code": "# replacing missing values in quantity# column with mean of that columndata['quantity'] = data['quantity'].fillna(data['quantity'].mean()) # replacing missing values in price column# with median of that columndata['price'] = data['price'].fillna(data['price'].median()) # replacing missing values in bought column with# standard deviation of that columndata['bought'] = data['bought'].fillna(data['bought'].std()) # replacing missing values in forenoon column with# minimum number of that columndata['forenoon'] = data['forenoon'].fillna(data['forenoon'].min()) # replacing missing values in afternoon column with # maximum number of that columndata['afternoon'] = data['afternoon'].fillna(data['afternoon'].max()) print(Data)",
"e": 1938,
"s": 1204,
"text": null
},
{
"code": null,
"e": 1946,
"s": 1938,
"text": "Output:"
},
{
"code": null,
"e": 1960,
"s": 1946,
"text": "Python-pandas"
},
{
"code": null,
"e": 1967,
"s": 1960,
"text": "Python"
}
]
|
Python Dictionary keys() method | 31 May, 2021
Dictionary in Python is a collection of data values which only maintains the order of insertion, used to store data values like a map, which, unlike other Data Types that hold only a single value as an element, Dictionary holds key: value pair.
keys() method in Python Dictionary, returns a view object that displays a list of all the keys in the dictionary in order of insertion.
Syntax: dict.keys()Parameters: There are no parameters.Returns: A view object is returned that displays all the keys. This view object changes according to the changes in the dictionary.
Example #1:
Python3
# Python program to show working# of keys in Dictionary # Dictionary with three keysDictionary1 = {'A': 'Geeks', 'B': 'For', 'C': 'Geeks'} # Printing keys of dictionaryprint(Dictionary1.keys()) # Creating empty Dictionaryempty_Dict1 = {} # Printing keys of Empty Dictionaryprint(empty_Dict1.keys())
Output:
dict_keys(['A', 'B', 'C'])
dict_keys([])
Note: The order of these key values in the list may not always be the same. Example #2: To show how updation of dictionary works
Python3
# Python program to show updation# of keys in Dictionary # Dictionary with two keysDictionary1 = {'A': 'Geeks', 'B': 'For'} # Printing keys of dictionaryprint("Keys before Dictionary Updation:")keys = Dictionary1.keys()print(keys) # adding an element to the dictionaryDictionary1.update({'C':'Geeks'}) print('\nAfter dictionary is updated:')print(keys)
Output:
Keys before Dictionary Updation:
dict_keys(['B', 'A'])
After dictionary is updated:
dict_keys(['B', 'A', 'C'])
Here, when the dictionary is updated, keys are also automatically updated to show the changes.
Practical Application: The keys() can be used to access the elements of the dictionary as we can do for the list, without the use of keys(), no other mechanism provides means to access dictionary keys as a list by index. This is demonstrated in the example below.
Example #3: Demonstrating the practical application of keys()
Python3
# Python program to demonstrate# working of keys() # initializing dictionarytest_dict = { "geeks" : 7, "for" : 1, "geeks" : 2 } # accessing 2nd element using naive method# using loopj = 0for i in test_dict: if (j == 1): print ('2nd key using loop : ' + i) j = j + 1 # accessing 2nd element using keys()print ('2nd key using keys() : ' + test_dict.keys()[1])
Output :
2nd key using loop : for
TypeError: 'dict_keys' object does not support indexing
Note: The second approach would not work because dict_keys in Python 3 does not support indexing.
manjeet_04
Rohan_Navlakhe
michaelalanwalters
python-dict
Python-dict-functions
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n31 May, 2021"
},
{
"code": null,
"e": 298,
"s": 53,
"text": "Dictionary in Python is a collection of data values which only maintains the order of insertion, used to store data values like a map, which, unlike other Data Types that hold only a single value as an element, Dictionary holds key: value pair."
},
{
"code": null,
"e": 435,
"s": 298,
"text": "keys() method in Python Dictionary, returns a view object that displays a list of all the keys in the dictionary in order of insertion. "
},
{
"code": null,
"e": 622,
"s": 435,
"text": "Syntax: dict.keys()Parameters: There are no parameters.Returns: A view object is returned that displays all the keys. This view object changes according to the changes in the dictionary."
},
{
"code": null,
"e": 635,
"s": 622,
"text": "Example #1: "
},
{
"code": null,
"e": 643,
"s": 635,
"text": "Python3"
},
{
"code": "# Python program to show working# of keys in Dictionary # Dictionary with three keysDictionary1 = {'A': 'Geeks', 'B': 'For', 'C': 'Geeks'} # Printing keys of dictionaryprint(Dictionary1.keys()) # Creating empty Dictionaryempty_Dict1 = {} # Printing keys of Empty Dictionaryprint(empty_Dict1.keys())",
"e": 942,
"s": 643,
"text": null
},
{
"code": null,
"e": 951,
"s": 942,
"text": "Output: "
},
{
"code": null,
"e": 992,
"s": 951,
"text": "dict_keys(['A', 'B', 'C'])\ndict_keys([])"
},
{
"code": null,
"e": 1124,
"s": 992,
"text": "Note: The order of these key values in the list may not always be the same. Example #2: To show how updation of dictionary works "
},
{
"code": null,
"e": 1132,
"s": 1124,
"text": "Python3"
},
{
"code": "# Python program to show updation# of keys in Dictionary # Dictionary with two keysDictionary1 = {'A': 'Geeks', 'B': 'For'} # Printing keys of dictionaryprint(\"Keys before Dictionary Updation:\")keys = Dictionary1.keys()print(keys) # adding an element to the dictionaryDictionary1.update({'C':'Geeks'}) print('\\nAfter dictionary is updated:')print(keys)",
"e": 1485,
"s": 1132,
"text": null
},
{
"code": null,
"e": 1494,
"s": 1485,
"text": "Output: "
},
{
"code": null,
"e": 1606,
"s": 1494,
"text": "Keys before Dictionary Updation:\ndict_keys(['B', 'A'])\n\nAfter dictionary is updated:\ndict_keys(['B', 'A', 'C'])"
},
{
"code": null,
"e": 1702,
"s": 1606,
"text": "Here, when the dictionary is updated, keys are also automatically updated to show the changes. "
},
{
"code": null,
"e": 1967,
"s": 1702,
"text": "Practical Application: The keys() can be used to access the elements of the dictionary as we can do for the list, without the use of keys(), no other mechanism provides means to access dictionary keys as a list by index. This is demonstrated in the example below. "
},
{
"code": null,
"e": 2030,
"s": 1967,
"text": "Example #3: Demonstrating the practical application of keys() "
},
{
"code": null,
"e": 2038,
"s": 2030,
"text": "Python3"
},
{
"code": "# Python program to demonstrate# working of keys() # initializing dictionarytest_dict = { \"geeks\" : 7, \"for\" : 1, \"geeks\" : 2 } # accessing 2nd element using naive method# using loopj = 0for i in test_dict: if (j == 1): print ('2nd key using loop : ' + i) j = j + 1 # accessing 2nd element using keys()print ('2nd key using keys() : ' + test_dict.keys()[1])",
"e": 2409,
"s": 2038,
"text": null
},
{
"code": null,
"e": 2419,
"s": 2409,
"text": "Output : "
},
{
"code": null,
"e": 2501,
"s": 2419,
"text": "2nd key using loop : for\nTypeError: 'dict_keys' object does not support indexing "
},
{
"code": null,
"e": 2601,
"s": 2501,
"text": "Note: The second approach would not work because dict_keys in Python 3 does not support indexing. "
},
{
"code": null,
"e": 2612,
"s": 2601,
"text": "manjeet_04"
},
{
"code": null,
"e": 2627,
"s": 2612,
"text": "Rohan_Navlakhe"
},
{
"code": null,
"e": 2646,
"s": 2627,
"text": "michaelalanwalters"
},
{
"code": null,
"e": 2658,
"s": 2646,
"text": "python-dict"
},
{
"code": null,
"e": 2680,
"s": 2658,
"text": "Python-dict-functions"
},
{
"code": null,
"e": 2687,
"s": 2680,
"text": "Python"
},
{
"code": null,
"e": 2699,
"s": 2687,
"text": "python-dict"
}
]
|
C# Program to Calculate the Sum of Array Elements using the LINQ Aggregate() Method - GeeksforGeeks | 09 Dec, 2021
Given an array of integers, now we calculate the sum of array elements. So we use the Aggregate() method of LINQ. This method applies a function to all the elements of the source sequence and calculates a cumulative result and return value. This method is overloaded in three different ways:
Aggregate<TSource, TAccumulate, TResult>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate, TSource, TAccumulate>, Func<TAccumulate, TResult>): It applies an accumulator function on the specified sequence. Here, the seed value is used to define the starting accumulator value, and the function is used to select the final result value.
Aggregate<TSource, TAccumulate>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate, TSource, TAccumulate>): It applies an accumulator function on the specified sequence. Here, the specified seed value is used to define the starting accumulator value.
Aggregate<TSource>(IEnumerable<TSource>, Func<TSource, TSource, TSource>): It applies an accumulator function on the specified sequence.
Example:
Input: { 34, 27, 34, 5, 6 }
Output: Sum = 106
Input: { 3, 4, 27, 34, 15, 26, 234, 123 }
Output: Sum = 466
Approach:
1. Create and initialize an array of integer type
2. Now find the sum of the array using the Aggregate() function.
sum = arr.Aggregate((element1,element2) => element1 + element2);
3. Display the sum of the elements of the array
Example:
C#
// C# program to finding the sum of the array elements// using Aggregate() Methodusing System;using System.Linq; class GFG{ static void Main(string[] args){ // Creating and initializing the array // with integer values int[] arr = { 1, 2, 3, 14, 5, 26, 7, 8, 90, 10}; int sum = 0; // Finding the sum of the elements of arr // using Aggregate() Method sum = arr.Aggregate((element1, element2) => element1 + element2); // Displaying the final output Console.Write("Sum is : " + sum);}}
Output:
Sum is : 166
surinderdawra388
CSharp LINQ
Picked
C#
C# Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Destructors in C#
Extension Method in C#
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
Convert String to Character Array in C#
Socket Programming in C#
Program to Print a New Line in C#
Getting a Month Name Using Month Number in C#
Program to find absolute value of a given number | [
{
"code": null,
"e": 24302,
"s": 24274,
"text": "\n09 Dec, 2021"
},
{
"code": null,
"e": 24594,
"s": 24302,
"text": "Given an array of integers, now we calculate the sum of array elements. So we use the Aggregate() method of LINQ. This method applies a function to all the elements of the source sequence and calculates a cumulative result and return value. This method is overloaded in three different ways:"
},
{
"code": null,
"e": 24932,
"s": 24594,
"text": "Aggregate<TSource, TAccumulate, TResult>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate, TSource, TAccumulate>, Func<TAccumulate, TResult>): It applies an accumulator function on the specified sequence. Here, the seed value is used to define the starting accumulator value, and the function is used to select the final result value."
},
{
"code": null,
"e": 25184,
"s": 24932,
"text": "Aggregate<TSource, TAccumulate>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate, TSource, TAccumulate>): It applies an accumulator function on the specified sequence. Here, the specified seed value is used to define the starting accumulator value."
},
{
"code": null,
"e": 25321,
"s": 25184,
"text": "Aggregate<TSource>(IEnumerable<TSource>, Func<TSource, TSource, TSource>): It applies an accumulator function on the specified sequence."
},
{
"code": null,
"e": 25330,
"s": 25321,
"text": "Example:"
},
{
"code": null,
"e": 25438,
"s": 25330,
"text": "Input: { 34, 27, 34, 5, 6 }\nOutput: Sum = 106\n\nInput: { 3, 4, 27, 34, 15, 26, 234, 123 }\nOutput: Sum = 466"
},
{
"code": null,
"e": 25448,
"s": 25438,
"text": "Approach:"
},
{
"code": null,
"e": 25498,
"s": 25448,
"text": "1. Create and initialize an array of integer type"
},
{
"code": null,
"e": 25563,
"s": 25498,
"text": "2. Now find the sum of the array using the Aggregate() function."
},
{
"code": null,
"e": 25628,
"s": 25563,
"text": "sum = arr.Aggregate((element1,element2) => element1 + element2);"
},
{
"code": null,
"e": 25676,
"s": 25628,
"text": "3. Display the sum of the elements of the array"
},
{
"code": null,
"e": 25685,
"s": 25676,
"text": "Example:"
},
{
"code": null,
"e": 25688,
"s": 25685,
"text": "C#"
},
{
"code": "// C# program to finding the sum of the array elements// using Aggregate() Methodusing System;using System.Linq; class GFG{ static void Main(string[] args){ // Creating and initializing the array // with integer values int[] arr = { 1, 2, 3, 14, 5, 26, 7, 8, 90, 10}; int sum = 0; // Finding the sum of the elements of arr // using Aggregate() Method sum = arr.Aggregate((element1, element2) => element1 + element2); // Displaying the final output Console.Write(\"Sum is : \" + sum);}}",
"e": 26214,
"s": 25688,
"text": null
},
{
"code": null,
"e": 26222,
"s": 26214,
"text": "Output:"
},
{
"code": null,
"e": 26235,
"s": 26222,
"text": "Sum is : 166"
},
{
"code": null,
"e": 26254,
"s": 26237,
"text": "surinderdawra388"
},
{
"code": null,
"e": 26266,
"s": 26254,
"text": "CSharp LINQ"
},
{
"code": null,
"e": 26273,
"s": 26266,
"text": "Picked"
},
{
"code": null,
"e": 26276,
"s": 26273,
"text": "C#"
},
{
"code": null,
"e": 26288,
"s": 26276,
"text": "C# Programs"
},
{
"code": null,
"e": 26386,
"s": 26288,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26404,
"s": 26386,
"text": "Destructors in C#"
},
{
"code": null,
"e": 26427,
"s": 26404,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 26455,
"s": 26427,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 26495,
"s": 26455,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 26538,
"s": 26495,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 26578,
"s": 26538,
"text": "Convert String to Character Array in C#"
},
{
"code": null,
"e": 26603,
"s": 26578,
"text": "Socket Programming in C#"
},
{
"code": null,
"e": 26637,
"s": 26603,
"text": "Program to Print a New Line in C#"
},
{
"code": null,
"e": 26683,
"s": 26637,
"text": "Getting a Month Name Using Month Number in C#"
}
]
|
Add New Row at Specific Index Position to Dataframe in R - GeeksforGeeks | 21 Apr, 2021
In this article, we will discuss how to add a new row at a specific index in the dataframe in the R programming language.
The main task here is to shift other rows and make space in the dataframe for the new row and then insert its contents. This can be done in two ways
rbind() function in R Language is used to combine specified Vector, Matrix, or Data Frame by rows.
Syntax: rbind(x1, x2, ..., deparse.level = 1)
Parameters:
x1, x2: vector, matrix, data frames
deparse.level: This value determines how the column names generated. The default value of deparse.level is 1.
Example
R
rm(list = ls()) # Function to create new dataframeinsertRow <- function(data, new_row, r) { data_new <- rbind(data[1:r, ], new_row, data[- (1:r), ]) rownames(data_new) <- 1:nrow(data_new) return(data_new)} existingDF <- data.frame(x1 = c(15,25,35,45,55), x2 = c(23,34,45,56,76), x3 = c(12,23,3,454,26)) index <- 4 newrow <- c(9, 99, 999) newDF=insertRow(existingDF, newrow, index) print(newDF)
Output:
Another approach of doing the same is to use seq() function. Here the approach is the same, but the method is somewhat different. We are accessing rows of the dataframe and creating the space in it. Also, we used nrows() to count the total number of rows.
seq() function in R Language is used to create a sequence of elements in a Vector. It takes the length and difference between values as an optional argument.
Syntax: seq(from, to, by, length.out)
Parameters:
from: Starting element of the sequence
to: Ending element of the sequence
by: Difference between the elements
length.out: Maximum length of the vector
Example:
R
rm(list = ls()) # Function to create new dataframeinsertRow <- function(existingDF, new_row, r) { existingDF[seq(r+1,nrow(existingDF)+1),] <- existingDF[seq(r,nrow(existingDF)),] existingDF[r,] <- new_row return(existingDF) } existingDF <- data.frame(x1 = c(1,7,13,25,31), x2 = c(2,8,14,26,32), x3 = c(3,9,15,27,33), x4 = c(4,10,16,28,34), x5 = c(5,11,17,29,35), x6 = c(6,12,18,30,36)) r <- 4 new_row <- c(19,20,21,22,23,24) newDF=insertRow(existingDF, new_row, r) print(newDF)
Output:
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
Replace Specific Characters in String in R
Convert Matrix to Dataframe in R | [
{
"code": null,
"e": 25242,
"s": 25214,
"text": "\n21 Apr, 2021"
},
{
"code": null,
"e": 25364,
"s": 25242,
"text": "In this article, we will discuss how to add a new row at a specific index in the dataframe in the R programming language."
},
{
"code": null,
"e": 25513,
"s": 25364,
"text": "The main task here is to shift other rows and make space in the dataframe for the new row and then insert its contents. This can be done in two ways"
},
{
"code": null,
"e": 25612,
"s": 25513,
"text": "rbind() function in R Language is used to combine specified Vector, Matrix, or Data Frame by rows."
},
{
"code": null,
"e": 25658,
"s": 25612,
"text": "Syntax: rbind(x1, x2, ..., deparse.level = 1)"
},
{
"code": null,
"e": 25670,
"s": 25658,
"text": "Parameters:"
},
{
"code": null,
"e": 25706,
"s": 25670,
"text": "x1, x2: vector, matrix, data frames"
},
{
"code": null,
"e": 25816,
"s": 25706,
"text": "deparse.level: This value determines how the column names generated. The default value of deparse.level is 1."
},
{
"code": null,
"e": 25824,
"s": 25816,
"text": "Example"
},
{
"code": null,
"e": 25826,
"s": 25824,
"text": "R"
},
{
"code": "rm(list = ls()) # Function to create new dataframeinsertRow <- function(data, new_row, r) { data_new <- rbind(data[1:r, ], new_row, data[- (1:r), ]) rownames(data_new) <- 1:nrow(data_new) return(data_new)} existingDF <- data.frame(x1 = c(15,25,35,45,55), x2 = c(23,34,45,56,76), x3 = c(12,23,3,454,26)) index <- 4 newrow <- c(9, 99, 999) newDF=insertRow(existingDF, newrow, index) print(newDF)",
"e": 26434,
"s": 25826,
"text": null
},
{
"code": null,
"e": 26442,
"s": 26434,
"text": "Output:"
},
{
"code": null,
"e": 26699,
"s": 26442,
"text": "Another approach of doing the same is to use seq() function. Here the approach is the same, but the method is somewhat different. We are accessing rows of the dataframe and creating the space in it. Also, we used nrows() to count the total number of rows. "
},
{
"code": null,
"e": 26857,
"s": 26699,
"text": "seq() function in R Language is used to create a sequence of elements in a Vector. It takes the length and difference between values as an optional argument."
},
{
"code": null,
"e": 26895,
"s": 26857,
"text": "Syntax: seq(from, to, by, length.out)"
},
{
"code": null,
"e": 26907,
"s": 26895,
"text": "Parameters:"
},
{
"code": null,
"e": 26946,
"s": 26907,
"text": "from: Starting element of the sequence"
},
{
"code": null,
"e": 26981,
"s": 26946,
"text": "to: Ending element of the sequence"
},
{
"code": null,
"e": 27017,
"s": 26981,
"text": "by: Difference between the elements"
},
{
"code": null,
"e": 27058,
"s": 27017,
"text": "length.out: Maximum length of the vector"
},
{
"code": null,
"e": 27067,
"s": 27058,
"text": "Example:"
},
{
"code": null,
"e": 27069,
"s": 27067,
"text": "R"
},
{
"code": "rm(list = ls()) # Function to create new dataframeinsertRow <- function(existingDF, new_row, r) { existingDF[seq(r+1,nrow(existingDF)+1),] <- existingDF[seq(r,nrow(existingDF)),] existingDF[r,] <- new_row return(existingDF) } existingDF <- data.frame(x1 = c(1,7,13,25,31), x2 = c(2,8,14,26,32), x3 = c(3,9,15,27,33), x4 = c(4,10,16,28,34), x5 = c(5,11,17,29,35), x6 = c(6,12,18,30,36)) r <- 4 new_row <- c(19,20,21,22,23,24) newDF=insertRow(existingDF, new_row, r) print(newDF)",
"e": 27770,
"s": 27069,
"text": null
},
{
"code": null,
"e": 27778,
"s": 27770,
"text": "Output:"
},
{
"code": null,
"e": 27785,
"s": 27778,
"text": "Picked"
},
{
"code": null,
"e": 27806,
"s": 27785,
"text": "R DataFrame-Programs"
},
{
"code": null,
"e": 27818,
"s": 27806,
"text": "R-DataFrame"
},
{
"code": null,
"e": 27829,
"s": 27818,
"text": "R Language"
},
{
"code": null,
"e": 27840,
"s": 27829,
"text": "R Programs"
},
{
"code": null,
"e": 27938,
"s": 27840,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27990,
"s": 27938,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 28028,
"s": 27990,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 28063,
"s": 28028,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 28121,
"s": 28063,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 28170,
"s": 28121,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 28228,
"s": 28170,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 28277,
"s": 28228,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 28327,
"s": 28277,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 28370,
"s": 28327,
"text": "Replace Specific Characters in String in R"
}
]
|
Pattern asPredicate() method in Java with examples | The Predicate interface of the java.util.function package can be used as a target for lambda expressions. The test method of this interface accepts a value ad validates it with the current value of the Predicate object. This method returns true in-case of a match, else false.
The asPredicate() method of the java.util.regex.Pattern class returns a Predicate object which can match a string with the regular expression using which the current Pattern object was compiled.
import java.util.Scanner;
import java.util.function.Predicate;
import java.util.regex.Pattern;
public class AsPredicateExample {
public static void main( String args[] ) {
//Reading string value
Scanner sc = new Scanner(System.in);
System.out.println("Enter input string");
String input = sc.nextLine();
//Regular expression to find digits
String regex = "[t]";
//Compiling the regular expression
Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
//Converting the regular expression to predicate
Predicate<String> predicate = pattern.asPredicate();
//Testing the predicate with the input string
boolean result = predicate.test(input);
if(result) {
System.out.println("Match found");
} else {
System.out.print("Match not found");
}
}
}
Enter input string
Tutorialspoint
Number of matches: 3
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import java.util.function.Predicate;
import java.util.regex.Pattern;
public class AsPredicateExample {
public static void main( String args[] ) {
ArrayList<String> list = new ArrayList<String>();
list.addAll(Arrays.asList("Java", "JavaFX", "Hbase", "JavaScript"));
//Regular expression to find digits
String regex = "[J]";
//Compiling the regular expression
Pattern pattern = Pattern.compile(regex);
//Converting the regular expression to predicate
Predicate<String> predicate = pattern.asPredicate();
list.forEach(n -> { if (predicate.test(n)) System.out.println("Match found "+n); });
}
}
Match found Java
Match found JavaFX
Match found JavaScript | [
{
"code": null,
"e": 1339,
"s": 1062,
"text": "The Predicate interface of the java.util.function package can be used as a target for lambda expressions. The test method of this interface accepts a value ad validates it with the current value of the Predicate object. This method returns true in-case of a match, else false."
},
{
"code": null,
"e": 1534,
"s": 1339,
"text": "The asPredicate() method of the java.util.regex.Pattern class returns a Predicate object which can match a string with the regular expression using which the current Pattern object was compiled."
},
{
"code": null,
"e": 2401,
"s": 1534,
"text": "import java.util.Scanner;\nimport java.util.function.Predicate;\nimport java.util.regex.Pattern;\npublic class AsPredicateExample {\n public static void main( String args[] ) {\n //Reading string value\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter input string\");\n String input = sc.nextLine();\n //Regular expression to find digits\n String regex = \"[t]\";\n //Compiling the regular expression\n Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);\n //Converting the regular expression to predicate\n Predicate<String> predicate = pattern.asPredicate();\n //Testing the predicate with the input string\n boolean result = predicate.test(input);\n if(result) {\n System.out.println(\"Match found\");\n } else {\n System.out.print(\"Match not found\");\n }\n }\n}"
},
{
"code": null,
"e": 2456,
"s": 2401,
"text": "Enter input string\nTutorialspoint\nNumber of matches: 3"
},
{
"code": null,
"e": 3186,
"s": 2456,
"text": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Scanner;\nimport java.util.function.Predicate;\nimport java.util.regex.Pattern;\npublic class AsPredicateExample {\n public static void main( String args[] ) {\n ArrayList<String> list = new ArrayList<String>();\n list.addAll(Arrays.asList(\"Java\", \"JavaFX\", \"Hbase\", \"JavaScript\"));\n //Regular expression to find digits\n String regex = \"[J]\";\n //Compiling the regular expression\n Pattern pattern = Pattern.compile(regex);\n //Converting the regular expression to predicate\n Predicate<String> predicate = pattern.asPredicate();\n list.forEach(n -> { if (predicate.test(n)) System.out.println(\"Match found \"+n); });\n }\n}"
},
{
"code": null,
"e": 3245,
"s": 3186,
"text": "Match found Java\nMatch found JavaFX\nMatch found JavaScript"
}
]
|
Object Oriented Python - Libraries | Requests is a Python module which is an elegant and simple HTTP library for Python. With this you can send all kinds of HTTP requests. With this library we can add headers, form data, multipart files and parameters and access the response data.
As Requests is not a built-in module, so we need to install it first.
You can install it by running the following command in the terminal −
pip install requests
Once you have installed the module, you can verify if the installation is successful by typing below command in the Python shell.
import requests
If the installation has been successful, you won’t see any error message.
As a means of example we’ll be using the “pokeapi”
The requests library methods for all of the HTTP verbs currently in use. If you wanted to make a simple POST request to an API endpoint then you can do that like so −
req = requests.post(‘http://api/user’, data = None, json = None)
This would work in exactly the same fashion as our previous GET request, however it features two additional keyword parameters −
data which can be populated with say a dictionary, a file or bytes that will be passed in the HTTP body of our POST request.
data which can be populated with say a dictionary, a file or bytes that will be passed in the HTTP body of our POST request.
json which can be populated with a json object that will be passed in the body of our HTTP request also.
json which can be populated with a json object that will be passed in the body of our HTTP request also.
Pandas is an open-source Python Library providing high-performance data manipulation and analysis tool using its powerful data structures. Pandas is one of the most widely used Python libraries in data science. It is mainly used for data munging, and with good reason: Powerful and flexible group of functionality.
Built on Numpy package and the key data structure is called the DataFrame. These dataframes allows us to store and manipulate tabular data in rows of observations and columns of variables.
There are several ways to create a DataFrame. One way is to use a dictionary. For example −
From the output we can see new brics DataFrame, Pandas has assigned a key for each country as the numerical values 0 through 4.
If instead of giving indexing values from 0 to 4, we would like to have different index values, say the two letter country code, you can do that easily as well −
Adding below one lines in the above code, gives
brics.index = ['BR', 'RU', 'IN', 'CH', 'SA']
Pygame is the open source and cross-platform library that is for making multimedia applications including games. It includes computer graphics and sound libraries designed to be used with the Python programming language. You can develop many cool games with Pygame.’
Pygame is composed of various modules, each dealing with a specific set of tasks. For example, the display module deals with the display window and screen, the draw module provides functions to draw shapes and the key module works with the keyboard. These are just some of the modules of the library.
The home of the Pygame library is at https://www.pygame.org/news
To make a Pygame application, you follow these steps −
Import the Pygame library
import pygame
Initialize the Pygame library
pygame.init()
Create a window.
screen = Pygame.display.set_mode((560,480))
Pygame.display.set_caption(‘First Pygame Game’)
Initialize game objects
In this step we load images, load sounds, do object positioning, set up some state variables, etc.
Start the game loop.
It is just a loop where we continuously handle events, checks for input, move objects, and draw them. Each iteration of the loop is called a frame.
Let’s put all the above logic into one below program,
Pygame_script.py
The general idea behind web scraping is to get the data that exists on a website, and convert it into some format that is usable for analysis.
It’s a Python library for pulling data out of HTML or XML files. With your favourite parser it provide idiomatic ways of navigating, searching and modifying the parse tree.
As BeautifulSoup is not a built-in library, we need to install it before we try to use it. To install BeautifulSoup, run the below command
$ apt-get install Python-bs4 # For Linux and Python2
$ apt-get install Python3-bs4 # for Linux based system and Python3.
$ easy_install beautifulsoup4 # For windows machine,
Or
$ pip instal beatifulsoup4 # For window machine
Once the installation is done, we are ready to run few examples and explores Beautifulsoup in details,
Below are some simple ways to navigate that data structure −
One common task is extracting all the URLs found within a page’s <a> tags −
Another common task is extracting all the text from a page −
14 Lectures
1.5 hours
Harshit Srivastava
60 Lectures
8 hours
DigiFisk (Programming Is Fun)
11 Lectures
35 mins
Sandip Bhattacharya
21 Lectures
2 hours
Pranjal Srivastava
6 Lectures
43 mins
Frahaan Hussain
49 Lectures
4.5 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2055,
"s": 1810,
"text": "Requests is a Python module which is an elegant and simple HTTP library for Python. With this you can send all kinds of HTTP requests. With this library we can add headers, form data, multipart files and parameters and access the response data."
},
{
"code": null,
"e": 2125,
"s": 2055,
"text": "As Requests is not a built-in module, so we need to install it first."
},
{
"code": null,
"e": 2195,
"s": 2125,
"text": "You can install it by running the following command in the terminal −"
},
{
"code": null,
"e": 2216,
"s": 2195,
"text": "pip install requests"
},
{
"code": null,
"e": 2346,
"s": 2216,
"text": "Once you have installed the module, you can verify if the installation is successful by typing below command in the Python shell."
},
{
"code": null,
"e": 2362,
"s": 2346,
"text": "import requests"
},
{
"code": null,
"e": 2436,
"s": 2362,
"text": "If the installation has been successful, you won’t see any error message."
},
{
"code": null,
"e": 2487,
"s": 2436,
"text": "As a means of example we’ll be using the “pokeapi”"
},
{
"code": null,
"e": 2654,
"s": 2487,
"text": "The requests library methods for all of the HTTP verbs currently in use. If you wanted to make a simple POST request to an API endpoint then you can do that like so −"
},
{
"code": null,
"e": 2719,
"s": 2654,
"text": "req = requests.post(‘http://api/user’, data = None, json = None)"
},
{
"code": null,
"e": 2848,
"s": 2719,
"text": "This would work in exactly the same fashion as our previous GET request, however it features two additional keyword parameters −"
},
{
"code": null,
"e": 2973,
"s": 2848,
"text": "data which can be populated with say a dictionary, a file or bytes that will be passed in the HTTP body of our POST request."
},
{
"code": null,
"e": 3098,
"s": 2973,
"text": "data which can be populated with say a dictionary, a file or bytes that will be passed in the HTTP body of our POST request."
},
{
"code": null,
"e": 3203,
"s": 3098,
"text": "json which can be populated with a json object that will be passed in the body of our HTTP request also."
},
{
"code": null,
"e": 3308,
"s": 3203,
"text": "json which can be populated with a json object that will be passed in the body of our HTTP request also."
},
{
"code": null,
"e": 3623,
"s": 3308,
"text": "Pandas is an open-source Python Library providing high-performance data manipulation and analysis tool using its powerful data structures. Pandas is one of the most widely used Python libraries in data science. It is mainly used for data munging, and with good reason: Powerful and flexible group of functionality."
},
{
"code": null,
"e": 3812,
"s": 3623,
"text": "Built on Numpy package and the key data structure is called the DataFrame. These dataframes allows us to store and manipulate tabular data in rows of observations and columns of variables."
},
{
"code": null,
"e": 3904,
"s": 3812,
"text": "There are several ways to create a DataFrame. One way is to use a dictionary. For example −"
},
{
"code": null,
"e": 4032,
"s": 3904,
"text": "From the output we can see new brics DataFrame, Pandas has assigned a key for each country as the numerical values 0 through 4."
},
{
"code": null,
"e": 4194,
"s": 4032,
"text": "If instead of giving indexing values from 0 to 4, we would like to have different index values, say the two letter country code, you can do that easily as well −"
},
{
"code": null,
"e": 4242,
"s": 4194,
"text": "Adding below one lines in the above code, gives"
},
{
"code": null,
"e": 4287,
"s": 4242,
"text": "brics.index = ['BR', 'RU', 'IN', 'CH', 'SA']"
},
{
"code": null,
"e": 4554,
"s": 4287,
"text": "Pygame is the open source and cross-platform library that is for making multimedia applications including games. It includes computer graphics and sound libraries designed to be used with the Python programming language. You can develop many cool games with Pygame.’"
},
{
"code": null,
"e": 4855,
"s": 4554,
"text": "Pygame is composed of various modules, each dealing with a specific set of tasks. For example, the display module deals with the display window and screen, the draw module provides functions to draw shapes and the key module works with the keyboard. These are just some of the modules of the library."
},
{
"code": null,
"e": 4920,
"s": 4855,
"text": "The home of the Pygame library is at https://www.pygame.org/news"
},
{
"code": null,
"e": 4975,
"s": 4920,
"text": "To make a Pygame application, you follow these steps −"
},
{
"code": null,
"e": 5001,
"s": 4975,
"text": "Import the Pygame library"
},
{
"code": null,
"e": 5015,
"s": 5001,
"text": "import pygame"
},
{
"code": null,
"e": 5045,
"s": 5015,
"text": "Initialize the Pygame library"
},
{
"code": null,
"e": 5059,
"s": 5045,
"text": "pygame.init()"
},
{
"code": null,
"e": 5076,
"s": 5059,
"text": "Create a window."
},
{
"code": null,
"e": 5168,
"s": 5076,
"text": "screen = Pygame.display.set_mode((560,480))\nPygame.display.set_caption(‘First Pygame Game’)"
},
{
"code": null,
"e": 5192,
"s": 5168,
"text": "Initialize game objects"
},
{
"code": null,
"e": 5291,
"s": 5192,
"text": "In this step we load images, load sounds, do object positioning, set up some state variables, etc."
},
{
"code": null,
"e": 5312,
"s": 5291,
"text": "Start the game loop."
},
{
"code": null,
"e": 5460,
"s": 5312,
"text": "It is just a loop where we continuously handle events, checks for input, move objects, and draw them. Each iteration of the loop is called a frame."
},
{
"code": null,
"e": 5514,
"s": 5460,
"text": "Let’s put all the above logic into one below program,"
},
{
"code": null,
"e": 5531,
"s": 5514,
"text": "Pygame_script.py"
},
{
"code": null,
"e": 5674,
"s": 5531,
"text": "The general idea behind web scraping is to get the data that exists on a website, and convert it into some format that is usable for analysis."
},
{
"code": null,
"e": 5847,
"s": 5674,
"text": "It’s a Python library for pulling data out of HTML or XML files. With your favourite parser it provide idiomatic ways of navigating, searching and modifying the parse tree."
},
{
"code": null,
"e": 5986,
"s": 5847,
"text": "As BeautifulSoup is not a built-in library, we need to install it before we try to use it. To install BeautifulSoup, run the below command"
},
{
"code": null,
"e": 6215,
"s": 5986,
"text": "$ apt-get install Python-bs4 # For Linux and Python2 \n$ apt-get install Python3-bs4 # for Linux based system and Python3.\n\n$ easy_install beautifulsoup4 # For windows machine, \nOr \n$ pip instal beatifulsoup4 # For window machine"
},
{
"code": null,
"e": 6318,
"s": 6215,
"text": "Once the installation is done, we are ready to run few examples and explores Beautifulsoup in details,"
},
{
"code": null,
"e": 6379,
"s": 6318,
"text": "Below are some simple ways to navigate that data structure −"
},
{
"code": null,
"e": 6455,
"s": 6379,
"text": "One common task is extracting all the URLs found within a page’s <a> tags −"
},
{
"code": null,
"e": 6516,
"s": 6455,
"text": "Another common task is extracting all the text from a page −"
},
{
"code": null,
"e": 6551,
"s": 6516,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6571,
"s": 6551,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 6604,
"s": 6571,
"text": "\n 60 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 6635,
"s": 6604,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 6667,
"s": 6635,
"text": "\n 11 Lectures \n 35 mins\n"
},
{
"code": null,
"e": 6688,
"s": 6667,
"text": " Sandip Bhattacharya"
},
{
"code": null,
"e": 6721,
"s": 6688,
"text": "\n 21 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6741,
"s": 6721,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 6772,
"s": 6741,
"text": "\n 6 Lectures \n 43 mins\n"
},
{
"code": null,
"e": 6789,
"s": 6772,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6824,
"s": 6789,
"text": "\n 49 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 6841,
"s": 6824,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 6848,
"s": 6841,
"text": " Print"
},
{
"code": null,
"e": 6859,
"s": 6848,
"text": " Add Notes"
}
]
|
Twenty-five SQL practice exercises | by Michael Boles | Towards Data Science | Structured query language (SQL) is used to retrieve and manipulate data stored in relational databases. Gaining working proficiency in SQL is an important prerequisite for many technology jobs and requires a bit of practice.
To complement SQL training resources (PGExercises, LeetCode, HackerRank, Mode) available on the web, I’ve compiled a list of my favorite questions that you can tackle by hand or solve with a PostgreSQL instance.
These questions cover the following critical concepts:
Basic retrieval (SELECT, FROM)
Creating and aliasing (WITH, AS, GENERATE_SERIES)
Filtering (DISTINCT, WHERE, HAVING, AND, OR, IN, NOT IN)
Aggregation (GROUP BY with COUNT, SUM, AVERAGE)
Joins (INNER JOIN, LEFT JOIN, FULL OUTER JOIN on one or multiple (in)equalities, CROSS JOIN, UNION and UNION ALL)
Conditional statements (CASE - WHEN - THEN - ELSE - END)
Window functions (RANK, DENSE_RANK, ROW_NUMBER, SUM with PARTITION BY - ORDER BY)
Formatting (LIMIT, ORDER BY, casting as an integer, float, or date, CONCAT, COALESCE)
Arithmetic operations and comparisons (+, -, *, /, //, ^, <, >, =, !=)
Datetime operations (EXTRACT(month/day/year))
You can try these out yourself by downloading PostgreSQL and PSequel (see this tutorial for a step-by-step installation guide) and then running the queries shown in the grey boxes in the text below. PSequel is only available for Mac — if you’re using a PC, you can try one of these Windows alternatives.
The first block of text in each query shown below establishes the input table and follows the format:
WITH input_table (column_1, column_2) AS (VALUES (1, 'A'), (2, 'B'))
You can query against the input table using PSequel (shown above) and easily construct new tables for your own problems using this template.
Web-based SQL training resources fall short along a few dimensions. LeetCode, for instance, doesn’t support the use of window functions and hides its most interesting questions behind a paywall. In addition, running SQL queries in your browser can be extremely slow — the data sets are large and retrieval speed is often throttled for non-premium users. Locally executing a query, on the other hand, is instantaneous and allows for rapid iteration through syntax bugs and intermediate tables. I’ve found this to be a more satisfying learning experience.
The questions outlined below include example solutions confirmed to work in PostgreSQL. Keep in mind there is usually more than one way to obtain the correct answer to a SQL problem. My preference is to use common table expressions (CTEs) rather than nested subqueries — CTEs allow for a more linear illustration of the data wrangling sequence. Both approaches, however, can yield identical solutions. I also like to follow the convention of keeping SQL operators in all caps (SELECT, FROM, WHERE, etc.), column names in lowercase (user_id, date, etc.), and simple table aliasing (t1, t2, etc.) where possible.
The code snippets shown below can be run in PSequel as-is to yield the displayed result. Note one quirk of Postgres: fractions must be multiplied by 1.0 to convert from integer to float format. This is not needed in other implementations of SQL and is not expected in interviews.
Feel free to leave your alternative answers in the comments!
From the following table of user IDs, actions, and dates, write a query to return the publication and cancellation rate for each user.
WITH users (user_id, action, date) AS (VALUES (1,'start', CAST('01-01-20' AS date)), (1,'cancel', CAST('01-02-20' AS date)), (2,'start', CAST('01-03-20' AS date)), (2,'publish', CAST('01-04-20' AS date)), (3,'start', CAST('01-05-20' AS date)), (3,'cancel', CAST('01-06-20' AS date)), (1,'start', CAST('01-07-20' AS date)), (1,'publish', CAST('01-08-20' AS date))),-- retrieve count of starts, cancels, and publishes for each usert1 AS (SELECT user_id, SUM(CASE WHEN action = 'start' THEN 1 ELSE 0 END) AS starts, SUM(CASE WHEN action = 'cancel' THEN 1 ELSE 0 END) AS cancels, SUM(CASE WHEN action = 'publish' THEN 1 ELSE 0 END) AS publishesFROM usersGROUP BY 1ORDER BY 1)-- calculate publication, cancelation rate for each user by dividing by number of starts, casting as float by multiplying by 1.0 (default floor division is a quirk of some SQL tools, not always needed)SELECT user_id, 1.0*publishes/starts AS publish_rate, 1.0*cancels/starts AS cancel_rateFROM t1
From the following table of transactions between two users, write a query to return the change in net worth for each user, ordered by decreasing net change.
WITH transactions (sender, receiver, amount, transaction_date) AS (VALUES (5, 2, 10, CAST('2-12-20' AS date)),(1, 3, 15, CAST('2-13-20' AS date)), (2, 1, 20, CAST('2-13-20' AS date)), (2, 3, 25, CAST('2-14-20' AS date)), (3, 1, 20, CAST('2-15-20' AS date)), (3, 2, 15, CAST('2-15-20' AS date)), (1, 4, 5, CAST('2-16-20' AS date))),-- sum amounts for each sender (debits) and receiver (credits)debits AS (SELECT sender, SUM(amount) AS debitedFROM transactionsGROUP BY 1 ),credits AS (SELECT receiver, SUM(amount) AS creditedFROM transactionsGROUP BY 1 )-- full (outer) join debits and credits tables on user id, taking net change as difference between credits and debits, coercing nulls to zeros with coalesce()SELECT COALESCE(sender, receiver) AS user, COALESCE(credited, 0) - COALESCE(debited, 0) AS net_change FROM debits dFULL JOIN credits cON d.sender = c.receiverORDER BY 2 DESC
From the following table containing a list of dates and items ordered, write a query to return the most frequent item ordered on each date. Return multiple items in the case of a tie.
WITH items (date, item) AS (VALUES (CAST('01-01-20' AS date),'apple'), (CAST('01-01-20' AS date),'apple'), (CAST('01-01-20' AS date),'pear'), (CAST('01-01-20' AS date),'pear'), (CAST('01-02-20' AS date),'pear'), (CAST('01-02-20' AS date),'pear'), (CAST('01-02-20' AS date),'pear'), (CAST('01-02-20' AS date),'orange')),-- add an item count column to existing table, grouping by date and item columnst1 AS (SELECT date, item, COUNT(*) AS item_countFROM itemsGROUP BY 1, 2ORDER BY 1),-- add a rank column in descending order, partitioning by datet2 AS (SELECT *, RANK() OVER (PARTITION BY date ORDER BY item_count DESC) AS date_rankFROM t1)-- return all dates and items where rank = 1SELECT date, itemFROM t2WHERE date_rank = 1
From the following table of user actions, write a query to return for each user the time elapsed between the last action and the second-to-last action, in ascending order by user ID.
WITH users (user_id, action, action_date) AS (VALUES (1, 'start', CAST('2-12-20' AS date)), (1, 'cancel', CAST('2-13-20' AS date)), (2, 'start', CAST('2-11-20' AS date)), (2, 'publish', CAST('2-14-20' AS date)), (3, 'start', CAST('2-15-20' AS date)), (3, 'cancel', CAST('2-15-20' AS date)), (4, 'start', CAST('2-18-20' AS date)), (1, 'publish', CAST('2-19-20' AS date))),-- create a date rank column, partitioned by user ID, using the ROW_NUMBER() window function t1 AS (SELECT *, ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY action_date DESC) AS date_rankFROM users ),-- filter on date rank column to pull latest and next latest actions from this tablelatest AS (SELECT *FROM t1 WHERE date_rank = 1 ),next_latest AS (SELECT *FROM t1 WHERE date_rank = 2 )-- left join these two tables, subtracting latest from second latest to get time elapsed SELECT l1.user_id, l1.action_date - l2.action_date AS days_elapsedFROM latest l1LEFT JOIN next_latest l2ON l1.user_id = l2.user_idORDER BY 1
A company defines its super users as those who have made at least two transactions. From the following table, write a query to return, for each user, the date when they become a super user, ordered by oldest super users first. Users who are not super users should also be present in the table.
WITH users (user_id, product_id, transaction_date) AS (VALUES (1, 101, CAST('2-12-20' AS date)), (2, 105, CAST('2-13-20' AS date)), (1, 111, CAST('2-14-20' AS date)), (3, 121, CAST('2-15-20' AS date)), (1, 101, CAST('2-16-20' AS date)), (2, 105, CAST('2-17-20' AS date)),(4, 101, CAST('2-16-20' AS date)), (3, 105, CAST('2-15-20' AS date))),-- create a transaction number column using ROW_NUMBER(), partitioning by user IDt1 AS (SELECT *, ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY transaction_date) AS transaction_numberFROM users),-- filter resulting table on transaction_number = 2t2 AS (SELECT user_id, transaction_dateFROM t1WHERE transaction_number = 2 ),-- left join super users onto full user table, order by date t3 AS (SELECT DISTINCT user_idFROM users )SELECT t3.user_id, transaction_date AS superuser_dateFROM t3LEFT JOIN t2ON t3.user_id = t2.user_idORDER BY 2
Using the following two tables, write a query to return page recommendations to a social media user based on the pages that their friends have liked, but that they have not yet marked as liked. Order the result by ascending user ID. Source.
WITH friends (user_id, friend) AS (VALUES (1, 2), (1, 3), (1, 4), (2, 1), (3, 1), (3, 4), (4, 1), (4, 3)),likes (user_id, page_likes) AS (VALUES (1, 'A'), (1, 'B'), (1, 'C'), (2, 'A'), (3, 'B'), (3, 'C'), (4, 'B')),-- inner join friends and page likes tables on user_idt1 AS (SELECT l.user_id, l.page_likes, f.friendFROM likes lJOIN friends fON l.user_id = f.user_id ),-- left join likes on this, requiring user = friend and user likes = friend likes t2 AS (SELECT t1.user_id, t1.page_likes, t1.friend, l.page_likes AS friend_likesFROM t1LEFT JOIN likes lON t1.friend = l.user_idAND t1.page_likes = l.page_likes )-- if a friend pair doesn’t share a common page like, friend likes column will be null - pull out these entries SELECT DISTINCT friend AS user_id, page_likes AS recommended_pageFROM t2WHERE friend_likes IS NULLORDER BY 1
With the following two tables, return the fraction of users who only visited mobile, only visited web, and visited both.
WITH mobile (user_id, page_url) AS (VALUES (1, 'A'), (2, 'B'), (3, 'C'), (4, 'A'), (9, 'B'), (2, 'C'), (10, 'B')),web (user_id, page_url) AS (VALUES (6, 'A'), (2, 'B'), (3, 'C'), (7, 'A'), (4, 'B'), (8, 'C'), (5, 'B')),-- outer join mobile and web users on user IDt1 AS (SELECT DISTINCT m.user_id AS mobile_user, w.user_id AS web_userFROM mobile mFULL JOIN web wON m.user_id = w.user_id)-- calculate fraction of mobile-only, web-only, and both as average of values (ones and zeros) specified in case statement conditionSELECT AVG(CASE WHEN mobile_user IS NOT NULL AND web_user IS NULL THEN 1 ELSE 0 END) AS mobile_fraction, AVG(CASE WHEN web_user IS NOT NULL AND mobile_user IS NULL THEN 1 ELSE 0 END) AS web_fraction, AVG(CASE WHEN web_user IS NOT NULL AND mobile_user IS NOT NULL THEN 1 ELSE 0 END) AS both_fractionFROM t1
Given the following two tables, return the fraction of users, rounded to two decimal places, who accessed feature two (type: F2 in events table) and upgraded to premium within the first 30 days of signing up.
WITH users (user_id, name, join_date) AS (VALUES (1, 'Jon', CAST('2-14-20' AS date)), (2, 'Jane', CAST('2-14-20' AS date)), (3, 'Jill', CAST('2-15-20' AS date)), (4, 'Josh', CAST('2-15-20' AS date)), (5, 'Jean', CAST('2-16-20' AS date)), (6, 'Justin', CAST('2-17-20' AS date)),(7, 'Jeremy', CAST('2-18-20' AS date))),events (user_id, type, access_date) AS (VALUES (1, 'F1', CAST('3-1-20' AS date)), (2, 'F2', CAST('3-2-20' AS date)), (2, 'P', CAST('3-12-20' AS date)),(3, 'F2', CAST('3-15-20' AS date)), (4, 'F2', CAST('3-15-20' AS date)), (1, 'P', CAST('3-16-20' AS date)), (3, 'P', CAST('3-22-20' AS date))),-- get feature 2 users and their date of feature 2 accesst1 AS (SELECT user_id, type, access_date AS f2_dateFROM eventsWHERE type = 'F2' ),-- get premium users and their date of premium upgradet2 AS (SELECT user_id, type, access_date AS premium_dateFROM eventsWHERE type = 'P' ),-- for each feature 2 user, get time between joining and premium upgrade (or null if no upgrade) by inner joining full users table with feature 2 users on user ID and left joining premium users on user ID, then subtracting premium upgrade date from join datet3 AS (SELECT t2.premium_date - u.join_date AS upgrade_timeFROM users uJOIN t1ON u.user_id = t1.user_idLEFT JOIN t2ON u.user_id = t2.user_id )-- calculate fraction of users with upgrade time less than 30 days as average of values (ones and zeros) specified in case statement condition, rounding to two decimal places SELECT ROUND(AVG(CASE WHEN upgrade_time < 30 THEN 1 ELSE 0 END), 2) AS upgrade_rateFROM t3
Given the following table, return a list of users and their corresponding friend count. Order the result by descending friend count, and in the case of a tie, by ascending user ID. Assume that only unique friendships are displayed (i.e., [1, 2] will not show up again as [2, 1] ). From LeetCode.
WITH friends (user1, user2) AS (VALUES (1, 2), (1, 3), (1, 4), (2, 3)),-- compile all user appearances into one column, preserving duplicate entries with UNION ALL t1 AS (SELECT user1 AS user_idFROM friendsUNION ALLSELECT user2 AS user_idFROM friends)-- grouping by user ID, count up all appearances of that userSELECT user_id, COUNT(*) AS friend_countFROM t1GROUP BY 1ORDER BY 2 DESC
The projects table contains three columns: task_id, start_date, and end_date. The difference between end_date and start_date is 1 day for each row in the table. If task end dates are consecutive they are part of the same project. Projects do not overlap.
Write a query to return the start and end dates of each project, and the number of days it took to complete. Order by ascending project duration, and ascending start date in the case of a tie. From HackerRank.
WITH projects (task_id, start_date, end_date) AS (VALUES (1, CAST('10-01-20' AS date), CAST('10-02-20' AS date)), (2, CAST('10-02-20' AS date), CAST('10-03-20' AS date)), (3, CAST('10-03-20' AS date), CAST('10-04-20' AS date)), (4, CAST('10-13-20' AS date), CAST('10-14-20' AS date)), (5, CAST('10-14-20' AS date), CAST('10-15-20' AS date)), (6, CAST('10-28-20' AS date), CAST('10-29-20' AS date)), (7, CAST('10-30-20' AS date), CAST('10-31-20' AS date))),-- get start dates not present in end date column (these are “true” project start dates) t1 AS (SELECT start_dateFROM projectsWHERE start_date NOT IN (SELECT end_date FROM projects) ),-- get end dates not present in start date column (these are “true” project end dates) t2 AS (SELECT end_dateFROM projectsWHERE end_date NOT IN (SELECT start_date FROM projects) ),-- filter to plausible start-end pairs (start < end), then find correct end date for each start date (the minimum end date, since there are no overlapping projects)t3 AS (SELECT start_date, MIN(end_date) AS end_dateFROM t1, t2WHERE start_date < end_dateGROUP BY 1 )SELECT *, end_date - start_date AS project_durationFROM t3ORDER BY 3, 1
Given the following two tables, write a query to return the fraction of students, rounded to two decimal places, who attended school (attendance = 1) on their birthday. Source.
WITH attendance (student_id, school_date, attendance)AS (VALUES(1, CAST('2020-04-03' AS date), 0),(2, CAST('2020-04-03' AS date), 1),(3, CAST('2020-04-03' AS date), 1), (1, CAST('2020-04-04' AS date), 1), (2, CAST('2020-04-04' AS date), 1), (3, CAST('2020-04-04' AS date), 1), (1, CAST('2020-04-05' AS date), 0), (2, CAST('2020-04-05' AS date), 1), (3, CAST('2020-04-05' AS date), 1), (4, CAST('2020-04-05' AS date), 1)),students (student_id, school_id, grade_level, date_of_birth)AS (VALUES(1, 2, 5, CAST('2012-04-03' AS date)),(2, 1, 4, CAST('2013-04-04' AS date)),(3, 1, 3, CAST('2014-04-05' AS date)), (4, 2, 4, CAST('2013-04-03' AS date)))-- join attendance and students table on student ID, and day and month of school day = day and month of birthday, taking average of attendance column values and roundingSELECT ROUND(AVG(attendance), 2) AS birthday_attendanceFROM attendance aJOIN students sON a.student_id = s.student_id AND EXTRACT(MONTH FROM school_date) = EXTRACT(MONTH FROM date_of_birth)AND EXTRACT(DAY FROM school_date) = EXTRACT(DAY FROM date_of_birth)
Given the following two tables, write a query to return the hacker ID, name, and total score (the sum of maximum scores for each challenge completed) ordered by descending score, and by ascending hacker ID in the case of score tie. Do not display entries for hackers with a score of zero. From HackerRank.
WITH hackers (hacker_id, name)AS (VALUES(1, 'John'),(2, 'Jane'),(3, 'Joe'),(4, 'Jim')),submissions (submission_id, hacker_id, challenge_id, score)AS (VALUES(101, 1, 1, 10),(102, 1, 1, 12),(103, 2, 1, 11),(104, 2, 1, 9),(105, 2, 2, 13),(106, 3, 1, 9),(107, 3, 2, 12),(108, 3, 2, 15),(109, 4, 1, 0)),-- from submissions table, get maximum score for each hacker-challenge pairt1 AS (SELECT hacker_id, challenge_id, MAX(score) AS max_scoreFROM submissions GROUP BY 1, 2 )-- inner join this with the hackers table, sum up all maximum scores, filter to exclude hackers with total score of zero, and order result by total score and hacker IDSELECT t1.hacker_id, h.name, SUM(t1.max_score) AS total_scoreFROM t1JOIN hackers hON t1.hacker_id = h.hacker_idGROUP BY 1, 2HAVING SUM(max_score) > 0ORDER BY 3 DESC, 1
Write a query to rank scores in the following table without using a window function. If there is a tie between two scores, both should have the same rank. After a tie, the following rank should be the next consecutive integer value. From LeetCode.
WITH scores (id, score)AS (VALUES(1, 3.50),(2, 3.65),(3, 4.00),(4, 3.85),(5, 4.00),(6, 3.65))-- self-join on inequality produces a table with one score and all scores as large as this joined to it, grouping by first id and score, and counting up all unique values of joined scores yields the equivalent of DENSE_RANK() [check join output to understand]SELECT s1.score, COUNT(DISTINCT s2.score) AS score_rankFROM scores s1 JOIN scores s2ON s1.score <= s2.scoreGROUP BY s1.id, s1.scoreORDER BY 1 DESC
The following table holds monthly salary information for several employees. Write a query to get, for each month, the cumulative sum of an employee’s salary over a period of 3 months, excluding the most recent month. The result should be ordered by ascending employee ID and month. From LeetCode.
WITH employee (id, pay_month, salary)AS (VALUES(1, 1, 20),(2, 1, 20),(1, 2, 30),(2, 2, 30),(3, 2, 40),(1, 3, 40),(3, 3, 60),(1, 4, 60),(3, 4, 70)),-- add column for descending month rank (latest month = 1) for each employeet1 AS (SELECT *, RANK() OVER (PARTITION BY id ORDER BY pay_month DESC) AS month_rankFROM employee )-- filter to exclude latest month and months 5+, create cumulative salary sum using SUM() as window function, order by ID and monthSELECT id, pay_month, salary, SUM(salary) OVER (PARTITION BY id ORDER BY month_rank DESC) AS cumulative_sumFROM t1 WHERE month_rank != 1AND month_rank <= 4ORDER BY 1, 2
Write a query to return the scores of each team in the teams table after all matches displayed in the matches table. Points are awarded as follows: zero points for a loss, one point for a tie, and three points for a win. The result should include team name and points, and be ordered by decreasing points. In case of a tie, order by alphabetized team name.
WITH teams (team_id, team_name)AS (VALUES(1, 'New York'),(2, 'Atlanta'),(3, 'Chicago'),(4, 'Toronto'),(5, 'Los Angeles'),(6, 'Seattle')),matches (match_id, host_team, guest_team, host_goals, guest_goals)AS (VALUES(1, 1, 2, 3, 0),(2, 2, 3, 2, 4),(3, 3, 4, 4, 3),(4, 4, 5, 1, 1),(5, 5, 6, 2, 1),(6, 6, 1, 1, 2)),-- add host points and guest points columns to matches table, using case-when-then to tally up points for wins, ties, and lossest1 AS (SELECT *, CASE WHEN host_goals > guest_goals THEN 3 WHEN host_goals = guest_goals THEN 1 ELSE 0 END AS host_points, CASE WHEN host_goals < guest_goals THEN 3 WHEN host_goals = guest_goals THEN 1 ELSE 0 END AS guest_pointsFROM matches )-- join result onto teams table twice to add up for each team the points earned as host team and guest team, then order as requestedSELECT t.team_name, a.host_points + b.guest_points AS total_pointsFROM teams tJOIN t1 aON t.team_id = a.host_teamJOIN t1 bON t.team_id = b.guest_teamORDER BY 2 DESC, 1
From the following table, write a query to display the ID and name of customers who bought products A and B, but didn’t buy product C, ordered by ascending customer ID.
WITH customers (id, name)AS (VALUES(1, 'Daniel'),(2, 'Diana'),(3, 'Elizabeth'),(4, 'John')),orders (order_id, customer_id, product_name)AS (VALUES(1, 1, 'A'),(2, 1, 'B'),(3, 2, 'A'),(4, 2, 'B'),(5, 2, 'C'),(6, 3, 'A'), (7, 3, 'A'),(8, 3, 'B'),(9, 3, 'D'))-- join customers and orders tables on customer ID, filtering to those who bought both products A and B, removing those who bought product C, returning ID and name columns ordered by ascending IDSELECT DISTINCT id, nameFROM orders oJOIN customers cON o.customer_id = c.idWHERE customer_id IN (SELECT customer_id FROM orders WHERE product_name = 'A') AND customer_id IN (SELECT customer_id FROM orders WHERE product_name = 'B') AND customer_id NOT IN (SELECT customer_id FROM orders WHERE product_name = 'C')ORDER BY 1
Write a query to return the median latitude of weather stations from each state in the following table, rounding to the nearest tenth of a degree. Note that there is no MEDIAN() function in SQL! From HackerRank.
WITH stations (id, city, state, latitude, longitude)AS (VALUES(1, 'Asheville', 'North Carolina', 35.6, 82.6),(2, 'Burlington', 'North Carolina', 36.1, 79.4),(3, 'Chapel Hill', 'North Carolina', 35.9, 79.1),(4, 'Davidson', 'North Carolina', 35.5, 80.8),(5, 'Elizabeth City', 'North Carolina', 36.3, 76.3),(6, 'Fargo', 'North Dakota', 46.9, 96.8),(7, 'Grand Forks', 'North Dakota', 47.9, 97.0),(8, 'Hettinger', 'North Dakota', 46.0, 102.6),(9, 'Inkster', 'North Dakota', 48.2, 97.6)),-- assign latitude-ordered row numbers for each state, and get total row count for each statet1 AS (SELECT *, ROW_NUMBER() OVER (PARTITION BY state ORDER BY latitude ASC) AS row_number_state, count(*) OVER (PARTITION BY state) AS row_countFROM stations )-- filter to middle row (for odd total row number) or middle two rows (for even total row number), then get average value of those, grouping by stateSELECT state, AVG(latitude) AS median_latitudeFROM t1WHERE row_number_state >= 1.0*row_count/2 AND row_number_state <= 1.0*row_count/2 + 1GROUP BY 1
From the same table in question 17, write a query to return the furthest-separated pair of cities for each state, and the corresponding distance (in degrees, rounded to 2 decimal places) between those two cities. From HackerRank.
WITH stations (id, city, state, latitude, longitude)AS (VALUES(1, 'Asheville', 'North Carolina', 35.6, 82.6),(2, 'Burlington', 'North Carolina', 36.1, 79.4),(3, 'Chapel Hill', 'North Carolina', 35.9, 79.1),(4, 'Davidson', 'North Carolina', 35.5, 80.8),(5, 'Elizabeth City', 'North Carolina', 36.3, 76.3),(6, 'Fargo', 'North Dakota', 46.9, 96.8),(7, 'Grand Forks', 'North Dakota', 47.9, 97.0),(8, 'Hettinger', 'North Dakota', 46.0, 102.6),(9, 'Inkster', 'North Dakota', 48.2, 97.6)),-- self-join on matching states and city < city (avoids identical and double-counted city pairs), pulling state, city pair, and latitude/longitude coordinates for each cityt1 AS (SELECT s1.state, s1.city AS city1, s2.city AS city2, s1.latitude AS city1_lat, s1.longitude AS city1_long, s2.latitude AS city2_lat, s2.longitude AS city2_longFROM stations s1JOIN stations s2ON s1.state = s2.state AND s1.city < s2.city ),-- add a column displaying rounded Euclidean distance t2 AS (SELECT *, ROUND(( (city1_lat - city2_lat)^2 + (city1_long - city2_long)^2 ) ^ 0.5, 2) AS distanceFROM t1 ),-- rank each city pair by descending distance for each statet3 AS (SELECT *, RANK() OVER (PARTITION BY state ORDER BY distance DESC) AS dist_rankFROM t2 )-- return the city pair with maximium separationSELECT state, city1, city2, distanceFROM t3WHERE dist_rank = 1
Write a query to return the average cycle time across each month. Cycle time is the time elapsed between one user joining and their invitees joining. Users who joined without an invitation have a zero in the “invited by” column.
WITH users (user_id, join_date, invited_by) AS (VALUES (1, CAST('01-01-20' AS date), 0), (2, CAST('01-10-20' AS date), 1), (3, CAST('02-05-20' AS date), 2), (4, CAST('02-12-20' AS date), 3), (5, CAST('02-25-20' AS date), 2), (6, CAST('03-01-20' AS date), 0), (7, CAST('03-01-20' AS date), 4),(8, CAST('03-04-20' AS date), 7)),-- self-join on invited by = user ID, extract join month from inviter join date, and calculate cycle time as difference between join dates of inviter and inviteet1 AS (SELECT CAST(EXTRACT(MONTH FROM u2.join_date) AS int) AS month, u1.join_date - u2.join_date AS cycle_timeFROM users u1JOIN users u2ON u1.invited_by = u2.user_id )-- group by join month, take average of cycle times within each monthSELECT month, AVG(cycle_time) AS cycle_time_month_avgFROM t1GROUP BY 1ORDER BY 1
The attendance table logs the number of people counted in a crowd each day an event is held. Write a query to return a table showing the date and visitor count of high-attendance periods, defined as three consecutive entries (not necessarily consecutive dates) with more than 100 visitors. From LeetCode.
WITH attendance (event_date, visitors) AS (VALUES (CAST('01-01-20' AS date), 10), (CAST('01-04-20' AS date), 109), (CAST('01-05-20' AS date), 150), (CAST('01-06-20' AS date), 99), (CAST('01-07-20' AS date), 145), (CAST('01-08-20' AS date), 1455), (CAST('01-11-20' AS date), 199),(CAST('01-12-20' AS date), 188)),-- add row numbers to identify consecutive entries, since date column has some gapst1 AS (SELECT *, ROW_NUMBER() OVER (ORDER BY event_date) AS day_numFROM attendance ),-- filter this to exclude days with > 100 visitorst2 AS (SELECT *FROM t1WHERE visitors > 100 ),-- self-join (inner) twice on offset = 1 day and offset = 2 dayst3 AS (SELECT a.day_num AS day1, b.day_num AS day2, c.day_num AS day3FROM t2 aJOIN t2 bON a.day_num = b.day_num - 1JOIN t2 cON a.day_num = c.day_num - 2 )-- pull date and visitor count for consecutive days surfaced in previous tableSELECT event_date, visitorsFROM t1WHERE day_num IN (SELECT day1 FROM t3) OR day_num IN (SELECT day2 FROM t3) OR day_num IN (SELECT day3 FROM t3)
Using the following two tables, write a query to return the names and purchase frequency of the top three pairs of products most often bought together. The names of both products should appear in one column. Source.
WITH orders (order_id, customer_id, product_id) AS (VALUES (1, 1, 1),(1, 1, 2),(1, 1, 3),(2, 2, 1),(2, 2, 2),(2, 2, 4),(3, 1, 5)),products (id, name) AS (VALUES (1, 'A'),(2, 'B'),(3, 'C'),(4, 'D'),(5, 'E')),-- get unique product pairs from same order by self-joining orders table on order ID and product ID < product ID (avoids identical and double-counted product pairs)t1 AS (SELECT o1.product_id AS prod_1, o2.product_id AS prod_2FROM orders o1JOIN orders o2ON o1.order_id = o2.order_idAND o1.product_id < o2.product_id ),-- join products table onto this to get product names, concatenate to get product pairs in one columnt2 AS (SELECT CONCAT(p1.name, ' ', p2.name) AS product_pairFROM t1JOIN products p1ON t1.prod_1 = p1.idJOIN products p2ON t1.prod_2 = p2.id )-- grouping by product pair, return top 3 entries sorted by purchase frequencySELECT *, COUNT(*) AS purchase_freqFROM t2GROUP BY 1ORDER BY 2 DESC LIMIT 3
From the following table summarizing the results of a study, calculate the average treatment effect as well as upper and lower bounds of the 95% confidence interval. Round these numbers to 3 decimal places.
WITH study (participant_id, assignment, outcome) AS (VALUES (1, 0, 0),(2, 1, 1),(3, 0, 1),(4, 1, 0),(5, 0, 1),(6, 1, 1),(7, 0, 0),(8, 1, 1),(9, 1, 1)),-- get average outcomes, standard deviations, and group sizes for control and treatment groupscontrol AS (SELECT AVG(outcome) AS avg_outcome, STDDEV(outcome) AS std_dev, COUNT(*) AS group_sizeFROM studyWHERE assignment = 0 ),treatment AS (SELECT AVG(outcome) AS avg_outcome, STDDEV(outcome) AS std_dev, COUNT(*) AS group_sizeFROM studyWHERE assignment = 1 ),-- get average treatment effect sizeeffect_size AS (SELECT t.avg_outcome - c.avg_outcome AS effect_sizeFROM control c, treatment t ),-- construct 95% confidence interval using z* = 1.96 and magnitude of individual standard errors [ std dev / sqrt(sample size) ]conf_interval AS (SELECT 1.96 * (t.std_dev^2 / t.group_size + c.std_dev^2 / c.group_size)^0.5 AS conf_intFROM treatment t, control c )SELECT round(es.effect_size, 3) AS point_estimate, round(es.effect_size - ci.conf_int, 3) AS lower_bound, round(es.effect_size + ci.conf_int, 3) AS upper_boundFROM effect_size es, conf_interval ci
The following table shows the monthly salary for an employee for the first nine months in a given year. From this, write a query to return a table that displays, for each month in the first half of the year, the rolling sum of the employee’s salary for that month and the following two months, ordered chronologically.
WITH salaries (month, salary) AS (VALUES (1, 2000),(2, 3000),(3, 5000),(4, 4000),(5, 2000),(6, 1000),(7, 2000),(8, 4000),(9, 5000))-- self-join to match month n with months n, n+1, and n+2, then sum salary across those months, filter to first half of year, and sortSELECT s1.month, SUM(s2.salary) AS salary_3mosFROM salaries s1JOIN salaries s2ON s1.month <= s2.month AND s1.month > s2.month - 3GROUP BY 1HAVING s1.month < 7ORDER BY 1
From the given trips and users tables for a taxi service, write a query to return the cancellation rate in the first two days in October, rounded to two decimal places, for trips not involving banned riders or drivers. From LeetCode.
WITH trips (trip_id, rider_id, driver_id, status, request_date)AS (VALUES(1, 1, 10, 'completed', CAST('2020-10-01' AS date)),(2, 2, 11, 'cancelled_by_driver', CAST('2020-10-01' AS date)),(3, 3, 12, 'completed', CAST('2020-10-01' AS date)),(4, 4, 10, 'cancelled_by_rider', CAST('2020-10-02' AS date)),(5, 1, 11, 'completed', CAST('2020-10-02' AS date)),(6, 2, 12, 'completed', CAST('2020-10-02' AS date)),(7, 3, 11, 'completed', CAST('2020-10-03' AS date))),users (user_id, banned, type)AS (VALUES(1, 'no', 'rider'),(2, 'yes', 'rider'),(3, 'no', 'rider'),(4, 'no', 'rider'),(10, 'no', 'driver'),(11, 'no', 'driver'),(12, 'no', 'driver'))-- filter trips table to exclude banned riders and drivers, then calculate cancellation rate as 1 - fraction of trips completed, filtering to first two days of the monthSELECT request_date, 1 - AVG(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) AS cancel_rateFROM tripsWHERE rider_id NOT IN (SELECT user_id FROM users WHERE banned = 'yes' )AND driver_id NOT IN (SELECT user_id FROM users WHERE banned = 'yes' )GROUP BY 1HAVING EXTRACT(DAY FROM request_date) <= 2
From the following user activity table, write a query to return the fraction of users who are retained (show some activity) a given number of days after joining. By convention, users are considered active on their join day (day 0).
WITH users (user_id, action_date, action) AS (VALUES (1, CAST('01-01-20' AS date), 'Join'), (1, CAST('01-02-20' AS date), 'Access'), (2, CAST('01-02-20' AS date), 'Join'), (3, CAST('01-02-20' AS date), 'Join'), (1, CAST('01-03-20' AS date), 'Access'), (3, CAST('01-03-20' AS date), 'Access'),(1, CAST('01-04-20' AS date), 'Access')),-- get join dates for each userjoin_dates AS (SELECT user_id, action_date AS join_dateFROM usersWHERE action = 'Join' ),-- create vector containing all dates in date rangedate_vector AS (SELECT CAST(GENERATE_SERIES(MIN(action_date), MAX(action_date), '1 day'::interval) AS date) AS datesFROM users ),-- cross join to get all possible user-date combinationsall_users_dates AS (SELECT DISTINCT user_id, d.datesFROM usersCROSS JOIN date_vector d ),-- left join users table onto all user-date combinations on matching user ID and date (null on days where user didn't engage), join onto this each user's signup date, exclude user-date combinations falling before user signupt1 AS (SELECT a.dates - c.join_date AS day_no, b.user_idFROM all_users_dates aLEFT JOIN users bON a.user_id = b.user_idAND a.dates = b.action_dateJOIN join_dates cON a.user_id = c.user_id WHERE a.dates - c.join_date >= 0 )-- grouping by days since signup, count (non-null) user IDs as active users, total users, and the quotient as retention rateSELECT day_no, COUNT(*) AS n_total, COUNT(DISTINCT user_id) AS n_active, ROUND(1.0*COUNT(DISTINCT user_id)/COUNT(*), 2) AS retentionFROM t1GROUP BY 1
A note on one common problem: if you see a syntax error when using CTEs, check that you have commas between CTEs and no comma after the last CTE.
WITH input_table (column_1, column_2) AS (VALUES (1, 'A'), (2, 'B')), -- comma between CTEst1 AS (SELECT *FROM input_tableWHERE column_2 = 'A') -- no comma after last CTESELECT *FROM t1
Thanks to Ben Lacar and Minting Ye. | [
{
"code": null,
"e": 397,
"s": 172,
"text": "Structured query language (SQL) is used to retrieve and manipulate data stored in relational databases. Gaining working proficiency in SQL is an important prerequisite for many technology jobs and requires a bit of practice."
},
{
"code": null,
"e": 609,
"s": 397,
"text": "To complement SQL training resources (PGExercises, LeetCode, HackerRank, Mode) available on the web, I’ve compiled a list of my favorite questions that you can tackle by hand or solve with a PostgreSQL instance."
},
{
"code": null,
"e": 664,
"s": 609,
"text": "These questions cover the following critical concepts:"
},
{
"code": null,
"e": 695,
"s": 664,
"text": "Basic retrieval (SELECT, FROM)"
},
{
"code": null,
"e": 745,
"s": 695,
"text": "Creating and aliasing (WITH, AS, GENERATE_SERIES)"
},
{
"code": null,
"e": 802,
"s": 745,
"text": "Filtering (DISTINCT, WHERE, HAVING, AND, OR, IN, NOT IN)"
},
{
"code": null,
"e": 850,
"s": 802,
"text": "Aggregation (GROUP BY with COUNT, SUM, AVERAGE)"
},
{
"code": null,
"e": 964,
"s": 850,
"text": "Joins (INNER JOIN, LEFT JOIN, FULL OUTER JOIN on one or multiple (in)equalities, CROSS JOIN, UNION and UNION ALL)"
},
{
"code": null,
"e": 1021,
"s": 964,
"text": "Conditional statements (CASE - WHEN - THEN - ELSE - END)"
},
{
"code": null,
"e": 1103,
"s": 1021,
"text": "Window functions (RANK, DENSE_RANK, ROW_NUMBER, SUM with PARTITION BY - ORDER BY)"
},
{
"code": null,
"e": 1189,
"s": 1103,
"text": "Formatting (LIMIT, ORDER BY, casting as an integer, float, or date, CONCAT, COALESCE)"
},
{
"code": null,
"e": 1260,
"s": 1189,
"text": "Arithmetic operations and comparisons (+, -, *, /, //, ^, <, >, =, !=)"
},
{
"code": null,
"e": 1306,
"s": 1260,
"text": "Datetime operations (EXTRACT(month/day/year))"
},
{
"code": null,
"e": 1610,
"s": 1306,
"text": "You can try these out yourself by downloading PostgreSQL and PSequel (see this tutorial for a step-by-step installation guide) and then running the queries shown in the grey boxes in the text below. PSequel is only available for Mac — if you’re using a PC, you can try one of these Windows alternatives."
},
{
"code": null,
"e": 1712,
"s": 1610,
"text": "The first block of text in each query shown below establishes the input table and follows the format:"
},
{
"code": null,
"e": 1781,
"s": 1712,
"text": "WITH input_table (column_1, column_2) AS (VALUES (1, 'A'), (2, 'B'))"
},
{
"code": null,
"e": 1922,
"s": 1781,
"text": "You can query against the input table using PSequel (shown above) and easily construct new tables for your own problems using this template."
},
{
"code": null,
"e": 2476,
"s": 1922,
"text": "Web-based SQL training resources fall short along a few dimensions. LeetCode, for instance, doesn’t support the use of window functions and hides its most interesting questions behind a paywall. In addition, running SQL queries in your browser can be extremely slow — the data sets are large and retrieval speed is often throttled for non-premium users. Locally executing a query, on the other hand, is instantaneous and allows for rapid iteration through syntax bugs and intermediate tables. I’ve found this to be a more satisfying learning experience."
},
{
"code": null,
"e": 3087,
"s": 2476,
"text": "The questions outlined below include example solutions confirmed to work in PostgreSQL. Keep in mind there is usually more than one way to obtain the correct answer to a SQL problem. My preference is to use common table expressions (CTEs) rather than nested subqueries — CTEs allow for a more linear illustration of the data wrangling sequence. Both approaches, however, can yield identical solutions. I also like to follow the convention of keeping SQL operators in all caps (SELECT, FROM, WHERE, etc.), column names in lowercase (user_id, date, etc.), and simple table aliasing (t1, t2, etc.) where possible."
},
{
"code": null,
"e": 3367,
"s": 3087,
"text": "The code snippets shown below can be run in PSequel as-is to yield the displayed result. Note one quirk of Postgres: fractions must be multiplied by 1.0 to convert from integer to float format. This is not needed in other implementations of SQL and is not expected in interviews."
},
{
"code": null,
"e": 3428,
"s": 3367,
"text": "Feel free to leave your alternative answers in the comments!"
},
{
"code": null,
"e": 3563,
"s": 3428,
"text": "From the following table of user IDs, actions, and dates, write a query to return the publication and cancellation rate for each user."
},
{
"code": null,
"e": 4550,
"s": 3563,
"text": "WITH users (user_id, action, date) AS (VALUES (1,'start', CAST('01-01-20' AS date)), (1,'cancel', CAST('01-02-20' AS date)), (2,'start', CAST('01-03-20' AS date)), (2,'publish', CAST('01-04-20' AS date)), (3,'start', CAST('01-05-20' AS date)), (3,'cancel', CAST('01-06-20' AS date)), (1,'start', CAST('01-07-20' AS date)), (1,'publish', CAST('01-08-20' AS date))),-- retrieve count of starts, cancels, and publishes for each usert1 AS (SELECT user_id, SUM(CASE WHEN action = 'start' THEN 1 ELSE 0 END) AS starts, SUM(CASE WHEN action = 'cancel' THEN 1 ELSE 0 END) AS cancels, SUM(CASE WHEN action = 'publish' THEN 1 ELSE 0 END) AS publishesFROM usersGROUP BY 1ORDER BY 1)-- calculate publication, cancelation rate for each user by dividing by number of starts, casting as float by multiplying by 1.0 (default floor division is a quirk of some SQL tools, not always needed)SELECT user_id, 1.0*publishes/starts AS publish_rate, 1.0*cancels/starts AS cancel_rateFROM t1"
},
{
"code": null,
"e": 4707,
"s": 4550,
"text": "From the following table of transactions between two users, write a query to return the change in net worth for each user, ordered by decreasing net change."
},
{
"code": null,
"e": 5609,
"s": 4707,
"text": "WITH transactions (sender, receiver, amount, transaction_date) AS (VALUES (5, 2, 10, CAST('2-12-20' AS date)),(1, 3, 15, CAST('2-13-20' AS date)), (2, 1, 20, CAST('2-13-20' AS date)), (2, 3, 25, CAST('2-14-20' AS date)), (3, 1, 20, CAST('2-15-20' AS date)), (3, 2, 15, CAST('2-15-20' AS date)), (1, 4, 5, CAST('2-16-20' AS date))),-- sum amounts for each sender (debits) and receiver (credits)debits AS (SELECT sender, SUM(amount) AS debitedFROM transactionsGROUP BY 1 ),credits AS (SELECT receiver, SUM(amount) AS creditedFROM transactionsGROUP BY 1 )-- full (outer) join debits and credits tables on user id, taking net change as difference between credits and debits, coercing nulls to zeros with coalesce()SELECT COALESCE(sender, receiver) AS user, COALESCE(credited, 0) - COALESCE(debited, 0) AS net_change FROM debits dFULL JOIN credits cON d.sender = c.receiverORDER BY 2 DESC"
},
{
"code": null,
"e": 5793,
"s": 5609,
"text": "From the following table containing a list of dates and items ordered, write a query to return the most frequent item ordered on each date. Return multiple items in the case of a tie."
},
{
"code": null,
"e": 6540,
"s": 5793,
"text": "WITH items (date, item) AS (VALUES (CAST('01-01-20' AS date),'apple'), (CAST('01-01-20' AS date),'apple'), (CAST('01-01-20' AS date),'pear'), (CAST('01-01-20' AS date),'pear'), (CAST('01-02-20' AS date),'pear'), (CAST('01-02-20' AS date),'pear'), (CAST('01-02-20' AS date),'pear'), (CAST('01-02-20' AS date),'orange')),-- add an item count column to existing table, grouping by date and item columnst1 AS (SELECT date, item, COUNT(*) AS item_countFROM itemsGROUP BY 1, 2ORDER BY 1),-- add a rank column in descending order, partitioning by datet2 AS (SELECT *, RANK() OVER (PARTITION BY date ORDER BY item_count DESC) AS date_rankFROM t1)-- return all dates and items where rank = 1SELECT date, itemFROM t2WHERE date_rank = 1"
},
{
"code": null,
"e": 6723,
"s": 6540,
"text": "From the following table of user actions, write a query to return for each user the time elapsed between the last action and the second-to-last action, in ascending order by user ID."
},
{
"code": null,
"e": 7724,
"s": 6723,
"text": "WITH users (user_id, action, action_date) AS (VALUES (1, 'start', CAST('2-12-20' AS date)), (1, 'cancel', CAST('2-13-20' AS date)), (2, 'start', CAST('2-11-20' AS date)), (2, 'publish', CAST('2-14-20' AS date)), (3, 'start', CAST('2-15-20' AS date)), (3, 'cancel', CAST('2-15-20' AS date)), (4, 'start', CAST('2-18-20' AS date)), (1, 'publish', CAST('2-19-20' AS date))),-- create a date rank column, partitioned by user ID, using the ROW_NUMBER() window function t1 AS (SELECT *, ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY action_date DESC) AS date_rankFROM users ),-- filter on date rank column to pull latest and next latest actions from this tablelatest AS (SELECT *FROM t1 WHERE date_rank = 1 ),next_latest AS (SELECT *FROM t1 WHERE date_rank = 2 )-- left join these two tables, subtracting latest from second latest to get time elapsed SELECT l1.user_id, l1.action_date - l2.action_date AS days_elapsedFROM latest l1LEFT JOIN next_latest l2ON l1.user_id = l2.user_idORDER BY 1"
},
{
"code": null,
"e": 8018,
"s": 7724,
"text": "A company defines its super users as those who have made at least two transactions. From the following table, write a query to return, for each user, the date when they become a super user, ordered by oldest super users first. Users who are not super users should also be present in the table."
},
{
"code": null,
"e": 8915,
"s": 8018,
"text": "WITH users (user_id, product_id, transaction_date) AS (VALUES (1, 101, CAST('2-12-20' AS date)), (2, 105, CAST('2-13-20' AS date)), (1, 111, CAST('2-14-20' AS date)), (3, 121, CAST('2-15-20' AS date)), (1, 101, CAST('2-16-20' AS date)), (2, 105, CAST('2-17-20' AS date)),(4, 101, CAST('2-16-20' AS date)), (3, 105, CAST('2-15-20' AS date))),-- create a transaction number column using ROW_NUMBER(), partitioning by user IDt1 AS (SELECT *, ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY transaction_date) AS transaction_numberFROM users),-- filter resulting table on transaction_number = 2t2 AS (SELECT user_id, transaction_dateFROM t1WHERE transaction_number = 2 ),-- left join super users onto full user table, order by date t3 AS (SELECT DISTINCT user_idFROM users )SELECT t3.user_id, transaction_date AS superuser_dateFROM t3LEFT JOIN t2ON t3.user_id = t2.user_idORDER BY 2"
},
{
"code": null,
"e": 9156,
"s": 8915,
"text": "Using the following two tables, write a query to return page recommendations to a social media user based on the pages that their friends have liked, but that they have not yet marked as liked. Order the result by ascending user ID. Source."
},
{
"code": null,
"e": 10016,
"s": 9156,
"text": "WITH friends (user_id, friend) AS (VALUES (1, 2), (1, 3), (1, 4), (2, 1), (3, 1), (3, 4), (4, 1), (4, 3)),likes (user_id, page_likes) AS (VALUES (1, 'A'), (1, 'B'), (1, 'C'), (2, 'A'), (3, 'B'), (3, 'C'), (4, 'B')),-- inner join friends and page likes tables on user_idt1 AS (SELECT l.user_id, l.page_likes, f.friendFROM likes lJOIN friends fON l.user_id = f.user_id ),-- left join likes on this, requiring user = friend and user likes = friend likes t2 AS (SELECT t1.user_id, t1.page_likes, t1.friend, l.page_likes AS friend_likesFROM t1LEFT JOIN likes lON t1.friend = l.user_idAND t1.page_likes = l.page_likes )-- if a friend pair doesn’t share a common page like, friend likes column will be null - pull out these entries SELECT DISTINCT friend AS user_id, page_likes AS recommended_pageFROM t2WHERE friend_likes IS NULLORDER BY 1"
},
{
"code": null,
"e": 10137,
"s": 10016,
"text": "With the following two tables, return the fraction of users who only visited mobile, only visited web, and visited both."
},
{
"code": null,
"e": 10977,
"s": 10137,
"text": "WITH mobile (user_id, page_url) AS (VALUES (1, 'A'), (2, 'B'), (3, 'C'), (4, 'A'), (9, 'B'), (2, 'C'), (10, 'B')),web (user_id, page_url) AS (VALUES (6, 'A'), (2, 'B'), (3, 'C'), (7, 'A'), (4, 'B'), (8, 'C'), (5, 'B')),-- outer join mobile and web users on user IDt1 AS (SELECT DISTINCT m.user_id AS mobile_user, w.user_id AS web_userFROM mobile mFULL JOIN web wON m.user_id = w.user_id)-- calculate fraction of mobile-only, web-only, and both as average of values (ones and zeros) specified in case statement conditionSELECT AVG(CASE WHEN mobile_user IS NOT NULL AND web_user IS NULL THEN 1 ELSE 0 END) AS mobile_fraction, AVG(CASE WHEN web_user IS NOT NULL AND mobile_user IS NULL THEN 1 ELSE 0 END) AS web_fraction, AVG(CASE WHEN web_user IS NOT NULL AND mobile_user IS NOT NULL THEN 1 ELSE 0 END) AS both_fractionFROM t1"
},
{
"code": null,
"e": 11186,
"s": 10977,
"text": "Given the following two tables, return the fraction of users, rounded to two decimal places, who accessed feature two (type: F2 in events table) and upgraded to premium within the first 30 days of signing up."
},
{
"code": null,
"e": 12762,
"s": 11186,
"text": "WITH users (user_id, name, join_date) AS (VALUES (1, 'Jon', CAST('2-14-20' AS date)), (2, 'Jane', CAST('2-14-20' AS date)), (3, 'Jill', CAST('2-15-20' AS date)), (4, 'Josh', CAST('2-15-20' AS date)), (5, 'Jean', CAST('2-16-20' AS date)), (6, 'Justin', CAST('2-17-20' AS date)),(7, 'Jeremy', CAST('2-18-20' AS date))),events (user_id, type, access_date) AS (VALUES (1, 'F1', CAST('3-1-20' AS date)), (2, 'F2', CAST('3-2-20' AS date)), (2, 'P', CAST('3-12-20' AS date)),(3, 'F2', CAST('3-15-20' AS date)), (4, 'F2', CAST('3-15-20' AS date)), (1, 'P', CAST('3-16-20' AS date)), (3, 'P', CAST('3-22-20' AS date))),-- get feature 2 users and their date of feature 2 accesst1 AS (SELECT user_id, type, access_date AS f2_dateFROM eventsWHERE type = 'F2' ),-- get premium users and their date of premium upgradet2 AS (SELECT user_id, type, access_date AS premium_dateFROM eventsWHERE type = 'P' ),-- for each feature 2 user, get time between joining and premium upgrade (or null if no upgrade) by inner joining full users table with feature 2 users on user ID and left joining premium users on user ID, then subtracting premium upgrade date from join datet3 AS (SELECT t2.premium_date - u.join_date AS upgrade_timeFROM users uJOIN t1ON u.user_id = t1.user_idLEFT JOIN t2ON u.user_id = t2.user_id )-- calculate fraction of users with upgrade time less than 30 days as average of values (ones and zeros) specified in case statement condition, rounding to two decimal places SELECT ROUND(AVG(CASE WHEN upgrade_time < 30 THEN 1 ELSE 0 END), 2) AS upgrade_rateFROM t3"
},
{
"code": null,
"e": 13058,
"s": 12762,
"text": "Given the following table, return a list of users and their corresponding friend count. Order the result by descending friend count, and in the case of a tie, by ascending user ID. Assume that only unique friendships are displayed (i.e., [1, 2] will not show up again as [2, 1] ). From LeetCode."
},
{
"code": null,
"e": 13449,
"s": 13058,
"text": "WITH friends (user1, user2) AS (VALUES (1, 2), (1, 3), (1, 4), (2, 3)),-- compile all user appearances into one column, preserving duplicate entries with UNION ALL t1 AS (SELECT user1 AS user_idFROM friendsUNION ALLSELECT user2 AS user_idFROM friends)-- grouping by user ID, count up all appearances of that userSELECT user_id, COUNT(*) AS friend_countFROM t1GROUP BY 1ORDER BY 2 DESC"
},
{
"code": null,
"e": 13704,
"s": 13449,
"text": "The projects table contains three columns: task_id, start_date, and end_date. The difference between end_date and start_date is 1 day for each row in the table. If task end dates are consecutive they are part of the same project. Projects do not overlap."
},
{
"code": null,
"e": 13914,
"s": 13704,
"text": "Write a query to return the start and end dates of each project, and the number of days it took to complete. Order by ascending project duration, and ascending start date in the case of a tie. From HackerRank."
},
{
"code": null,
"e": 15083,
"s": 13914,
"text": "WITH projects (task_id, start_date, end_date) AS (VALUES (1, CAST('10-01-20' AS date), CAST('10-02-20' AS date)), (2, CAST('10-02-20' AS date), CAST('10-03-20' AS date)), (3, CAST('10-03-20' AS date), CAST('10-04-20' AS date)), (4, CAST('10-13-20' AS date), CAST('10-14-20' AS date)), (5, CAST('10-14-20' AS date), CAST('10-15-20' AS date)), (6, CAST('10-28-20' AS date), CAST('10-29-20' AS date)), (7, CAST('10-30-20' AS date), CAST('10-31-20' AS date))),-- get start dates not present in end date column (these are “true” project start dates) t1 AS (SELECT start_dateFROM projectsWHERE start_date NOT IN (SELECT end_date FROM projects) ),-- get end dates not present in start date column (these are “true” project end dates) t2 AS (SELECT end_dateFROM projectsWHERE end_date NOT IN (SELECT start_date FROM projects) ),-- filter to plausible start-end pairs (start < end), then find correct end date for each start date (the minimum end date, since there are no overlapping projects)t3 AS (SELECT start_date, MIN(end_date) AS end_dateFROM t1, t2WHERE start_date < end_dateGROUP BY 1 )SELECT *, end_date - start_date AS project_durationFROM t3ORDER BY 3, 1"
},
{
"code": null,
"e": 15260,
"s": 15083,
"text": "Given the following two tables, write a query to return the fraction of students, rounded to two decimal places, who attended school (attendance = 1) on their birthday. Source."
},
{
"code": null,
"e": 16330,
"s": 15260,
"text": "WITH attendance (student_id, school_date, attendance)AS (VALUES(1, CAST('2020-04-03' AS date), 0),(2, CAST('2020-04-03' AS date), 1),(3, CAST('2020-04-03' AS date), 1), (1, CAST('2020-04-04' AS date), 1), (2, CAST('2020-04-04' AS date), 1), (3, CAST('2020-04-04' AS date), 1), (1, CAST('2020-04-05' AS date), 0), (2, CAST('2020-04-05' AS date), 1), (3, CAST('2020-04-05' AS date), 1), (4, CAST('2020-04-05' AS date), 1)),students (student_id, school_id, grade_level, date_of_birth)AS (VALUES(1, 2, 5, CAST('2012-04-03' AS date)),(2, 1, 4, CAST('2013-04-04' AS date)),(3, 1, 3, CAST('2014-04-05' AS date)), (4, 2, 4, CAST('2013-04-03' AS date)))-- join attendance and students table on student ID, and day and month of school day = day and month of birthday, taking average of attendance column values and roundingSELECT ROUND(AVG(attendance), 2) AS birthday_attendanceFROM attendance aJOIN students sON a.student_id = s.student_id AND EXTRACT(MONTH FROM school_date) = EXTRACT(MONTH FROM date_of_birth)AND EXTRACT(DAY FROM school_date) = EXTRACT(DAY FROM date_of_birth)"
},
{
"code": null,
"e": 16636,
"s": 16330,
"text": "Given the following two tables, write a query to return the hacker ID, name, and total score (the sum of maximum scores for each challenge completed) ordered by descending score, and by ascending hacker ID in the case of score tie. Do not display entries for hackers with a score of zero. From HackerRank."
},
{
"code": null,
"e": 17456,
"s": 16636,
"text": "WITH hackers (hacker_id, name)AS (VALUES(1, 'John'),(2, 'Jane'),(3, 'Joe'),(4, 'Jim')),submissions (submission_id, hacker_id, challenge_id, score)AS (VALUES(101, 1, 1, 10),(102, 1, 1, 12),(103, 2, 1, 11),(104, 2, 1, 9),(105, 2, 2, 13),(106, 3, 1, 9),(107, 3, 2, 12),(108, 3, 2, 15),(109, 4, 1, 0)),-- from submissions table, get maximum score for each hacker-challenge pairt1 AS (SELECT hacker_id, challenge_id, MAX(score) AS max_scoreFROM submissions GROUP BY 1, 2 )-- inner join this with the hackers table, sum up all maximum scores, filter to exclude hackers with total score of zero, and order result by total score and hacker IDSELECT t1.hacker_id, h.name, SUM(t1.max_score) AS total_scoreFROM t1JOIN hackers hON t1.hacker_id = h.hacker_idGROUP BY 1, 2HAVING SUM(max_score) > 0ORDER BY 3 DESC, 1"
},
{
"code": null,
"e": 17704,
"s": 17456,
"text": "Write a query to rank scores in the following table without using a window function. If there is a tie between two scores, both should have the same rank. After a tie, the following rank should be the next consecutive integer value. From LeetCode."
},
{
"code": null,
"e": 18211,
"s": 17704,
"text": "WITH scores (id, score)AS (VALUES(1, 3.50),(2, 3.65),(3, 4.00),(4, 3.85),(5, 4.00),(6, 3.65))-- self-join on inequality produces a table with one score and all scores as large as this joined to it, grouping by first id and score, and counting up all unique values of joined scores yields the equivalent of DENSE_RANK() [check join output to understand]SELECT s1.score, COUNT(DISTINCT s2.score) AS score_rankFROM scores s1 JOIN scores s2ON s1.score <= s2.scoreGROUP BY s1.id, s1.scoreORDER BY 1 DESC"
},
{
"code": null,
"e": 18508,
"s": 18211,
"text": "The following table holds monthly salary information for several employees. Write a query to get, for each month, the cumulative sum of an employee’s salary over a period of 3 months, excluding the most recent month. The result should be ordered by ascending employee ID and month. From LeetCode."
},
{
"code": null,
"e": 19145,
"s": 18508,
"text": "WITH employee (id, pay_month, salary)AS (VALUES(1, 1, 20),(2, 1, 20),(1, 2, 30),(2, 2, 30),(3, 2, 40),(1, 3, 40),(3, 3, 60),(1, 4, 60),(3, 4, 70)),-- add column for descending month rank (latest month = 1) for each employeet1 AS (SELECT *, RANK() OVER (PARTITION BY id ORDER BY pay_month DESC) AS month_rankFROM employee )-- filter to exclude latest month and months 5+, create cumulative salary sum using SUM() as window function, order by ID and monthSELECT id, pay_month, salary, SUM(salary) OVER (PARTITION BY id ORDER BY month_rank DESC) AS cumulative_sumFROM t1 WHERE month_rank != 1AND month_rank <= 4ORDER BY 1, 2"
},
{
"code": null,
"e": 19502,
"s": 19145,
"text": "Write a query to return the scores of each team in the teams table after all matches displayed in the matches table. Points are awarded as follows: zero points for a loss, one point for a tie, and three points for a win. The result should include team name and points, and be ordered by decreasing points. In case of a tie, order by alphabetized team name."
},
{
"code": null,
"e": 20519,
"s": 19502,
"text": "WITH teams (team_id, team_name)AS (VALUES(1, 'New York'),(2, 'Atlanta'),(3, 'Chicago'),(4, 'Toronto'),(5, 'Los Angeles'),(6, 'Seattle')),matches (match_id, host_team, guest_team, host_goals, guest_goals)AS (VALUES(1, 1, 2, 3, 0),(2, 2, 3, 2, 4),(3, 3, 4, 4, 3),(4, 4, 5, 1, 1),(5, 5, 6, 2, 1),(6, 6, 1, 1, 2)),-- add host points and guest points columns to matches table, using case-when-then to tally up points for wins, ties, and lossest1 AS (SELECT *, CASE WHEN host_goals > guest_goals THEN 3 WHEN host_goals = guest_goals THEN 1 ELSE 0 END AS host_points, CASE WHEN host_goals < guest_goals THEN 3 WHEN host_goals = guest_goals THEN 1 ELSE 0 END AS guest_pointsFROM matches )-- join result onto teams table twice to add up for each team the points earned as host team and guest team, then order as requestedSELECT t.team_name, a.host_points + b.guest_points AS total_pointsFROM teams tJOIN t1 aON t.team_id = a.host_teamJOIN t1 bON t.team_id = b.guest_teamORDER BY 2 DESC, 1"
},
{
"code": null,
"e": 20688,
"s": 20519,
"text": "From the following table, write a query to display the ID and name of customers who bought products A and B, but didn’t buy product C, ordered by ascending customer ID."
},
{
"code": null,
"e": 21599,
"s": 20688,
"text": "WITH customers (id, name)AS (VALUES(1, 'Daniel'),(2, 'Diana'),(3, 'Elizabeth'),(4, 'John')),orders (order_id, customer_id, product_name)AS (VALUES(1, 1, 'A'),(2, 1, 'B'),(3, 2, 'A'),(4, 2, 'B'),(5, 2, 'C'),(6, 3, 'A'), (7, 3, 'A'),(8, 3, 'B'),(9, 3, 'D'))-- join customers and orders tables on customer ID, filtering to those who bought both products A and B, removing those who bought product C, returning ID and name columns ordered by ascending IDSELECT DISTINCT id, nameFROM orders oJOIN customers cON o.customer_id = c.idWHERE customer_id IN (SELECT customer_id FROM orders WHERE product_name = 'A') AND customer_id IN (SELECT customer_id FROM orders WHERE product_name = 'B') AND customer_id NOT IN (SELECT customer_id FROM orders WHERE product_name = 'C')ORDER BY 1"
},
{
"code": null,
"e": 21811,
"s": 21599,
"text": "Write a query to return the median latitude of weather stations from each state in the following table, rounding to the nearest tenth of a degree. Note that there is no MEDIAN() function in SQL! From HackerRank."
},
{
"code": null,
"e": 22869,
"s": 21811,
"text": "WITH stations (id, city, state, latitude, longitude)AS (VALUES(1, 'Asheville', 'North Carolina', 35.6, 82.6),(2, 'Burlington', 'North Carolina', 36.1, 79.4),(3, 'Chapel Hill', 'North Carolina', 35.9, 79.1),(4, 'Davidson', 'North Carolina', 35.5, 80.8),(5, 'Elizabeth City', 'North Carolina', 36.3, 76.3),(6, 'Fargo', 'North Dakota', 46.9, 96.8),(7, 'Grand Forks', 'North Dakota', 47.9, 97.0),(8, 'Hettinger', 'North Dakota', 46.0, 102.6),(9, 'Inkster', 'North Dakota', 48.2, 97.6)),-- assign latitude-ordered row numbers for each state, and get total row count for each statet1 AS (SELECT *, ROW_NUMBER() OVER (PARTITION BY state ORDER BY latitude ASC) AS row_number_state, count(*) OVER (PARTITION BY state) AS row_countFROM stations )-- filter to middle row (for odd total row number) or middle two rows (for even total row number), then get average value of those, grouping by stateSELECT state, AVG(latitude) AS median_latitudeFROM t1WHERE row_number_state >= 1.0*row_count/2 AND row_number_state <= 1.0*row_count/2 + 1GROUP BY 1"
},
{
"code": null,
"e": 23099,
"s": 22869,
"text": "From the same table in question 17, write a query to return the furthest-separated pair of cities for each state, and the corresponding distance (in degrees, rounded to 2 decimal places) between those two cities. From HackerRank."
},
{
"code": null,
"e": 24464,
"s": 23099,
"text": "WITH stations (id, city, state, latitude, longitude)AS (VALUES(1, 'Asheville', 'North Carolina', 35.6, 82.6),(2, 'Burlington', 'North Carolina', 36.1, 79.4),(3, 'Chapel Hill', 'North Carolina', 35.9, 79.1),(4, 'Davidson', 'North Carolina', 35.5, 80.8),(5, 'Elizabeth City', 'North Carolina', 36.3, 76.3),(6, 'Fargo', 'North Dakota', 46.9, 96.8),(7, 'Grand Forks', 'North Dakota', 47.9, 97.0),(8, 'Hettinger', 'North Dakota', 46.0, 102.6),(9, 'Inkster', 'North Dakota', 48.2, 97.6)),-- self-join on matching states and city < city (avoids identical and double-counted city pairs), pulling state, city pair, and latitude/longitude coordinates for each cityt1 AS (SELECT s1.state, s1.city AS city1, s2.city AS city2, s1.latitude AS city1_lat, s1.longitude AS city1_long, s2.latitude AS city2_lat, s2.longitude AS city2_longFROM stations s1JOIN stations s2ON s1.state = s2.state AND s1.city < s2.city ),-- add a column displaying rounded Euclidean distance t2 AS (SELECT *, ROUND(( (city1_lat - city2_lat)^2 + (city1_long - city2_long)^2 ) ^ 0.5, 2) AS distanceFROM t1 ),-- rank each city pair by descending distance for each statet3 AS (SELECT *, RANK() OVER (PARTITION BY state ORDER BY distance DESC) AS dist_rankFROM t2 )-- return the city pair with maximium separationSELECT state, city1, city2, distanceFROM t3WHERE dist_rank = 1"
},
{
"code": null,
"e": 24693,
"s": 24464,
"text": "Write a query to return the average cycle time across each month. Cycle time is the time elapsed between one user joining and their invitees joining. Users who joined without an invitation have a zero in the “invited by” column."
},
{
"code": null,
"e": 25509,
"s": 24693,
"text": "WITH users (user_id, join_date, invited_by) AS (VALUES (1, CAST('01-01-20' AS date), 0), (2, CAST('01-10-20' AS date), 1), (3, CAST('02-05-20' AS date), 2), (4, CAST('02-12-20' AS date), 3), (5, CAST('02-25-20' AS date), 2), (6, CAST('03-01-20' AS date), 0), (7, CAST('03-01-20' AS date), 4),(8, CAST('03-04-20' AS date), 7)),-- self-join on invited by = user ID, extract join month from inviter join date, and calculate cycle time as difference between join dates of inviter and inviteet1 AS (SELECT CAST(EXTRACT(MONTH FROM u2.join_date) AS int) AS month, u1.join_date - u2.join_date AS cycle_timeFROM users u1JOIN users u2ON u1.invited_by = u2.user_id )-- group by join month, take average of cycle times within each monthSELECT month, AVG(cycle_time) AS cycle_time_month_avgFROM t1GROUP BY 1ORDER BY 1"
},
{
"code": null,
"e": 25814,
"s": 25509,
"text": "The attendance table logs the number of people counted in a crowd each day an event is held. Write a query to return a table showing the date and visitor count of high-attendance periods, defined as three consecutive entries (not necessarily consecutive dates) with more than 100 visitors. From LeetCode."
},
{
"code": null,
"e": 26852,
"s": 25814,
"text": "WITH attendance (event_date, visitors) AS (VALUES (CAST('01-01-20' AS date), 10), (CAST('01-04-20' AS date), 109), (CAST('01-05-20' AS date), 150), (CAST('01-06-20' AS date), 99), (CAST('01-07-20' AS date), 145), (CAST('01-08-20' AS date), 1455), (CAST('01-11-20' AS date), 199),(CAST('01-12-20' AS date), 188)),-- add row numbers to identify consecutive entries, since date column has some gapst1 AS (SELECT *, ROW_NUMBER() OVER (ORDER BY event_date) AS day_numFROM attendance ),-- filter this to exclude days with > 100 visitorst2 AS (SELECT *FROM t1WHERE visitors > 100 ),-- self-join (inner) twice on offset = 1 day and offset = 2 dayst3 AS (SELECT a.day_num AS day1, b.day_num AS day2, c.day_num AS day3FROM t2 aJOIN t2 bON a.day_num = b.day_num - 1JOIN t2 cON a.day_num = c.day_num - 2 )-- pull date and visitor count for consecutive days surfaced in previous tableSELECT event_date, visitorsFROM t1WHERE day_num IN (SELECT day1 FROM t3) OR day_num IN (SELECT day2 FROM t3) OR day_num IN (SELECT day3 FROM t3)"
},
{
"code": null,
"e": 27068,
"s": 26852,
"text": "Using the following two tables, write a query to return the names and purchase frequency of the top three pairs of products most often bought together. The names of both products should appear in one column. Source."
},
{
"code": null,
"e": 27997,
"s": 27068,
"text": "WITH orders (order_id, customer_id, product_id) AS (VALUES (1, 1, 1),(1, 1, 2),(1, 1, 3),(2, 2, 1),(2, 2, 2),(2, 2, 4),(3, 1, 5)),products (id, name) AS (VALUES (1, 'A'),(2, 'B'),(3, 'C'),(4, 'D'),(5, 'E')),-- get unique product pairs from same order by self-joining orders table on order ID and product ID < product ID (avoids identical and double-counted product pairs)t1 AS (SELECT o1.product_id AS prod_1, o2.product_id AS prod_2FROM orders o1JOIN orders o2ON o1.order_id = o2.order_idAND o1.product_id < o2.product_id ),-- join products table onto this to get product names, concatenate to get product pairs in one columnt2 AS (SELECT CONCAT(p1.name, ' ', p2.name) AS product_pairFROM t1JOIN products p1ON t1.prod_1 = p1.idJOIN products p2ON t1.prod_2 = p2.id )-- grouping by product pair, return top 3 entries sorted by purchase frequencySELECT *, COUNT(*) AS purchase_freqFROM t2GROUP BY 1ORDER BY 2 DESC LIMIT 3"
},
{
"code": null,
"e": 28204,
"s": 27997,
"text": "From the following table summarizing the results of a study, calculate the average treatment effect as well as upper and lower bounds of the 95% confidence interval. Round these numbers to 3 decimal places."
},
{
"code": null,
"e": 29351,
"s": 28204,
"text": "WITH study (participant_id, assignment, outcome) AS (VALUES (1, 0, 0),(2, 1, 1),(3, 0, 1),(4, 1, 0),(5, 0, 1),(6, 1, 1),(7, 0, 0),(8, 1, 1),(9, 1, 1)),-- get average outcomes, standard deviations, and group sizes for control and treatment groupscontrol AS (SELECT AVG(outcome) AS avg_outcome, STDDEV(outcome) AS std_dev, COUNT(*) AS group_sizeFROM studyWHERE assignment = 0 ),treatment AS (SELECT AVG(outcome) AS avg_outcome, STDDEV(outcome) AS std_dev, COUNT(*) AS group_sizeFROM studyWHERE assignment = 1 ),-- get average treatment effect sizeeffect_size AS (SELECT t.avg_outcome - c.avg_outcome AS effect_sizeFROM control c, treatment t ),-- construct 95% confidence interval using z* = 1.96 and magnitude of individual standard errors [ std dev / sqrt(sample size) ]conf_interval AS (SELECT 1.96 * (t.std_dev^2 / t.group_size + c.std_dev^2 / c.group_size)^0.5 AS conf_intFROM treatment t, control c )SELECT round(es.effect_size, 3) AS point_estimate, round(es.effect_size - ci.conf_int, 3) AS lower_bound, round(es.effect_size + ci.conf_int, 3) AS upper_boundFROM effect_size es, conf_interval ci"
},
{
"code": null,
"e": 29670,
"s": 29351,
"text": "The following table shows the monthly salary for an employee for the first nine months in a given year. From this, write a query to return a table that displays, for each month in the first half of the year, the rolling sum of the employee’s salary for that month and the following two months, ordered chronologically."
},
{
"code": null,
"e": 30110,
"s": 29670,
"text": "WITH salaries (month, salary) AS (VALUES (1, 2000),(2, 3000),(3, 5000),(4, 4000),(5, 2000),(6, 1000),(7, 2000),(8, 4000),(9, 5000))-- self-join to match month n with months n, n+1, and n+2, then sum salary across those months, filter to first half of year, and sortSELECT s1.month, SUM(s2.salary) AS salary_3mosFROM salaries s1JOIN salaries s2ON s1.month <= s2.month AND s1.month > s2.month - 3GROUP BY 1HAVING s1.month < 7ORDER BY 1"
},
{
"code": null,
"e": 30344,
"s": 30110,
"text": "From the given trips and users tables for a taxi service, write a query to return the cancellation rate in the first two days in October, rounded to two decimal places, for trips not involving banned riders or drivers. From LeetCode."
},
{
"code": null,
"e": 31540,
"s": 30344,
"text": "WITH trips (trip_id, rider_id, driver_id, status, request_date)AS (VALUES(1, 1, 10, 'completed', CAST('2020-10-01' AS date)),(2, 2, 11, 'cancelled_by_driver', CAST('2020-10-01' AS date)),(3, 3, 12, 'completed', CAST('2020-10-01' AS date)),(4, 4, 10, 'cancelled_by_rider', CAST('2020-10-02' AS date)),(5, 1, 11, 'completed', CAST('2020-10-02' AS date)),(6, 2, 12, 'completed', CAST('2020-10-02' AS date)),(7, 3, 11, 'completed', CAST('2020-10-03' AS date))),users (user_id, banned, type)AS (VALUES(1, 'no', 'rider'),(2, 'yes', 'rider'),(3, 'no', 'rider'),(4, 'no', 'rider'),(10, 'no', 'driver'),(11, 'no', 'driver'),(12, 'no', 'driver'))-- filter trips table to exclude banned riders and drivers, then calculate cancellation rate as 1 - fraction of trips completed, filtering to first two days of the monthSELECT request_date, 1 - AVG(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) AS cancel_rateFROM tripsWHERE rider_id NOT IN (SELECT user_id FROM users WHERE banned = 'yes' )AND driver_id NOT IN (SELECT user_id FROM users WHERE banned = 'yes' )GROUP BY 1HAVING EXTRACT(DAY FROM request_date) <= 2"
},
{
"code": null,
"e": 31772,
"s": 31540,
"text": "From the following user activity table, write a query to return the fraction of users who are retained (show some activity) a given number of days after joining. By convention, users are considered active on their join day (day 0)."
},
{
"code": null,
"e": 33312,
"s": 31772,
"text": "WITH users (user_id, action_date, action) AS (VALUES (1, CAST('01-01-20' AS date), 'Join'), (1, CAST('01-02-20' AS date), 'Access'), (2, CAST('01-02-20' AS date), 'Join'), (3, CAST('01-02-20' AS date), 'Join'), (1, CAST('01-03-20' AS date), 'Access'), (3, CAST('01-03-20' AS date), 'Access'),(1, CAST('01-04-20' AS date), 'Access')),-- get join dates for each userjoin_dates AS (SELECT user_id, action_date AS join_dateFROM usersWHERE action = 'Join' ),-- create vector containing all dates in date rangedate_vector AS (SELECT CAST(GENERATE_SERIES(MIN(action_date), MAX(action_date), '1 day'::interval) AS date) AS datesFROM users ),-- cross join to get all possible user-date combinationsall_users_dates AS (SELECT DISTINCT user_id, d.datesFROM usersCROSS JOIN date_vector d ),-- left join users table onto all user-date combinations on matching user ID and date (null on days where user didn't engage), join onto this each user's signup date, exclude user-date combinations falling before user signupt1 AS (SELECT a.dates - c.join_date AS day_no, b.user_idFROM all_users_dates aLEFT JOIN users bON a.user_id = b.user_idAND a.dates = b.action_dateJOIN join_dates cON a.user_id = c.user_id WHERE a.dates - c.join_date >= 0 )-- grouping by days since signup, count (non-null) user IDs as active users, total users, and the quotient as retention rateSELECT day_no, COUNT(*) AS n_total, COUNT(DISTINCT user_id) AS n_active, ROUND(1.0*COUNT(DISTINCT user_id)/COUNT(*), 2) AS retentionFROM t1GROUP BY 1"
},
{
"code": null,
"e": 33458,
"s": 33312,
"text": "A note on one common problem: if you see a syntax error when using CTEs, check that you have commas between CTEs and no comma after the last CTE."
},
{
"code": null,
"e": 33651,
"s": 33458,
"text": "WITH input_table (column_1, column_2) AS (VALUES (1, 'A'), (2, 'B')), -- comma between CTEst1 AS (SELECT *FROM input_tableWHERE column_2 = 'A') -- no comma after last CTESELECT *FROM t1"
}
]
|
Where is MySQL bin directory located in Windows OS? | Let’s say we installed MySQL version is 8.0 on our Windows OS. The bin directory is present at the following location −
C:\Program Files\MySQL\MySQL Server 8.0\bin
Let us check the location. The screenshot is as follows −
These are the drives −
Go to C: drive and click Program Files −
Now, click “MySQL” and open the folder −
After that, click the current MySQL version folder. For us, it is MySQL Server 8.0 −
Inside the folder, you can easily locate the bin folder as shown in the following screenshot − | [
{
"code": null,
"e": 1182,
"s": 1062,
"text": "Let’s say we installed MySQL version is 8.0 on our Windows OS. The bin directory is present at the following location −"
},
{
"code": null,
"e": 1226,
"s": 1182,
"text": "C:\\Program Files\\MySQL\\MySQL Server 8.0\\bin"
},
{
"code": null,
"e": 1284,
"s": 1226,
"text": "Let us check the location. The screenshot is as follows −"
},
{
"code": null,
"e": 1307,
"s": 1284,
"text": "These are the drives −"
},
{
"code": null,
"e": 1348,
"s": 1307,
"text": "Go to C: drive and click Program Files −"
},
{
"code": null,
"e": 1389,
"s": 1348,
"text": "Now, click “MySQL” and open the folder −"
},
{
"code": null,
"e": 1474,
"s": 1389,
"text": "After that, click the current MySQL version folder. For us, it is MySQL Server 8.0 −"
},
{
"code": null,
"e": 1569,
"s": 1474,
"text": "Inside the folder, you can easily locate the bin folder as shown in the following screenshot −"
}
]
|
How to create a custom navigation drawer in Android? | This example demonstrate about How to resize Image in Android App.
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" ?>
<android.support.v4.widget.DrawerLayout
xmlns: android = "http://schemas.android.com/apk/res/android"
xmlns: app = "http://schemas.android.com/apk/res-auto"
xmlns: tools = "http://schemas.android.com/tools"
android :id= "@+id/drawer_layout"
android :layout_width= "match_parent"
android :layout_height= "match_parent"
android :fitsSystemWindows= "true"
tools :openDrawer= "start" >
<include
layout= "@layout/app_bar_main"
android :layout_width= "match_parent"
android :layout_height= "match_parent" />
<android.support.design.widget.NavigationView
android :id= "@+id/nav_view"
android :layout_width= "wrap_content"
android :layout_height= "match_parent"
android :layout_gravity= "start"
android :fitsSystemWindows= "true"
app :headerLayout= "@layout/nav_header_main"
app :menu= "@menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>
Step 3 − Add the following code to res/layout/nav_header_main.xml.
<? xml version= "1.0" encoding= "utf-8" ?>
<LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android"
xmlns: app = "http://schemas.android.com/apk/res-auto"
android :layout_width= "match_parent"
android :layout_height= "@dimen/nav_header_height"
android :background= "@drawable/side_nav_bar"
android :gravity= "bottom"
android :orientation= "vertical"
android :paddingLeft= "@dimen/activity_horizontal_margin"
android :paddingTop= "@dimen/activity_vertical_margin"
android :paddingRight= "@dimen/activity_horizontal_margin"
android :paddingBottom= "@dimen/activity_vertical_margin"
android :theme= "@style/ThemeOverlay.AppCompat.Dark" >
<ImageView
android :id= "@+id/imageView"
android :layout_width= "wrap_content"
android :layout_height= "wrap_content"
android :contentDescription= "@string/nav_header_desc"
android :paddingTop= "@dimen/nav_header_vertical_spacing"
app :srcCompat= "@mipmap/ic_launcher_round" />
<TextView
android :layout_width= "match_parent"
android :layout_height= "wrap_content"
android :paddingTop= "@dimen/nav_header_vertical_spacing"
android :text= "@string/nav_header_title"
android :textAppearance= "@style/TextAppearance.AppCompat.Body1" />
<TextView
android :id= "@+id/textView"
android :layout_width= "wrap_content"
android :layout_height= "wrap_content"
android :text= "@string/nav_header_subtitle" />
</LinearLayout>
Step 4 − Add the following code to res/layout/app_bar_main.xml.
<? xml version= "1.0" encoding= "utf-8" ?>
<android.support.design.widget.CoordinatorLayout
xmlns: android = "http://schemas.android.com/apk/res/android"
xmlns: app = "http://schemas.android.com/apk/res-auto"
xmlns: tools = "http://schemas.android.com/tools"
android :layout_width= "match_parent"
android :layout_height= "match_parent"
tools :context= ".MainActivity" >
<android.support.design.widget.AppBarLayout
android :layout_width= "match_parent"
android :layout_height= "wrap_content"
android :theme= "@style/AppTheme.AppBarOverlay" >
<android.support.v7.widget.Toolbar
android :id= "@+id/toolbar"
android :layout_width= "match_parent"
android :layout_height= "?attr/actionBarSize"
android :background= "?attr/colorPrimary"
app :popupTheme= "@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout= "@layout/content_main" />
<android.support.design.widget.FloatingActionButton
android :id= "@+id/fab"
android :layout_width= "wrap_content"
android :layout_height= "wrap_content"
android :layout_gravity= "bottom|end"
android :layout_margin= "@dimen/fab_margin"
app :srcCompat= "@android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
Step 5 − Add the following code to res/layout/content_main.xml.
<? xml version= "1.0" encoding= "utf-8" ?>
<android.support.constraint.ConstraintLayout
xmlns: android = "http://schemas.android.com/apk/res/android"
xmlns: app = "http://schemas.android.com/apk/res-auto"
xmlns: tools = "http://schemas.android.com/tools"
android :layout_width= "match_parent"
android :layout_height= "match_parent"
app :layout_behavior= "@string/appbar_scrolling_view_behavior"
tools :context= ".MainActivity"
tools :showIn= "@layout/app_bar_main" >
</android.support.constraint.ConstraintLayout>
Step 6 − Add the following code to res/menu/activity_main_drawer.xml.
<? xml version= "1.0" encoding= "utf-8" ?>
<menu xmlns: android = "http://schemas.android.com/apk/res/android"
xmlns: tools = "http://schemas.android.com/tools"
tools :showIn= "navigation_view" >
<group android :checkableBehavior= "single" >
<item
android :id= "@+id/nav_camera"
android :icon= "@drawable/ic_menu_camera"
android :title= "Import" />
<item
android :id= "@+id/nav_gallery"
android :icon= "@drawable/ic_menu_gallery"
android :title= "Gallery" />
<item
android :id= "@+id/nav_slideshow"
android :icon= "@drawable/ic_menu_slideshow"
android :title= "Slideshow" />
<item
android :id= "@+id/nav_manage"
android :icon= "@drawable/ic_menu_manage"
android :title= "Tools" />
</group>
<item android :title= "Communicate" >
<menu>
<item
android :id= "@+id/nav_share"
android :icon= "@drawable/ic_menu_share"
android :title= "Share" />
<item
android :id= "@+id/nav_send"
android :icon= "@drawable/ic_menu_send"
android :title= "Send" />
</menu>
</item>
</menu>
Step 7 − Add the following code to src/MainActivity.java
package app.tutorialspoint.com.sample ;
import android.os.Bundle ;
import android.support.annotation. NonNull ;
import android.support.design.widget.FloatingActionButton ;
import android.support.design.widget.Snackbar ;
import android.view.View ;
import android.support.design.widget.NavigationView ;
import android.support.v4.view.GravityCompat ;
import android.support.v4.widget.DrawerLayout ;
import android.support.v7.app.ActionBarDrawerToggle ;
import android.support.v7.app.AppCompatActivity ;
import android.support.v7.widget.Toolbar ;
import android.view.Menu ;
import android.view.MenuItem ;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
@Override
protected void onCreate (Bundle savedInstanceState) {
super .onCreate(savedInstanceState) ;
setContentView(R.layout. activity_main ) ;
Toolbar toolbar = findViewById(R.id. toolbar ) ;
setSupportActionBar(toolbar) ;
FloatingActionButton fab = findViewById(R.id. fab ) ;
fab.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick (View view) {
Snackbar. make (view , "Replace with your own action" ,
Snackbar. LENGTH_LONG )
.setAction( "Action" , null ).show() ;
}
}) ;
DrawerLayout drawer = findViewById(R.id. drawer_layout ) ;
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer , toolbar , R.string. navigation_drawer_open ,
R.string. navigation_drawer_close ) ;
drawer.addDrawerListener(toggle) ;
toggle.syncState() ;
NavigationView navigationView = findViewById(R.id. nav_view ) ;
navigationView.setNavigationItemSelectedListener( this ) ;
}
@Override
public void onBackPressed () {
DrawerLayout drawer = findViewById(R.id. drawer_layout ) ;
if (drawer.isDrawerOpen(GravityCompat. START )) {
drawer.closeDrawer(GravityCompat. START ) ;
} else {
super .onBackPressed() ;
}
}
@Override
public boolean onCreateOptionsMenu (Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu. main , menu) ;
return true;
}
@Override
public boolean onOptionsItemSelected (MenuItem item) {
int id = item.getItemId() ;
if (id == R.id. action_settings ) {
return true;
}
return super .onOptionsItemSelected(item) ;
}
@SuppressWarnings ( "StatementWithEmptyBody" )
@Override
public boolean onNavigationItemSelected ( @NonNull MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId() ;
if (id == R.id. nav_camera ) {
// Handle the camera action
} else if (id == R.id. nav_gallery ) {
} else if (id == R.id. nav_slideshow ) {
} else if (id == R.id. nav_manage ) {
} else if (id == R.id. nav_share ) {
} else if (id == R.id. nav_send ) {
}
DrawerLayout drawer = findViewById(R.id. drawer_layout ) ;
drawer.closeDrawer(GravityCompat. START ) ;
return true;
}
}
Step 8 − 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.sample" >
<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"
android :theme= "@style/AppTheme.NoActionBar" >
<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 – | [
{
"code": null,
"e": 1129,
"s": 1062,
"text": "This example demonstrate about How to resize Image in Android App."
},
{
"code": null,
"e": 1258,
"s": 1129,
"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": 1323,
"s": 1258,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2308,
"s": 1323,
"text": "<? xml version= \"1.0\" encoding= \"utf-8\" ?>\n<android.support.v4.widget.DrawerLayout\n xmlns: android = \"http://schemas.android.com/apk/res/android\"\n xmlns: app = \"http://schemas.android.com/apk/res-auto\"\n xmlns: tools = \"http://schemas.android.com/tools\"\n android :id= \"@+id/drawer_layout\"\n android :layout_width= \"match_parent\"\n android :layout_height= \"match_parent\"\n android :fitsSystemWindows= \"true\"\n tools :openDrawer= \"start\" >\n <include\n layout= \"@layout/app_bar_main\"\n android :layout_width= \"match_parent\"\n android :layout_height= \"match_parent\" />\n <android.support.design.widget.NavigationView\n android :id= \"@+id/nav_view\"\n android :layout_width= \"wrap_content\"\n android :layout_height= \"match_parent\"\n android :layout_gravity= \"start\"\n android :fitsSystemWindows= \"true\"\n app :headerLayout= \"@layout/nav_header_main\"\n app :menu= \"@menu/activity_main_drawer\" />\n</android.support.v4.widget.DrawerLayout>"
},
{
"code": null,
"e": 2375,
"s": 2308,
"text": "Step 3 − Add the following code to res/layout/nav_header_main.xml."
},
{
"code": null,
"e": 3874,
"s": 2375,
"text": "<? xml version= \"1.0\" encoding= \"utf-8\" ?>\n<LinearLayout xmlns: android = \"http://schemas.android.com/apk/res/android\"\n xmlns: app = \"http://schemas.android.com/apk/res-auto\"\n android :layout_width= \"match_parent\"\n android :layout_height= \"@dimen/nav_header_height\"\n android :background= \"@drawable/side_nav_bar\"\n android :gravity= \"bottom\"\n android :orientation= \"vertical\"\n android :paddingLeft= \"@dimen/activity_horizontal_margin\"\n android :paddingTop= \"@dimen/activity_vertical_margin\"\n android :paddingRight= \"@dimen/activity_horizontal_margin\"\n android :paddingBottom= \"@dimen/activity_vertical_margin\"\n android :theme= \"@style/ThemeOverlay.AppCompat.Dark\" >\n <ImageView\n android :id= \"@+id/imageView\"\n android :layout_width= \"wrap_content\"\n android :layout_height= \"wrap_content\"\n android :contentDescription= \"@string/nav_header_desc\"\n android :paddingTop= \"@dimen/nav_header_vertical_spacing\"\n app :srcCompat= \"@mipmap/ic_launcher_round\" />\n <TextView\n android :layout_width= \"match_parent\"\n android :layout_height= \"wrap_content\"\n android :paddingTop= \"@dimen/nav_header_vertical_spacing\"\n android :text= \"@string/nav_header_title\"\n android :textAppearance= \"@style/TextAppearance.AppCompat.Body1\" />\n <TextView\n android :id= \"@+id/textView\"\n android :layout_width= \"wrap_content\"\n android :layout_height= \"wrap_content\"\n android :text= \"@string/nav_header_subtitle\" />\n</LinearLayout>"
},
{
"code": null,
"e": 3938,
"s": 3874,
"text": "Step 4 − Add the following code to res/layout/app_bar_main.xml."
},
{
"code": null,
"e": 5266,
"s": 3938,
"text": "<? xml version= \"1.0\" encoding= \"utf-8\" ?>\n<android.support.design.widget.CoordinatorLayout\n xmlns: android = \"http://schemas.android.com/apk/res/android\"\n xmlns: app = \"http://schemas.android.com/apk/res-auto\"\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 <android.support.design.widget.AppBarLayout\n android :layout_width= \"match_parent\"\n android :layout_height= \"wrap_content\"\n android :theme= \"@style/AppTheme.AppBarOverlay\" >\n <android.support.v7.widget.Toolbar\n android :id= \"@+id/toolbar\"\n android :layout_width= \"match_parent\"\n android :layout_height= \"?attr/actionBarSize\"\n android :background= \"?attr/colorPrimary\"\n app :popupTheme= \"@style/AppTheme.PopupOverlay\" />\n </android.support.design.widget.AppBarLayout>\n <include layout= \"@layout/content_main\" />\n <android.support.design.widget.FloatingActionButton\n android :id= \"@+id/fab\"\n android :layout_width= \"wrap_content\"\n android :layout_height= \"wrap_content\"\n android :layout_gravity= \"bottom|end\"\n android :layout_margin= \"@dimen/fab_margin\"\n app :srcCompat= \"@android:drawable/ic_dialog_email\" />\n</android.support.design.widget.CoordinatorLayout>"
},
{
"code": null,
"e": 5330,
"s": 5266,
"text": "Step 5 − Add the following code to res/layout/content_main.xml."
},
{
"code": null,
"e": 5868,
"s": 5330,
"text": "<? xml version= \"1.0\" encoding= \"utf-8\" ?>\n<android.support.constraint.ConstraintLayout\n xmlns: android = \"http://schemas.android.com/apk/res/android\"\n xmlns: app = \"http://schemas.android.com/apk/res-auto\"\n xmlns: tools = \"http://schemas.android.com/tools\"\n android :layout_width= \"match_parent\"\n android :layout_height= \"match_parent\"\n app :layout_behavior= \"@string/appbar_scrolling_view_behavior\"\n tools :context= \".MainActivity\"\n tools :showIn= \"@layout/app_bar_main\" >\n</android.support.constraint.ConstraintLayout>"
},
{
"code": null,
"e": 5938,
"s": 5868,
"text": "Step 6 − Add the following code to res/menu/activity_main_drawer.xml."
},
{
"code": null,
"e": 7154,
"s": 5938,
"text": "<? xml version= \"1.0\" encoding= \"utf-8\" ?>\n<menu xmlns: android = \"http://schemas.android.com/apk/res/android\"\n xmlns: tools = \"http://schemas.android.com/tools\"\n tools :showIn= \"navigation_view\" >\n <group android :checkableBehavior= \"single\" >\n <item\n android :id= \"@+id/nav_camera\"\n android :icon= \"@drawable/ic_menu_camera\"\n android :title= \"Import\" />\n <item\n android :id= \"@+id/nav_gallery\"\n android :icon= \"@drawable/ic_menu_gallery\"\n android :title= \"Gallery\" />\n <item\n android :id= \"@+id/nav_slideshow\"\n android :icon= \"@drawable/ic_menu_slideshow\"\n android :title= \"Slideshow\" />\n <item\n android :id= \"@+id/nav_manage\"\n android :icon= \"@drawable/ic_menu_manage\"\n android :title= \"Tools\" />\n </group>\n <item android :title= \"Communicate\" >\n <menu>\n <item\n android :id= \"@+id/nav_share\"\n android :icon= \"@drawable/ic_menu_share\"\n android :title= \"Share\" />\n <item\n android :id= \"@+id/nav_send\"\n android :icon= \"@drawable/ic_menu_send\"\n android :title= \"Send\" />\n </menu>\n </item>\n</menu>"
},
{
"code": null,
"e": 7211,
"s": 7154,
"text": "Step 7 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 10394,
"s": 7211,
"text": "package app.tutorialspoint.com.sample ;\nimport android.os.Bundle ;\nimport android.support.annotation. NonNull ;\nimport android.support.design.widget.FloatingActionButton ;\nimport android.support.design.widget.Snackbar ;\nimport android.view.View ;\nimport android.support.design.widget.NavigationView ;\nimport android.support.v4.view.GravityCompat ;\nimport android.support.v4.widget.DrawerLayout ;\nimport android.support.v7.app.ActionBarDrawerToggle ;\nimport android.support.v7.app.AppCompatActivity ;\nimport android.support.v7.widget.Toolbar ;\nimport android.view.Menu ;\nimport android.view.MenuItem ;\npublic class MainActivity extends AppCompatActivity\nimplements NavigationView.OnNavigationItemSelectedListener {\n @Override\n protected void onCreate (Bundle savedInstanceState) {\n super .onCreate(savedInstanceState) ;\n setContentView(R.layout. activity_main ) ;\n Toolbar toolbar = findViewById(R.id. toolbar ) ;\n setSupportActionBar(toolbar) ;\n FloatingActionButton fab = findViewById(R.id. fab ) ;\n fab.setOnClickListener( new View.OnClickListener() {\n @Override\n public void onClick (View view) {\n Snackbar. make (view , \"Replace with your own action\" ,\n Snackbar. LENGTH_LONG )\n .setAction( \"Action\" , null ).show() ;\n }\n }) ;\n DrawerLayout drawer = findViewById(R.id. drawer_layout ) ;\n ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(\n this, drawer , toolbar , R.string. navigation_drawer_open ,\n R.string. navigation_drawer_close ) ;\n drawer.addDrawerListener(toggle) ;\n toggle.syncState() ;\n NavigationView navigationView = findViewById(R.id. nav_view ) ;\n navigationView.setNavigationItemSelectedListener( this ) ;\n }\n @Override\n public void onBackPressed () {\n DrawerLayout drawer = findViewById(R.id. drawer_layout ) ;\n if (drawer.isDrawerOpen(GravityCompat. START )) {\n drawer.closeDrawer(GravityCompat. START ) ;\n } else {\n super .onBackPressed() ;\n }\n }\n @Override\n public boolean onCreateOptionsMenu (Menu menu) {\n // Inflate the menu; this adds items to the action bar if it is present.\n getMenuInflater().inflate(R.menu. main , menu) ;\n return true;\n }\n @Override\n public boolean onOptionsItemSelected (MenuItem item) {\n int id = item.getItemId() ;\n if (id == R.id. action_settings ) {\n return true;\n }\n return super .onOptionsItemSelected(item) ;\n }\n @SuppressWarnings ( \"StatementWithEmptyBody\" )\n @Override\n public boolean onNavigationItemSelected ( @NonNull MenuItem item) {\n // Handle navigation view item clicks here.\n int id = item.getItemId() ;\n if (id == R.id. nav_camera ) {\n // Handle the camera action\n } else if (id == R.id. nav_gallery ) {\n } else if (id == R.id. nav_slideshow ) {\n } else if (id == R.id. nav_manage ) {\n } else if (id == R.id. nav_share ) {\n } else if (id == R.id. nav_send ) {\n }\n DrawerLayout drawer = findViewById(R.id. drawer_layout ) ;\n drawer.closeDrawer(GravityCompat. START ) ;\n return true;\n }\n}"
},
{
"code": null,
"e": 10449,
"s": 10394,
"text": "Step 8 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 11230,
"s": 10449,
"text": "<? xml version= \"1.0\" encoding= \"utf-8\" ?>\n<manifest xmlns: android = \"http://schemas.android.com/apk/res/android\"\n package= \"app.tutorialspoint.com.sample\" >\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\n android :name= \".MainActivity\"\n android :theme= \"@style/AppTheme.NoActionBar\" >\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": 11577,
"s": 11230,
"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 –"
}
]
|
Ancestors in Binary Tree | Practice | GeeksforGeeks | Given a Binary Tree and a target key, you need to find all the ancestors of the given target key.
1
/ \
2 3
/ \
4 5
/
7
Key: 7
Ancestor: 4 2 1
Example 1:
Input:
1
/ \
2 3
target = 2
Output: 1
Example 2:
Input:
1
/ \
2 3
/ \ / \
4 5 6 8
/
7
target = 7
Output: 4 2 1
Your Task:
Your task is to complete the function Ancestors() that finds all the ancestors of the key in the given binary tree.
Note:
The return type is
cpp: vector
Java: ArrayList
python: list
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(H).
Note: H is the height of the tree and this space is used implicitly for the recursion stack.
Constraints:
1 ≤ N ≤ 103
1 ≤ data of node ≤ 104
0
adityagagtiwari3 weeks ago
Easy solution doston!!
class Solution
{
public static ArrayList<Integer> Ancestors(Node root, int target)
{
// add your code here
ArrayList<Integer> result = new ArrayList<>();
getAncestors(root,target,result);
return result;
}
//our method returns whether there exists a path to the target
//if there exists a path to target then add the node to result and return true
public static boolean getAncestors(Node root,int target,ArrayList<Integer> result)
{
if(root==null)
return false;
if(root.data==target)
return true;
//if the target exists in the left or right tree then return true after adding the node
//via which we are getting the target
if(getAncestors(root.left,target,result)||getAncestors(root.right,target,result))
{
result.add(root.data);
return true;
}
return false;
}
}
0
tapanmanu20001 month ago
class Solution{
public:
// Function should return all the ancestor of the target node
bool preorder(Node* root, int target, vector<int>& res){
if(root == NULL) return false;
if(root->data == target){
return true;
}
res.push_back(root->data);
bool l = preorder(root->left,target,res);
if(l) return true;
bool r = preorder(root->right,target,res);
if(r) return true;
res.pop_back();
return false;
}
vector<int> Ancestors(struct Node *root, int target)
{
vector<int> res;
if(root == NULL || root->data == target) return res;
res.push_back(root->data);
bool l = preorder(root->left, target, res);
if(l) {
reverse(res.begin(),res.end());
return res;
}
bool r = preorder(root->right, target, res);
if(r) {
reverse(res.begin(), res.end());
return res;
}
res.pop_back();
return res;
}
};
0
patildhiren442 months ago
// java sol
// 0.9 sec
class Solution
{
static boolean util(Node root, int tar,ArrayList<Integer> al ){
if(root==null){
return false;
}
if(root.data==tar){
return true;
}
if(util(root.left, tar, al) || util(root.right, tar, al)){
al.add(root.data);
return true;
}
return false;
}
public static ArrayList<Integer> Ancestors(Node root, int tar)
{
// add your code here
ArrayList<Integer> al = new ArrayList<>();
util(root, tar, al);
return al;
}
}
0
mohankumarit20012 months ago
class Solution{
public:
// Function should return all the ancestor of the target node
bool found = false;
void rec(Node* root,int target,stack<int> &res){
if(found)return;
if(!root)return;
if(root->data==target){found =true;return;}
res.push(root->data);
rec(root->left,target,res);
if(found)return;
rec(root->right,target,res);
if(found)return;
res.pop();
}
vector<int> Ancestors(struct Node *root, int target)
{
// Code
vector<int> res;
stack<int> q;
rec(root,target,q);
while(!q.empty()){res.push_back(q.top());q.pop();}
return res;
}
};
0
aryangarg19993 months ago
class Solution{
public:
// Function should return all the ancestor of the target node
vector<int>ans ;
Node *findAncestors(Node *node, int target)
{
if(node == nullptr)
return nullptr ;
if(node->left != nullptr)
{
if(node->left->data == target) // Then this is the first ancestor (root)
return node ;
}
if(node->right != nullptr)
{
if(node->right->data == target)
return node ;
}
Node *left = findAncestors(node->left, target) ;
Node *right = findAncestors(node->right, target) ;
if(left) // Means there is something returned in it.
{
ans.push_back(left->data) ;
return node ; // then the root of this left will be returned
}
if(right)
{
ans.push_back(right->data) ;
return node ;
}
}
vector<int> Ancestors(struct Node *root, int target)
{
ans.clear() ;
Node *ret = findAncestors(root, target) ;
ans.push_back(ret->data) ;
return ans ;
}
};
+1
codemohitprakanojia21033 months ago
ArrayList<Integer> Ancestors(Node root, int target)
{
// add your code here
fun(root,target);
return lis;
}
ArrayList<Integer> lis=new ArrayList<>();
Stack<Integer> st=new Stack<>();
void fun(Node root,int key){
if(root==null) return;
if(root.data!=key) st.push(root.data);
else{
while(!st.empty()){
lis.add(st.pop());
}
}
fun(root.left,key);
fun(root.right,key);
if(!st.empty())st.pop();
}
+3
kronizerdeltac3 months ago
JAVA SOLUTION
public static boolean nodeToRootPath(Node root, int target, ArrayList<Integer> ans) { if(root == null) return false;
if(root.data == target) return true;
boolean res = nodeToRootPath(root.left, target, ans) || nodeToRootPath(root.right, target, ans); if(res) ans.add(root.data); return res; } public static ArrayList<Integer> Ancestors(Node root, int target) { ArrayList<Integer> ans = new ArrayList<>(); nodeToRootPath(root, target, ans); return ans; }
+1
sohamdas86973 months ago
bool solve(Node* root, int target, vector <int>& v)
{
if(root == NULL)
return false;
v.push_back(root->data);
if(root->data == target)
return true;
bool lh = solve(root->left, target, v);
bool rh = solve(root->right, target, v);
if(lh || rh)
return true;
v.pop_back();
return false;
}
// Function should return all the ancestor of the target node
vector<int> Ancestors(struct Node *root, int target)
{
vector <int> v;
bool l = solve(root, target, v);
v.pop_back();
reverse(v.begin(), v.end());
return v;
}
0
radheshyamnitj4 months ago
void helper(Node* root,int target, vector<int> &ans,bool &flag){
if(!root) return;
if(root->data==target){
flag= true;
return ;
}
if(!flag)
helper(root->left,target,ans,flag);
if(!flag)
helper(root->right,target,ans,flag);
if(flag==true){
ans.push_back(root->data);
return;
}
}
vector<int> Ancestors(struct Node *root, int target)
{
vector<int>ans;
bool flag;
helper(root,target,ans,flag);
return ans;
}
0
mayurxxivk4 months ago
CorrectAnswer.🥇
Total Time Taken:0.9/2.3
static boolean pleaseHelp(Node root, int target , ArrayList<Integer>al)
{
if(root == null) return false;
if(root.data == target) return true;
if(pleaseHelp(root.left , target , al ) || pleaseHelp(root.right , target , al))
{
al.add(root.data);
return true;
}
return false;
}
public static ArrayList<Integer> Ancestors(Node root, int target)
{
ArrayList<Integer>al = new ArrayList<>();
pleaseHelp(root ,target , al);
return al;
}
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": 336,
"s": 238,
"text": "Given a Binary Tree and a target key, you need to find all the ancestors of the given target key."
},
{
"code": null,
"e": 452,
"s": 336,
"text": " 1\n / \\\n 2 3\n / \\\n 4 5\n /\n 7\nKey: 7\nAncestor: 4 2 1"
},
{
"code": null,
"e": 463,
"s": 452,
"text": "Example 1:"
},
{
"code": null,
"e": 527,
"s": 463,
"text": "Input:\n 1\n / \\\n 2 3\ntarget = 2\nOutput: 1\n"
},
{
"code": null,
"e": 538,
"s": 527,
"text": "Example 2:"
},
{
"code": null,
"e": 649,
"s": 538,
"text": "Input:\n 1\n / \\\n 2 3\n / \\ / \\\n 4 5 6 8\n /\n 7\ntarget = 7\nOutput: 4 2 1\n"
},
{
"code": null,
"e": 842,
"s": 649,
"text": "Your Task:\nYour task is to complete the function Ancestors() that finds all the ancestors of the key in the given binary tree.\nNote:\nThe return type is\ncpp: vector\nJava: ArrayList\npython: list"
},
{
"code": null,
"e": 999,
"s": 842,
"text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(H).\nNote: H is the height of the tree and this space is used implicitly for the recursion stack."
},
{
"code": null,
"e": 1047,
"s": 999,
"text": "Constraints:\n1 ≤ N ≤ 103\n1 ≤ data of node ≤ 104"
},
{
"code": null,
"e": 1049,
"s": 1047,
"text": "0"
},
{
"code": null,
"e": 1076,
"s": 1049,
"text": "adityagagtiwari3 weeks ago"
},
{
"code": null,
"e": 1099,
"s": 1076,
"text": "Easy solution doston!!"
},
{
"code": null,
"e": 2030,
"s": 1101,
"text": "class Solution\n{\n \n public static ArrayList<Integer> Ancestors(Node root, int target)\n {\n // add your code here\n ArrayList<Integer> result = new ArrayList<>();\n getAncestors(root,target,result);\n return result;\n }\n //our method returns whether there exists a path to the target\n //if there exists a path to target then add the node to result and return true\n public static boolean getAncestors(Node root,int target,ArrayList<Integer> result)\n {\n if(root==null)\n return false;\n \n if(root.data==target)\n return true;\n //if the target exists in the left or right tree then return true after adding the node \n //via which we are getting the target\n if(getAncestors(root.left,target,result)||getAncestors(root.right,target,result))\n {\n result.add(root.data);\n return true;\n }\n return false;\n }\n}"
},
{
"code": null,
"e": 2032,
"s": 2030,
"text": "0"
},
{
"code": null,
"e": 2057,
"s": 2032,
"text": "tapanmanu20001 month ago"
},
{
"code": null,
"e": 3058,
"s": 2057,
"text": "class Solution{\n public:\n // Function should return all the ancestor of the target node\n bool preorder(Node* root, int target, vector<int>& res){\n if(root == NULL) return false;\n if(root->data == target){\n return true;\n }\n res.push_back(root->data);\n bool l = preorder(root->left,target,res);\n if(l) return true;\n bool r = preorder(root->right,target,res);\n if(r) return true;\n res.pop_back();\n return false;\n }\n vector<int> Ancestors(struct Node *root, int target)\n {\n vector<int> res;\n if(root == NULL || root->data == target) return res;\n res.push_back(root->data);\n bool l = preorder(root->left, target, res);\n if(l) {\n reverse(res.begin(),res.end());\n return res;\n }\n bool r = preorder(root->right, target, res);\n if(r) {\n reverse(res.begin(), res.end());\n return res;\n }\n res.pop_back();\n return res;\n }\n};"
},
{
"code": null,
"e": 3060,
"s": 3058,
"text": "0"
},
{
"code": null,
"e": 3086,
"s": 3060,
"text": "patildhiren442 months ago"
},
{
"code": null,
"e": 3727,
"s": 3086,
"text": "// java sol\n// 0.9 sec\n\n\nclass Solution\n{\n \n static boolean util(Node root, int tar,ArrayList<Integer> al ){\n if(root==null){\n return false;\n }\n \n if(root.data==tar){\n return true;\n }\n \n if(util(root.left, tar, al) || util(root.right, tar, al)){\n al.add(root.data);\n return true;\n }\n return false;\n }\n \n public static ArrayList<Integer> Ancestors(Node root, int tar)\n {\n // add your code here\n ArrayList<Integer> al = new ArrayList<>();\n \n util(root, tar, al);\n return al;\n }\n}"
},
{
"code": null,
"e": 3729,
"s": 3727,
"text": "0"
},
{
"code": null,
"e": 3758,
"s": 3729,
"text": "mohankumarit20012 months ago"
},
{
"code": null,
"e": 4472,
"s": 3758,
"text": "class Solution{\n public:\n // Function should return all the ancestor of the target node\n bool found = false;\n void rec(Node* root,int target,stack<int> &res){\n if(found)return;\n if(!root)return;\n if(root->data==target){found =true;return;}\n res.push(root->data);\n rec(root->left,target,res);\n if(found)return;\n rec(root->right,target,res);\n if(found)return;\n res.pop();\n }\n vector<int> Ancestors(struct Node *root, int target)\n {\n // Code \n vector<int> res;\n stack<int> q;\n rec(root,target,q);\n while(!q.empty()){res.push_back(q.top());q.pop();}\n return res;\n \n }\n};"
},
{
"code": null,
"e": 4474,
"s": 4472,
"text": "0"
},
{
"code": null,
"e": 4500,
"s": 4474,
"text": "aryangarg19993 months ago"
},
{
"code": null,
"e": 5777,
"s": 4500,
"text": "class Solution{\n public:\n // Function should return all the ancestor of the target node\n \n vector<int>ans ;\n \n Node *findAncestors(Node *node, int target)\n {\n if(node == nullptr)\n return nullptr ;\n \n if(node->left != nullptr)\n {\n if(node->left->data == target) // Then this is the first ancestor (root)\n return node ;\n }\n \n \n if(node->right != nullptr)\n {\n if(node->right->data == target)\n return node ;\n }\n \n Node *left = findAncestors(node->left, target) ;\n Node *right = findAncestors(node->right, target) ;\n \n \n if(left) // Means there is something returned in it.\n {\n ans.push_back(left->data) ;\n return node ; // then the root of this left will be returned\n }\n \n \n if(right)\n {\n ans.push_back(right->data) ;\n return node ;\n }\n \n }\n \n vector<int> Ancestors(struct Node *root, int target)\n {\n ans.clear() ;\n Node *ret = findAncestors(root, target) ;\n ans.push_back(ret->data) ;\n return ans ;\n }\n};"
},
{
"code": null,
"e": 5780,
"s": 5777,
"text": "+1"
},
{
"code": null,
"e": 5816,
"s": 5780,
"text": "codemohitprakanojia21033 months ago"
},
{
"code": null,
"e": 6356,
"s": 5816,
"text": "ArrayList<Integer> Ancestors(Node root, int target)\n {\n // add your code here\n fun(root,target);\n return lis;\n }\n ArrayList<Integer> lis=new ArrayList<>();\n Stack<Integer> st=new Stack<>();\n \n void fun(Node root,int key){\n if(root==null) return;\n if(root.data!=key) st.push(root.data);\n else{\n while(!st.empty()){\n lis.add(st.pop());\n }\n }\n fun(root.left,key);\n fun(root.right,key);\n if(!st.empty())st.pop();\n }"
},
{
"code": null,
"e": 6359,
"s": 6356,
"text": "+3"
},
{
"code": null,
"e": 6386,
"s": 6359,
"text": "kronizerdeltac3 months ago"
},
{
"code": null,
"e": 6400,
"s": 6386,
"text": "JAVA SOLUTION"
},
{
"code": null,
"e": 6535,
"s": 6402,
"text": "public static boolean nodeToRootPath(Node root, int target, ArrayList<Integer> ans) { if(root == null) return false;"
},
{
"code": null,
"e": 6589,
"s": 6535,
"text": " if(root.data == target) return true;"
},
{
"code": null,
"e": 6945,
"s": 6589,
"text": " boolean res = nodeToRootPath(root.left, target, ans) || nodeToRootPath(root.right, target, ans); if(res) ans.add(root.data); return res; } public static ArrayList<Integer> Ancestors(Node root, int target) { ArrayList<Integer> ans = new ArrayList<>(); nodeToRootPath(root, target, ans); return ans; }"
},
{
"code": null,
"e": 6948,
"s": 6945,
"text": "+1"
},
{
"code": null,
"e": 6973,
"s": 6948,
"text": "sohamdas86973 months ago"
},
{
"code": null,
"e": 7644,
"s": 6973,
"text": "bool solve(Node* root, int target, vector <int>& v) \n {\n if(root == NULL)\n return false;\n v.push_back(root->data);\n if(root->data == target)\n return true;\n bool lh = solve(root->left, target, v);\n bool rh = solve(root->right, target, v);\n if(lh || rh)\n return true;\n v.pop_back();\n return false;\n }\n // Function should return all the ancestor of the target node\n vector<int> Ancestors(struct Node *root, int target)\n {\n vector <int> v;\n bool l = solve(root, target, v);\n v.pop_back();\n reverse(v.begin(), v.end());\n return v;\n }"
},
{
"code": null,
"e": 7646,
"s": 7644,
"text": "0"
},
{
"code": null,
"e": 7673,
"s": 7646,
"text": "radheshyamnitj4 months ago"
},
{
"code": null,
"e": 8267,
"s": 7673,
"text": "void helper(Node* root,int target, vector<int> &ans,bool &flag){\n \n if(!root) return;\n if(root->data==target){\n flag= true;\n return ;\n }\n if(!flag)\n helper(root->left,target,ans,flag);\n if(!flag)\n helper(root->right,target,ans,flag);\n \n if(flag==true){\n ans.push_back(root->data);\n return;\n }\n }\n vector<int> Ancestors(struct Node *root, int target)\n {\n vector<int>ans;\n bool flag;\n helper(root,target,ans,flag);\n return ans;\n }"
},
{
"code": null,
"e": 8269,
"s": 8267,
"text": "0"
},
{
"code": null,
"e": 8292,
"s": 8269,
"text": "mayurxxivk4 months ago"
},
{
"code": null,
"e": 8308,
"s": 8292,
"text": "CorrectAnswer.🥇"
},
{
"code": null,
"e": 8333,
"s": 8308,
"text": "Total Time Taken:0.9/2.3"
},
{
"code": null,
"e": 8920,
"s": 8335,
"text": " static boolean pleaseHelp(Node root, int target , ArrayList<Integer>al)\n {\n \n if(root == null) return false;\n if(root.data == target) return true;\n \n if(pleaseHelp(root.left , target , al ) || pleaseHelp(root.right , target , al))\n { \n al.add(root.data);\n return true;\n }\n return false;\n \n }\n public static ArrayList<Integer> Ancestors(Node root, int target)\n {\n ArrayList<Integer>al = new ArrayList<>();\n pleaseHelp(root ,target , al);\n return al;\n }"
},
{
"code": null,
"e": 9068,
"s": 8922,
"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": 9104,
"s": 9068,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 9114,
"s": 9104,
"text": "\nProblem\n"
},
{
"code": null,
"e": 9124,
"s": 9114,
"text": "\nContest\n"
},
{
"code": null,
"e": 9187,
"s": 9124,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 9335,
"s": 9187,
"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": 9543,
"s": 9335,
"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": 9649,
"s": 9543,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
]
|
What is typeof Operator in JavaScript? | The typeof operator is a unary operator that is placed before its single operand, which can be of any type. Its value is a string indicating the data type of the operand. The typeof operator evaluates to "number", "string" or "boolean" if its operand is a number, string, or boolean value and returns true or false based on the evaluation.
Here is a list of the return values for the typeof Operator.
The following code shows how to implement typeof operator −
<html>
<body>
<script>
var a = 10;
var b = "String";
var linebreak = "<br />";
result = (typeof b == "string" ? "B is String" : "Bis Numeric");
document.write("Result => ");
document.write(result);
document.write(linebreak);
result = (typeof a == "string" ? "A is String" : "Ais Numeric");
document.write("Result => ");
document.write(result);
document.write(linebreak);
</script>
</body>
</html> | [
{
"code": null,
"e": 1403,
"s": 1062,
"text": "The typeof operator is a unary operator that is placed before its single operand, which can be of any type. Its value is a string indicating the data type of the operand. The typeof operator evaluates to \"number\", \"string\" or \"boolean\" if its operand is a number, string, or boolean value and returns true or false based on the evaluation."
},
{
"code": null,
"e": 1464,
"s": 1403,
"text": "Here is a list of the return values for the typeof Operator."
},
{
"code": null,
"e": 1524,
"s": 1464,
"text": "The following code shows how to implement typeof operator −"
},
{
"code": null,
"e": 2040,
"s": 1524,
"text": "<html>\n <body>\n <script>\n var a = 10;\n var b = \"String\";\n var linebreak = \"<br />\";\n\n result = (typeof b == \"string\" ? \"B is String\" : \"Bis Numeric\");\n document.write(\"Result => \");\n document.write(result);\n document.write(linebreak);\n\n result = (typeof a == \"string\" ? \"A is String\" : \"Ais Numeric\");\n document.write(\"Result => \");\n document.write(result);\n document.write(linebreak);\n </script>\n </body>\n</html>"
}
]
|
How to convert String to Long in Kotlin? | In this article, we will see how to convert a String to Long in Kotlin using a
library function. There are multiple ways to do it. Let's take a couple of
examples to demonstrate how it's done.
toLong() is a function that provides the most convenient way to convert a string to a long. In the following example, we will see how we can use toLong() to convert our String.
fun convertToLong(s: String) {
try {
val value = s.toLong()
println("The Long value is: $value")
}
catch (ex: NumberFormatException) {
println("Please enter a number: ")
}
}
fun main() {
val str = "1234567890"
convertToLong(str)
}
Once the above piece of code is executed, it will convert our String
"1234567890" to a Long value.
The Long value is: 1234567890
Like toLong(), we can use another function called toLongOrNull() to convert a String value to Long. In the following example, we will see how to convert a String to Long using toLongOrNull().
fun convertToLong(s: String) {
try {
val value = s.toLongOrNull()
println("The Long value is: $value")
}
catch (ex: NumberFormatException) {
println("Please enter a number: ")
}
}
fun main() {
val str = "1234567890"
convertToLong(str)
}
Once the above piece of code is executed, it will convert our String
"1234567890" to a Long value.
The Long value is: 1234567890
Kotlin is based on the JVM. Hence, we can use the Java Lang package to convert a String to a Long variable. In the following example, we have used the valueOf() function to convert a String to a Long variable.
fun main() {
val str = "12345678"
println("The given string is: " +str)
val value = java.lang.Long.valueOf(str)
println("After converting to Long: " +value)
}
One executed, the above piece of code will convert our String "1234567890"
to a Long value.
The given string is: 12345678
After converting to Long: 12345678 | [
{
"code": null,
"e": 1255,
"s": 1062,
"text": "In this article, we will see how to convert a String to Long in Kotlin using a\nlibrary function. There are multiple ways to do it. Let's take a couple of\nexamples to demonstrate how it's done."
},
{
"code": null,
"e": 1432,
"s": 1255,
"text": "toLong() is a function that provides the most convenient way to convert a string to a long. In the following example, we will see how we can use toLong() to convert our String."
},
{
"code": null,
"e": 1701,
"s": 1432,
"text": "fun convertToLong(s: String) {\n\n try {\n val value = s.toLong()\n println(\"The Long value is: $value\")\n }\n\n catch (ex: NumberFormatException) {\n println(\"Please enter a number: \")\n }\n}\nfun main() {\n val str = \"1234567890\"\n convertToLong(str)\n}"
},
{
"code": null,
"e": 1800,
"s": 1701,
"text": "Once the above piece of code is executed, it will convert our String\n\"1234567890\" to a Long value."
},
{
"code": null,
"e": 1830,
"s": 1800,
"text": "The Long value is: 1234567890"
},
{
"code": null,
"e": 2022,
"s": 1830,
"text": "Like toLong(), we can use another function called toLongOrNull() to convert a String value to Long. In the following example, we will see how to convert a String to Long using toLongOrNull()."
},
{
"code": null,
"e": 2297,
"s": 2022,
"text": "fun convertToLong(s: String) {\n\n try {\n val value = s.toLongOrNull()\n println(\"The Long value is: $value\")\n }\n catch (ex: NumberFormatException) {\n println(\"Please enter a number: \")\n }\n}\n\nfun main() {\n val str = \"1234567890\"\n convertToLong(str)\n}"
},
{
"code": null,
"e": 2396,
"s": 2297,
"text": "Once the above piece of code is executed, it will convert our String\n\"1234567890\" to a Long value."
},
{
"code": null,
"e": 2426,
"s": 2396,
"text": "The Long value is: 1234567890"
},
{
"code": null,
"e": 2636,
"s": 2426,
"text": "Kotlin is based on the JVM. Hence, we can use the Java Lang package to convert a String to a Long variable. In the following example, we have used the valueOf() function to convert a String to a Long variable."
},
{
"code": null,
"e": 2807,
"s": 2636,
"text": "fun main() {\n val str = \"12345678\"\n println(\"The given string is: \" +str)\n val value = java.lang.Long.valueOf(str)\n println(\"After converting to Long: \" +value)\n}"
},
{
"code": null,
"e": 2899,
"s": 2807,
"text": "One executed, the above piece of code will convert our String \"1234567890\"\nto a Long value."
},
{
"code": null,
"e": 2964,
"s": 2899,
"text": "The given string is: 12345678\nAfter converting to Long: 12345678"
}
]
|
Send your new year greetings by email and text message using Python | by Yong Cui | Towards Data Science | It’s new year time. Although we developers don’t usually bother to maintain friendship (is it a joke or not?), we don’t mind sending our greetings to our friends as long as there is a programmatic way to get this done!
Here, I’m showing you how to send your greetings by email and text message using Python in two parts.
Python has a built-in library called smtplib — a module that can be used to create an SMTP client session object, allowing us to send emails to any email service providers implementing SMTP or ESMTP. Another useful module for email sending is the email package that provides email-related functionalities, such as reading and writing.
For the simplicity of this current tutorial, we’ll just send a plain text email. To do that, we’ll just need MIMEText to create the email text body. In a later tutorial, I can show you how to send a more complex email (e.g., image attachment).
import smtplibimport emailfrom email.mime.text import MIMEText
In this tutorial, I’m going to use a gmail account to send the emails. Please note that you need to update your gmail security setting (https://myaccount.google.com/lesssecureapps) to allow your email to be sent programmatically using Python.
email_host = "smtp.gmail.com"email_port = 587email_sender = "" # change it to your own gmail accountemail_password = "" # change it to your gmail passwordemail_receivers = ["[email protected]", "[email protected]", "[email protected]"] # the list of recipient email addresses
Next, you can compose your message. You can specify the sender as your own email account. For the list of the email that is intended to be sent to, you can use the following format: First, Last<[email protected]>, which is a standard format of email recipient.
message = MIMEText("I wish you a great 2020.")message["From"] = "" # your email accountmessage["To"] = "John Smith<[email protected]>, Mike Dickson<[email protected]>" # the list of email addressesmessage["Subject"] = "Happy New Year"
You use the host and port to create the needed SMTP session. During initialization, Python will automatically establish the SMTP connection by calling the connect method . We then start the TLS for security reasons.
You just need to authenticate your identity using the email account and password. As mentioned previously, for gmail, you have to loosen your security setting before you can login using this method.
You can simply call the sendmail method to send your message and quit the session.
email_server = smtplib.SMTP(email_host, email_port)email_server.starttls()email_server.login(email_sender, email_password)email_server.sendmail(email_sender, email_receivers, message.as_string())email_server.quit()
There are multiple ways actually you can use Python to send your new year greetings by text messages.
As many of you may be aware, many cellphone carriers allow you to send text messages using email. Here are just a short list for major carriers in the United State.
AT&T: [email protected]
Sprint: [email protected]
T-Mobile: [email protected]
Verizon: [email protected]
So instead of using the email address for the email_receivers variable, you can simply use [email protected] as one of the email recipients.
However, there is a catch as you may have to know the carrier associated that number. If you don’t know it, you can just write some code to create all possible variations (e.g., [email protected], [email protected]) to cover all possibilities. I’ve also heard that there is paid third-party service allowing you to look up a certain phone number’s carrier. But I guess it’s an overkill for the objective we’re trying to accomplish.
You can also send text messages using AWS SNS. Apparently, you need to sign up an AWS account, which is beyond the scope of the current tutorial. You can refer to the official website (https://aws.amazon.com/premiumsupport/knowledge-center/create-and-activate-aws-account/).
Run the code (pip install boto3) in Terminal or a command line tool. The boto3 library is a Python module developed for AWS-related management.
The SNS is an AWS product that allows the developers to send text messages and other communications (e.g., emails) to end users.
import boto3client = boto3.client( "sns", aws_access_key_id="", # your aws access key aws_secret_access_key="", # your aws secrete access key region_name="us-east-1")
To send your greeting to multiple phone numbers, you need to create a topic, which allows you to add subscribers to this topic. Each subscriber is specified by a phone number, which should also include the country code (e.g., +1 for US) — the E.164 formatting. Because we’re sending messages (i.e., short message service or sms), we specify the protocol to be sms.
topic = client.create_topic(Name="new_year") # create a topictopic_arn = topic['TopicArn'] # get its Amazon Resource Name# Add SMS Subscribers to this topicphone_numbers = ["+1234567890"] for phone_number in phone_numbers: client.subscribe( TopicArn=topic_arn, Protocol='sms', Endpoint=phone_number )
Once you have added the subscribers to the topic, you’re ready to publish a message to the topic. You just need to provide the message and specify the topic on which you want to publish this message. By doing that, all the subscribers will receive the text message.
client.publish(Message="Happy New Year!", TopicArn=topic_arn)
You can also choose to send text messages using the Twilio. Certainly, it requires a Twilio account, which is free to register, similar to an AWS account. Once you create a Twilio account, we’re ready to play the game!
Run the command pip install twilio to install the Twilio module, which will give you access to various functionalities provided by Twilio. Text messaging is just one of them.
The Cilent method will be used to create a Twilio client by taking your Twilio account SID and AUTH Token, both of which can be found on the dashboard of your Twilio account.
from twilio.rest import Clientclient = Client( "", # your Twilio Account SID "", # your Twilio AUTH token)
You create a list of all the phone numbers to which you’ll send your new year greetings. Again, be noted that the phone number is using the E.164 formatting similar to the use of AWS SNS.
One catch is that with free Twilio account, you can only send text messages to you verified phone numbers, giving you less flexibility compared to AWS SNS. However, you can upgrade your Twilio account, which will give you an option of sending to multiple phone numbers of your choice at very low cost (less than 1 cent per message).
phone_numbers = ["+1234567890", "+1234567891"] # the list of phone numbers to receive the messagesfor phone_number in phone_numbers: client.messages.create( to=phone_number, from_="", # your Twilio phone number body="Happy New Year!" )
By following this tutorial, you should have created multiple python scripts for each of these jobs. In the future, you can use these scripts to send emails and text messages very conveniently.
So actually, programming does make certain things easier, doesn’t it? | [
{
"code": null,
"e": 390,
"s": 171,
"text": "It’s new year time. Although we developers don’t usually bother to maintain friendship (is it a joke or not?), we don’t mind sending our greetings to our friends as long as there is a programmatic way to get this done!"
},
{
"code": null,
"e": 492,
"s": 390,
"text": "Here, I’m showing you how to send your greetings by email and text message using Python in two parts."
},
{
"code": null,
"e": 827,
"s": 492,
"text": "Python has a built-in library called smtplib — a module that can be used to create an SMTP client session object, allowing us to send emails to any email service providers implementing SMTP or ESMTP. Another useful module for email sending is the email package that provides email-related functionalities, such as reading and writing."
},
{
"code": null,
"e": 1071,
"s": 827,
"text": "For the simplicity of this current tutorial, we’ll just send a plain text email. To do that, we’ll just need MIMEText to create the email text body. In a later tutorial, I can show you how to send a more complex email (e.g., image attachment)."
},
{
"code": null,
"e": 1134,
"s": 1071,
"text": "import smtplibimport emailfrom email.mime.text import MIMEText"
},
{
"code": null,
"e": 1377,
"s": 1134,
"text": "In this tutorial, I’m going to use a gmail account to send the emails. Please note that you need to update your gmail security setting (https://myaccount.google.com/lesssecureapps) to allow your email to be sent programmatically using Python."
},
{
"code": null,
"e": 1641,
"s": 1377,
"text": "email_host = \"smtp.gmail.com\"email_port = 587email_sender = \"\" # change it to your own gmail accountemail_password = \"\" # change it to your gmail passwordemail_receivers = [\"[email protected]\", \"[email protected]\", \"[email protected]\"] # the list of recipient email addresses"
},
{
"code": null,
"e": 1899,
"s": 1641,
"text": "Next, you can compose your message. You can specify the sender as your own email account. For the list of the email that is intended to be sent to, you can use the following format: First, Last<[email protected]>, which is a standard format of email recipient."
},
{
"code": null,
"e": 2132,
"s": 1899,
"text": "message = MIMEText(\"I wish you a great 2020.\")message[\"From\"] = \"\" # your email accountmessage[\"To\"] = \"John Smith<[email protected]>, Mike Dickson<[email protected]>\" # the list of email addressesmessage[\"Subject\"] = \"Happy New Year\""
},
{
"code": null,
"e": 2348,
"s": 2132,
"text": "You use the host and port to create the needed SMTP session. During initialization, Python will automatically establish the SMTP connection by calling the connect method . We then start the TLS for security reasons."
},
{
"code": null,
"e": 2547,
"s": 2348,
"text": "You just need to authenticate your identity using the email account and password. As mentioned previously, for gmail, you have to loosen your security setting before you can login using this method."
},
{
"code": null,
"e": 2630,
"s": 2547,
"text": "You can simply call the sendmail method to send your message and quit the session."
},
{
"code": null,
"e": 2845,
"s": 2630,
"text": "email_server = smtplib.SMTP(email_host, email_port)email_server.starttls()email_server.login(email_sender, email_password)email_server.sendmail(email_sender, email_receivers, message.as_string())email_server.quit()"
},
{
"code": null,
"e": 2947,
"s": 2845,
"text": "There are multiple ways actually you can use Python to send your new year greetings by text messages."
},
{
"code": null,
"e": 3112,
"s": 2947,
"text": "As many of you may be aware, many cellphone carriers allow you to send text messages using email. Here are just a short list for major carriers in the United State."
},
{
"code": null,
"e": 3148,
"s": 3112,
"text": "AT&T: [email protected]"
},
{
"code": null,
"e": 3198,
"s": 3148,
"text": "Sprint: [email protected]"
},
{
"code": null,
"e": 3238,
"s": 3198,
"text": "T-Mobile: [email protected]"
},
{
"code": null,
"e": 3275,
"s": 3238,
"text": "Verizon: [email protected]"
},
{
"code": null,
"e": 3421,
"s": 3275,
"text": "So instead of using the email address for the email_receivers variable, you can simply use [email protected] as one of the email recipients."
},
{
"code": null,
"e": 3876,
"s": 3421,
"text": "However, there is a catch as you may have to know the carrier associated that number. If you don’t know it, you can just write some code to create all possible variations (e.g., [email protected], [email protected]) to cover all possibilities. I’ve also heard that there is paid third-party service allowing you to look up a certain phone number’s carrier. But I guess it’s an overkill for the objective we’re trying to accomplish."
},
{
"code": null,
"e": 4151,
"s": 3876,
"text": "You can also send text messages using AWS SNS. Apparently, you need to sign up an AWS account, which is beyond the scope of the current tutorial. You can refer to the official website (https://aws.amazon.com/premiumsupport/knowledge-center/create-and-activate-aws-account/)."
},
{
"code": null,
"e": 4295,
"s": 4151,
"text": "Run the code (pip install boto3) in Terminal or a command line tool. The boto3 library is a Python module developed for AWS-related management."
},
{
"code": null,
"e": 4424,
"s": 4295,
"text": "The SNS is an AWS product that allows the developers to send text messages and other communications (e.g., emails) to end users."
},
{
"code": null,
"e": 4603,
"s": 4424,
"text": "import boto3client = boto3.client( \"sns\", aws_access_key_id=\"\", # your aws access key aws_secret_access_key=\"\", # your aws secrete access key region_name=\"us-east-1\")"
},
{
"code": null,
"e": 4968,
"s": 4603,
"text": "To send your greeting to multiple phone numbers, you need to create a topic, which allows you to add subscribers to this topic. Each subscriber is specified by a phone number, which should also include the country code (e.g., +1 for US) — the E.164 formatting. Because we’re sending messages (i.e., short message service or sms), we specify the protocol to be sms."
},
{
"code": null,
"e": 5297,
"s": 4968,
"text": "topic = client.create_topic(Name=\"new_year\") # create a topictopic_arn = topic['TopicArn'] # get its Amazon Resource Name# Add SMS Subscribers to this topicphone_numbers = [\"+1234567890\"] for phone_number in phone_numbers: client.subscribe( TopicArn=topic_arn, Protocol='sms', Endpoint=phone_number )"
},
{
"code": null,
"e": 5563,
"s": 5297,
"text": "Once you have added the subscribers to the topic, you’re ready to publish a message to the topic. You just need to provide the message and specify the topic on which you want to publish this message. By doing that, all the subscribers will receive the text message."
},
{
"code": null,
"e": 5625,
"s": 5563,
"text": "client.publish(Message=\"Happy New Year!\", TopicArn=topic_arn)"
},
{
"code": null,
"e": 5844,
"s": 5625,
"text": "You can also choose to send text messages using the Twilio. Certainly, it requires a Twilio account, which is free to register, similar to an AWS account. Once you create a Twilio account, we’re ready to play the game!"
},
{
"code": null,
"e": 6019,
"s": 5844,
"text": "Run the command pip install twilio to install the Twilio module, which will give you access to various functionalities provided by Twilio. Text messaging is just one of them."
},
{
"code": null,
"e": 6194,
"s": 6019,
"text": "The Cilent method will be used to create a Twilio client by taking your Twilio account SID and AUTH Token, both of which can be found on the dashboard of your Twilio account."
},
{
"code": null,
"e": 6307,
"s": 6194,
"text": "from twilio.rest import Clientclient = Client( \"\", # your Twilio Account SID \"\", # your Twilio AUTH token)"
},
{
"code": null,
"e": 6495,
"s": 6307,
"text": "You create a list of all the phone numbers to which you’ll send your new year greetings. Again, be noted that the phone number is using the E.164 formatting similar to the use of AWS SNS."
},
{
"code": null,
"e": 6828,
"s": 6495,
"text": "One catch is that with free Twilio account, you can only send text messages to you verified phone numbers, giving you less flexibility compared to AWS SNS. However, you can upgrade your Twilio account, which will give you an option of sending to multiple phone numbers of your choice at very low cost (less than 1 cent per message)."
},
{
"code": null,
"e": 7091,
"s": 6828,
"text": "phone_numbers = [\"+1234567890\", \"+1234567891\"] # the list of phone numbers to receive the messagesfor phone_number in phone_numbers: client.messages.create( to=phone_number, from_=\"\", # your Twilio phone number body=\"Happy New Year!\" )"
},
{
"code": null,
"e": 7284,
"s": 7091,
"text": "By following this tutorial, you should have created multiple python scripts for each of these jobs. In the future, you can use these scripts to send emails and text messages very conveniently."
}
]
|
Excel Addition Operator | Addition uses the + symbol in Excel, and is also known as plus.
There are two ways to do addition in Excel. Either by using the + symbol in a formula or by using the SUM function.
How to add cells:
Select a cell and type (=)
Select a cell
Type (+)
Select another cell
Hit enter
Select a cell and type (=)
Select a cell
Type (+)
Select another cell
Hit enter
You can add more cells to the formula by typing (+) between the cells.
Let's have a look at some examples.
Type A1(=)
Type 5+5
Hit enter
Congratulations! You have successfully added 5+5=10.
First let's add some numbers to work with. Type the following values:
How to do it, step by step:
Type B1(=)
Select A1
Type (+)
Select A2
Hit enter
Type B1(=)
Select A1
Type (+)
Select A2
Hit enter
Great! 30 is the result by adding A1 and A2.
First let's add some numbers to work with. Type the following values:
Step by step to add several cells:
Type B1(=)
Select A1
Type (+)
Select A2
Type (+)
Select A3
Type (+)
Select A4
Type (+)
Select A5
Hit enter
Type B1(=)
Select A1
Type (+)
Select A2
Type (+)
Select A3
Type (+)
Select A4
Type (+)
Select A5
Hit enter
Good job! You have successfully added five cells!
Let's keep the numbers from the last exercise. If you did last exercise, remove the value in B1.
Step by step to add with SUM:
Type B1(=SUM)
Double click the SUM command
Mark the range A1:A5
Hit enter
Type B1(=SUM)
Double click the SUM command
Mark the range A1:A5
Hit enter
Note: SUM saves you time! Keep practicing this function.
You can also lock a cell and add it to other cells.
How to do it, step by step:
Select a cell and type (=)
Select the cell you want to lock, add two dollar signs ($) before the column and row
Type (+)
Fill a range
Select a cell and type (=)
Select the cell you want to lock, add two dollar signs ($) before the column and row
Type (+)
Fill a range
Let's have a look at an example where we add B(5) to the range A1:A10 using absolute reference and the fill function.
Type the values:
Step by step:
Type C1(=)
Select B1
Type dollar sign before column and row $B$1
Type (+)
Select A1
Hit enter
Fill the range C1:C10
Type C1(=)
Select B1
Type dollar sign before column and row $B$1
Type (+)
Select A1
Hit enter
Fill the range C1:C10
Great! You have successfully used absolute reference to add B1(5) with the range A1:A10.
Type the symbol that Excel uses for addition:
Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your message has been sent to W3Schools. | [
{
"code": null,
"e": 64,
"s": 0,
"text": "Addition uses the + symbol in Excel, and is also known as plus."
},
{
"code": null,
"e": 180,
"s": 64,
"text": "There are two ways to do addition in Excel. Either by using the + symbol in a formula or by using the SUM function."
},
{
"code": null,
"e": 198,
"s": 180,
"text": "How to add cells:"
},
{
"code": null,
"e": 280,
"s": 198,
"text": "\nSelect a cell and type (=)\nSelect a cell\nType (+)\nSelect another cell\nHit enter\n"
},
{
"code": null,
"e": 307,
"s": 280,
"text": "Select a cell and type (=)"
},
{
"code": null,
"e": 321,
"s": 307,
"text": "Select a cell"
},
{
"code": null,
"e": 330,
"s": 321,
"text": "Type (+)"
},
{
"code": null,
"e": 350,
"s": 330,
"text": "Select another cell"
},
{
"code": null,
"e": 360,
"s": 350,
"text": "Hit enter"
},
{
"code": null,
"e": 431,
"s": 360,
"text": "You can add more cells to the formula by typing (+) between the cells."
},
{
"code": null,
"e": 468,
"s": 431,
"text": "Let's have a look at some examples. "
},
{
"code": null,
"e": 479,
"s": 468,
"text": "Type A1(=)"
},
{
"code": null,
"e": 488,
"s": 479,
"text": "Type 5+5"
},
{
"code": null,
"e": 498,
"s": 488,
"text": "Hit enter"
},
{
"code": null,
"e": 551,
"s": 498,
"text": "Congratulations! You have successfully added 5+5=10."
},
{
"code": null,
"e": 621,
"s": 551,
"text": "First let's add some numbers to work with. Type the following values:"
},
{
"code": null,
"e": 649,
"s": 621,
"text": "How to do it, step by step:"
},
{
"code": null,
"e": 701,
"s": 649,
"text": "\nType B1(=)\nSelect A1\nType (+)\nSelect A2\nHit enter\n"
},
{
"code": null,
"e": 712,
"s": 701,
"text": "Type B1(=)"
},
{
"code": null,
"e": 722,
"s": 712,
"text": "Select A1"
},
{
"code": null,
"e": 731,
"s": 722,
"text": "Type (+)"
},
{
"code": null,
"e": 741,
"s": 731,
"text": "Select A2"
},
{
"code": null,
"e": 751,
"s": 741,
"text": "Hit enter"
},
{
"code": null,
"e": 796,
"s": 751,
"text": "Great! 30 is the result by adding A1 and A2."
},
{
"code": null,
"e": 867,
"s": 796,
"text": "First let's add some numbers to work with. Type the following values:"
},
{
"code": null,
"e": 902,
"s": 867,
"text": "Step by step to add several cells:"
},
{
"code": null,
"e": 1011,
"s": 902,
"text": "\nType B1(=)\nSelect A1\nType (+)\nSelect A2\nType (+)\nSelect A3\nType (+)\nSelect A4\nType (+)\nSelect A5\nHit enter\n"
},
{
"code": null,
"e": 1022,
"s": 1011,
"text": "Type B1(=)"
},
{
"code": null,
"e": 1032,
"s": 1022,
"text": "Select A1"
},
{
"code": null,
"e": 1041,
"s": 1032,
"text": "Type (+)"
},
{
"code": null,
"e": 1051,
"s": 1041,
"text": "Select A2"
},
{
"code": null,
"e": 1060,
"s": 1051,
"text": "Type (+)"
},
{
"code": null,
"e": 1070,
"s": 1060,
"text": "Select A3"
},
{
"code": null,
"e": 1079,
"s": 1070,
"text": "Type (+)"
},
{
"code": null,
"e": 1089,
"s": 1079,
"text": "Select A4"
},
{
"code": null,
"e": 1098,
"s": 1089,
"text": "Type (+)"
},
{
"code": null,
"e": 1108,
"s": 1098,
"text": "Select A5"
},
{
"code": null,
"e": 1118,
"s": 1108,
"text": "Hit enter"
},
{
"code": null,
"e": 1168,
"s": 1118,
"text": "Good job! You have successfully added five cells!"
},
{
"code": null,
"e": 1266,
"s": 1168,
"text": "Let's keep the numbers from the last exercise. If you did last exercise, remove the value in B1. "
},
{
"code": null,
"e": 1296,
"s": 1266,
"text": "Step by step to add with SUM:"
},
{
"code": null,
"e": 1372,
"s": 1296,
"text": "\nType B1(=SUM)\nDouble click the SUM command\nMark the range A1:A5\nHit enter\n"
},
{
"code": null,
"e": 1386,
"s": 1372,
"text": "Type B1(=SUM)"
},
{
"code": null,
"e": 1415,
"s": 1386,
"text": "Double click the SUM command"
},
{
"code": null,
"e": 1436,
"s": 1415,
"text": "Mark the range A1:A5"
},
{
"code": null,
"e": 1446,
"s": 1436,
"text": "Hit enter"
},
{
"code": null,
"e": 1503,
"s": 1446,
"text": "Note: SUM saves you time! Keep practicing this function."
},
{
"code": null,
"e": 1555,
"s": 1503,
"text": "You can also lock a cell and add it to other cells."
},
{
"code": null,
"e": 1583,
"s": 1555,
"text": "How to do it, step by step:"
},
{
"code": null,
"e": 1719,
"s": 1583,
"text": "\nSelect a cell and type (=)\nSelect the cell you want to lock, add two dollar signs ($) before the column and row\nType (+)\nFill a range\n"
},
{
"code": null,
"e": 1746,
"s": 1719,
"text": "Select a cell and type (=)"
},
{
"code": null,
"e": 1831,
"s": 1746,
"text": "Select the cell you want to lock, add two dollar signs ($) before the column and row"
},
{
"code": null,
"e": 1840,
"s": 1831,
"text": "Type (+)"
},
{
"code": null,
"e": 1853,
"s": 1840,
"text": "Fill a range"
},
{
"code": null,
"e": 1971,
"s": 1853,
"text": "Let's have a look at an example where we add B(5) to the range A1:A10 using absolute reference and the fill function."
},
{
"code": null,
"e": 1988,
"s": 1971,
"text": "Type the values:"
},
{
"code": null,
"e": 2002,
"s": 1988,
"text": "Step by step:"
},
{
"code": null,
"e": 2120,
"s": 2002,
"text": "\nType C1(=)\nSelect B1\nType dollar sign before column and row $B$1\nType (+)\nSelect A1\nHit enter\nFill the range C1:C10\n"
},
{
"code": null,
"e": 2131,
"s": 2120,
"text": "Type C1(=)"
},
{
"code": null,
"e": 2141,
"s": 2131,
"text": "Select B1"
},
{
"code": null,
"e": 2185,
"s": 2141,
"text": "Type dollar sign before column and row $B$1"
},
{
"code": null,
"e": 2194,
"s": 2185,
"text": "Type (+)"
},
{
"code": null,
"e": 2204,
"s": 2194,
"text": "Select A1"
},
{
"code": null,
"e": 2214,
"s": 2204,
"text": "Hit enter"
},
{
"code": null,
"e": 2236,
"s": 2214,
"text": "Fill the range C1:C10"
},
{
"code": null,
"e": 2325,
"s": 2236,
"text": "Great! You have successfully used absolute reference to add B1(5) with the range A1:A10."
},
{
"code": null,
"e": 2371,
"s": 2325,
"text": "Type the symbol that Excel uses for addition:"
},
{
"code": null,
"e": 2392,
"s": 2373,
"text": "Start the Exercise"
},
{
"code": null,
"e": 2425,
"s": 2392,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 2467,
"s": 2425,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 2574,
"s": 2467,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 2593,
"s": 2574,
"text": "[email protected]"
}
]
|
How to remove a class name from an element with JavaScript? | To remove a class name from an element with JavaScript, the code is as follows −
Live Demo
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
.newStyle {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
width: 100%;
padding: 25px;
background-color: rgb(147, 80, 255);
color: white;
font-size: 25px;
box-sizing: border-box;
text-align: center;
}
</style>
</head>
<body>
<h1>Remove className with JavaScript Example</h1>
<button class="btn">Remove Class</button>
<h2>Click the above button to remove className from below div</h2>
<div class="newStyle" id="sampleDiv">
This is a DIV element.
</div>
<script>
document.querySelector(".btn").addEventListener("click", addClassName);
function addClassName() {
var element = document.getElementById("sampleDiv");
element.classList.remove("newStyle");
}
</script>
</body>
</html>
The above code will produce the following output −
On clicking the the “Remove Class” button − | [
{
"code": null,
"e": 1143,
"s": 1062,
"text": "To remove a class name from an element with JavaScript, the code is as follows −"
},
{
"code": null,
"e": 1154,
"s": 1143,
"text": " Live Demo"
},
{
"code": null,
"e": 2030,
"s": 1154,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n<style>\n .newStyle {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n width: 100%;\n padding: 25px;\n background-color: rgb(147, 80, 255);\n color: white;\n font-size: 25px;\n box-sizing: border-box;\n text-align: center;\n }\n</style>\n</head>\n<body>\n<h1>Remove className with JavaScript Example</h1>\n<button class=\"btn\">Remove Class</button>\n<h2>Click the above button to remove className from below div</h2>\n<div class=\"newStyle\" id=\"sampleDiv\">\nThis is a DIV element.\n</div>\n<script>\n document.querySelector(\".btn\").addEventListener(\"click\", addClassName);\n function addClassName() {\n var element = document.getElementById(\"sampleDiv\");\n element.classList.remove(\"newStyle\");\n }\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2081,
"s": 2030,
"text": "The above code will produce the following output −"
},
{
"code": null,
"e": 2125,
"s": 2081,
"text": "On clicking the the “Remove Class” button −"
}
]
|
Find the compatibility difference between two arrays in C++ | Consider there are two friends and now they want to test their bonding. So they will check, how much compatible they are. Given the numbers n, numbered from 1..n. And they are asked to rank the numbers. They have to find the compatibility difference between them. The compatibility difference is basically the number of mismatches in the relative ranking of the same movie given by them. So if A = [3, 1, 2, 4, 5], and B = [3, 2, 4, 1, 5], then the output will be 2. The compatibility difference is 2, as first ranks movie 1 before 2 and 4, but other ranks it after.
To solve this, we will traverse both arrays, when the current elements are same, then do nothing. Then find the next position of A and B, let the position be j, one by one move B[j] to B[i]
Live Demo
#include<iostream>
using namespace std;
int getArrayDiff(int A[], int B[], int n) {
int result = 0;
for (int i = 0; i < n; i++) {
if (A[i] != B[i]) {
int j = i + 1;
while (A[i] != B[j])
j++;
while (j != i) {
swap(B[j], B[j - 1]);
j--;
result++;
}
}
}
return result;
}
int main() {
int A[] = { 3, 1, 2, 4, 5 };
int B[] = { 3, 2, 4, 1, 5 };
int n = sizeof(A)/sizeof(A[0]);
cout << "Compatibility difference: " << getArrayDiff(A, B, n);
}
Compatibility difference: 2 | [
{
"code": null,
"e": 1629,
"s": 1062,
"text": "Consider there are two friends and now they want to test their bonding. So they will check, how much compatible they are. Given the numbers n, numbered from 1..n. And they are asked to rank the numbers. They have to find the compatibility difference between them. The compatibility difference is basically the number of mismatches in the relative ranking of the same movie given by them. So if A = [3, 1, 2, 4, 5], and B = [3, 2, 4, 1, 5], then the output will be 2. The compatibility difference is 2, as first ranks movie 1 before 2 and 4, but other ranks it after."
},
{
"code": null,
"e": 1819,
"s": 1629,
"text": "To solve this, we will traverse both arrays, when the current elements are same, then do nothing. Then find the next position of A and B, let the position be j, one by one move B[j] to B[i]"
},
{
"code": null,
"e": 1830,
"s": 1819,
"text": " Live Demo"
},
{
"code": null,
"e": 2396,
"s": 1830,
"text": "#include<iostream>\nusing namespace std;\n\nint getArrayDiff(int A[], int B[], int n) {\n int result = 0;\n\n for (int i = 0; i < n; i++) {\n if (A[i] != B[i]) {\n\n int j = i + 1;\n while (A[i] != B[j]) \n j++;\n\n while (j != i) {\n swap(B[j], B[j - 1]);\n j--;\n result++;\n }\n }\n }\n return result;\n}\n\nint main() {\n int A[] = { 3, 1, 2, 4, 5 };\n int B[] = { 3, 2, 4, 1, 5 };\n int n = sizeof(A)/sizeof(A[0]);\n\n cout << \"Compatibility difference: \" << getArrayDiff(A, B, n);\n}\n"
},
{
"code": null,
"e": 2424,
"s": 2396,
"text": "Compatibility difference: 2"
}
]
|
GATE | GATE-CS-2016 (Set 1) | Question 43 - GeeksforGeeks | 19 Nov, 2018
Consider a carry lookahead adder for adding two n-bit integers, built using gates of fan-in at most two. The time to perform addition using this adder is(A) Θ(1)(B) Θ(Log (n))(C) Θ(√ n)(D) Θ(n)Answer: (B)Explanation: Look ahead carry generator gives output in constant time if fan-in = number of inputs.
For Example:
It will take O(1) to calculate
c4 = g3 + p3g2 + p3p2g1 + p3p2p1g0 + p3p2p1p0c0c4
= g3 + p3g2 + p3p2g1 + p3p2p1g0 + p3p2p1p0c0,
if OR gate with 5 inputs is present.
And, if fan-in != number of inputs then we will have delay in each level, as given below.
If we have 8 inputs, and OR gate with 2 inputs, to build an OR gate with 8 inputs, we will need 4 gates in level-1, 2 in level-2 and 1 in level-3. Hence 3 gate delays, for each level.
Similarly an n-input gate constructed with 2-input gates, total delay will be O(log n).
// This Explanation has been provided by Saksham Raj Seth.Quiz of this Question
GATE-CS-2016 (Set 1)
GATE-GATE-CS-2016 (Set 1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-IT-2004 | Question 71
GATE | GATE CS 2011 | Question 7
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2016 (Set 2) | Question 61
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE CS 2010 | Question 24
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE CS 2018 | Question 37
GATE | GATE-IT-2004 | Question 83 | [
{
"code": null,
"e": 24414,
"s": 24386,
"text": "\n19 Nov, 2018"
},
{
"code": null,
"e": 24718,
"s": 24414,
"text": "Consider a carry lookahead adder for adding two n-bit integers, built using gates of fan-in at most two. The time to perform addition using this adder is(A) Θ(1)(B) Θ(Log (n))(C) Θ(√ n)(D) Θ(n)Answer: (B)Explanation: Look ahead carry generator gives output in constant time if fan-in = number of inputs."
},
{
"code": null,
"e": 24731,
"s": 24718,
"text": "For Example:"
},
{
"code": null,
"e": 24916,
"s": 24731,
"text": "It will take O(1) to calculate \nc4 = g3 + p3g2 + p3p2g1 + p3p2p1g0 + p3p2p1p0c0c4 \n = g3 + p3g2 + p3p2g1 + p3p2p1g0 + p3p2p1p0c0, \n if OR gate with 5 inputs is present.\n"
},
{
"code": null,
"e": 25006,
"s": 24916,
"text": "And, if fan-in != number of inputs then we will have delay in each level, as given below."
},
{
"code": null,
"e": 25190,
"s": 25006,
"text": "If we have 8 inputs, and OR gate with 2 inputs, to build an OR gate with 8 inputs, we will need 4 gates in level-1, 2 in level-2 and 1 in level-3. Hence 3 gate delays, for each level."
},
{
"code": null,
"e": 25278,
"s": 25190,
"text": "Similarly an n-input gate constructed with 2-input gates, total delay will be O(log n)."
},
{
"code": null,
"e": 25358,
"s": 25278,
"text": "// This Explanation has been provided by Saksham Raj Seth.Quiz of this Question"
},
{
"code": null,
"e": 25379,
"s": 25358,
"text": "GATE-CS-2016 (Set 1)"
},
{
"code": null,
"e": 25405,
"s": 25379,
"text": "GATE-GATE-CS-2016 (Set 1)"
},
{
"code": null,
"e": 25410,
"s": 25405,
"text": "GATE"
},
{
"code": null,
"e": 25508,
"s": 25410,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25517,
"s": 25508,
"text": "Comments"
},
{
"code": null,
"e": 25530,
"s": 25517,
"text": "Old Comments"
},
{
"code": null,
"e": 25564,
"s": 25530,
"text": "GATE | GATE-IT-2004 | Question 71"
},
{
"code": null,
"e": 25597,
"s": 25564,
"text": "GATE | GATE CS 2011 | Question 7"
},
{
"code": null,
"e": 25639,
"s": 25597,
"text": "GATE | GATE-CS-2016 (Set 2) | Question 48"
},
{
"code": null,
"e": 25681,
"s": 25639,
"text": "GATE | GATE-CS-2016 (Set 2) | Question 61"
},
{
"code": null,
"e": 25723,
"s": 25681,
"text": "GATE | GATE-CS-2015 (Set 3) | Question 65"
},
{
"code": null,
"e": 25757,
"s": 25723,
"text": "GATE | GATE CS 2010 | Question 24"
},
{
"code": null,
"e": 25799,
"s": 25757,
"text": "GATE | GATE-CS-2016 (Set 1) | Question 65"
},
{
"code": null,
"e": 25841,
"s": 25799,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 38"
},
{
"code": null,
"e": 25875,
"s": 25841,
"text": "GATE | GATE CS 2018 | Question 37"
}
]
|
Check if strings are rotations of each other or not | Practice | GeeksforGeeks | Given two strings s1 and s2. The task is to check if s2 is a rotated version of the string s1. The characters in the strings are in lowercase.
Example 1:
Input:
geeksforgeeks
forgeeksgeeks
Output:
1
Explanation: s1 is geeksforgeeks, s2 is
forgeeksgeeks. Clearly, s2 is a rotated
version of s1 as s2 can be obtained by
left-rotating s1 by 5 units.
Example 2:
Input:
mightandmagic
andmagicmigth
Output:
0
Explanation: Here with any amount of
rotation s2 can't be obtained by s1.
Your Task:
The task is to complete the function areRotations() which checks if the two strings are rotations of each other. The function returns true if string 1 can be obtained by rotating string 2, else it returns false.
Expected Time Complexity: O(N).
Expected Space Complexity: O(N).
Note: N = |s1|.
Constraints:
1 <= |s1|, |s2| <= 107
0
shresthjaiswal13 days ago
Java Solution
Test Cases Passed:
1011 / 1011
Total Time Taken:
0.45/1.6
public static boolean areRotations(String s1, String s2 ) { // Your code here if(s1.length() != s2.length()) return false; if((s1+s1).contains(s2)) return true; return false; }
+2
sharvilpatil135 days ago
JAVA CODE
class Solution{ //Function to check if two strings are rotations of each other or not. public static boolean areRotations(String s1, String s2 ) { if(s1.length()!=s2.length()) return false; if(s1.equals(s2)) return true; s1 = s1+s1; int l = s2.length(); for(int i=0; i<s1.length()-l; i++) { if(s1.substring(i, i+l).equals(s2)) return true; } return false; } }
0
nitishmishra9371 week ago
//Probably a lengthy code
class Solution{ //Function to check if two strings are rotations of each other or not. public static boolean checkForIndex(String s1, String s2, int currentIndex) { int s1Index = -1; for(int j = 0; j < s1.length(); ++j) { if(s2.charAt(currentIndex) == s1.charAt(j)) { s1Index = j; break; } }
if(s1Index == -1) { return false; } int count = 0; for(int i = s1Index, j = currentIndex; count < s1.length(); ++i, ++j, ++count) { if(s1.charAt(i) != s2.charAt(j)) { return false; } if(i == s1.length() - 1) { i = -1; } if(j == s2.length() - 1) { j = -1; } } return true; } public static boolean areRotations(String s1, String s2 ) { // Your code here if(s1.length() != s2.length()) { return false; } for(int i = 0; i < s2.length(); ++i) { if(checkForIndex(s1, s2, i)) { return true; } } return false; } }
+2
visionsameer391 week ago
IN PYTHON :
simplest ways:
class Solution: #Function to check if two strings are rotations of each other or not. def areRotations(self,s1,s2): if len(s1)!=len(s2): #firstly check both string length equal or not if not return false return False s3=s1+s1 # thats logic merge s1 twice time then assing s3 if s2 in s3: check if s2 in s3 if s2 in s3 return T else Return F return True else: return False#code here
+2
avi1221861 week ago
public static boolean areRotations(String s1, String s2 )
{
if(s1.length() != s2.length()){
return false;
}
String s = s1 +s1;
return s.contains(s2);
}
0
krtikeytiwari122 weeks ago
JAVA SOLUTION O(N) TIME COMPLEXITY AND O(1) SPACE COMPLEXITY!
class Solution{ public static boolean areRotations(String s1, String s2 ) { boolean res = false; if(s1.length()!=s2.length()) return false; if(s1.equals(s2)){ res = true; } for(int i=1 ; i<s1.length() ; i++){ String s = s1.substring(i,s1.length()) + s1.substring(0,i); if(s.equals(s2)) { res = true; break; } } return res; }}
0
eternalclumsee3 weeks ago
#iterate in s1for i in s1:#checking if s1 has become same as s2 if s1==s2: return 1#creating 'new' variable which stores s1[0] new=s1[0]
#s1[0] is sliced(khachaaak) s1=s1[1:]#(new aka previous s1[0]) is added at the end of s1 s1=s1+new
return 0
+2
solankiabhay9161 month ago
bool areRotations(string s1,string s2) { // Your code here int l1=s1.length(); int l2=s2.length(); if(l1!=l2) return false; else { string temp=s1+s1; if(temp.find(s2)!=string::npos) return true; } return false; }
-1
ashwinaditya211 month ago
Java Solution in O(N) time and O(1) space complexity.
Take two ref x and y. Keep incrementing the y till charAt(x)==charAt(y) for both the strings and keep count in matchCount variable. if matchCount reaches the value of length of the strings, then return true.
If you have check the length of the strings thrice in this way, break out of the loop and return false.
class Solution
{
//Function to check if two strings are rotations of each other or not.
public static boolean areRotations(String s1, String s2 )
{
// Your code here
int length = s1.length();
if(length != s2.length()) {
return false;
}
int x = 0;
int y = 0;
int matchCount = 0;
int loopCount = 0;
while(true) {
loopCount++;
if(loopCount > (3*length)) {
break;
}
if(matchCount == length) {
return true;
}
if(s1.charAt(x) == s2.charAt(y)) {
matchCount++;
} else {
y++;
if(y==length) y=0;
matchCount = 0;
continue;
}
x++;
y++;
if(x==length) x=0;
if(y==length) y=0;
}
return false;
}
}
+2
mohammadtanveer75401 month ago
class Solution
{
public:
bool areRotations(string s1,string s2)
{
for(int i=0;i<s1.size();i++)
{
if(s1==s2)
return true;
char c = s1[0];
s1.erase(0,1);
s1=s1+c;
}
return false;
}
};
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": 369,
"s": 226,
"text": "Given two strings s1 and s2. The task is to check if s2 is a rotated version of the string s1. The characters in the strings are in lowercase."
},
{
"code": null,
"e": 382,
"s": 371,
"text": "Example 1:"
},
{
"code": null,
"e": 577,
"s": 382,
"text": "Input:\ngeeksforgeeks\nforgeeksgeeks\nOutput: \n1\nExplanation: s1 is geeksforgeeks, s2 is\nforgeeksgeeks. Clearly, s2 is a rotated\nversion of s1 as s2 can be obtained by\nleft-rotating s1 by 5 units.\n"
},
{
"code": null,
"e": 590,
"s": 579,
"text": "Example 2:"
},
{
"code": null,
"e": 710,
"s": 590,
"text": "Input:\nmightandmagic\nandmagicmigth\nOutput: \n0\nExplanation: Here with any amount of\nrotation s2 can't be obtained by s1."
},
{
"code": null,
"e": 935,
"s": 712,
"text": "Your Task:\nThe task is to complete the function areRotations() which checks if the two strings are rotations of each other. The function returns true if string 1 can be obtained by rotating string 2, else it returns false."
},
{
"code": null,
"e": 1018,
"s": 937,
"text": "Expected Time Complexity: O(N).\nExpected Space Complexity: O(N).\nNote: N = |s1|."
},
{
"code": null,
"e": 1056,
"s": 1020,
"text": "Constraints:\n1 <= |s1|, |s2| <= 107"
},
{
"code": null,
"e": 1058,
"s": 1056,
"text": "0"
},
{
"code": null,
"e": 1084,
"s": 1058,
"text": "shresthjaiswal13 days ago"
},
{
"code": null,
"e": 1098,
"s": 1084,
"text": "Java Solution"
},
{
"code": null,
"e": 1117,
"s": 1098,
"text": "Test Cases Passed:"
},
{
"code": null,
"e": 1129,
"s": 1117,
"text": "1011 / 1011"
},
{
"code": null,
"e": 1147,
"s": 1129,
"text": "Total Time Taken:"
},
{
"code": null,
"e": 1156,
"s": 1147,
"text": "0.45/1.6"
},
{
"code": null,
"e": 1406,
"s": 1156,
"text": "public static boolean areRotations(String s1, String s2 ) { // Your code here if(s1.length() != s2.length()) return false; if((s1+s1).contains(s2)) return true; return false; }"
},
{
"code": null,
"e": 1409,
"s": 1406,
"text": "+2"
},
{
"code": null,
"e": 1434,
"s": 1409,
"text": "sharvilpatil135 days ago"
},
{
"code": null,
"e": 1444,
"s": 1434,
"text": "JAVA CODE"
},
{
"code": null,
"e": 1872,
"s": 1444,
"text": "class Solution{ //Function to check if two strings are rotations of each other or not. public static boolean areRotations(String s1, String s2 ) { if(s1.length()!=s2.length()) return false; if(s1.equals(s2)) return true; s1 = s1+s1; int l = s2.length(); for(int i=0; i<s1.length()-l; i++) { if(s1.substring(i, i+l).equals(s2)) return true; } return false; } }"
},
{
"code": null,
"e": 1874,
"s": 1872,
"text": "0"
},
{
"code": null,
"e": 1900,
"s": 1874,
"text": "nitishmishra9371 week ago"
},
{
"code": null,
"e": 1926,
"s": 1900,
"text": "//Probably a lengthy code"
},
{
"code": null,
"e": 2293,
"s": 1928,
"text": "class Solution{ //Function to check if two strings are rotations of each other or not. public static boolean checkForIndex(String s1, String s2, int currentIndex) { int s1Index = -1; for(int j = 0; j < s1.length(); ++j) { if(s2.charAt(currentIndex) == s1.charAt(j)) { s1Index = j; break; } }"
},
{
"code": null,
"e": 3062,
"s": 2293,
"text": " if(s1Index == -1) { return false; } int count = 0; for(int i = s1Index, j = currentIndex; count < s1.length(); ++i, ++j, ++count) { if(s1.charAt(i) != s2.charAt(j)) { return false; } if(i == s1.length() - 1) { i = -1; } if(j == s2.length() - 1) { j = -1; } } return true; } public static boolean areRotations(String s1, String s2 ) { // Your code here if(s1.length() != s2.length()) { return false; } for(int i = 0; i < s2.length(); ++i) { if(checkForIndex(s1, s2, i)) { return true; } } return false; } }"
},
{
"code": null,
"e": 3065,
"s": 3062,
"text": "+2"
},
{
"code": null,
"e": 3090,
"s": 3065,
"text": "visionsameer391 week ago"
},
{
"code": null,
"e": 3102,
"s": 3090,
"text": "IN PYTHON :"
},
{
"code": null,
"e": 3117,
"s": 3102,
"text": "simplest ways:"
},
{
"code": null,
"e": 3676,
"s": 3117,
"text": " class Solution: #Function to check if two strings are rotations of each other or not. def areRotations(self,s1,s2): if len(s1)!=len(s2): #firstly check both string length equal or not if not return false return False s3=s1+s1 # thats logic merge s1 twice time then assing s3 if s2 in s3: check if s2 in s3 if s2 in s3 return T else Return F return True else: return False#code here"
},
{
"code": null,
"e": 3679,
"s": 3676,
"text": "+2"
},
{
"code": null,
"e": 3699,
"s": 3679,
"text": "avi1221861 week ago"
},
{
"code": null,
"e": 3896,
"s": 3699,
"text": "public static boolean areRotations(String s1, String s2 )\n {\n if(s1.length() != s2.length()){\n return false;\n }\n String s = s1 +s1;\n return s.contains(s2);\n }"
},
{
"code": null,
"e": 3898,
"s": 3896,
"text": "0"
},
{
"code": null,
"e": 3925,
"s": 3898,
"text": "krtikeytiwari122 weeks ago"
},
{
"code": null,
"e": 3987,
"s": 3925,
"text": "JAVA SOLUTION O(N) TIME COMPLEXITY AND O(1) SPACE COMPLEXITY!"
},
{
"code": null,
"e": 4429,
"s": 3987,
"text": "class Solution{ public static boolean areRotations(String s1, String s2 ) { boolean res = false; if(s1.length()!=s2.length()) return false; if(s1.equals(s2)){ res = true; } for(int i=1 ; i<s1.length() ; i++){ String s = s1.substring(i,s1.length()) + s1.substring(0,i); if(s.equals(s2)) { res = true; break; } } return res; }}"
},
{
"code": null,
"e": 4431,
"s": 4429,
"text": "0"
},
{
"code": null,
"e": 4457,
"s": 4431,
"text": "eternalclumsee3 weeks ago"
},
{
"code": null,
"e": 4601,
"s": 4457,
"text": "#iterate in s1for i in s1:#checking if s1 has become same as s2 if s1==s2: return 1#creating 'new' variable which stores s1[0] new=s1[0]"
},
{
"code": null,
"e": 4702,
"s": 4601,
"text": "#s1[0] is sliced(khachaaak) s1=s1[1:]#(new aka previous s1[0]) is added at the end of s1 s1=s1+new"
},
{
"code": null,
"e": 4711,
"s": 4702,
"text": "return 0"
},
{
"code": null,
"e": 4714,
"s": 4711,
"text": "+2"
},
{
"code": null,
"e": 4741,
"s": 4714,
"text": "solankiabhay9161 month ago"
},
{
"code": null,
"e": 5042,
"s": 4741,
"text": "bool areRotations(string s1,string s2) { // Your code here int l1=s1.length(); int l2=s2.length(); if(l1!=l2) return false; else { string temp=s1+s1; if(temp.find(s2)!=string::npos) return true; } return false; }"
},
{
"code": null,
"e": 5045,
"s": 5042,
"text": "-1"
},
{
"code": null,
"e": 5071,
"s": 5045,
"text": "ashwinaditya211 month ago"
},
{
"code": null,
"e": 5125,
"s": 5071,
"text": "Java Solution in O(N) time and O(1) space complexity."
},
{
"code": null,
"e": 5333,
"s": 5125,
"text": "Take two ref x and y. Keep incrementing the y till charAt(x)==charAt(y) for both the strings and keep count in matchCount variable. if matchCount reaches the value of length of the strings, then return true."
},
{
"code": null,
"e": 5437,
"s": 5333,
"text": "If you have check the length of the strings thrice in this way, break out of the loop and return false."
},
{
"code": null,
"e": 6416,
"s": 5439,
"text": "class Solution\n{\n //Function to check if two strings are rotations of each other or not.\n public static boolean areRotations(String s1, String s2 )\n {\n // Your code here\n int length = s1.length();\n if(length != s2.length()) {\n return false;\n }\n \n int x = 0;\n int y = 0;\n int matchCount = 0;\n int loopCount = 0;\n \n while(true) {\n loopCount++;\n if(loopCount > (3*length)) {\n break;\n }\n if(matchCount == length) {\n return true;\n }\n if(s1.charAt(x) == s2.charAt(y)) {\n matchCount++;\n } else {\n y++;\n if(y==length) y=0;\n matchCount = 0;\n continue;\n }\n x++;\n y++;\n if(x==length) x=0;\n if(y==length) y=0;\n }\n return false;\n }\n \n}"
},
{
"code": null,
"e": 6419,
"s": 6416,
"text": "+2"
},
{
"code": null,
"e": 6450,
"s": 6419,
"text": "mohammadtanveer75401 month ago"
},
{
"code": null,
"e": 6744,
"s": 6450,
"text": "class Solution\n{\n public:\n bool areRotations(string s1,string s2)\n {\n for(int i=0;i<s1.size();i++)\n {\n if(s1==s2)\n return true;\n char c = s1[0];\n s1.erase(0,1);\n s1=s1+c;\n }\n return false;\n }\n};"
},
{
"code": null,
"e": 6890,
"s": 6744,
"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": 6926,
"s": 6890,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 6936,
"s": 6926,
"text": "\nProblem\n"
},
{
"code": null,
"e": 6946,
"s": 6936,
"text": "\nContest\n"
},
{
"code": null,
"e": 7009,
"s": 6946,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 7157,
"s": 7009,
"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": 7365,
"s": 7157,
"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": 7471,
"s": 7365,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
]
|
Python Pandas - Categorical Data | Often in real-time, data includes the text columns, which are repetitive. Features like gender, country, and codes are always repetitive. These are the examples for categorical data.
Categorical variables can take on only a limited, and usually fixed number of possible values. Besides the fixed length, categorical data might have an order but cannot perform numerical operation. Categorical are a Pandas data type.
The categorical data type is useful in the following cases −
A string variable consisting of only a few different values. Converting such a string variable to a categorical variable will save some memory.
A string variable consisting of only a few different values. Converting such a string variable to a categorical variable will save some memory.
The lexical order of a variable is not the same as the logical order (“one”, “two”, “three”). By converting to a categorical and specifying an order on the categories, sorting and min/max will use the logical order instead of the lexical order.
The lexical order of a variable is not the same as the logical order (“one”, “two”, “three”). By converting to a categorical and specifying an order on the categories, sorting and min/max will use the logical order instead of the lexical order.
As a signal to other python libraries that this column should be treated as a categorical variable (e.g. to use suitable statistical methods or plot types).
As a signal to other python libraries that this column should be treated as a categorical variable (e.g. to use suitable statistical methods or plot types).
Categorical object can be created in multiple ways. The different ways have been described below −
By specifying the dtype as "category" in pandas object creation.
import pandas as pd
s = pd.Series(["a","b","c","a"], dtype="category")
print s
Its output is as follows −
0 a
1 b
2 c
3 a
dtype: category
Categories (3, object): [a, b, c]
The number of elements passed to the series object is four, but the categories are only three. Observe the same in the output Categories.
Using the standard pandas Categorical constructor, we can create a category object.
pandas.Categorical(values, categories, ordered)
Let’s take an example −
import pandas as pd
cat = pd.Categorical(['a', 'b', 'c', 'a', 'b', 'c'])
print cat
Its output is as follows −
[a, b, c, a, b, c]
Categories (3, object): [a, b, c]
Let’s have another example −
import pandas as pd
cat = cat=pd.Categorical(['a','b','c','a','b','c','d'], ['c', 'b', 'a'])
print cat
Its output is as follows −
[a, b, c, a, b, c, NaN]
Categories (3, object): [c, b, a]
Here, the second argument signifies the categories. Thus, any value which is not present in the categories will be treated as NaN.
Now, take a look at the following example −
import pandas as pd
cat = cat=pd.Categorical(['a','b','c','a','b','c','d'], ['c', 'b', 'a'],ordered=True)
print cat
Its output is as follows −
[a, b, c, a, b, c, NaN]
Categories (3, object): [c < b < a]
Logically, the order means that, a is greater than b and b is greater than c.
Using the .describe() command on the categorical data, we get similar output to a Series or DataFrame of the type string.
import pandas as pd
import numpy as np
cat = pd.Categorical(["a", "c", "c", np.nan], categories=["b", "a", "c"])
df = pd.DataFrame({"cat":cat, "s":["a", "c", "c", np.nan]})
print df.describe()
print df["cat"].describe()
Its output is as follows −
cat s
count 3 3
unique 2 2
top c c
freq 2 2
count 3
unique 2
top c
freq 2
Name: cat, dtype: object
obj.cat.categories command is used to get the categories of the object.
import pandas as pd
import numpy as np
s = pd.Categorical(["a", "c", "c", np.nan], categories=["b", "a", "c"])
print s.categories
Its output is as follows −
Index([u'b', u'a', u'c'], dtype='object')
obj.ordered command is used to get the order of the object.
import pandas as pd
import numpy as np
cat = pd.Categorical(["a", "c", "c", np.nan], categories=["b", "a", "c"])
print cat.ordered
Its output is as follows −
False
The function returned false because we haven't specified any order.
Renaming categories is done by assigning new values to the series.cat.categoriesseries.cat.categories property.
import pandas as pd
s = pd.Series(["a","b","c","a"], dtype="category")
s.cat.categories = ["Group %s" % g for g in s.cat.categories]
print s.cat.categories
Its output is as follows −
Index([u'Group a', u'Group b', u'Group c'], dtype='object')
Initial categories [a,b,c] are updated by the s.cat.categories property of the object.
Using the Categorical.add.categories() method, new categories can be appended.
import pandas as pd
s = pd.Series(["a","b","c","a"], dtype="category")
s = s.cat.add_categories([4])
print s.cat.categories
Its output is as follows −
Index([u'a', u'b', u'c', 4], dtype='object')
Using the Categorical.remove_categories() method, unwanted categories can be removed.
import pandas as pd
s = pd.Series(["a","b","c","a"], dtype="category")
print ("Original object:")
print s
print ("After removal:")
print s.cat.remove_categories("a")
Its output is as follows −
Original object:
0 a
1 b
2 c
3 a
dtype: category
Categories (3, object): [a, b, c]
After removal:
0 NaN
1 b
2 c
3 NaN
dtype: category
Categories (2, object): [b, c]
Comparing categorical data with other objects is possible in three cases −
comparing equality (== and !=) to a list-like object (list, Series, array, ...) of the
same length as the categorical data.
comparing equality (== and !=) to a list-like object (list, Series, array, ...) of the
same length as the categorical data.
all comparisons (==, !=, >, >=, <, and <=) of categorical data to another
categorical Series, when ordered==True and the categories are the same.
all comparisons (==, !=, >, >=, <, and <=) of categorical data to another
categorical Series, when ordered==True and the categories are the same.
all comparisons of a categorical data to a scalar.
all comparisons of a categorical data to a scalar.
Take a look at the following example −
import pandas as pd
cat = pd.Series([1,2,3]).astype("category", categories=[1,2,3], ordered=True)
cat1 = pd.Series([2,2,2]).astype("category", categories=[1,2,3], ordered=True)
print cat>cat1
Its output is as follows −
0 False
1 False
2 True
dtype: bool
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2626,
"s": 2443,
"text": "Often in real-time, data includes the text columns, which are repetitive. Features like gender, country, and codes are always repetitive. These are the examples for categorical data."
},
{
"code": null,
"e": 2860,
"s": 2626,
"text": "Categorical variables can take on only a limited, and usually fixed number of possible values. Besides the fixed length, categorical data might have an order but cannot perform numerical operation. Categorical are a Pandas data type."
},
{
"code": null,
"e": 2921,
"s": 2860,
"text": "The categorical data type is useful in the following cases −"
},
{
"code": null,
"e": 3065,
"s": 2921,
"text": "A string variable consisting of only a few different values. Converting such a string variable to a categorical variable will save some memory."
},
{
"code": null,
"e": 3209,
"s": 3065,
"text": "A string variable consisting of only a few different values. Converting such a string variable to a categorical variable will save some memory."
},
{
"code": null,
"e": 3454,
"s": 3209,
"text": "The lexical order of a variable is not the same as the logical order (“one”, “two”, “three”). By converting to a categorical and specifying an order on the categories, sorting and min/max will use the logical order instead of the lexical order."
},
{
"code": null,
"e": 3699,
"s": 3454,
"text": "The lexical order of a variable is not the same as the logical order (“one”, “two”, “three”). By converting to a categorical and specifying an order on the categories, sorting and min/max will use the logical order instead of the lexical order."
},
{
"code": null,
"e": 3856,
"s": 3699,
"text": "As a signal to other python libraries that this column should be treated as a categorical variable (e.g. to use suitable statistical methods or plot types)."
},
{
"code": null,
"e": 4013,
"s": 3856,
"text": "As a signal to other python libraries that this column should be treated as a categorical variable (e.g. to use suitable statistical methods or plot types)."
},
{
"code": null,
"e": 4112,
"s": 4013,
"text": "Categorical object can be created in multiple ways. The different ways have been described below −"
},
{
"code": null,
"e": 4177,
"s": 4112,
"text": "By specifying the dtype as \"category\" in pandas object creation."
},
{
"code": null,
"e": 4257,
"s": 4177,
"text": "import pandas as pd\n\ns = pd.Series([\"a\",\"b\",\"c\",\"a\"], dtype=\"category\")\nprint s"
},
{
"code": null,
"e": 4284,
"s": 4257,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 4355,
"s": 4284,
"text": "0 a\n1 b\n2 c\n3 a\ndtype: category\nCategories (3, object): [a, b, c]\n"
},
{
"code": null,
"e": 4493,
"s": 4355,
"text": "The number of elements passed to the series object is four, but the categories are only three. Observe the same in the output Categories."
},
{
"code": null,
"e": 4577,
"s": 4493,
"text": "Using the standard pandas Categorical constructor, we can create a category object."
},
{
"code": null,
"e": 4626,
"s": 4577,
"text": "pandas.Categorical(values, categories, ordered)\n"
},
{
"code": null,
"e": 4650,
"s": 4626,
"text": "Let’s take an example −"
},
{
"code": null,
"e": 4734,
"s": 4650,
"text": "import pandas as pd\n\ncat = pd.Categorical(['a', 'b', 'c', 'a', 'b', 'c'])\nprint cat"
},
{
"code": null,
"e": 4761,
"s": 4734,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 4815,
"s": 4761,
"text": "[a, b, c, a, b, c]\nCategories (3, object): [a, b, c]\n"
},
{
"code": null,
"e": 4844,
"s": 4815,
"text": "Let’s have another example −"
},
{
"code": null,
"e": 4948,
"s": 4844,
"text": "import pandas as pd\n\ncat = cat=pd.Categorical(['a','b','c','a','b','c','d'], ['c', 'b', 'a'])\nprint cat"
},
{
"code": null,
"e": 4975,
"s": 4948,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 5034,
"s": 4975,
"text": "[a, b, c, a, b, c, NaN]\nCategories (3, object): [c, b, a]\n"
},
{
"code": null,
"e": 5165,
"s": 5034,
"text": "Here, the second argument signifies the categories. Thus, any value which is not present in the categories will be treated as NaN."
},
{
"code": null,
"e": 5209,
"s": 5165,
"text": "Now, take a look at the following example −"
},
{
"code": null,
"e": 5326,
"s": 5209,
"text": "import pandas as pd\n\ncat = cat=pd.Categorical(['a','b','c','a','b','c','d'], ['c', 'b', 'a'],ordered=True)\nprint cat"
},
{
"code": null,
"e": 5353,
"s": 5326,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 5414,
"s": 5353,
"text": "[a, b, c, a, b, c, NaN]\nCategories (3, object): [c < b < a]\n"
},
{
"code": null,
"e": 5492,
"s": 5414,
"text": "Logically, the order means that, a is greater than b and b is greater than c."
},
{
"code": null,
"e": 5614,
"s": 5492,
"text": "Using the .describe() command on the categorical data, we get similar output to a Series or DataFrame of the type string."
},
{
"code": null,
"e": 5836,
"s": 5614,
"text": "import pandas as pd\nimport numpy as np\n\ncat = pd.Categorical([\"a\", \"c\", \"c\", np.nan], categories=[\"b\", \"a\", \"c\"])\ndf = pd.DataFrame({\"cat\":cat, \"s\":[\"a\", \"c\", \"c\", np.nan]})\n\nprint df.describe()\nprint df[\"cat\"].describe()"
},
{
"code": null,
"e": 5863,
"s": 5836,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 6002,
"s": 5863,
"text": " cat s\ncount 3 3\nunique 2 2\ntop c c\nfreq 2 2\ncount 3\nunique 2\ntop c\nfreq 2\nName: cat, dtype: object\n"
},
{
"code": null,
"e": 6074,
"s": 6002,
"text": "obj.cat.categories command is used to get the categories of the object."
},
{
"code": null,
"e": 6205,
"s": 6074,
"text": "import pandas as pd\nimport numpy as np\n\ns = pd.Categorical([\"a\", \"c\", \"c\", np.nan], categories=[\"b\", \"a\", \"c\"])\nprint s.categories"
},
{
"code": null,
"e": 6232,
"s": 6205,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 6275,
"s": 6232,
"text": "Index([u'b', u'a', u'c'], dtype='object')\n"
},
{
"code": null,
"e": 6335,
"s": 6275,
"text": "obj.ordered command is used to get the order of the object."
},
{
"code": null,
"e": 6467,
"s": 6335,
"text": "import pandas as pd\nimport numpy as np\n\ncat = pd.Categorical([\"a\", \"c\", \"c\", np.nan], categories=[\"b\", \"a\", \"c\"])\nprint cat.ordered"
},
{
"code": null,
"e": 6494,
"s": 6467,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 6501,
"s": 6494,
"text": "False\n"
},
{
"code": null,
"e": 6569,
"s": 6501,
"text": "The function returned false because we haven't specified any order."
},
{
"code": null,
"e": 6681,
"s": 6569,
"text": "Renaming categories is done by assigning new values to the series.cat.categoriesseries.cat.categories property."
},
{
"code": null,
"e": 6838,
"s": 6681,
"text": "import pandas as pd\n\ns = pd.Series([\"a\",\"b\",\"c\",\"a\"], dtype=\"category\")\ns.cat.categories = [\"Group %s\" % g for g in s.cat.categories]\nprint s.cat.categories"
},
{
"code": null,
"e": 6865,
"s": 6838,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 6926,
"s": 6865,
"text": "Index([u'Group a', u'Group b', u'Group c'], dtype='object')\n"
},
{
"code": null,
"e": 7013,
"s": 6926,
"text": "Initial categories [a,b,c] are updated by the s.cat.categories property of the object."
},
{
"code": null,
"e": 7092,
"s": 7013,
"text": "Using the Categorical.add.categories() method, new categories can be appended."
},
{
"code": null,
"e": 7217,
"s": 7092,
"text": "import pandas as pd\n\ns = pd.Series([\"a\",\"b\",\"c\",\"a\"], dtype=\"category\")\ns = s.cat.add_categories([4])\nprint s.cat.categories"
},
{
"code": null,
"e": 7244,
"s": 7217,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 7290,
"s": 7244,
"text": "Index([u'a', u'b', u'c', 4], dtype='object')\n"
},
{
"code": null,
"e": 7376,
"s": 7290,
"text": "Using the Categorical.remove_categories() method, unwanted categories can be removed."
},
{
"code": null,
"e": 7544,
"s": 7376,
"text": "import pandas as pd\n\ns = pd.Series([\"a\",\"b\",\"c\",\"a\"], dtype=\"category\")\nprint (\"Original object:\")\nprint s\n\nprint (\"After removal:\")\nprint s.cat.remove_categories(\"a\")"
},
{
"code": null,
"e": 7571,
"s": 7544,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 7746,
"s": 7571,
"text": "Original object:\n0 a\n1 b\n2 c\n3 a\ndtype: category\nCategories (3, object): [a, b, c]\n\nAfter removal:\n0 NaN\n1 b\n2 c\n3 NaN\ndtype: category\nCategories (2, object): [b, c]\n"
},
{
"code": null,
"e": 7821,
"s": 7746,
"text": "Comparing categorical data with other objects is possible in three cases −"
},
{
"code": null,
"e": 7945,
"s": 7821,
"text": "comparing equality (== and !=) to a list-like object (list, Series, array, ...) of the\nsame length as the categorical data."
},
{
"code": null,
"e": 8069,
"s": 7945,
"text": "comparing equality (== and !=) to a list-like object (list, Series, array, ...) of the\nsame length as the categorical data."
},
{
"code": null,
"e": 8215,
"s": 8069,
"text": "all comparisons (==, !=, >, >=, <, and <=) of categorical data to another\ncategorical Series, when ordered==True and the categories are the same."
},
{
"code": null,
"e": 8361,
"s": 8215,
"text": "all comparisons (==, !=, >, >=, <, and <=) of categorical data to another\ncategorical Series, when ordered==True and the categories are the same."
},
{
"code": null,
"e": 8412,
"s": 8361,
"text": "all comparisons of a categorical data to a scalar."
},
{
"code": null,
"e": 8463,
"s": 8412,
"text": "all comparisons of a categorical data to a scalar."
},
{
"code": null,
"e": 8502,
"s": 8463,
"text": "Take a look at the following example −"
},
{
"code": null,
"e": 8696,
"s": 8502,
"text": "import pandas as pd\n\ncat = pd.Series([1,2,3]).astype(\"category\", categories=[1,2,3], ordered=True)\ncat1 = pd.Series([2,2,2]).astype(\"category\", categories=[1,2,3], ordered=True)\n\nprint cat>cat1"
},
{
"code": null,
"e": 8723,
"s": 8696,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 8762,
"s": 8723,
"text": "0 False\n1 False\n2 True\ndtype: bool\n"
},
{
"code": null,
"e": 8799,
"s": 8762,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 8815,
"s": 8799,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 8848,
"s": 8815,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 8867,
"s": 8848,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 8902,
"s": 8867,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 8924,
"s": 8902,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 8958,
"s": 8924,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 8986,
"s": 8958,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 9021,
"s": 8986,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 9035,
"s": 9021,
"text": " Lets Kode It"
},
{
"code": null,
"e": 9068,
"s": 9035,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 9085,
"s": 9068,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 9092,
"s": 9085,
"text": " Print"
},
{
"code": null,
"e": 9103,
"s": 9092,
"text": " Add Notes"
}
]
|
TestNG - Asserts | In the previous chapters we executed some tests using TestNG. We didn't declare a test success or fail. A test is considered successful if it completed without throwing any exception or if it threw an exception that was expected.
A test method will typically be made of calls that can throw an exception, or of various assertions (using the Java "assert" keyword). TestNG asserts the tester decides whether the test was successful or not, along with the exceptions. Assertions in TestNG are a way to verify that the expected result and the actual result matched or not.
Following is the generic syntax of TestNG Assertions:
Assert.Method( actual, expected)
actual: The actual value that the tester gets.
actual: The actual value that the tester gets.
expected: The value that you expect.
expected: The value that you expect.
Let us see an example of assertion here. Create a java class to be tested, say, MessageUtil.java in /work/testng/src.
/*
* This class prints the given message on console.
*/
public class MessageUtil {
private String message;
//Constructor
//@param message to be printed
public MessageUtil(String message) {
this.message = message;
}
// prints the message
public String printMessage() {
System.out.println(message);
return message;
}
}
Create a java class, say, TestAssertion.java in /work/testng/src. Here we assert the actual and expected result.
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestAssertion {
String message = "Manisha";
MessageUtil messageUtil = new MessageUtil(message);
@Test
public void testPrintMessage() {
Assert.assertEquals("Tutorialspoint", messageUtil.printMessage());
}
}
The preceding test class contains two test methods which will run in separate threads.
Create testng.xml in /work/testng/src to execute test case(s).
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name = "Suite1">
<test name = "test1">
<classes>
<class name = "TestAssertion"/>
</classes>
</test>
</suite>
Compile the java files using javac.
/work/testng/src$ javac TestAssertion.java MessageUtil.java
Now, run testng.xml.
/work/testng/src$ java org.testng.TestNG testng.xml
Verify the output.
Manisha
===============================================
Suite1
Total tests run: 1, Passes: 0, Failures: 1, Skips: 0
===============================================
You can check the /work/testng/src/test-output/index.html for detailed report. You will see a report as below:
38 Lectures
4.5 hours
Lets Kode It
15 Lectures
1.5 hours
Quaatso Learning
28 Lectures
3 hours
Dezlearn Education
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2290,
"s": 2060,
"text": "In the previous chapters we executed some tests using TestNG. We didn't declare a test success or fail. A test is considered successful if it completed without throwing any exception or if it threw an exception that was expected."
},
{
"code": null,
"e": 2630,
"s": 2290,
"text": "A test method will typically be made of calls that can throw an exception, or of various assertions (using the Java \"assert\" keyword). TestNG asserts the tester decides whether the test was successful or not, along with the exceptions. Assertions in TestNG are a way to verify that the expected result and the actual result matched or not."
},
{
"code": null,
"e": 2684,
"s": 2630,
"text": "Following is the generic syntax of TestNG Assertions:"
},
{
"code": null,
"e": 2719,
"s": 2684,
"text": " Assert.Method( actual, expected)"
},
{
"code": null,
"e": 2767,
"s": 2719,
"text": "actual: The actual value that the tester gets."
},
{
"code": null,
"e": 2815,
"s": 2767,
"text": "actual: The actual value that the tester gets."
},
{
"code": null,
"e": 2853,
"s": 2815,
"text": "expected: The value that you expect."
},
{
"code": null,
"e": 2891,
"s": 2853,
"text": "expected: The value that you expect."
},
{
"code": null,
"e": 3009,
"s": 2891,
"text": "Let us see an example of assertion here. Create a java class to be tested, say, MessageUtil.java in /work/testng/src."
},
{
"code": null,
"e": 3372,
"s": 3009,
"text": "/*\n* This class prints the given message on console.\n*/\n\npublic class MessageUtil {\n\n private String message;\n\n //Constructor\n //@param message to be printed\n public MessageUtil(String message) {\n this.message = message;\n }\n\n // prints the message\n public String printMessage() {\n System.out.println(message);\n return message;\n }\n}"
},
{
"code": null,
"e": 3485,
"s": 3372,
"text": "Create a java class, say, TestAssertion.java in /work/testng/src. Here we assert the actual and expected result."
},
{
"code": null,
"e": 3809,
"s": 3485,
"text": " import org.testng.Assert;\n import org.testng.annotations.Test;\n\n public class TestAssertion {\n String message = \"Manisha\";\n MessageUtil messageUtil = new MessageUtil(message);\n\n @Test\n public void testPrintMessage() {\n Assert.assertEquals(\"Tutorialspoint\", messageUtil.printMessage());\n }\n }"
},
{
"code": null,
"e": 3896,
"s": 3809,
"text": "The preceding test class contains two test methods which will run in separate threads."
},
{
"code": null,
"e": 3959,
"s": 3896,
"text": "Create testng.xml in /work/testng/src to execute test case(s)."
},
{
"code": null,
"e": 4223,
"s": 3959,
"text": " <?xml version = \"1.0\" encoding = \"UTF-8\"?>\n <!DOCTYPE suite SYSTEM \"http://testng.org/testng-1.0.dtd\" >\n <suite name = \"Suite1\">\n <test name = \"test1\">\n <classes>\n <class name = \"TestAssertion\"/>\n </classes>\n </test>\n </suite>"
},
{
"code": null,
"e": 4259,
"s": 4223,
"text": "Compile the java files using javac."
},
{
"code": null,
"e": 4319,
"s": 4259,
"text": "/work/testng/src$ javac TestAssertion.java MessageUtil.java"
},
{
"code": null,
"e": 4340,
"s": 4319,
"text": "Now, run testng.xml."
},
{
"code": null,
"e": 4392,
"s": 4340,
"text": "/work/testng/src$ java org.testng.TestNG testng.xml"
},
{
"code": null,
"e": 4411,
"s": 4392,
"text": "Verify the output."
},
{
"code": null,
"e": 4586,
"s": 4411,
"text": " Manisha\n\n ===============================================\n Suite1\n Total tests run: 1, Passes: 0, Failures: 1, Skips: 0\n ==============================================="
},
{
"code": null,
"e": 4697,
"s": 4586,
"text": "You can check the /work/testng/src/test-output/index.html for detailed report. You will see a report as below:"
},
{
"code": null,
"e": 4732,
"s": 4697,
"text": "\n 38 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4746,
"s": 4732,
"text": " Lets Kode It"
},
{
"code": null,
"e": 4781,
"s": 4746,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4799,
"s": 4781,
"text": " Quaatso Learning"
},
{
"code": null,
"e": 4832,
"s": 4799,
"text": "\n 28 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 4852,
"s": 4832,
"text": " Dezlearn Education"
},
{
"code": null,
"e": 4859,
"s": 4852,
"text": " Print"
},
{
"code": null,
"e": 4870,
"s": 4859,
"text": " Add Notes"
}
]
|
DAX Aggregation - COUNTX function | Counts the number of rows that contain a number or an expression that evaluates to a number, when evaluating an expression over a table.
COUNTX (<table>, <expression>)
table
The table containing the rows to be counted.
expression
An expression that returns the numbers you want to count.
Returns a whole number.
The COUNTX function counts only numeric values or dates. Parameters that are logical values or text that cannot be translated into numbers are not counted.
If the function finds no rows to count, it returns a blank. When there are rows, but none meets the specified criteria, then the function returns 0.
= COUNTX (RELATEDTABLE (East_Sales), IF ([Product] = East_Sales[Product],1,0))
53 Lectures
5.5 hours
Abhay Gadiya
24 Lectures
2 hours
Randy Minder
26 Lectures
4.5 hours
Randy Minder
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2138,
"s": 2001,
"text": "Counts the number of rows that contain a number or an expression that evaluates to a number, when evaluating an expression over a table."
},
{
"code": null,
"e": 2170,
"s": 2138,
"text": "COUNTX (<table>, <expression>)\n"
},
{
"code": null,
"e": 2176,
"s": 2170,
"text": "table"
},
{
"code": null,
"e": 2221,
"s": 2176,
"text": "The table containing the rows to be counted."
},
{
"code": null,
"e": 2232,
"s": 2221,
"text": "expression"
},
{
"code": null,
"e": 2290,
"s": 2232,
"text": "An expression that returns the numbers you want to count."
},
{
"code": null,
"e": 2314,
"s": 2290,
"text": "Returns a whole number."
},
{
"code": null,
"e": 2470,
"s": 2314,
"text": "The COUNTX function counts only numeric values or dates. Parameters that are logical values or text that cannot be translated into numbers are not counted."
},
{
"code": null,
"e": 2619,
"s": 2470,
"text": "If the function finds no rows to count, it returns a blank. When there are rows, but none meets the specified criteria, then the function returns 0."
},
{
"code": null,
"e": 2699,
"s": 2619,
"text": "= COUNTX (RELATEDTABLE (East_Sales), IF ([Product] = East_Sales[Product],1,0)) "
},
{
"code": null,
"e": 2734,
"s": 2699,
"text": "\n 53 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 2748,
"s": 2734,
"text": " Abhay Gadiya"
},
{
"code": null,
"e": 2781,
"s": 2748,
"text": "\n 24 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 2795,
"s": 2781,
"text": " Randy Minder"
},
{
"code": null,
"e": 2830,
"s": 2795,
"text": "\n 26 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 2844,
"s": 2830,
"text": " Randy Minder"
},
{
"code": null,
"e": 2851,
"s": 2844,
"text": " Print"
},
{
"code": null,
"e": 2862,
"s": 2851,
"text": " Add Notes"
}
]
|
SAP HANA Admin - Solman Integration | You can also support your SAP HANA system by using SAP Solution Manager. To make two systems communicate with each other, you need to register your SAP HANA system to SAP solution manager’s System Landscape Directory (SLD). This directory contains the information about the landscape and software component versions. A SAP system can be configured to register under SLD. SLD manages the information about all installable and installed elements of your system landscape.
To register your SAP HANA system under SLD, you should meet the following prerequisites −
Your SAP HANA system should be installed with SAP HANA Database Lifecycle Manager (HDBLCM).
Your SAP HANA system should be installed with SAP HANA Database Lifecycle Manager (HDBLCM).
You should be logged in with Administrator account of SID credentials.
You should be logged in with Administrator account of SID credentials.
SAP HANA system is running.
SAP HANA system is running.
To perform the integration of SAP HANA system under SLD, open SAP HANA Database Lifecycle Manager GUI. You can open SAP HANA Database Lifecycle Manager via HANA cockpit or via HANA Studio → Platform Lifecycle Manager.
Navigate to Configure System Landscape Registry Configuration under SAP HANA Platform Lifecycle Management.
Enter the following information under System Landscape Directory −
SLD Host Name − Name of the host where the SLD system is installed.
SLD Host Name − Name of the host where the SLD system is installed.
SLD Port − Enter the standard HTTP access port of the SLD.
SLD Port − Enter the standard HTTP access port of the SLD.
SLD User Name − Enter the user of the SLD system. It must be a user that already exists on the host where the SLD system is running.
SLD User Name − Enter the user of the SLD system. It must be a user that already exists on the host where the SLD system is running.
SLD Password − Enter the password for the SLD system.
SLD Password − Enter the password for the SLD system.
Use HTTPS − Here you can mention whether to use HTTPS or not.
Use HTTPS − Here you can mention whether to use HTTPS or not.
Click the Run button to finish the configuration under System Landscape Directory.
You can also perform the above steps from the command line, by executing the following command −
./hdblcm --action=configure_sld
Enter the above specified parameters using command line. Select ’y’ to finalize the configuration under SLD.
25 Lectures
6 hours
Sanjo Thomas
26 Lectures
2 hours
Neha Gupta
30 Lectures
2.5 hours
Sumit Agarwal
30 Lectures
4 hours
Sumit Agarwal
14 Lectures
1.5 hours
Neha Malik
13 Lectures
1.5 hours
Neha Malik
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2794,
"s": 2324,
"text": "You can also support your SAP HANA system by using SAP Solution Manager. To make two systems communicate with each other, you need to register your SAP HANA system to SAP solution manager’s System Landscape Directory (SLD). This directory contains the information about the landscape and software component versions. A SAP system can be configured to register under SLD. SLD manages the information about all installable and installed elements of your system landscape."
},
{
"code": null,
"e": 2884,
"s": 2794,
"text": "To register your SAP HANA system under SLD, you should meet the following prerequisites −"
},
{
"code": null,
"e": 2976,
"s": 2884,
"text": "Your SAP HANA system should be installed with SAP HANA Database Lifecycle Manager (HDBLCM)."
},
{
"code": null,
"e": 3068,
"s": 2976,
"text": "Your SAP HANA system should be installed with SAP HANA Database Lifecycle Manager (HDBLCM)."
},
{
"code": null,
"e": 3139,
"s": 3068,
"text": "You should be logged in with Administrator account of SID credentials."
},
{
"code": null,
"e": 3210,
"s": 3139,
"text": "You should be logged in with Administrator account of SID credentials."
},
{
"code": null,
"e": 3238,
"s": 3210,
"text": "SAP HANA system is running."
},
{
"code": null,
"e": 3266,
"s": 3238,
"text": "SAP HANA system is running."
},
{
"code": null,
"e": 3484,
"s": 3266,
"text": "To perform the integration of SAP HANA system under SLD, open SAP HANA Database Lifecycle Manager GUI. You can open SAP HANA Database Lifecycle Manager via HANA cockpit or via HANA Studio → Platform Lifecycle Manager."
},
{
"code": null,
"e": 3592,
"s": 3484,
"text": "Navigate to Configure System Landscape Registry Configuration under SAP HANA Platform Lifecycle Management."
},
{
"code": null,
"e": 3659,
"s": 3592,
"text": "Enter the following information under System Landscape Directory −"
},
{
"code": null,
"e": 3727,
"s": 3659,
"text": "SLD Host Name − Name of the host where the SLD system is installed."
},
{
"code": null,
"e": 3795,
"s": 3727,
"text": "SLD Host Name − Name of the host where the SLD system is installed."
},
{
"code": null,
"e": 3854,
"s": 3795,
"text": "SLD Port − Enter the standard HTTP access port of the SLD."
},
{
"code": null,
"e": 3913,
"s": 3854,
"text": "SLD Port − Enter the standard HTTP access port of the SLD."
},
{
"code": null,
"e": 4046,
"s": 3913,
"text": "SLD User Name − Enter the user of the SLD system. It must be a user that already exists on the host where the SLD system is running."
},
{
"code": null,
"e": 4179,
"s": 4046,
"text": "SLD User Name − Enter the user of the SLD system. It must be a user that already exists on the host where the SLD system is running."
},
{
"code": null,
"e": 4233,
"s": 4179,
"text": "SLD Password − Enter the password for the SLD system."
},
{
"code": null,
"e": 4287,
"s": 4233,
"text": "SLD Password − Enter the password for the SLD system."
},
{
"code": null,
"e": 4349,
"s": 4287,
"text": "Use HTTPS − Here you can mention whether to use HTTPS or not."
},
{
"code": null,
"e": 4411,
"s": 4349,
"text": "Use HTTPS − Here you can mention whether to use HTTPS or not."
},
{
"code": null,
"e": 4494,
"s": 4411,
"text": "Click the Run button to finish the configuration under System Landscape Directory."
},
{
"code": null,
"e": 4591,
"s": 4494,
"text": "You can also perform the above steps from the command line, by executing the following command −"
},
{
"code": null,
"e": 4625,
"s": 4591,
"text": "./hdblcm --action=configure_sld \n"
},
{
"code": null,
"e": 4734,
"s": 4625,
"text": "Enter the above specified parameters using command line. Select ’y’ to finalize the configuration under SLD."
},
{
"code": null,
"e": 4767,
"s": 4734,
"text": "\n 25 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4781,
"s": 4767,
"text": " Sanjo Thomas"
},
{
"code": null,
"e": 4814,
"s": 4781,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4826,
"s": 4814,
"text": " Neha Gupta"
},
{
"code": null,
"e": 4861,
"s": 4826,
"text": "\n 30 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4876,
"s": 4861,
"text": " Sumit Agarwal"
},
{
"code": null,
"e": 4909,
"s": 4876,
"text": "\n 30 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4924,
"s": 4909,
"text": " Sumit Agarwal"
},
{
"code": null,
"e": 4959,
"s": 4924,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4971,
"s": 4959,
"text": " Neha Malik"
},
{
"code": null,
"e": 5006,
"s": 4971,
"text": "\n 13 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5018,
"s": 5006,
"text": " Neha Malik"
},
{
"code": null,
"e": 5025,
"s": 5018,
"text": " Print"
},
{
"code": null,
"e": 5036,
"s": 5025,
"text": " Add Notes"
}
]
|
Full outer join in PySpark dataframe - GeeksforGeeks | 19 Dec, 2021
In this article, we are going to see how to perform Full Outer Join in PySpark DataFrames in Python.
Python3
# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [["1", "sravan", "company 1"], ["2", "ojaswi", "company 1"], ["3", "rohith", "company 2"], ["4", "sridevi", "company 1"], ["5", "bobby", "company 1"]] # specify column namescolumns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) dataframe.show()
Output:
Python3
# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata1 = [["1", "45000", "IT"], ["2", "145000", "Manager"], ["6", "45000", "HR"], ["5", "34000", "Sales"]] # specify column namescolumns = ['ID', 'salary', 'department'] # creating a dataframe from the lists of datadataframe1 = spark.createDataFrame(data1, columns) dataframe1.show()
Output:
This is used to join the two PySpark dataframes with all rows and columns using full keyword
Syntax: dataframe1.join(dataframe2,dataframe1.column_name == dataframe2.column_name,”full”).show()
where
dataframe1 is the first PySpark dataframe
dataframe2 is the second PySpark dataframe
column_name is the column with respect to dataframe
Example: Python program to join two dataframes based on the ID column.
Python3
# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [["1", "sravan", "company 1"], ["2", "ojaswi", "company 1"], ["3", "rohith", "company 2"], ["4", "sridevi", "company 1"], ["5", "bobby", "company 1"]] # specify column namescolumns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # list of employee datadata1 = [["1", "45000", "IT"], ["2", "145000", "Manager"], ["6", "45000", "HR"], ["5", "34000", "Sales"]] # specify column namescolumns = ['ID', 'salary', 'department'] # creating a dataframe from the lists of datadataframe1 = spark.createDataFrame(data1, columns) # join two dataframes based on# ID column using full keyworddataframe.join(dataframe1, dataframe.ID == dataframe1.ID, "full").show()
Output:
This is used to join the two PySpark dataframes with all rows and columns using fullouter keyword
Syntax: dataframe1.join(dataframe2,dataframe1.column_name == dataframe2.column_name,”fullouter”).show()
where
dataframe1 is the first PySpark dataframe
dataframe2 is the second PySpark dataframe
column_name is the column with respect to dataframe
Example: Python program to join two dataframes based on the ID column.
Python3
# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [["1", "sravan", "company 1"], ["2", "ojaswi", "company 1"], ["3", "rohith", "company 2"], ["4", "sridevi", "company 1"], ["5", "bobby", "company 1"]] # specify column namescolumns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # list of employee datadata1 = [["1", "45000", "IT"], ["2", "145000", "Manager"], ["6", "45000", "HR"], ["5", "34000", "Sales"]] # specify column namescolumns = ['ID', 'salary', 'department'] # creating a dataframe from the lists of datadataframe1 = spark.createDataFrame(data1, columns) # join two dataframes based on ID# column using full outer keyworddataframe.join(dataframe1, dataframe.ID == dataframe1.ID, "fullouter").show()
Output:
This is used to join the two PySpark dataframes with all rows and columns using the outer keyword.
Syntax: dataframe1.join(dataframe2,dataframe1.column_name == dataframe2.column_name,”outer”).show()
where,
dataframe1 is the first PySpark dataframe
dataframe2 is the second PySpark dataframe
column_name is the column with respect to dataframe
Python3
# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [["1", "sravan", "company 1"], ["2", "ojaswi", "company 1"], ["3", "rohith", "company 2"], ["4", "sridevi", "company 1"], ["5", "bobby", "company 1"]] # specify column namescolumns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # list of employee datadata1 = [["1", "45000", "IT"], ["2", "145000", "Manager"], ["6", "45000", "HR"], ["5", "34000", "Sales"]] # specify column namescolumns = ['ID', 'salary', 'department'] # creating a dataframe from the lists of datadataframe1 = spark.createDataFrame(data1, columns) # join two dataframes based on# ID column using outer keyworddataframe.join(dataframe1, dataframe.ID == dataframe1.ID, "outer").show()
Output:
Picked
Python-Pyspark
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Selecting rows in pandas DataFrame based on conditions
Check if element exists in list in Python
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": 24292,
"s": 24264,
"text": "\n19 Dec, 2021"
},
{
"code": null,
"e": 24393,
"s": 24292,
"text": "In this article, we are going to see how to perform Full Outer Join in PySpark DataFrames in Python."
},
{
"code": null,
"e": 24401,
"s": 24393,
"text": "Python3"
},
{
"code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [[\"1\", \"sravan\", \"company 1\"], [\"2\", \"ojaswi\", \"company 1\"], [\"3\", \"rohith\", \"company 2\"], [\"4\", \"sridevi\", \"company 1\"], [\"5\", \"bobby\", \"company 1\"]] # specify column namescolumns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) dataframe.show()",
"e": 25012,
"s": 24401,
"text": null
},
{
"code": null,
"e": 25020,
"s": 25012,
"text": "Output:"
},
{
"code": null,
"e": 25028,
"s": 25020,
"text": "Python3"
},
{
"code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata1 = [[\"1\", \"45000\", \"IT\"], [\"2\", \"145000\", \"Manager\"], [\"6\", \"45000\", \"HR\"], [\"5\", \"34000\", \"Sales\"]] # specify column namescolumns = ['ID', 'salary', 'department'] # creating a dataframe from the lists of datadataframe1 = spark.createDataFrame(data1, columns) dataframe1.show()",
"e": 25593,
"s": 25028,
"text": null
},
{
"code": null,
"e": 25601,
"s": 25593,
"text": "Output:"
},
{
"code": null,
"e": 25694,
"s": 25601,
"text": "This is used to join the two PySpark dataframes with all rows and columns using full keyword"
},
{
"code": null,
"e": 25794,
"s": 25694,
"text": "Syntax: dataframe1.join(dataframe2,dataframe1.column_name == dataframe2.column_name,”full”).show()"
},
{
"code": null,
"e": 25800,
"s": 25794,
"text": "where"
},
{
"code": null,
"e": 25842,
"s": 25800,
"text": "dataframe1 is the first PySpark dataframe"
},
{
"code": null,
"e": 25885,
"s": 25842,
"text": "dataframe2 is the second PySpark dataframe"
},
{
"code": null,
"e": 25937,
"s": 25885,
"text": "column_name is the column with respect to dataframe"
},
{
"code": null,
"e": 26008,
"s": 25937,
"text": "Example: Python program to join two dataframes based on the ID column."
},
{
"code": null,
"e": 26016,
"s": 26008,
"text": "Python3"
},
{
"code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [[\"1\", \"sravan\", \"company 1\"], [\"2\", \"ojaswi\", \"company 1\"], [\"3\", \"rohith\", \"company 2\"], [\"4\", \"sridevi\", \"company 1\"], [\"5\", \"bobby\", \"company 1\"]] # specify column namescolumns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # list of employee datadata1 = [[\"1\", \"45000\", \"IT\"], [\"2\", \"145000\", \"Manager\"], [\"6\", \"45000\", \"HR\"], [\"5\", \"34000\", \"Sales\"]] # specify column namescolumns = ['ID', 'salary', 'department'] # creating a dataframe from the lists of datadataframe1 = spark.createDataFrame(data1, columns) # join two dataframes based on# ID column using full keyworddataframe.join(dataframe1, dataframe.ID == dataframe1.ID, \"full\").show()",
"e": 27092,
"s": 26016,
"text": null
},
{
"code": null,
"e": 27100,
"s": 27092,
"text": "Output:"
},
{
"code": null,
"e": 27198,
"s": 27100,
"text": "This is used to join the two PySpark dataframes with all rows and columns using fullouter keyword"
},
{
"code": null,
"e": 27303,
"s": 27198,
"text": "Syntax: dataframe1.join(dataframe2,dataframe1.column_name == dataframe2.column_name,”fullouter”).show()"
},
{
"code": null,
"e": 27309,
"s": 27303,
"text": "where"
},
{
"code": null,
"e": 27351,
"s": 27309,
"text": "dataframe1 is the first PySpark dataframe"
},
{
"code": null,
"e": 27394,
"s": 27351,
"text": "dataframe2 is the second PySpark dataframe"
},
{
"code": null,
"e": 27446,
"s": 27394,
"text": "column_name is the column with respect to dataframe"
},
{
"code": null,
"e": 27517,
"s": 27446,
"text": "Example: Python program to join two dataframes based on the ID column."
},
{
"code": null,
"e": 27525,
"s": 27517,
"text": "Python3"
},
{
"code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [[\"1\", \"sravan\", \"company 1\"], [\"2\", \"ojaswi\", \"company 1\"], [\"3\", \"rohith\", \"company 2\"], [\"4\", \"sridevi\", \"company 1\"], [\"5\", \"bobby\", \"company 1\"]] # specify column namescolumns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # list of employee datadata1 = [[\"1\", \"45000\", \"IT\"], [\"2\", \"145000\", \"Manager\"], [\"6\", \"45000\", \"HR\"], [\"5\", \"34000\", \"Sales\"]] # specify column namescolumns = ['ID', 'salary', 'department'] # creating a dataframe from the lists of datadataframe1 = spark.createDataFrame(data1, columns) # join two dataframes based on ID# column using full outer keyworddataframe.join(dataframe1, dataframe.ID == dataframe1.ID, \"fullouter\").show()",
"e": 28612,
"s": 27525,
"text": null
},
{
"code": null,
"e": 28620,
"s": 28612,
"text": "Output:"
},
{
"code": null,
"e": 28719,
"s": 28620,
"text": "This is used to join the two PySpark dataframes with all rows and columns using the outer keyword."
},
{
"code": null,
"e": 28820,
"s": 28719,
"text": "Syntax: dataframe1.join(dataframe2,dataframe1.column_name == dataframe2.column_name,”outer”).show()"
},
{
"code": null,
"e": 28827,
"s": 28820,
"text": "where,"
},
{
"code": null,
"e": 28869,
"s": 28827,
"text": "dataframe1 is the first PySpark dataframe"
},
{
"code": null,
"e": 28912,
"s": 28869,
"text": "dataframe2 is the second PySpark dataframe"
},
{
"code": null,
"e": 28964,
"s": 28912,
"text": "column_name is the column with respect to dataframe"
},
{
"code": null,
"e": 28972,
"s": 28964,
"text": "Python3"
},
{
"code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [[\"1\", \"sravan\", \"company 1\"], [\"2\", \"ojaswi\", \"company 1\"], [\"3\", \"rohith\", \"company 2\"], [\"4\", \"sridevi\", \"company 1\"], [\"5\", \"bobby\", \"company 1\"]] # specify column namescolumns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # list of employee datadata1 = [[\"1\", \"45000\", \"IT\"], [\"2\", \"145000\", \"Manager\"], [\"6\", \"45000\", \"HR\"], [\"5\", \"34000\", \"Sales\"]] # specify column namescolumns = ['ID', 'salary', 'department'] # creating a dataframe from the lists of datadataframe1 = spark.createDataFrame(data1, columns) # join two dataframes based on# ID column using outer keyworddataframe.join(dataframe1, dataframe.ID == dataframe1.ID, \"outer\").show()",
"e": 30049,
"s": 28972,
"text": null
},
{
"code": null,
"e": 30057,
"s": 30049,
"text": "Output:"
},
{
"code": null,
"e": 30064,
"s": 30057,
"text": "Picked"
},
{
"code": null,
"e": 30079,
"s": 30064,
"text": "Python-Pyspark"
},
{
"code": null,
"e": 30086,
"s": 30079,
"text": "Python"
},
{
"code": null,
"e": 30184,
"s": 30086,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30216,
"s": 30184,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 30272,
"s": 30216,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 30314,
"s": 30272,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 30369,
"s": 30314,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 30411,
"s": 30369,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 30433,
"s": 30411,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 30472,
"s": 30433,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 30503,
"s": 30472,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 30532,
"s": 30503,
"text": "Create a directory in Python"
}
]
|
Java Math getExponent() method with Example - GeeksforGeeks | 09 Apr, 2018
The java.lang.Math.getExponent() returns the unbiased exponent used in the representation of a double or float.Note:
If the argument is NaN or infinite of double or float type, then the result is (Double.MAX_EXPONENT + 1) or (Float.MAX_EXPONENT + 1).
If the argument is zero or subnormal of double or float type, then the result is (Double.MIN_EXPONENT -1) or (Float.MIN_EXPONENT -1).
Syntax :
public static int getExponent(DataType a)
Parameter :
a : an argument of double or float type
Return :
This method returns the unbiased exponent of the argument.
// Java program to demonstrate working// of java.lang.Math.getExponent() methodimport java.lang.Math; class Gfg { // driver code public static void main(String args[]) { double a = 345.65; double b = 1.0 / 0; double c = 0; // Input double value // Output unbiased exponent of it System.out.println(Math.getExponent(a)); // Input Infinity // Output (Double.MAX_EXPONENT + 1) System.out.println(Math.getExponent(b)); // Input Zero // Output (Double.MIN_EXPONENT - 1) System.out.println(Math.getExponent(c)); float d = 237.2f; float e = 1.0f / 0; float f = 0f; // Input float value // Output unbiased exponent of it System.out.println(Math.getExponent(d)); // Input Infinity // Output (Float.MAX_EXPONENT + 1) System.out.println(Math.getExponent(e)); // Input Zero // Output (Float.MIN_EXPONENT - 1) System.out.println(Math.getExponent(f)); }}
Output:
8
1024
-1023
7
128
-127
Java-lang package
java-math
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Functional Interfaces in Java
Generics in Java
Comparator Interface in Java with Examples
Introduction to Java
HashMap get() Method in Java
Strings in Java | [
{
"code": null,
"e": 23948,
"s": 23920,
"text": "\n09 Apr, 2018"
},
{
"code": null,
"e": 24065,
"s": 23948,
"text": "The java.lang.Math.getExponent() returns the unbiased exponent used in the representation of a double or float.Note:"
},
{
"code": null,
"e": 24199,
"s": 24065,
"text": "If the argument is NaN or infinite of double or float type, then the result is (Double.MAX_EXPONENT + 1) or (Float.MAX_EXPONENT + 1)."
},
{
"code": null,
"e": 24333,
"s": 24199,
"text": "If the argument is zero or subnormal of double or float type, then the result is (Double.MIN_EXPONENT -1) or (Float.MIN_EXPONENT -1)."
},
{
"code": null,
"e": 24342,
"s": 24333,
"text": "Syntax :"
},
{
"code": null,
"e": 24504,
"s": 24342,
"text": "public static int getExponent(DataType a)\nParameter :\na : an argument of double or float type\nReturn :\nThis method returns the unbiased exponent of the argument."
},
{
"code": "// Java program to demonstrate working// of java.lang.Math.getExponent() methodimport java.lang.Math; class Gfg { // driver code public static void main(String args[]) { double a = 345.65; double b = 1.0 / 0; double c = 0; // Input double value // Output unbiased exponent of it System.out.println(Math.getExponent(a)); // Input Infinity // Output (Double.MAX_EXPONENT + 1) System.out.println(Math.getExponent(b)); // Input Zero // Output (Double.MIN_EXPONENT - 1) System.out.println(Math.getExponent(c)); float d = 237.2f; float e = 1.0f / 0; float f = 0f; // Input float value // Output unbiased exponent of it System.out.println(Math.getExponent(d)); // Input Infinity // Output (Float.MAX_EXPONENT + 1) System.out.println(Math.getExponent(e)); // Input Zero // Output (Float.MIN_EXPONENT - 1) System.out.println(Math.getExponent(f)); }}",
"e": 25542,
"s": 24504,
"text": null
},
{
"code": null,
"e": 25550,
"s": 25542,
"text": "Output:"
},
{
"code": null,
"e": 25575,
"s": 25550,
"text": "8\n1024\n-1023\n7\n128\n-127\n"
},
{
"code": null,
"e": 25593,
"s": 25575,
"text": "Java-lang package"
},
{
"code": null,
"e": 25603,
"s": 25593,
"text": "java-math"
},
{
"code": null,
"e": 25608,
"s": 25603,
"text": "Java"
},
{
"code": null,
"e": 25613,
"s": 25608,
"text": "Java"
},
{
"code": null,
"e": 25711,
"s": 25613,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25726,
"s": 25711,
"text": "Stream In Java"
},
{
"code": null,
"e": 25747,
"s": 25726,
"text": "Constructors in Java"
},
{
"code": null,
"e": 25793,
"s": 25747,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 25812,
"s": 25793,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 25842,
"s": 25812,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 25859,
"s": 25842,
"text": "Generics in Java"
},
{
"code": null,
"e": 25902,
"s": 25859,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 25923,
"s": 25902,
"text": "Introduction to Java"
},
{
"code": null,
"e": 25952,
"s": 25923,
"text": "HashMap get() Method in Java"
}
]
|
Advanced Data Visualization in Python with HoloViews | by Andrew Riley | Towards Data Science | HoloViews is an open source package that produces high quality and interactive visualizations with minimal code and effort. The project page can found here here along with many examples to understand the capabilities of the package. I have been very pleased with the easy of use and performance relative to the legacy options (Matplotlib, Seaborn, etc... ).
Exploring and learning new packages is more engaging when solving a real world data analysis exercise. This article steps through a cohort analysis of a simplified SaaS business to identify whether there are any emerging trends in the customer base. Such an analysis is useful in a number of contexts including preparing and validating top-line forecasts and assessing the impact of recent changes in the product offerings or pricing. A cohort in this example will be defined as all users who appear in a given month for the first time. The goal of this exercise is to examine how the mix of new business is changing over time and what the change in mix may mean for retention. In this case the mix refers to product tier and subscription duration, in other cases it could be any categorical field available.
The data underlying the analysis are simulated to replicate a pattern observed across multiple companies.
There are two files:
mrr.csv contains the monthly revenue for each subscription over a 2.5 year period. There is no left censoring.
user.csv contains the a user id, subscription id, product tier and a subscription duration
A user may have more than one subscription and they may swap the product tier and subscription duration. For simplicity, retention is calculated on a subscription basis rather than user basis.
The analysis begins with the imports. The point of showing this is to make sure that the reader has all the dependent packages installed. Please note the hvplot package which is built on HoloViews and has among other things a convenient API for plotting with pandas, this requires a separate install from HoloViews.
import pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport osimport hvplot.pandasimport holoviews as hvfrom holoviews import optshv.extension('bokeh')
Side note: The default behavior of datetime formatting in HoloViews is to print the date/time down to the nanosecond. Documentation for controlling this behavior is often hard to find and not entirely clear for beginners. This formatting problem can be solved by creating a DatetimeTickFormatter object and passing it to the graphs as needed.
from bokeh.models.formatters import DatetimeTickFormatterdtf = DatetimeTickFormatter( days = '%m-%Y', months = '%m-%Y' , years = '%m-%Y')
Before plotting the data it needs to be transformed into content that will make the plots meaningful and in the proper format to be passed to HoloVeiws. Some of the basic pandas manipulations are excluded from this article. The full file can be found at github.
Creating the cohorts is the first step in a cohort analysis and there are many ways one can produce this calculation. Given the format of the input data, the following steps are applied here:
### Calculate start period of the subscription## #1 Create cohorts based on the first observation of a month with a positive mrr valuecohort = (mrr > 0).idxmax( axis = 1).rename('cohort')## #2 Add the cohort date to the indextenure = mrr.join( cohort ).set_index( 'cohort', append = True).stack()tenure = tenure.reset_index( ).rename( columns = {'level_2':'date',## #3 Calculate the number of periods (months) from the cohort date to the mrr date0:'revenue'} )tenure['periods'] = np.round( (tenure['date'] - tenure['cohort']) / np.timedelta64(1, 'M') ,0).astype(int)
The code in #1 converts the dataframe into values into binary variables that are true when there is positive revenue in a month. Then idxmax is applied to extract the column title of the first occurrence of the maximum value, which will be the first date when revenue is positive. The result is a series with the same index as mrr and the series is appended as a secondary index in #2 to mrr, stacked (this operation unvpivots the data by turning the column headers, monthly dates in this case, into a value field) and saved as a new dataframe called tenure. Step #3 calculates the number of periods (months in this case) that have elapsed between the cohort month and the current month.
Two curves that are often useful to produce in the EDA phase of a cohort analysis that will give a general understanding of the customer retention. Both represent the percentage of business that is remaining at a given point in time relative to the first period that each customer was active. One uses customers as the numerator and denominator and the other uses revenue. These calculations are broken up into two segments as follows:
## #1 Calculate revenue and subs count by cohort by monthgb = tenure.groupby( [ pd.Grouper( key ='cohort' , freq = 'M') , 'periods'])rev_cohorts = gb['revenue'].sum().unstack()count_cohorts = gb['sub_id'].nunique().unstack()## #2 turn them into a percentage relative to the first monthscaled_revenue_cohorts = rev_cohorts.apply( lambda x : x/x[0] ,axis = 1)scaled_count_cohorts = count_cohorts.apply( lambda x : x/x[0] ,axis = 1)
The calculations in #1 compute the total revenue and unique count of customers for a monthly cohort of customers in each period where there are observations and the unstack command pivots the periods into column headers, which will be useful for plotting with hvplot. The calculations in #2 take advantage of the new data shape and apply a lambda function to divide each period value (revenue or customer count) by the value observed in the first month.
The hvplot extension to HoloViews provides a very quick way to generate interactive visualizations from pandas objects that can help with EDA. The following code, which follows the same API format as the matplotlib, quickly produces line plots for exploration.
### Quick hvplot of both dataframesp1 = scaled_revenue_cohorts[scaled_revenue_cohorts>0].T.hvplot( figsize = [11,7], legend=False , title = 'Revenue')p2 = scaled_count_cohorts[scaled_count_cohorts>0].T.hvplot(figsize = [11,7], legend=False , title = 'Logo Count')### Add the graphs together to display as one output(p1 + p2).cols(1)
There are two things that are easier to implement than would be in HoloViews than in plotting packages. The tooltips allow one to explore the data interactively and are generated automatically. The syntax for adding the graphs together into a single visualization is easier than calling the axes objects from matplotlib.
These graphs are already very informative and help to guide the rest of the analysis. First, notice that there is a mix of different subscription lengths. It will be best to analyze the retention of the different duration options separately since obviously a one year subscription is going to have a different profile than a one month subscription. Secondly, the profile of the retention curves is changing. The shorter lines are the most recent ones since there is simply less data available. These have more curvature than the older ones and also they appear to have a lower retention percentage. Later this article will show a better way to demonstrate this pattern. Before that, we will explore what is changing in the underlying subscription base.
Retention patterns often begin to change when there is a change in the mix of new business. The mix of new business could be changing because of new marketing activities, product offerings, duration options, regional or demographic characteristics, among many other things. In this data set only duration and subscription tiers are available as categorical features. A good way to assess how the mix of any categorical feature changes over time is to plot them in a stacked two bar charts showing the total volume and the relative percentage.
In order to generate the next set of graphs the data will need to be reshaped splitting the cohorts by tier and duration.
## #1 Create product duration cohortsgb = tenure.groupby( ['sub_product','sub_duration','cohort', 'subs_id','periods'])## #2 Divide each periods user count (observations with revenue > 0) by the month 0 countcohorts_scaled = gb['revenue'].sum().unstack().groupby(level=[0,1,2]).apply( lambda x : (x>0).sum()/(x[0]>0).sum())
With the new cohorts data creating the bar charts is fairly easy but does require a few lines:
## #1 mix = cohorts[0].rename('count').reset_index()mix = mix.set_index(['cohort','sub_product','sub_duration'] )mix = mix.sort_index()## #2abs_bars = hv.Bars( mix )abs_bars.opts( stacked = True, xrotation = 45 , width = 700 , height = 400 , xaxis= None , ylabel = 'Conversions')## #3hund_bars = hv.Bars( mix/mix.groupby( level =0 ).sum() )hund_bars.opts( stacked = True, xrotation = 45 , width = 700 , height = 400 , xformatter = dtf, ylabel = 'Relative %')layout = (abs_bars + hund_bars).cols(1)layout.opts(shared_axes=False)
The code under #1 create a multi indexed series that can be passed to the HoloViews bars class. Holoviews requires flat data as opposed to hvplot which can operate smoothly with tabular data. The .opts() method in HoloViews gives the developer very detailed control over almost every part of the visualization.
The bar charts shows that the product tier has not been changing in any clear trend over time. However, repeating this step for duration shows a significant change in the mix of new business.
Six month subscriptions are being replaced entirely by one month subscriptions. This result is almost certainly causing the overall shift in the retention curve. In order to prove that out we will plot the retention curves by product and duration.
The previously shown plots are easy to produce and appealing, but limited in terms of interactivity. One of the nice features of HoloViews is being able to produce dashboard like visualizations. Additionally it produces these visualizations in html so that they may be embedded in a web page. These features require more code than simply passing a dataframe into hvplot. These features are demonstrated with two visualizations are useful for identifying retention trends.
Before producing the visualizations, building some helper functions will keep the code more readable. In the previously shown cohort curve plots, it can be a difficult to see which line belongs to which vintage. In order to make that more clear one can assign a color that fades with the cohort age. The following code block colors the lines blue and has the blue fade to white/gray with age.
def gen_cohort_plot( cohort ): cohort = cohort[ cohort > 0]## #1 Create curves with hvplot plot = cohort.T.hvplot( width=700, height=350, legend=False ) d_min = 2015 REPLACE d_max = 2017 REPLACE## #2 loop through curves to adjust the formatting for item in plot.items(): date , curve = item year = pd.to_datetime( date ).year ## #3 interpolate the blue scale bounded between .2 and .8 c = plt.cm.Blues( .8* (year - d_min ) / ( d_max - d_min ) + .2) curve.opts( hv.opts.Curve( color=c )) return plot
The function looks intimidating, but the logic is pretty simple. In #1 hvplot is used to generate the same curves as shown previously. These curves are looped through in #2, while #3 linearly interpolates the cohort year cohort year relative to the minimum and maximum cohort year onto the blue color map from matplotlib.
## #1 loop through possible pairs of product and duration ## pd_curve is a helper function that just filters data before ## being passed to gen_cohort_plot()curve_dict_2D = {(d,p):pd_curve(p,d, cohorts_scaled) for p in products for d in durations }## #2 create hmap visualizations hmap = hv.HoloMap(curve_dict_2D , kdims=['Duration', 'Product'])## generate a plot of the number of conversionsconv_curve_dict_2D = {(d,p):conversion_plot( p , d , cohorts ) for p in products for d in durations }conv_hmap = hv.HoloMap(conv_curve_dict_2D, kdims=['Duration', 'Product'])## generate a plot of the average price for a cohorts first monthasp_curve_dict_2D = {(d,p):asp_plot(p,d, cohort_asp) for p in products for d in durations }asp_hmap = hv.HoloMap(asp_curve_dict_2D, kdims=['Duration', 'Product'])(hmap +conv_hmap + asp_hmap ).cols(1)
The curves are stored in a dictionary that can be passed in different layout options. Shown here is the HoloMap. A HoloMap produces a drop downs selectors based on the dictionary keys shown:
The darker the line the more recent the cohort. After clicking through the different combinations it becomes clear that the one month subscriptions have a worsen retention profile. We’ve previously observed that one month subscriptions are making up a growing portion of the new customer base.
While coloring the the lines different shades aids in visualizing the age of the cohorts, heatmaps provide an alternative method to display the information which makes certain trends more easy to identify. Heatmaps do however require more explanation than the line plot, if it is being presented to parties who are unfamiliar with this format. The tutorial will conclude with a discussion of how to produce and interpret the heatmap view.
Helper functions are created to format the graphs and make the code more manageable.
def heatmap_product_duration( product , duration , data = cohorts_scaled):## #1 filter the data for the product duration pair idx = pd.IndexSlice data = data.loc[ idx[product, duration, :] , :].reset_index( level = [0,1], drop = True) data = data[data>0] data = data.stack().rename( 'retention').reset_index() data = data[ data['retention'] > 0] data.columns = ['cohort','tenure','retention']## #2 Create a heatmap hm = hv.HeatMap(data , kdims=['tenure','cohort']).sort()## #3 Formatting options note the addition of the hover tool hm.opts( opts.HeatMap( width = 500 , height = 500 ,colorbar = True, yformatter = dtf , xrotation = 90 ,cmap = 'RdYlGn' ,tools=['hover'], toolbar='above')) return hmdef left_conv_bar( product , duration, data = cohorts ):## #1 filter the data for the product duration pair idx = pd.IndexSlice data = data.loc[ idx[product, duration, :] , :].reset_index( level = [0,1], drop = True) data = data.loc[:,0].rename( 'conversions').reset_index() ## #2 similar to the previous bar charts, note the invert_axes option bar = hv.Bars( data ).opts( invert_axes=True , height = 500 , width = 200 , color = 'Green' , yaxis = None, invert_xaxis=True ) return bar
After building the helper functions, in a way similar to before, the code loops through the product duration pairs and creates a dictionary to store the visualizations before ultimately passing them to a HoloMap.
heatmap_curve_dict_2D = {(d,p):heatmap_product_duration(p,d) for p in products for d in durations }heatmap_hmap = hv.HoloMap(heatmap_curve_dict_2D, kdims=['Duration', 'Product'])left_bar_curve_dict_2D = {(d,p):left_conv_bar(p,d) for p in products for d in durations }left_bar_hmap = hv.HoloMap(left_bar_curve_dict_2D, kdims=['Duration', 'Product'])layout = (left_bar_hmap + heatmap_hmap ).opts( shared_axes = True)layout
This view shows how the cohorts are aging differently by observing the green in early tenure periods shift to yellow after October 2018 for all tiers of the one month subscription. Note that this shift also corresponds to the period when the number of conversions begins to increase. This phenomenon is fairly common in evolving businesses. Increasing marketing spend or making product/pricing changes will attract more new customers but the incremental new customers are not necessarily the same as the customers in the previous cohorts.
HoloViews allows analysts to produce high quality visualizations that accelerate the time to generate meaningful insights with a high degree of customization. Thanks for reading this far and I hope you check out the library. | [
{
"code": null,
"e": 530,
"s": 172,
"text": "HoloViews is an open source package that produces high quality and interactive visualizations with minimal code and effort. The project page can found here here along with many examples to understand the capabilities of the package. I have been very pleased with the easy of use and performance relative to the legacy options (Matplotlib, Seaborn, etc... )."
},
{
"code": null,
"e": 1339,
"s": 530,
"text": "Exploring and learning new packages is more engaging when solving a real world data analysis exercise. This article steps through a cohort analysis of a simplified SaaS business to identify whether there are any emerging trends in the customer base. Such an analysis is useful in a number of contexts including preparing and validating top-line forecasts and assessing the impact of recent changes in the product offerings or pricing. A cohort in this example will be defined as all users who appear in a given month for the first time. The goal of this exercise is to examine how the mix of new business is changing over time and what the change in mix may mean for retention. In this case the mix refers to product tier and subscription duration, in other cases it could be any categorical field available."
},
{
"code": null,
"e": 1445,
"s": 1339,
"text": "The data underlying the analysis are simulated to replicate a pattern observed across multiple companies."
},
{
"code": null,
"e": 1466,
"s": 1445,
"text": "There are two files:"
},
{
"code": null,
"e": 1577,
"s": 1466,
"text": "mrr.csv contains the monthly revenue for each subscription over a 2.5 year period. There is no left censoring."
},
{
"code": null,
"e": 1668,
"s": 1577,
"text": "user.csv contains the a user id, subscription id, product tier and a subscription duration"
},
{
"code": null,
"e": 1861,
"s": 1668,
"text": "A user may have more than one subscription and they may swap the product tier and subscription duration. For simplicity, retention is calculated on a subscription basis rather than user basis."
},
{
"code": null,
"e": 2177,
"s": 1861,
"text": "The analysis begins with the imports. The point of showing this is to make sure that the reader has all the dependent packages installed. Please note the hvplot package which is built on HoloViews and has among other things a convenient API for plotting with pandas, this requires a separate install from HoloViews."
},
{
"code": null,
"e": 2344,
"s": 2177,
"text": "import pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport osimport hvplot.pandasimport holoviews as hvfrom holoviews import optshv.extension('bokeh')"
},
{
"code": null,
"e": 2687,
"s": 2344,
"text": "Side note: The default behavior of datetime formatting in HoloViews is to print the date/time down to the nanosecond. Documentation for controlling this behavior is often hard to find and not entirely clear for beginners. This formatting problem can be solved by creating a DatetimeTickFormatter object and passing it to the graphs as needed."
},
{
"code": null,
"e": 2825,
"s": 2687,
"text": "from bokeh.models.formatters import DatetimeTickFormatterdtf = DatetimeTickFormatter( days = '%m-%Y', months = '%m-%Y' , years = '%m-%Y')"
},
{
"code": null,
"e": 3087,
"s": 2825,
"text": "Before plotting the data it needs to be transformed into content that will make the plots meaningful and in the proper format to be passed to HoloVeiws. Some of the basic pandas manipulations are excluded from this article. The full file can be found at github."
},
{
"code": null,
"e": 3279,
"s": 3087,
"text": "Creating the cohorts is the first step in a cohort analysis and there are many ways one can produce this calculation. Given the format of the input data, the following steps are applied here:"
},
{
"code": null,
"e": 3848,
"s": 3279,
"text": "### Calculate start period of the subscription## #1 Create cohorts based on the first observation of a month with a positive mrr valuecohort = (mrr > 0).idxmax( axis = 1).rename('cohort')## #2 Add the cohort date to the indextenure = mrr.join( cohort ).set_index( 'cohort', append = True).stack()tenure = tenure.reset_index( ).rename( columns = {'level_2':'date',## #3 Calculate the number of periods (months) from the cohort date to the mrr date0:'revenue'} )tenure['periods'] = np.round( (tenure['date'] - tenure['cohort']) / np.timedelta64(1, 'M') ,0).astype(int)"
},
{
"code": null,
"e": 4536,
"s": 3848,
"text": "The code in #1 converts the dataframe into values into binary variables that are true when there is positive revenue in a month. Then idxmax is applied to extract the column title of the first occurrence of the maximum value, which will be the first date when revenue is positive. The result is a series with the same index as mrr and the series is appended as a secondary index in #2 to mrr, stacked (this operation unvpivots the data by turning the column headers, monthly dates in this case, into a value field) and saved as a new dataframe called tenure. Step #3 calculates the number of periods (months in this case) that have elapsed between the cohort month and the current month."
},
{
"code": null,
"e": 4972,
"s": 4536,
"text": "Two curves that are often useful to produce in the EDA phase of a cohort analysis that will give a general understanding of the customer retention. Both represent the percentage of business that is remaining at a given point in time relative to the first period that each customer was active. One uses customers as the numerator and denominator and the other uses revenue. These calculations are broken up into two segments as follows:"
},
{
"code": null,
"e": 5403,
"s": 4972,
"text": "## #1 Calculate revenue and subs count by cohort by monthgb = tenure.groupby( [ pd.Grouper( key ='cohort' , freq = 'M') , 'periods'])rev_cohorts = gb['revenue'].sum().unstack()count_cohorts = gb['sub_id'].nunique().unstack()## #2 turn them into a percentage relative to the first monthscaled_revenue_cohorts = rev_cohorts.apply( lambda x : x/x[0] ,axis = 1)scaled_count_cohorts = count_cohorts.apply( lambda x : x/x[0] ,axis = 1)"
},
{
"code": null,
"e": 5857,
"s": 5403,
"text": "The calculations in #1 compute the total revenue and unique count of customers for a monthly cohort of customers in each period where there are observations and the unstack command pivots the periods into column headers, which will be useful for plotting with hvplot. The calculations in #2 take advantage of the new data shape and apply a lambda function to divide each period value (revenue or customer count) by the value observed in the first month."
},
{
"code": null,
"e": 6118,
"s": 5857,
"text": "The hvplot extension to HoloViews provides a very quick way to generate interactive visualizations from pandas objects that can help with EDA. The following code, which follows the same API format as the matplotlib, quickly produces line plots for exploration."
},
{
"code": null,
"e": 6451,
"s": 6118,
"text": "### Quick hvplot of both dataframesp1 = scaled_revenue_cohorts[scaled_revenue_cohorts>0].T.hvplot( figsize = [11,7], legend=False , title = 'Revenue')p2 = scaled_count_cohorts[scaled_count_cohorts>0].T.hvplot(figsize = [11,7], legend=False , title = 'Logo Count')### Add the graphs together to display as one output(p1 + p2).cols(1)"
},
{
"code": null,
"e": 6772,
"s": 6451,
"text": "There are two things that are easier to implement than would be in HoloViews than in plotting packages. The tooltips allow one to explore the data interactively and are generated automatically. The syntax for adding the graphs together into a single visualization is easier than calling the axes objects from matplotlib."
},
{
"code": null,
"e": 7525,
"s": 6772,
"text": "These graphs are already very informative and help to guide the rest of the analysis. First, notice that there is a mix of different subscription lengths. It will be best to analyze the retention of the different duration options separately since obviously a one year subscription is going to have a different profile than a one month subscription. Secondly, the profile of the retention curves is changing. The shorter lines are the most recent ones since there is simply less data available. These have more curvature than the older ones and also they appear to have a lower retention percentage. Later this article will show a better way to demonstrate this pattern. Before that, we will explore what is changing in the underlying subscription base."
},
{
"code": null,
"e": 8068,
"s": 7525,
"text": "Retention patterns often begin to change when there is a change in the mix of new business. The mix of new business could be changing because of new marketing activities, product offerings, duration options, regional or demographic characteristics, among many other things. In this data set only duration and subscription tiers are available as categorical features. A good way to assess how the mix of any categorical feature changes over time is to plot them in a stacked two bar charts showing the total volume and the relative percentage."
},
{
"code": null,
"e": 8190,
"s": 8068,
"text": "In order to generate the next set of graphs the data will need to be reshaped splitting the cohorts by tier and duration."
},
{
"code": null,
"e": 8514,
"s": 8190,
"text": "## #1 Create product duration cohortsgb = tenure.groupby( ['sub_product','sub_duration','cohort', 'subs_id','periods'])## #2 Divide each periods user count (observations with revenue > 0) by the month 0 countcohorts_scaled = gb['revenue'].sum().unstack().groupby(level=[0,1,2]).apply( lambda x : (x>0).sum()/(x[0]>0).sum())"
},
{
"code": null,
"e": 8609,
"s": 8514,
"text": "With the new cohorts data creating the bar charts is fairly easy but does require a few lines:"
},
{
"code": null,
"e": 9137,
"s": 8609,
"text": "## #1 mix = cohorts[0].rename('count').reset_index()mix = mix.set_index(['cohort','sub_product','sub_duration'] )mix = mix.sort_index()## #2abs_bars = hv.Bars( mix )abs_bars.opts( stacked = True, xrotation = 45 , width = 700 , height = 400 , xaxis= None , ylabel = 'Conversions')## #3hund_bars = hv.Bars( mix/mix.groupby( level =0 ).sum() )hund_bars.opts( stacked = True, xrotation = 45 , width = 700 , height = 400 , xformatter = dtf, ylabel = 'Relative %')layout = (abs_bars + hund_bars).cols(1)layout.opts(shared_axes=False)"
},
{
"code": null,
"e": 9448,
"s": 9137,
"text": "The code under #1 create a multi indexed series that can be passed to the HoloViews bars class. Holoviews requires flat data as opposed to hvplot which can operate smoothly with tabular data. The .opts() method in HoloViews gives the developer very detailed control over almost every part of the visualization."
},
{
"code": null,
"e": 9640,
"s": 9448,
"text": "The bar charts shows that the product tier has not been changing in any clear trend over time. However, repeating this step for duration shows a significant change in the mix of new business."
},
{
"code": null,
"e": 9888,
"s": 9640,
"text": "Six month subscriptions are being replaced entirely by one month subscriptions. This result is almost certainly causing the overall shift in the retention curve. In order to prove that out we will plot the retention curves by product and duration."
},
{
"code": null,
"e": 10360,
"s": 9888,
"text": "The previously shown plots are easy to produce and appealing, but limited in terms of interactivity. One of the nice features of HoloViews is being able to produce dashboard like visualizations. Additionally it produces these visualizations in html so that they may be embedded in a web page. These features require more code than simply passing a dataframe into hvplot. These features are demonstrated with two visualizations are useful for identifying retention trends."
},
{
"code": null,
"e": 10753,
"s": 10360,
"text": "Before producing the visualizations, building some helper functions will keep the code more readable. In the previously shown cohort curve plots, it can be a difficult to see which line belongs to which vintage. In order to make that more clear one can assign a color that fades with the cohort age. The following code block colors the lines blue and has the blue fade to white/gray with age."
},
{
"code": null,
"e": 11300,
"s": 10753,
"text": "def gen_cohort_plot( cohort ): cohort = cohort[ cohort > 0]## #1 Create curves with hvplot plot = cohort.T.hvplot( width=700, height=350, legend=False ) d_min = 2015 REPLACE d_max = 2017 REPLACE## #2 loop through curves to adjust the formatting for item in plot.items(): date , curve = item year = pd.to_datetime( date ).year ## #3 interpolate the blue scale bounded between .2 and .8 c = plt.cm.Blues( .8* (year - d_min ) / ( d_max - d_min ) + .2) curve.opts( hv.opts.Curve( color=c )) return plot"
},
{
"code": null,
"e": 11622,
"s": 11300,
"text": "The function looks intimidating, but the logic is pretty simple. In #1 hvplot is used to generate the same curves as shown previously. These curves are looped through in #2, while #3 linearly interpolates the cohort year cohort year relative to the minimum and maximum cohort year onto the blue color map from matplotlib."
},
{
"code": null,
"e": 12454,
"s": 11622,
"text": "## #1 loop through possible pairs of product and duration ## pd_curve is a helper function that just filters data before ## being passed to gen_cohort_plot()curve_dict_2D = {(d,p):pd_curve(p,d, cohorts_scaled) for p in products for d in durations }## #2 create hmap visualizations hmap = hv.HoloMap(curve_dict_2D , kdims=['Duration', 'Product'])## generate a plot of the number of conversionsconv_curve_dict_2D = {(d,p):conversion_plot( p , d , cohorts ) for p in products for d in durations }conv_hmap = hv.HoloMap(conv_curve_dict_2D, kdims=['Duration', 'Product'])## generate a plot of the average price for a cohorts first monthasp_curve_dict_2D = {(d,p):asp_plot(p,d, cohort_asp) for p in products for d in durations }asp_hmap = hv.HoloMap(asp_curve_dict_2D, kdims=['Duration', 'Product'])(hmap +conv_hmap + asp_hmap ).cols(1)"
},
{
"code": null,
"e": 12645,
"s": 12454,
"text": "The curves are stored in a dictionary that can be passed in different layout options. Shown here is the HoloMap. A HoloMap produces a drop downs selectors based on the dictionary keys shown:"
},
{
"code": null,
"e": 12939,
"s": 12645,
"text": "The darker the line the more recent the cohort. After clicking through the different combinations it becomes clear that the one month subscriptions have a worsen retention profile. We’ve previously observed that one month subscriptions are making up a growing portion of the new customer base."
},
{
"code": null,
"e": 13378,
"s": 12939,
"text": "While coloring the the lines different shades aids in visualizing the age of the cohorts, heatmaps provide an alternative method to display the information which makes certain trends more easy to identify. Heatmaps do however require more explanation than the line plot, if it is being presented to parties who are unfamiliar with this format. The tutorial will conclude with a discussion of how to produce and interpret the heatmap view."
},
{
"code": null,
"e": 13463,
"s": 13378,
"text": "Helper functions are created to format the graphs and make the code more manageable."
},
{
"code": null,
"e": 14700,
"s": 13463,
"text": "def heatmap_product_duration( product , duration , data = cohorts_scaled):## #1 filter the data for the product duration pair idx = pd.IndexSlice data = data.loc[ idx[product, duration, :] , :].reset_index( level = [0,1], drop = True) data = data[data>0] data = data.stack().rename( 'retention').reset_index() data = data[ data['retention'] > 0] data.columns = ['cohort','tenure','retention']## #2 Create a heatmap hm = hv.HeatMap(data , kdims=['tenure','cohort']).sort()## #3 Formatting options note the addition of the hover tool hm.opts( opts.HeatMap( width = 500 , height = 500 ,colorbar = True, yformatter = dtf , xrotation = 90 ,cmap = 'RdYlGn' ,tools=['hover'], toolbar='above')) return hmdef left_conv_bar( product , duration, data = cohorts ):## #1 filter the data for the product duration pair idx = pd.IndexSlice data = data.loc[ idx[product, duration, :] , :].reset_index( level = [0,1], drop = True) data = data.loc[:,0].rename( 'conversions').reset_index() ## #2 similar to the previous bar charts, note the invert_axes option bar = hv.Bars( data ).opts( invert_axes=True , height = 500 , width = 200 , color = 'Green' , yaxis = None, invert_xaxis=True ) return bar"
},
{
"code": null,
"e": 14913,
"s": 14700,
"text": "After building the helper functions, in a way similar to before, the code loops through the product duration pairs and creates a dictionary to store the visualizations before ultimately passing them to a HoloMap."
},
{
"code": null,
"e": 15335,
"s": 14913,
"text": "heatmap_curve_dict_2D = {(d,p):heatmap_product_duration(p,d) for p in products for d in durations }heatmap_hmap = hv.HoloMap(heatmap_curve_dict_2D, kdims=['Duration', 'Product'])left_bar_curve_dict_2D = {(d,p):left_conv_bar(p,d) for p in products for d in durations }left_bar_hmap = hv.HoloMap(left_bar_curve_dict_2D, kdims=['Duration', 'Product'])layout = (left_bar_hmap + heatmap_hmap ).opts( shared_axes = True)layout"
},
{
"code": null,
"e": 15874,
"s": 15335,
"text": "This view shows how the cohorts are aging differently by observing the green in early tenure periods shift to yellow after October 2018 for all tiers of the one month subscription. Note that this shift also corresponds to the period when the number of conversions begins to increase. This phenomenon is fairly common in evolving businesses. Increasing marketing spend or making product/pricing changes will attract more new customers but the incremental new customers are not necessarily the same as the customers in the previous cohorts."
}
]
|
An Introductory Reinforcement Learning Project: Learning Tic-Tac-Toe via Self-Play Tabular Q-learning | by Ryan Rudes | Towards Data Science | In this project, I’ll walk through an introductory project on tabular Q-learning. We’ll train a simple RL agent to be able to evaluate tic-tac-toe positions in order to return the best move by playing against itself for many games.
First, let’s import the required libraries
Note that tabular q-learning only works for environments which can be represented by a reasonable number of actions and states. Tic-tac-toe has 9 squares, each of which can be either an X, and O, or empty. Therefore, there are approximately 39 = 19683 states (and 9 actions, of course). Therefore, we have a table with 19683 x 9 = 177147 cells. This is not small, but it is certainly feasible for tabular q-learning. In fact, we could exploit the fact that the game of tic-tac-toe is unchanged by rotations of the board. Therefore, there are actually far fewer “unique states”, if you consider rotations and reflections of a particular board configuration the same. I won’t get into deep Q-learning, because this is intended to be an introductory project.
First, we initialize our q-table with the aforementioned shape:
Now, let’s set some hyperparameters for training:
Now, we need to set up an exploration strategy. Assuming you understand exploration-exploitation in RL, the exploration strategy is the way we will gradually decrease epsilon (the probability of taking random actions). We need to initially play at least semi-randomly in order to properly explore the environment (the possible tic-tac-toe board configurations). But we cannot forever take random actions, because RL is an iterative process that relies under the assumption that the evaluation of future reward gets better over time. If we simply played random games forever, we would be trying to associate a random list of actions with some final game result that has no actual dependency upon any particular action we took.
Now, let’s create a graph of epsilon vs. episodes (number of games simulated) with matplotlib, saving the figure to an image file:
When we start to simulate games, we need to set some restrictions so that the agents can’t make insensible moves. In tic-tac-toe, occupied squares are no longer available, so we need a function to return the legal moves, given a board configuration. We will be representing our board by a 3x3 NumPy array, where unoccupied squares are 0, X’s are 1, and O’s are -1. We can use NumPy’s np.argwhereto retrieve the indices of the 0 elements.
We also need a helper function to convert between a 3x3 board representation and an integer state. We’re storing the future reward estimations in a q-table, so we need to be able to index any particular board configuration with ease. My algorithm for converting between the board in the format I previously described works by partitioning the total number of possible states into a number of sections corresponding to the number of actions. For each cell in the board:
If the cell is -1, you don’t change state
If the cell is 0, you change state by one-third of the window size
If the cell is 1, you change state by two-thirds of the window size.
Finally, we need one last helper function to determine when the game has reached a terminal state. This function also needs to return the result of the game if it is indeed over. My implementation checks the rows, columns, and diagonals for a series of either 3 consecutive 1's or 3 consecutive -1’s by taking the sum of the board array across each axis. This produces 3 sums, one for each axis or column. If -3 is one of these sums, this axis must have all -1’s, indicating that the player corresponding to -1 won and vice versa. The diagonals work just the same, except there are only 2 diagonals, while there are 3 rows and 3 columns. My original implementation is a bit naive, I found a much better one online. It’s much shorter and improves speed slightly.
Now, let’s initialize some lists to record training metrics.
past_results will store the results of each simulated game, with 0 representing a tie, 1 indicating that the player corresponding to the positive integer won, and vice versa with -1.
win_probs will store a list of percentages, updated after each episode. Each value tells the fraction of games up to the current episode in which either player has won. draw_probs also records percentages, but corresponding to the fraction of games in which a draw occurred.
After training, if we were to graph win_probs and draw_probs, they should demonstrate the following behavior.
Early in training, the win probability will be high, while the draw probability will be low. This is because when both opponents are taking random actions in a game like tic-tac-toe, there will more often be wins than draws simply due to the existence of a larger number of win states than draw states.Mid-way through training, when the agent begins to play according to its table’s policy, the win and draw probabilities will fluctuate with symmetry across the 50% line. Once the agent starts playing competitively against itself, it will encounter more draws, as both sides are playing according to the same strategic policy. Each time the agent discovers a new offensive strategy, there will be a fluctuation in the graph, for the agent is able to trick its opponent (itself) for a short period of time.After fluctuating for a while, draw probabilities should approach 100%. If the agent was truly playing optimally against itself, it would always encounter a draw, for it is attempting to maximize reward according to a table of expected future rewards... the same table being used by the opponent (itself).
Early in training, the win probability will be high, while the draw probability will be low. This is because when both opponents are taking random actions in a game like tic-tac-toe, there will more often be wins than draws simply due to the existence of a larger number of win states than draw states.
Mid-way through training, when the agent begins to play according to its table’s policy, the win and draw probabilities will fluctuate with symmetry across the 50% line. Once the agent starts playing competitively against itself, it will encounter more draws, as both sides are playing according to the same strategic policy. Each time the agent discovers a new offensive strategy, there will be a fluctuation in the graph, for the agent is able to trick its opponent (itself) for a short period of time.
After fluctuating for a while, draw probabilities should approach 100%. If the agent was truly playing optimally against itself, it would always encounter a draw, for it is attempting to maximize reward according to a table of expected future rewards... the same table being used by the opponent (itself).
Let’s write the training script. For each episode, we begin at a non-terminal state: an empty 3x3 board filled with 0’s. It each move, with some probability epsilon, the agent takes a random action from the list of available squares. Otherwise, it looks up the row of the q-table corresponding to the current state and selects the action which maximizes the expected future reward. The integer representation of the new board state is computed, and we record the pair (s, a, s’). Once this game ends, we will need to correlate the state-action pair we just observed with the final game results (which are yet-to-be-determined). Once the game ends, we refer back to each recorded state-action pair, and update the corresponding cell of the q-table according to the following:
In the above update formula, s is the integer representation of the state, a is the integer representation of the action the agent took at state s , alpha is the learning rate, R(s, a) is the reward (in our case, the end result of the corresponding game in which this pair (s, a) was observed), Q is the q-table, and the statement involving max represents the maximum expected reward for the resulting state. Say the board configuration was:
[[0, 0, 0], [0, 0, 0], [0, 0, 1]]
and we took the action 3, corresponding to the cell at coordinate (1, 0), the resulting state would be:
[[0 0, 0], [-1, 0, 0], [0, 0, 1]]
This part of the update formula is referring to the maximum expected reward for any of the actions we could take from here, according to the policy defined by our current q-table. Therefore, s' is the second state I just described, and a' is all of the actions we could theoretically take from this state (0–8), although in reality, some are illegal (but this is irrelevant).
At the end of every 1000 episodes, I just save the list of training metrics, and a plot of these metrics. At the end, I save the q-table and the lists storing these training metrics.
I trained mine with Google Colab’s online GPU, but you can train yours locally if you’d like; you don’t necessarily have to train all the way to convergence to see great results.
Just as I previously mentioned, the relationship between games terminating in a win/loss and those terminating in a draw should work as follows:
Earlier in training, an unskilled, randomly-playing agent will frequently encounter win-loss scenarios.
Each time the agent discovers a new strategy, there will be fluctuations.
Towards the end of training, near convergence, the agent will almost always encounter a draw, as it is playing optimally against itself.
Therefore, the larger fluctuations in the graph indicate moments when the agent learned to evaluate a particular board configuration very well, and in doing so this allowed it to prevent draws.
We can see this is clearly demonstrated in the resulting graph:
Throughout the middle of training, it frequently appears as if the q-table will converge, only to quickly change entirely. These are the aforementioned moments when a significant strategy was exploited for the first time.
Also, as you can see, the fluctuations occur more rarely as you progress throughout training. This is due to the fact that there are less yet-to-be-discovered tactics as your progress. Theoretically, if the agent converged, there would never be any more great fluctuations like this. Draws would occur 100% of the time and after the rapid rise in the draw percentage, it would not fall back down again.
I decided it would be a good idea to visualize the change in the q-values over time, so I retrained it while recording the sum of the absolute values of the Q table at each episode. Whether a particular q-value is positive or negative recording the sum of all absolute q-values shows us when convergence is occurring (the gradient of the q-values over time decreases as we reach convergence).
You can visit the full code on Google Colab here:
colab.research.google.com
Or on GitHub here:
Experimenting with the exploration strategy will influence training. You can change parameters relating to epsilon, as well as how it is decayed in order to get different results.
One final thing to note is that Tic-Tac-Toe can be approached much more easily with simpler value iteration methods because the transition matrix is a given, as well as the reward matrix. This sort of epsilon-greedy optimization is really unnecessary for an environment like Tic-Tac-Toe. | [
{
"code": null,
"e": 403,
"s": 171,
"text": "In this project, I’ll walk through an introductory project on tabular Q-learning. We’ll train a simple RL agent to be able to evaluate tic-tac-toe positions in order to return the best move by playing against itself for many games."
},
{
"code": null,
"e": 446,
"s": 403,
"text": "First, let’s import the required libraries"
},
{
"code": null,
"e": 1202,
"s": 446,
"text": "Note that tabular q-learning only works for environments which can be represented by a reasonable number of actions and states. Tic-tac-toe has 9 squares, each of which can be either an X, and O, or empty. Therefore, there are approximately 39 = 19683 states (and 9 actions, of course). Therefore, we have a table with 19683 x 9 = 177147 cells. This is not small, but it is certainly feasible for tabular q-learning. In fact, we could exploit the fact that the game of tic-tac-toe is unchanged by rotations of the board. Therefore, there are actually far fewer “unique states”, if you consider rotations and reflections of a particular board configuration the same. I won’t get into deep Q-learning, because this is intended to be an introductory project."
},
{
"code": null,
"e": 1266,
"s": 1202,
"text": "First, we initialize our q-table with the aforementioned shape:"
},
{
"code": null,
"e": 1316,
"s": 1266,
"text": "Now, let’s set some hyperparameters for training:"
},
{
"code": null,
"e": 2042,
"s": 1316,
"text": "Now, we need to set up an exploration strategy. Assuming you understand exploration-exploitation in RL, the exploration strategy is the way we will gradually decrease epsilon (the probability of taking random actions). We need to initially play at least semi-randomly in order to properly explore the environment (the possible tic-tac-toe board configurations). But we cannot forever take random actions, because RL is an iterative process that relies under the assumption that the evaluation of future reward gets better over time. If we simply played random games forever, we would be trying to associate a random list of actions with some final game result that has no actual dependency upon any particular action we took."
},
{
"code": null,
"e": 2173,
"s": 2042,
"text": "Now, let’s create a graph of epsilon vs. episodes (number of games simulated) with matplotlib, saving the figure to an image file:"
},
{
"code": null,
"e": 2611,
"s": 2173,
"text": "When we start to simulate games, we need to set some restrictions so that the agents can’t make insensible moves. In tic-tac-toe, occupied squares are no longer available, so we need a function to return the legal moves, given a board configuration. We will be representing our board by a 3x3 NumPy array, where unoccupied squares are 0, X’s are 1, and O’s are -1. We can use NumPy’s np.argwhereto retrieve the indices of the 0 elements."
},
{
"code": null,
"e": 3080,
"s": 2611,
"text": "We also need a helper function to convert between a 3x3 board representation and an integer state. We’re storing the future reward estimations in a q-table, so we need to be able to index any particular board configuration with ease. My algorithm for converting between the board in the format I previously described works by partitioning the total number of possible states into a number of sections corresponding to the number of actions. For each cell in the board:"
},
{
"code": null,
"e": 3122,
"s": 3080,
"text": "If the cell is -1, you don’t change state"
},
{
"code": null,
"e": 3189,
"s": 3122,
"text": "If the cell is 0, you change state by one-third of the window size"
},
{
"code": null,
"e": 3258,
"s": 3189,
"text": "If the cell is 1, you change state by two-thirds of the window size."
},
{
"code": null,
"e": 4020,
"s": 3258,
"text": "Finally, we need one last helper function to determine when the game has reached a terminal state. This function also needs to return the result of the game if it is indeed over. My implementation checks the rows, columns, and diagonals for a series of either 3 consecutive 1's or 3 consecutive -1’s by taking the sum of the board array across each axis. This produces 3 sums, one for each axis or column. If -3 is one of these sums, this axis must have all -1’s, indicating that the player corresponding to -1 won and vice versa. The diagonals work just the same, except there are only 2 diagonals, while there are 3 rows and 3 columns. My original implementation is a bit naive, I found a much better one online. It’s much shorter and improves speed slightly."
},
{
"code": null,
"e": 4081,
"s": 4020,
"text": "Now, let’s initialize some lists to record training metrics."
},
{
"code": null,
"e": 4264,
"s": 4081,
"text": "past_results will store the results of each simulated game, with 0 representing a tie, 1 indicating that the player corresponding to the positive integer won, and vice versa with -1."
},
{
"code": null,
"e": 4539,
"s": 4264,
"text": "win_probs will store a list of percentages, updated after each episode. Each value tells the fraction of games up to the current episode in which either player has won. draw_probs also records percentages, but corresponding to the fraction of games in which a draw occurred."
},
{
"code": null,
"e": 4649,
"s": 4539,
"text": "After training, if we were to graph win_probs and draw_probs, they should demonstrate the following behavior."
},
{
"code": null,
"e": 5761,
"s": 4649,
"text": "Early in training, the win probability will be high, while the draw probability will be low. This is because when both opponents are taking random actions in a game like tic-tac-toe, there will more often be wins than draws simply due to the existence of a larger number of win states than draw states.Mid-way through training, when the agent begins to play according to its table’s policy, the win and draw probabilities will fluctuate with symmetry across the 50% line. Once the agent starts playing competitively against itself, it will encounter more draws, as both sides are playing according to the same strategic policy. Each time the agent discovers a new offensive strategy, there will be a fluctuation in the graph, for the agent is able to trick its opponent (itself) for a short period of time.After fluctuating for a while, draw probabilities should approach 100%. If the agent was truly playing optimally against itself, it would always encounter a draw, for it is attempting to maximize reward according to a table of expected future rewards... the same table being used by the opponent (itself)."
},
{
"code": null,
"e": 6064,
"s": 5761,
"text": "Early in training, the win probability will be high, while the draw probability will be low. This is because when both opponents are taking random actions in a game like tic-tac-toe, there will more often be wins than draws simply due to the existence of a larger number of win states than draw states."
},
{
"code": null,
"e": 6569,
"s": 6064,
"text": "Mid-way through training, when the agent begins to play according to its table’s policy, the win and draw probabilities will fluctuate with symmetry across the 50% line. Once the agent starts playing competitively against itself, it will encounter more draws, as both sides are playing according to the same strategic policy. Each time the agent discovers a new offensive strategy, there will be a fluctuation in the graph, for the agent is able to trick its opponent (itself) for a short period of time."
},
{
"code": null,
"e": 6875,
"s": 6569,
"text": "After fluctuating for a while, draw probabilities should approach 100%. If the agent was truly playing optimally against itself, it would always encounter a draw, for it is attempting to maximize reward according to a table of expected future rewards... the same table being used by the opponent (itself)."
},
{
"code": null,
"e": 7650,
"s": 6875,
"text": "Let’s write the training script. For each episode, we begin at a non-terminal state: an empty 3x3 board filled with 0’s. It each move, with some probability epsilon, the agent takes a random action from the list of available squares. Otherwise, it looks up the row of the q-table corresponding to the current state and selects the action which maximizes the expected future reward. The integer representation of the new board state is computed, and we record the pair (s, a, s’). Once this game ends, we will need to correlate the state-action pair we just observed with the final game results (which are yet-to-be-determined). Once the game ends, we refer back to each recorded state-action pair, and update the corresponding cell of the q-table according to the following:"
},
{
"code": null,
"e": 8092,
"s": 7650,
"text": "In the above update formula, s is the integer representation of the state, a is the integer representation of the action the agent took at state s , alpha is the learning rate, R(s, a) is the reward (in our case, the end result of the corresponding game in which this pair (s, a) was observed), Q is the q-table, and the statement involving max represents the maximum expected reward for the resulting state. Say the board configuration was:"
},
{
"code": null,
"e": 8126,
"s": 8092,
"text": "[[0, 0, 0], [0, 0, 0], [0, 0, 1]]"
},
{
"code": null,
"e": 8230,
"s": 8126,
"text": "and we took the action 3, corresponding to the cell at coordinate (1, 0), the resulting state would be:"
},
{
"code": null,
"e": 8265,
"s": 8230,
"text": "[[0 0, 0], [-1, 0, 0], [0, 0, 1]]"
},
{
"code": null,
"e": 8641,
"s": 8265,
"text": "This part of the update formula is referring to the maximum expected reward for any of the actions we could take from here, according to the policy defined by our current q-table. Therefore, s' is the second state I just described, and a' is all of the actions we could theoretically take from this state (0–8), although in reality, some are illegal (but this is irrelevant)."
},
{
"code": null,
"e": 8824,
"s": 8641,
"text": "At the end of every 1000 episodes, I just save the list of training metrics, and a plot of these metrics. At the end, I save the q-table and the lists storing these training metrics."
},
{
"code": null,
"e": 9003,
"s": 8824,
"text": "I trained mine with Google Colab’s online GPU, but you can train yours locally if you’d like; you don’t necessarily have to train all the way to convergence to see great results."
},
{
"code": null,
"e": 9148,
"s": 9003,
"text": "Just as I previously mentioned, the relationship between games terminating in a win/loss and those terminating in a draw should work as follows:"
},
{
"code": null,
"e": 9252,
"s": 9148,
"text": "Earlier in training, an unskilled, randomly-playing agent will frequently encounter win-loss scenarios."
},
{
"code": null,
"e": 9326,
"s": 9252,
"text": "Each time the agent discovers a new strategy, there will be fluctuations."
},
{
"code": null,
"e": 9463,
"s": 9326,
"text": "Towards the end of training, near convergence, the agent will almost always encounter a draw, as it is playing optimally against itself."
},
{
"code": null,
"e": 9657,
"s": 9463,
"text": "Therefore, the larger fluctuations in the graph indicate moments when the agent learned to evaluate a particular board configuration very well, and in doing so this allowed it to prevent draws."
},
{
"code": null,
"e": 9721,
"s": 9657,
"text": "We can see this is clearly demonstrated in the resulting graph:"
},
{
"code": null,
"e": 9943,
"s": 9721,
"text": "Throughout the middle of training, it frequently appears as if the q-table will converge, only to quickly change entirely. These are the aforementioned moments when a significant strategy was exploited for the first time."
},
{
"code": null,
"e": 10346,
"s": 9943,
"text": "Also, as you can see, the fluctuations occur more rarely as you progress throughout training. This is due to the fact that there are less yet-to-be-discovered tactics as your progress. Theoretically, if the agent converged, there would never be any more great fluctuations like this. Draws would occur 100% of the time and after the rapid rise in the draw percentage, it would not fall back down again."
},
{
"code": null,
"e": 10739,
"s": 10346,
"text": "I decided it would be a good idea to visualize the change in the q-values over time, so I retrained it while recording the sum of the absolute values of the Q table at each episode. Whether a particular q-value is positive or negative recording the sum of all absolute q-values shows us when convergence is occurring (the gradient of the q-values over time decreases as we reach convergence)."
},
{
"code": null,
"e": 10789,
"s": 10739,
"text": "You can visit the full code on Google Colab here:"
},
{
"code": null,
"e": 10815,
"s": 10789,
"text": "colab.research.google.com"
},
{
"code": null,
"e": 10834,
"s": 10815,
"text": "Or on GitHub here:"
},
{
"code": null,
"e": 11014,
"s": 10834,
"text": "Experimenting with the exploration strategy will influence training. You can change parameters relating to epsilon, as well as how it is decayed in order to get different results."
}
]
|
ContainsKey in C# | ContainsKey is a Dictionary method in C# and check whether a key exists in the Dictionary or not.
Declare a Dictionary and add elements −
var dict = new Dictionary<string, int>() {
{"TV", 1},
{"Home Theatre", 2},
{"Amazon Alexa", 3},
{"Google Home", 5},
{"Laptop", 5},
{"Bluetooth Speaker", 6}
};
Now, let’s say you need to check for the existence of a particular element in the Dictionary. For that, use the ContainsKey() method −
if (dict.ContainsKey("Laptop") == true) {
Console.WriteLine(dict["Laptop"]);
}
The following is the code −
Live Demo
using System;
using System.Collections.Generic;
public class Demo {
public static void Main() {
var dict = new Dictionary<string, int>() {
{"TV", 1},
{"Home Theatre", 2},
{"Amazon Alexa", 3},
{"Google Home", 5},
{"Laptop", 5},
{"Bluetooth Speaker", 6}
};
if (dict.ContainsKey("Laptop") == true) {
Console.WriteLine(dict["Laptop"]);
}
if (dict.ContainsKey("Amazon Alexa") == true) {
Console.WriteLine(dict["Amazon Alexa"]);
}
}
}
5
3 | [
{
"code": null,
"e": 1160,
"s": 1062,
"text": "ContainsKey is a Dictionary method in C# and check whether a key exists in the Dictionary or not."
},
{
"code": null,
"e": 1200,
"s": 1160,
"text": "Declare a Dictionary and add elements −"
},
{
"code": null,
"e": 1377,
"s": 1200,
"text": "var dict = new Dictionary<string, int>() {\n {\"TV\", 1},\n {\"Home Theatre\", 2},\n {\"Amazon Alexa\", 3},\n {\"Google Home\", 5},\n {\"Laptop\", 5},\n {\"Bluetooth Speaker\", 6}\n};"
},
{
"code": null,
"e": 1512,
"s": 1377,
"text": "Now, let’s say you need to check for the existence of a particular element in the Dictionary. For that, use the ContainsKey() method −"
},
{
"code": null,
"e": 1594,
"s": 1512,
"text": "if (dict.ContainsKey(\"Laptop\") == true) {\n Console.WriteLine(dict[\"Laptop\"]);\n}"
},
{
"code": null,
"e": 1622,
"s": 1594,
"text": "The following is the code −"
},
{
"code": null,
"e": 1633,
"s": 1622,
"text": " Live Demo"
},
{
"code": null,
"e": 2176,
"s": 1633,
"text": "using System;\nusing System.Collections.Generic;\npublic class Demo {\n public static void Main() {\n var dict = new Dictionary<string, int>() {\n {\"TV\", 1},\n {\"Home Theatre\", 2},\n {\"Amazon Alexa\", 3},\n {\"Google Home\", 5},\n {\"Laptop\", 5},\n {\"Bluetooth Speaker\", 6}\n };\n if (dict.ContainsKey(\"Laptop\") == true) {\n Console.WriteLine(dict[\"Laptop\"]);\n }\n if (dict.ContainsKey(\"Amazon Alexa\") == true) {\n Console.WriteLine(dict[\"Amazon Alexa\"]);\n }\n }\n}"
},
{
"code": null,
"e": 2180,
"s": 2176,
"text": "5\n3"
}
]
|
Java | ==, equals(), compareTo(), equalsIgnoreCase() and compare() | 06 Jun, 2021
There are many ways to compare two Strings in Java:
Using == operator
Using equals() method
Using compareTo() method
Using compareToIgnoreCase() method
Using compare() methodMethod 1: using == operatorDouble equals operator is used to compare two or more than two objects, If they are referring to the same object then return true, otherwise return false. String is immutable in java. When two or more objects are created without new keyword, then both object refer same value. Double equals operator actually compares objects references.
Method 1: using == operatorDouble equals operator is used to compare two or more than two objects, If they are referring to the same object then return true, otherwise return false. String is immutable in java. When two or more objects are created without new keyword, then both object refer same value. Double equals operator actually compares objects references.
Below example illustrate the use of == for string comparison in Java:
JAVA
// Java program to demonstrate// use of == operator in Java class GFG { public static void main(String[] args) { // Get some Strings to compare String s1 = "A"; String s2 = "A"; String s3 = "A"; String s4 = new String("A"); // Compare s1 and s2 // It should return true as they both // refer to same object in memory System.out.println(s1 + " == " + s2 + ": " + (s1 == s2)); // Compare s1 and s3 // It should return true as they both // refer to same object in memory System.out.println(s1 + " == " + s3 + ": " + (s1 == s3)); // Compare s2 and s3 // It should return true as they both // refer to same object in memory System.out.println(s2 + " == " + s3 + ": " + (s2 == s3)); // Compare s1 and s4 // It should return false as they both // refer to different object in memory System.out.println(s1 + " == " + s4 + ": " + (s1 == s4)); }}
A == A: true
A == A: true
A == A: true
A == A: false
Method 2: Using equals() methodIn Java, string equals() method compares the two given strings based on the data / content of the string. If all the contents of both the strings are same then it returns true. If all characters are not matched then it returns false.
Below example illustrate the use of .equals for string comparison in Java:
JAVA
// Java program to demonstrate// use of .equals operator in Java class GFG { public static void main(String[] args) { // Get some Strings to compare String s1 = "A"; String s2 = "A"; String s3 = "a"; String s4 = new String("A"); // Compare s1 and s2 // It should return true as they both // have the same content System.out.println(s1 + " .equals " + s2 + ": " + s1.equals(s2)); // Compare s1 and s3 // It should return false as they both // have the different content System.out.println(s1 + " .equals " + s3 + ": " + s1.equals(s3)); // Compare s2 and s3 // It should return false as they both // have the different content System.out.println(s2 + " .equals " + s3 + ": " + s2.equals(s3)); // Compare s1 and s4 // It should return true as they both // have the same content System.out.println(s1 + " .equals " + s4 + ": " + s1.equals(s4)); }}
A .equals A: true
A .equals a: false
A .equals a: false
A .equals A: true
Method 3: Using compareTo() methodIn java Comparable interface compares values and returns an int, these int values may be less than, equal, or greater than. The java compare two string is based on the Unicode value of each character in the strings. If two strings are different, then they have different characters at some index that is a valid index for both strings, or their lengths are different, or both. Assuming index ‘i’ is where characters are different then compareTo() will return firstString.charAt(i)-secondString.charAt(i).
Below example illustrate the use of .compareTo for string comparison in Java:
JAVA
// Java program to demonstrate// use of .compareTo operator in Java class GFG { public static void main(String[] args) { // Get some Strings to compare String s1 = "A"; String s2 = "A"; String s3 = "a"; String s4 = new String("A"); // Compare s1 and s2 // It should return 0 as they both // have the same ASCII value System.out.println(s1 + " .compareTo " + s2 + ": " + s1.compareTo(s2)); // Compare s1 and s3 // It should return -32 as they both // have the different ASCII value System.out.println(s1 + " .compareTo " + s3 + ": " + s1.compareTo(s3)); // Compare s3 and s2 // It should return 32 as they both // have the different ASCII value System.out.println(s3 + " .compareTo " + s2 + ": " + s3.compareTo(s2)); // Compare s1 and s4 // It should return 0 as they both // have the same ASCII value System.out.println(s1 + " .compareTo " + s4 + ": " + s1.compareTo(s4)); }}
A .compareTo A: 0
A .compareTo a: -32
a .compareTo A: 32
A .compareTo A: 0
Method 4: Using equalsIgnoreCase() methodJava String equalsIgnoreCase() method is much similar to equals() method, except that case is ignored like in above example String object s4 compare to s3 then equals() method return false, but here in case of equalsIgnoreCase() it will return true. Hence equalsIgnoreCase() method is Case Insensitive.
Below example illustrate the use of .equalsIgnoreCase for string comparison in Java:
JAVA
// Java program to demonstrate// use of .equalsIgnoreCase operator in Java class GFG { public static void main(String[] args) { // Get some Strings to compare String s1 = "A"; String s2 = "A"; String s3 = "a"; String s4 = new String("A"); // Compare s1 and s2 // It should return true as they both // have the same content System.out.println(s1 + " .equalsIgnoreCase " + s2 + ": " + s1.equalsIgnoreCase(s2)); // Compare s1 and s3 // It should return true as they both // have the same content being case insensitive System.out.println(s1 + " .equalsIgnoreCase " + s3 + ": " + s1.equalsIgnoreCase(s3)); // Compare s2 and s3 // It should return true as they both // have the same content being case insensitive System.out.println(s2 + " .equalsIgnoreCase " + s3 + ": " + s2.equalsIgnoreCase(s3)); // Compare s1 and s4 // It should return true as they both // have the same content System.out.println(s1 + " .equalsIgnoreCase " + s4 + ": " + s1.equalsIgnoreCase(s4)); }}
A .equalsIgnoreCase A: true
A .equalsIgnoreCase a: true
A .equalsIgnoreCase a: true
A .equalsIgnoreCase A: true
Method 5: Using compare() methodIn Java for locale specific comparison, one should use Collator class which is in java.text package. The one most important feature of Collator class is the ability to define our own custom comparison rules.
Below example illustrate the use of compare() method in Java to compare Strings:
JAVA
// Java program to demonstrate// use of collator.compare operator in Java import java.text.Collator; class GFG { public static void main(String[] args) { // Get Collator instance Collator collator = Collator.getInstance(); // Get some Strings to compare String s1 = "A"; String s2 = "A"; String s3 = "a"; String s4 = new String("A"); // Compare s1 and s2 // It should return 0 as they both // have the same ASCII value System.out.println(s1 + " collator.compare " + s2 + ": " + collator.compare(s1, s2)); // Compare s1 and s3 // It should return 1 System.out.println(s1 + " collator.compare " + s3 + ": " + collator.compare(s1, s3)); // Compare s3 and s2 // It should return -1 System.out.println(s3 + " collator.compare " + s2 + ": " + collator.compare(s3, s2)); // Compare s1 and s4 // It should return 0 as they both // have the same ASCII value System.out.println(s1 + " collator.compare " + s4 + ": " + collator.compare(s1, s4)); }}
A collator.compare A: 0
A collator.compare a: 1
a collator.compare A: -1
A collator.compare A: 0
sumitgumber28
Java-String-Programs
Java-Strings
Picked
Technical Scripter 2018
Java
Technical Scripter
Java-Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Multidimensional Arrays in Java
Collections in Java
Stream In Java
Set in Java
Singleton Class in Java | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n06 Jun, 2021"
},
{
"code": null,
"e": 108,
"s": 54,
"text": "There are many ways to compare two Strings in Java: "
},
{
"code": null,
"e": 126,
"s": 108,
"text": "Using == operator"
},
{
"code": null,
"e": 148,
"s": 126,
"text": "Using equals() method"
},
{
"code": null,
"e": 173,
"s": 148,
"text": "Using compareTo() method"
},
{
"code": null,
"e": 208,
"s": 173,
"text": "Using compareToIgnoreCase() method"
},
{
"code": null,
"e": 597,
"s": 208,
"text": "Using compare() methodMethod 1: using == operatorDouble equals operator is used to compare two or more than two objects, If they are referring to the same object then return true, otherwise return false. String is immutable in java. When two or more objects are created without new keyword, then both object refer same value. Double equals operator actually compares objects references. "
},
{
"code": null,
"e": 964,
"s": 597,
"text": "Method 1: using == operatorDouble equals operator is used to compare two or more than two objects, If they are referring to the same object then return true, otherwise return false. String is immutable in java. When two or more objects are created without new keyword, then both object refer same value. Double equals operator actually compares objects references. "
},
{
"code": null,
"e": 1035,
"s": 964,
"text": "Below example illustrate the use of == for string comparison in Java: "
},
{
"code": null,
"e": 1040,
"s": 1035,
"text": "JAVA"
},
{
"code": "// Java program to demonstrate// use of == operator in Java class GFG { public static void main(String[] args) { // Get some Strings to compare String s1 = \"A\"; String s2 = \"A\"; String s3 = \"A\"; String s4 = new String(\"A\"); // Compare s1 and s2 // It should return true as they both // refer to same object in memory System.out.println(s1 + \" == \" + s2 + \": \" + (s1 == s2)); // Compare s1 and s3 // It should return true as they both // refer to same object in memory System.out.println(s1 + \" == \" + s3 + \": \" + (s1 == s3)); // Compare s2 and s3 // It should return true as they both // refer to same object in memory System.out.println(s2 + \" == \" + s3 + \": \" + (s2 == s3)); // Compare s1 and s4 // It should return false as they both // refer to different object in memory System.out.println(s1 + \" == \" + s4 + \": \" + (s1 == s4)); }}",
"e": 2134,
"s": 1040,
"text": null
},
{
"code": null,
"e": 2189,
"s": 2136,
"text": "A == A: true\nA == A: true\nA == A: true\nA == A: false"
},
{
"code": null,
"e": 2460,
"s": 2193,
"text": "Method 2: Using equals() methodIn Java, string equals() method compares the two given strings based on the data / content of the string. If all the contents of both the strings are same then it returns true. If all characters are not matched then it returns false. "
},
{
"code": null,
"e": 2536,
"s": 2460,
"text": "Below example illustrate the use of .equals for string comparison in Java: "
},
{
"code": null,
"e": 2541,
"s": 2536,
"text": "JAVA"
},
{
"code": "// Java program to demonstrate// use of .equals operator in Java class GFG { public static void main(String[] args) { // Get some Strings to compare String s1 = \"A\"; String s2 = \"A\"; String s3 = \"a\"; String s4 = new String(\"A\"); // Compare s1 and s2 // It should return true as they both // have the same content System.out.println(s1 + \" .equals \" + s2 + \": \" + s1.equals(s2)); // Compare s1 and s3 // It should return false as they both // have the different content System.out.println(s1 + \" .equals \" + s3 + \": \" + s1.equals(s3)); // Compare s2 and s3 // It should return false as they both // have the different content System.out.println(s2 + \" .equals \" + s3 + \": \" + s2.equals(s3)); // Compare s1 and s4 // It should return true as they both // have the same content System.out.println(s1 + \" .equals \" + s4 + \": \" + s1.equals(s4)); }}",
"e": 3642,
"s": 2541,
"text": null
},
{
"code": null,
"e": 3718,
"s": 3644,
"text": "A .equals A: true\nA .equals a: false\nA .equals a: false\nA .equals A: true"
},
{
"code": null,
"e": 4262,
"s": 3722,
"text": "Method 3: Using compareTo() methodIn java Comparable interface compares values and returns an int, these int values may be less than, equal, or greater than. The java compare two string is based on the Unicode value of each character in the strings. If two strings are different, then they have different characters at some index that is a valid index for both strings, or their lengths are different, or both. Assuming index ‘i’ is where characters are different then compareTo() will return firstString.charAt(i)-secondString.charAt(i). "
},
{
"code": null,
"e": 4341,
"s": 4262,
"text": "Below example illustrate the use of .compareTo for string comparison in Java: "
},
{
"code": null,
"e": 4346,
"s": 4341,
"text": "JAVA"
},
{
"code": "// Java program to demonstrate// use of .compareTo operator in Java class GFG { public static void main(String[] args) { // Get some Strings to compare String s1 = \"A\"; String s2 = \"A\"; String s3 = \"a\"; String s4 = new String(\"A\"); // Compare s1 and s2 // It should return 0 as they both // have the same ASCII value System.out.println(s1 + \" .compareTo \" + s2 + \": \" + s1.compareTo(s2)); // Compare s1 and s3 // It should return -32 as they both // have the different ASCII value System.out.println(s1 + \" .compareTo \" + s3 + \": \" + s1.compareTo(s3)); // Compare s3 and s2 // It should return 32 as they both // have the different ASCII value System.out.println(s3 + \" .compareTo \" + s2 + \": \" + s3.compareTo(s2)); // Compare s1 and s4 // It should return 0 as they both // have the same ASCII value System.out.println(s1 + \" .compareTo \" + s4 + \": \" + s1.compareTo(s4)); }}",
"e": 5479,
"s": 4346,
"text": null
},
{
"code": null,
"e": 5556,
"s": 5481,
"text": "A .compareTo A: 0\nA .compareTo a: -32\na .compareTo A: 32\nA .compareTo A: 0"
},
{
"code": null,
"e": 5906,
"s": 5560,
"text": "Method 4: Using equalsIgnoreCase() methodJava String equalsIgnoreCase() method is much similar to equals() method, except that case is ignored like in above example String object s4 compare to s3 then equals() method return false, but here in case of equalsIgnoreCase() it will return true. Hence equalsIgnoreCase() method is Case Insensitive. "
},
{
"code": null,
"e": 5992,
"s": 5906,
"text": "Below example illustrate the use of .equalsIgnoreCase for string comparison in Java: "
},
{
"code": null,
"e": 5997,
"s": 5992,
"text": "JAVA"
},
{
"code": "// Java program to demonstrate// use of .equalsIgnoreCase operator in Java class GFG { public static void main(String[] args) { // Get some Strings to compare String s1 = \"A\"; String s2 = \"A\"; String s3 = \"a\"; String s4 = new String(\"A\"); // Compare s1 and s2 // It should return true as they both // have the same content System.out.println(s1 + \" .equalsIgnoreCase \" + s2 + \": \" + s1.equalsIgnoreCase(s2)); // Compare s1 and s3 // It should return true as they both // have the same content being case insensitive System.out.println(s1 + \" .equalsIgnoreCase \" + s3 + \": \" + s1.equalsIgnoreCase(s3)); // Compare s2 and s3 // It should return true as they both // have the same content being case insensitive System.out.println(s2 + \" .equalsIgnoreCase \" + s3 + \": \" + s2.equalsIgnoreCase(s3)); // Compare s1 and s4 // It should return true as they both // have the same content System.out.println(s1 + \" .equalsIgnoreCase \" + s4 + \": \" + s1.equalsIgnoreCase(s4)); }}",
"e": 7222,
"s": 5997,
"text": null
},
{
"code": null,
"e": 7336,
"s": 7224,
"text": "A .equalsIgnoreCase A: true\nA .equalsIgnoreCase a: true\nA .equalsIgnoreCase a: true\nA .equalsIgnoreCase A: true"
},
{
"code": null,
"e": 7581,
"s": 7340,
"text": "Method 5: Using compare() methodIn Java for locale specific comparison, one should use Collator class which is in java.text package. The one most important feature of Collator class is the ability to define our own custom comparison rules. "
},
{
"code": null,
"e": 7663,
"s": 7581,
"text": "Below example illustrate the use of compare() method in Java to compare Strings: "
},
{
"code": null,
"e": 7668,
"s": 7663,
"text": "JAVA"
},
{
"code": "// Java program to demonstrate// use of collator.compare operator in Java import java.text.Collator; class GFG { public static void main(String[] args) { // Get Collator instance Collator collator = Collator.getInstance(); // Get some Strings to compare String s1 = \"A\"; String s2 = \"A\"; String s3 = \"a\"; String s4 = new String(\"A\"); // Compare s1 and s2 // It should return 0 as they both // have the same ASCII value System.out.println(s1 + \" collator.compare \" + s2 + \": \" + collator.compare(s1, s2)); // Compare s1 and s3 // It should return 1 System.out.println(s1 + \" collator.compare \" + s3 + \": \" + collator.compare(s1, s3)); // Compare s3 and s2 // It should return -1 System.out.println(s3 + \" collator.compare \" + s2 + \": \" + collator.compare(s3, s2)); // Compare s1 and s4 // It should return 0 as they both // have the same ASCII value System.out.println(s1 + \" collator.compare \" + s4 + \": \" + collator.compare(s1, s4)); }}",
"e": 8864,
"s": 7668,
"text": null
},
{
"code": null,
"e": 8963,
"s": 8866,
"text": "A collator.compare A: 0\nA collator.compare a: 1\na collator.compare A: -1\nA collator.compare A: 0"
},
{
"code": null,
"e": 8981,
"s": 8967,
"text": "sumitgumber28"
},
{
"code": null,
"e": 9002,
"s": 8981,
"text": "Java-String-Programs"
},
{
"code": null,
"e": 9015,
"s": 9002,
"text": "Java-Strings"
},
{
"code": null,
"e": 9022,
"s": 9015,
"text": "Picked"
},
{
"code": null,
"e": 9046,
"s": 9022,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 9051,
"s": 9046,
"text": "Java"
},
{
"code": null,
"e": 9070,
"s": 9051,
"text": "Technical Scripter"
},
{
"code": null,
"e": 9083,
"s": 9070,
"text": "Java-Strings"
},
{
"code": null,
"e": 9088,
"s": 9083,
"text": "Java"
},
{
"code": null,
"e": 9186,
"s": 9088,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9237,
"s": 9186,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 9268,
"s": 9237,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 9287,
"s": 9268,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 9317,
"s": 9287,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 9335,
"s": 9317,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 9367,
"s": 9335,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 9387,
"s": 9367,
"text": "Collections in Java"
},
{
"code": null,
"e": 9402,
"s": 9387,
"text": "Stream In Java"
},
{
"code": null,
"e": 9414,
"s": 9402,
"text": "Set in Java"
}
]
|
Impact of Image Flattening | 22 Jan, 2021
Flattening is a technique that is used to convert multi-dimensional arrays into a 1-D array, it is generally used in Deep Learning while feeding the 1-D array information to the classification model.
What is the need for Flattening of an Image?
Multi-Dimensional arrays take more amount of memory while 1-D arrays take less memory, which is the most important reason why we flatten the Image Array before processing/feeding the information to our model. In most cases, we will be dealing with a dataset which contains a large amount of images thus flattening helps in decreasing the memory as well as reducing the time to train the model.
Step 1: Importing the necessary libraries
Python3
import numpy as npimport pandas as pdimport cv2 as cvfrom google.colab.patches import cv2_imshowfrom skimage import iofrom PIL import Imageimport matplotlib.pylab as pltfrom numpy import arrayfrom sys import getsizeof
Step 2: Fetching a random image through web
Python3
#Fetching the url and showing the image using cv2_imshowurls=["https://iiif.lib.ncsu.edu/iiif/0052574/full/800,/0/default.jpg"]for url in urls: image = io.imread(url) cv2_imshow(image) print('\n')
Step 3: Transforming the image into a multi-dimensional array
Python3
#Getting the multi-dimensional array from the imagearray1 = array(image)#Memory occupied by the multi-dimensional arraysize1 = getsizeof(array1)print(array1)
Step 4: Now Flattening the multi-dimensional array using flatten() function
Python3
#Using Flatten function on array 1 to convert the multi-dimensional # array to 1-D arrayarray2 = array1.flatten()#Memory occupied by array 2size2 = getsizeof(array2)#displaying the 1-D arrayprint(array2)
Step5: Results of Flattening
Python3
#Print's the two different size's of the arrayprint(f"Size of Multidimensional Image : {size1}")print(f"Size of Flattened Image : {size2}")difference = size1 - size2#Print's the difference of memory between the size of Multidimensional & 1-D arrayprint("Size difference in the images: ", difference)
Size of Multidimensional Image : 1324928
Size of Flattened Image : 1324896
Size difference in the images: 32
Step 6: Full Code
Python3
#importing librariesimport numpy as npimport pandas as pdimport cv2 as cvfrom google.colab.patches import cv2_imshowfrom skimage import iofrom PIL import Imageimport matplotlib.pylab as pltfrom numpy import arrayfrom sys import getsizeof #Fetching the url and showing the image using cv2_imshowurls=["https://iiif.lib.ncsu.edu/iiif/0052574/full/800,/0/default.jpg"]for url in urls: image = io.imread(url) cv2_imshow(image) print('\n') #Getting the multi-dimensional array from the imagearray1 = array(image)#Memory occupied by the multi-dimensional arraysize1 = getsizeof(array1)print(array1) #Using Flatten function on array 1 to convert the multi-dimensional # array to 1-D arrayarray2 = array1.flatten()#Memory occupied by array 2size2 = getsizeof(array2)#displaying the 1-D arrayprint(array2) #Print's the two different size's of the arrayprint(f"Size of Multidimensional Image : {size1}")print(f"Size of Flattened Image : {size2}")difference = size1 - size2#Print's the difference of memory between the size of Multidimensional & 1-D arrayprint(difference)
Conclusion:
After running the whole code we see that there is not a major difference in memory used in the multi-dimensional image array and the flattened array. Then people may ask why we are doing the flattening when the effect is negligible. In a large datasets when we are dealing with thousands of images the net amount of the memory saved due to all the images accumulates to be pretty big.
Image-Processing
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n22 Jan, 2021"
},
{
"code": null,
"e": 254,
"s": 54,
"text": "Flattening is a technique that is used to convert multi-dimensional arrays into a 1-D array, it is generally used in Deep Learning while feeding the 1-D array information to the classification model."
},
{
"code": null,
"e": 299,
"s": 254,
"text": "What is the need for Flattening of an Image?"
},
{
"code": null,
"e": 693,
"s": 299,
"text": "Multi-Dimensional arrays take more amount of memory while 1-D arrays take less memory, which is the most important reason why we flatten the Image Array before processing/feeding the information to our model. In most cases, we will be dealing with a dataset which contains a large amount of images thus flattening helps in decreasing the memory as well as reducing the time to train the model."
},
{
"code": null,
"e": 735,
"s": 693,
"text": "Step 1: Importing the necessary libraries"
},
{
"code": null,
"e": 743,
"s": 735,
"text": "Python3"
},
{
"code": "import numpy as npimport pandas as pdimport cv2 as cvfrom google.colab.patches import cv2_imshowfrom skimage import iofrom PIL import Imageimport matplotlib.pylab as pltfrom numpy import arrayfrom sys import getsizeof",
"e": 961,
"s": 743,
"text": null
},
{
"code": null,
"e": 1005,
"s": 961,
"text": "Step 2: Fetching a random image through web"
},
{
"code": null,
"e": 1013,
"s": 1005,
"text": "Python3"
},
{
"code": "#Fetching the url and showing the image using cv2_imshowurls=[\"https://iiif.lib.ncsu.edu/iiif/0052574/full/800,/0/default.jpg\"]for url in urls: image = io.imread(url) cv2_imshow(image) print('\\n')",
"e": 1213,
"s": 1013,
"text": null
},
{
"code": null,
"e": 1275,
"s": 1213,
"text": "Step 3: Transforming the image into a multi-dimensional array"
},
{
"code": null,
"e": 1283,
"s": 1275,
"text": "Python3"
},
{
"code": "#Getting the multi-dimensional array from the imagearray1 = array(image)#Memory occupied by the multi-dimensional arraysize1 = getsizeof(array1)print(array1)",
"e": 1441,
"s": 1283,
"text": null
},
{
"code": null,
"e": 1517,
"s": 1441,
"text": "Step 4: Now Flattening the multi-dimensional array using flatten() function"
},
{
"code": null,
"e": 1525,
"s": 1517,
"text": "Python3"
},
{
"code": "#Using Flatten function on array 1 to convert the multi-dimensional # array to 1-D arrayarray2 = array1.flatten()#Memory occupied by array 2size2 = getsizeof(array2)#displaying the 1-D arrayprint(array2)",
"e": 1729,
"s": 1525,
"text": null
},
{
"code": null,
"e": 1758,
"s": 1729,
"text": "Step5: Results of Flattening"
},
{
"code": null,
"e": 1766,
"s": 1758,
"text": "Python3"
},
{
"code": "#Print's the two different size's of the arrayprint(f\"Size of Multidimensional Image : {size1}\")print(f\"Size of Flattened Image : {size2}\")difference = size1 - size2#Print's the difference of memory between the size of Multidimensional & 1-D arrayprint(\"Size difference in the images: \", difference)",
"e": 2066,
"s": 1766,
"text": null
},
{
"code": null,
"e": 2176,
"s": 2066,
"text": "Size of Multidimensional Image : 1324928 \nSize of Flattened Image : 1324896\nSize difference in the images: 32"
},
{
"code": null,
"e": 2194,
"s": 2176,
"text": "Step 6: Full Code"
},
{
"code": null,
"e": 2202,
"s": 2194,
"text": "Python3"
},
{
"code": "#importing librariesimport numpy as npimport pandas as pdimport cv2 as cvfrom google.colab.patches import cv2_imshowfrom skimage import iofrom PIL import Imageimport matplotlib.pylab as pltfrom numpy import arrayfrom sys import getsizeof #Fetching the url and showing the image using cv2_imshowurls=[\"https://iiif.lib.ncsu.edu/iiif/0052574/full/800,/0/default.jpg\"]for url in urls: image = io.imread(url) cv2_imshow(image) print('\\n') #Getting the multi-dimensional array from the imagearray1 = array(image)#Memory occupied by the multi-dimensional arraysize1 = getsizeof(array1)print(array1) #Using Flatten function on array 1 to convert the multi-dimensional # array to 1-D arrayarray2 = array1.flatten()#Memory occupied by array 2size2 = getsizeof(array2)#displaying the 1-D arrayprint(array2) #Print's the two different size's of the arrayprint(f\"Size of Multidimensional Image : {size1}\")print(f\"Size of Flattened Image : {size2}\")difference = size1 - size2#Print's the difference of memory between the size of Multidimensional & 1-D arrayprint(difference)",
"e": 3271,
"s": 2202,
"text": null
},
{
"code": null,
"e": 3283,
"s": 3271,
"text": "Conclusion:"
},
{
"code": null,
"e": 3668,
"s": 3283,
"text": "After running the whole code we see that there is not a major difference in memory used in the multi-dimensional image array and the flattened array. Then people may ask why we are doing the flattening when the effect is negligible. In a large datasets when we are dealing with thousands of images the net amount of the memory saved due to all the images accumulates to be pretty big."
},
{
"code": null,
"e": 3685,
"s": 3668,
"text": "Image-Processing"
},
{
"code": null,
"e": 3702,
"s": 3685,
"text": "Machine Learning"
},
{
"code": null,
"e": 3709,
"s": 3702,
"text": "Python"
},
{
"code": null,
"e": 3726,
"s": 3709,
"text": "Machine Learning"
}
]
|
PHP | call_user_func() Function | 25 Jun, 2018
The call_user_func() is an inbuilt function in PHP which is used to call the callback given by the first parameter and passes the remaining parameters as argument. It is used to call the user-defined functions.
Syntax:
mixed call_user_func ( $function_name[, mixed $value1[, mixed $... ]])
Here, mixed indicates that a parameter may accept multiple types.Parameter: The call_user_func() function accepts two types of parameters as mentioned above and described below:
$function_name: It is the name of function call in the list of defined function. It is a string type parameter.
$value: It is mixed value. One or more parameters to be passed to the function.
Return Value: This function returns the value returned by the callback function.
Below programs illustrate the call_user_func() function in PHP:
Program 1: Call the function
<?phpfunction GFG($value){ echo "This is $value site.\n";} call_user_func('GFG', "GeeksforGeeks");call_user_func('GFG', "Content"); ?>
This is GeeksforGeeks site.
This is Content site.
Program 2: call_user_func() using namespace name
<?php namespace Geeks; class GFG { static public function demo() { print "GeeksForGeeks\n"; }} call_user_func(__NAMESPACE__ .'\GFG::demo'); // Another way of declarationcall_user_func(array(__NAMESPACE__ .'\GFG', 'demo')); ?>
GeeksForGeeks
GeeksForGeeks
Program 3: Using a class method with call_user_func()
<?php class GFG { static function show() { echo "Geeks\n"; }} $classname = "GFG";call_user_func($classname .'::show'); // Another way to use object$obj = new GFG();call_user_func(array($obj, 'show')); ?>
Geeks
Geeks
Program 4: Using lambda function with call_user_func()
<?phpcall_user_func(function($arg) { print "$arg\n"; }, 'GeeksforGeeks');?>
GeeksforGeeks
References: http://php.net/manual/en/function.call-user-func.php
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Jun, 2018"
},
{
"code": null,
"e": 239,
"s": 28,
"text": "The call_user_func() is an inbuilt function in PHP which is used to call the callback given by the first parameter and passes the remaining parameters as argument. It is used to call the user-defined functions."
},
{
"code": null,
"e": 247,
"s": 239,
"text": "Syntax:"
},
{
"code": null,
"e": 318,
"s": 247,
"text": "mixed call_user_func ( $function_name[, mixed $value1[, mixed $... ]])"
},
{
"code": null,
"e": 496,
"s": 318,
"text": "Here, mixed indicates that a parameter may accept multiple types.Parameter: The call_user_func() function accepts two types of parameters as mentioned above and described below:"
},
{
"code": null,
"e": 608,
"s": 496,
"text": "$function_name: It is the name of function call in the list of defined function. It is a string type parameter."
},
{
"code": null,
"e": 688,
"s": 608,
"text": "$value: It is mixed value. One or more parameters to be passed to the function."
},
{
"code": null,
"e": 769,
"s": 688,
"text": "Return Value: This function returns the value returned by the callback function."
},
{
"code": null,
"e": 833,
"s": 769,
"text": "Below programs illustrate the call_user_func() function in PHP:"
},
{
"code": null,
"e": 862,
"s": 833,
"text": "Program 1: Call the function"
},
{
"code": "<?phpfunction GFG($value){ echo \"This is $value site.\\n\";} call_user_func('GFG', \"GeeksforGeeks\");call_user_func('GFG', \"Content\"); ?>",
"e": 1002,
"s": 862,
"text": null
},
{
"code": null,
"e": 1053,
"s": 1002,
"text": "This is GeeksforGeeks site.\nThis is Content site.\n"
},
{
"code": null,
"e": 1102,
"s": 1053,
"text": "Program 2: call_user_func() using namespace name"
},
{
"code": "<?php namespace Geeks; class GFG { static public function demo() { print \"GeeksForGeeks\\n\"; }} call_user_func(__NAMESPACE__ .'\\GFG::demo'); // Another way of declarationcall_user_func(array(__NAMESPACE__ .'\\GFG', 'demo')); ?>",
"e": 1348,
"s": 1102,
"text": null
},
{
"code": null,
"e": 1377,
"s": 1348,
"text": "GeeksForGeeks\nGeeksForGeeks\n"
},
{
"code": null,
"e": 1431,
"s": 1377,
"text": "Program 3: Using a class method with call_user_func()"
},
{
"code": "<?php class GFG { static function show() { echo \"Geeks\\n\"; }} $classname = \"GFG\";call_user_func($classname .'::show'); // Another way to use object$obj = new GFG();call_user_func(array($obj, 'show')); ?>",
"e": 1655,
"s": 1431,
"text": null
},
{
"code": null,
"e": 1668,
"s": 1655,
"text": "Geeks\nGeeks\n"
},
{
"code": null,
"e": 1723,
"s": 1668,
"text": "Program 4: Using lambda function with call_user_func()"
},
{
"code": "<?phpcall_user_func(function($arg) { print \"$arg\\n\"; }, 'GeeksforGeeks');?>",
"e": 1799,
"s": 1723,
"text": null
},
{
"code": null,
"e": 1814,
"s": 1799,
"text": "GeeksforGeeks\n"
},
{
"code": null,
"e": 1879,
"s": 1814,
"text": "References: http://php.net/manual/en/function.call-user-func.php"
},
{
"code": null,
"e": 1892,
"s": 1879,
"text": "PHP-function"
},
{
"code": null,
"e": 1896,
"s": 1892,
"text": "PHP"
},
{
"code": null,
"e": 1913,
"s": 1896,
"text": "Web Technologies"
},
{
"code": null,
"e": 1917,
"s": 1913,
"text": "PHP"
}
]
|
Set title of window in PyQt5 – setWindowTitle | 24 Nov, 2021
PyQt5 is a comprehensive set of Python bindings for Qt v5. It is implemented as more than 35 extension modules and enables Python to be used as an alternative application development language to C++ on all supported platforms including iOS and Android.In this article, we will see how to set title of the window in PyQt5. In order to do so setWindowTitle() method is used, this method belongs to the QWidget class.
Syntax : self.setWindowTitle(title)Argument : It takes title i.e string as argument.
Below is the Python implementation –
Python3
# importing the required librariesfrom PyQt5.QtGui import *from PyQt5.QtWidgets import *import sys class Window(QMainWindow): def __init__(self): super().__init__() # string value title = "Title of window" # set the title self.setWindowTitle(title) # setting the geometry of window self.setGeometry(0, 0, 500, 300) # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
gabaa406
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Nov, 2021"
},
{
"code": null,
"e": 444,
"s": 28,
"text": "PyQt5 is a comprehensive set of Python bindings for Qt v5. It is implemented as more than 35 extension modules and enables Python to be used as an alternative application development language to C++ on all supported platforms including iOS and Android.In this article, we will see how to set title of the window in PyQt5. In order to do so setWindowTitle() method is used, this method belongs to the QWidget class. "
},
{
"code": null,
"e": 529,
"s": 444,
"text": "Syntax : self.setWindowTitle(title)Argument : It takes title i.e string as argument."
},
{
"code": null,
"e": 568,
"s": 529,
"text": "Below is the Python implementation – "
},
{
"code": null,
"e": 576,
"s": 568,
"text": "Python3"
},
{
"code": "# importing the required librariesfrom PyQt5.QtGui import *from PyQt5.QtWidgets import *import sys class Window(QMainWindow): def __init__(self): super().__init__() # string value title = \"Title of window\" # set the title self.setWindowTitle(title) # setting the geometry of window self.setGeometry(0, 0, 500, 300) # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 1141,
"s": 576,
"text": null
},
{
"code": null,
"e": 1152,
"s": 1141,
"text": "Output : "
},
{
"code": null,
"e": 1163,
"s": 1154,
"text": "gabaa406"
},
{
"code": null,
"e": 1174,
"s": 1163,
"text": "Python-gui"
},
{
"code": null,
"e": 1186,
"s": 1174,
"text": "Python-PyQt"
},
{
"code": null,
"e": 1193,
"s": 1186,
"text": "Python"
}
]
|
C program to check whether a given number is even or odd | 10 Jun, 2022
Given an integer N, the task is to check if the given number N is even or odd. If it is found to be even, then print “Even”. Otherwise, print “Odd”.
Examples:
Input: N = 2Output: Even
Input: N = 5Output: Odd
Method 1: The simplest approach is to check if the remainder obtained after dividing the given number N by 2 is 0 or 1. If the remainder is 0, then print “Even”. Otherwise, print “Odd”.
Below is the implementation of the above approach:
C
// C program for the above approach#include <stdio.h> // Function to check if a// number is even or oddvoid checkEvenOdd(int N){ // Find remainder int r = N % 2; // Condition for even if (r == 0) { printf("Even"); } // Otherwise else { printf("Odd"); }} // Driver Codeint main(){ // Given number N int N = 101; // Function Call checkEvenOdd(N); return 0;}
Odd
Time Complexity: O(1)Auxiliary Space: O(1)
Method 2: Another approach is to use Bitwise Operators. The idea is to check whether the last bit of the given number N is 1 or not. To check whether the last bit is 1 find the value of (N & 1). If the result is 1, then print “Odd”. Otherwise, print “Even”.
Below is the illustration for N = 5:
N = 5.Binary representation of 5 is 00000101Binary representation of 1 is 00000001——————————————————————-The value of Bitwise AND is 00000001
Since the result is 1. Therefore, the number N = 5 is odd.
Below is the implementation of the above approach:
C
// C program for the above approach #include <stdio.h> // Function to check if a// number is even or oddvoid checkEvenOdd(int N){ // If N & 1 is true if (N & 1) { printf("Odd"); } // Otherwise else { printf("Even"); }} // Driver Codeint main(){ // Given number N int N = 101; // Function Call checkEvenOdd(N); return 0;}
Odd
Time Complexity: O(1)Auxiliary Space: O(1)
Method 3: The idea is to initialize an integer variable var as 1 and change it from 1 to 0 and vice-versa alternately, N times. If var is equal to 1 after N operations, print “Even”. Otherwise, print “Odd”.
Below is the implementation of the above approach:
C
// C program for the above approach#include <stdio.h> // Function to check a number is// even or oddvoid checkEvenOdd(int N){ // Initialise a variable var int var = 1; // Iterate till N for (int i = 1; i <= N; i++) { // Subtract var from 1 var = 1 - var; } // Condition for even if (var == 1) { printf("Even"); } // Otherwise else { printf("Odd"); }} // Driver Codeint main(){ // Given number N int N = 101; // Function Call checkEvenOdd(N); return 0;}
Odd
Time Complexity: O(1)Auxiliary Space: O(1)
C Basic Programs
Natural Numbers
Number Divisibility
Bit Magic
C Programs
Mathematical
Mathematical
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n10 Jun, 2022"
},
{
"code": null,
"e": 203,
"s": 54,
"text": "Given an integer N, the task is to check if the given number N is even or odd. If it is found to be even, then print “Even”. Otherwise, print “Odd”."
},
{
"code": null,
"e": 213,
"s": 203,
"text": "Examples:"
},
{
"code": null,
"e": 238,
"s": 213,
"text": "Input: N = 2Output: Even"
},
{
"code": null,
"e": 262,
"s": 238,
"text": "Input: N = 5Output: Odd"
},
{
"code": null,
"e": 448,
"s": 262,
"text": "Method 1: The simplest approach is to check if the remainder obtained after dividing the given number N by 2 is 0 or 1. If the remainder is 0, then print “Even”. Otherwise, print “Odd”."
},
{
"code": null,
"e": 499,
"s": 448,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 501,
"s": 499,
"text": "C"
},
{
"code": "// C program for the above approach#include <stdio.h> // Function to check if a// number is even or oddvoid checkEvenOdd(int N){ // Find remainder int r = N % 2; // Condition for even if (r == 0) { printf(\"Even\"); } // Otherwise else { printf(\"Odd\"); }} // Driver Codeint main(){ // Given number N int N = 101; // Function Call checkEvenOdd(N); return 0;}",
"e": 920,
"s": 501,
"text": null
},
{
"code": null,
"e": 925,
"s": 920,
"text": "Odd\n"
},
{
"code": null,
"e": 968,
"s": 925,
"text": "Time Complexity: O(1)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1226,
"s": 968,
"text": "Method 2: Another approach is to use Bitwise Operators. The idea is to check whether the last bit of the given number N is 1 or not. To check whether the last bit is 1 find the value of (N & 1). If the result is 1, then print “Odd”. Otherwise, print “Even”."
},
{
"code": null,
"e": 1263,
"s": 1226,
"text": "Below is the illustration for N = 5:"
},
{
"code": null,
"e": 1405,
"s": 1263,
"text": "N = 5.Binary representation of 5 is 00000101Binary representation of 1 is 00000001——————————————————————-The value of Bitwise AND is 00000001"
},
{
"code": null,
"e": 1464,
"s": 1405,
"text": "Since the result is 1. Therefore, the number N = 5 is odd."
},
{
"code": null,
"e": 1515,
"s": 1464,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1517,
"s": 1515,
"text": "C"
},
{
"code": "// C program for the above approach #include <stdio.h> // Function to check if a// number is even or oddvoid checkEvenOdd(int N){ // If N & 1 is true if (N & 1) { printf(\"Odd\"); } // Otherwise else { printf(\"Even\"); }} // Driver Codeint main(){ // Given number N int N = 101; // Function Call checkEvenOdd(N); return 0;}",
"e": 1894,
"s": 1517,
"text": null
},
{
"code": null,
"e": 1899,
"s": 1894,
"text": "Odd\n"
},
{
"code": null,
"e": 1942,
"s": 1899,
"text": "Time Complexity: O(1)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 2149,
"s": 1942,
"text": "Method 3: The idea is to initialize an integer variable var as 1 and change it from 1 to 0 and vice-versa alternately, N times. If var is equal to 1 after N operations, print “Even”. Otherwise, print “Odd”."
},
{
"code": null,
"e": 2200,
"s": 2149,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 2202,
"s": 2200,
"text": "C"
},
{
"code": "// C program for the above approach#include <stdio.h> // Function to check a number is// even or oddvoid checkEvenOdd(int N){ // Initialise a variable var int var = 1; // Iterate till N for (int i = 1; i <= N; i++) { // Subtract var from 1 var = 1 - var; } // Condition for even if (var == 1) { printf(\"Even\"); } // Otherwise else { printf(\"Odd\"); }} // Driver Codeint main(){ // Given number N int N = 101; // Function Call checkEvenOdd(N); return 0;}",
"e": 2745,
"s": 2202,
"text": null
},
{
"code": null,
"e": 2750,
"s": 2745,
"text": "Odd\n"
},
{
"code": null,
"e": 2793,
"s": 2750,
"text": "Time Complexity: O(1)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 2810,
"s": 2793,
"text": "C Basic Programs"
},
{
"code": null,
"e": 2826,
"s": 2810,
"text": "Natural Numbers"
},
{
"code": null,
"e": 2846,
"s": 2826,
"text": "Number Divisibility"
},
{
"code": null,
"e": 2856,
"s": 2846,
"text": "Bit Magic"
},
{
"code": null,
"e": 2867,
"s": 2856,
"text": "C Programs"
},
{
"code": null,
"e": 2880,
"s": 2867,
"text": "Mathematical"
},
{
"code": null,
"e": 2893,
"s": 2880,
"text": "Mathematical"
},
{
"code": null,
"e": 2903,
"s": 2893,
"text": "Bit Magic"
}
]
|
Python Tweepy – Getting the number of followers of a user | 18 Jun, 2020
In this article we will see how we can get the number of followers of a user. The followers_count attribute provides us with an integer donating the number of followers the user account has.
Identifying the number of followers in the GUI :
In the above mentioned profile the number of followers are : 17.8K (17, 800+)
In order to get the number of followers we have to do the following :
Identify the user ID or the screen name of the profile.Get the User object of the profile using the get_user() method with the user ID or the screen name.From this object, fetch the followers_count attribute present in it.
Identify the user ID or the screen name of the profile.
Get the User object of the profile using the get_user() method with the user ID or the screen name.
From this object, fetch the followers_count attribute present in it.
Example 1: Consider the following profile :We will use the user ID to fetch the user. The user ID of the above mentioned profile is 57741058.
# import the moduleimport tweepy # assign the values accordinglyconsumer_key = ""consumer_secret = ""access_token = ""access_token_secret = "" # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret) # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret) # calling the api api = tweepy.API(auth) # the ID of the userid = 57741058 # fetching the useruser = api.get_user(id) # fetching the followers_countfollowers_count = user.followers_count print("The number of followers of the user are : " + str(followers_count))
Output :
The number of followers of the user are : 17814
Example 2: Consider the following profile :We will use the screen name to fetch the user. The screen name of the above mentioned profile is PracticeGfG.
# the screen name of the userscreen_name = "PracticeGfG" # fetching the useruser = api.get_user(screen_name) # fetching the followers_countfollowers_count = user.followers_count print("The number of followers of the user are : " + str(followers_count))
Output :
The number of followers of the user are : 2204
Python-Tweepy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Jun, 2020"
},
{
"code": null,
"e": 219,
"s": 28,
"text": "In this article we will see how we can get the number of followers of a user. The followers_count attribute provides us with an integer donating the number of followers the user account has."
},
{
"code": null,
"e": 268,
"s": 219,
"text": "Identifying the number of followers in the GUI :"
},
{
"code": null,
"e": 346,
"s": 268,
"text": "In the above mentioned profile the number of followers are : 17.8K (17, 800+)"
},
{
"code": null,
"e": 416,
"s": 346,
"text": "In order to get the number of followers we have to do the following :"
},
{
"code": null,
"e": 639,
"s": 416,
"text": "Identify the user ID or the screen name of the profile.Get the User object of the profile using the get_user() method with the user ID or the screen name.From this object, fetch the followers_count attribute present in it."
},
{
"code": null,
"e": 695,
"s": 639,
"text": "Identify the user ID or the screen name of the profile."
},
{
"code": null,
"e": 795,
"s": 695,
"text": "Get the User object of the profile using the get_user() method with the user ID or the screen name."
},
{
"code": null,
"e": 864,
"s": 795,
"text": "From this object, fetch the followers_count attribute present in it."
},
{
"code": null,
"e": 1006,
"s": 864,
"text": "Example 1: Consider the following profile :We will use the user ID to fetch the user. The user ID of the above mentioned profile is 57741058."
},
{
"code": "# import the moduleimport tweepy # assign the values accordinglyconsumer_key = \"\"consumer_secret = \"\"access_token = \"\"access_token_secret = \"\" # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret) # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret) # calling the api api = tweepy.API(auth) # the ID of the userid = 57741058 # fetching the useruser = api.get_user(id) # fetching the followers_countfollowers_count = user.followers_count print(\"The number of followers of the user are : \" + str(followers_count))",
"e": 1637,
"s": 1006,
"text": null
},
{
"code": null,
"e": 1646,
"s": 1637,
"text": "Output :"
},
{
"code": null,
"e": 1695,
"s": 1646,
"text": "The number of followers of the user are : 17814\n"
},
{
"code": null,
"e": 1848,
"s": 1695,
"text": "Example 2: Consider the following profile :We will use the screen name to fetch the user. The screen name of the above mentioned profile is PracticeGfG."
},
{
"code": "# the screen name of the userscreen_name = \"PracticeGfG\" # fetching the useruser = api.get_user(screen_name) # fetching the followers_countfollowers_count = user.followers_count print(\"The number of followers of the user are : \" + str(followers_count))",
"e": 2104,
"s": 1848,
"text": null
},
{
"code": null,
"e": 2113,
"s": 2104,
"text": "Output :"
},
{
"code": null,
"e": 2161,
"s": 2113,
"text": "The number of followers of the user are : 2204\n"
},
{
"code": null,
"e": 2175,
"s": 2161,
"text": "Python-Tweepy"
},
{
"code": null,
"e": 2182,
"s": 2175,
"text": "Python"
}
]
|
JSON Schema | 22 Jun, 2020
JSON Schema is a content specification language used for validating the structure of a JSON data.It helps you specify the objects and what values are valid inside the object’s properties. JSON schema is useful in offering clear, human-readable, and machine-readable documentation.
Structure of a JSON Schema: Since JSON format contains an object, array, and name-value pair elements. Name-value pairs are used for providing schema processing elements as well as validating the JSON content. Schema processing elements include(not limited to).
$schema” To specify the version of JSON schema.
title and description: To provide information about the schema.
required: It’s an array of elements that indicates which elements should be present.
additionalProperties: To indicate whether existence of specified elements are allowed or not.
JSON content definition:
When a JSON object is defined, JSON schema uses name-value pair “type”:”object”
When arrays are defined, JSON schema uses the name-value pair “type”:”array”
Example:
{
"$id": "https://example.com/person.schema.json",
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Voters information",
"type": "object",
"properties": {
"firstName": {
"type": "string",
"description": "The person's first name."
},
"lastName": {
"type": "string",
"description": "The person's last name."
},
"age": {
"description": "Age in years which must be equal to or
greater than eighteen in order to vote.",
"type": "integer",
"minimum": 18
}
}
}
Output:
{
"firstName": "Indra",
"lastName": "Sen",
"age": 20
}
The above JSON schema contains the following:
$id keyword
$schema keyword
title annotation keyword
properties validation keyword
Three keys: firstName, lastName and age each with their own description keyword.
type instance data model (see above)
minimum validation keyword on the age key.
JSON
Picked
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Jun, 2020"
},
{
"code": null,
"e": 309,
"s": 28,
"text": "JSON Schema is a content specification language used for validating the structure of a JSON data.It helps you specify the objects and what values are valid inside the object’s properties. JSON schema is useful in offering clear, human-readable, and machine-readable documentation."
},
{
"code": null,
"e": 571,
"s": 309,
"text": "Structure of a JSON Schema: Since JSON format contains an object, array, and name-value pair elements. Name-value pairs are used for providing schema processing elements as well as validating the JSON content. Schema processing elements include(not limited to)."
},
{
"code": null,
"e": 619,
"s": 571,
"text": "$schema” To specify the version of JSON schema."
},
{
"code": null,
"e": 683,
"s": 619,
"text": "title and description: To provide information about the schema."
},
{
"code": null,
"e": 768,
"s": 683,
"text": "required: It’s an array of elements that indicates which elements should be present."
},
{
"code": null,
"e": 862,
"s": 768,
"text": "additionalProperties: To indicate whether existence of specified elements are allowed or not."
},
{
"code": null,
"e": 887,
"s": 862,
"text": "JSON content definition:"
},
{
"code": null,
"e": 967,
"s": 887,
"text": "When a JSON object is defined, JSON schema uses name-value pair “type”:”object”"
},
{
"code": null,
"e": 1044,
"s": 967,
"text": "When arrays are defined, JSON schema uses the name-value pair “type”:”array”"
},
{
"code": null,
"e": 1053,
"s": 1044,
"text": "Example:"
},
{
"code": null,
"e": 1625,
"s": 1053,
"text": "{\n \"$id\": \"https://example.com/person.schema.json\",\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"title\": \"Voters information\",\n \"type\": \"object\",\n \"properties\": {\n \"firstName\": {\n \"type\": \"string\",\n \"description\": \"The person's first name.\"\n },\n \"lastName\": {\n \"type\": \"string\",\n \"description\": \"The person's last name.\"\n },\n \"age\": {\n \"description\": \"Age in years which must be equal to or \n greater than eighteen in order to vote.\",\n \"type\": \"integer\",\n \"minimum\": 18\n }\n }\n}\n\n"
},
{
"code": null,
"e": 1633,
"s": 1625,
"text": "Output:"
},
{
"code": null,
"e": 1695,
"s": 1633,
"text": "{\n \"firstName\": \"Indra\",\n \"lastName\": \"Sen\",\n \"age\": 20\n}\n"
},
{
"code": null,
"e": 1741,
"s": 1695,
"text": "The above JSON schema contains the following:"
},
{
"code": null,
"e": 1753,
"s": 1741,
"text": "$id keyword"
},
{
"code": null,
"e": 1769,
"s": 1753,
"text": "$schema keyword"
},
{
"code": null,
"e": 1794,
"s": 1769,
"text": "title annotation keyword"
},
{
"code": null,
"e": 1824,
"s": 1794,
"text": "properties validation keyword"
},
{
"code": null,
"e": 1905,
"s": 1824,
"text": "Three keys: firstName, lastName and age each with their own description keyword."
},
{
"code": null,
"e": 1942,
"s": 1905,
"text": "type instance data model (see above)"
},
{
"code": null,
"e": 1985,
"s": 1942,
"text": "minimum validation keyword on the age key."
},
{
"code": null,
"e": 1990,
"s": 1985,
"text": "JSON"
},
{
"code": null,
"e": 1997,
"s": 1990,
"text": "Picked"
},
{
"code": null,
"e": 2008,
"s": 1997,
"text": "JavaScript"
}
]
|
Python – Cross Pairing in Tuple List | 02 Sep, 2020
Given 2 tuples, perform cross pairing of corresponding tuples, convert to single tuple if 1st element of both tuple matches.
Input : test_list1 = [(1, 7), (6, 7), (8, 100), (4, 21)], test_list2 = [(1, 3), (2, 1), (9, 7), (2, 17)]Output : [(7, 3)]Explanation : 1 occurs as tuple element at pos. 1 in both tuple, its 2nd elements are paired and returned.
Input : test_list1 = [(10, 7), (6, 7), (8, 100), (4, 21)], test_list2 = [(1, 3), (2, 1), (9, 7), (2, 17)]Output : []Explanation : NO pairing possible.
Method #1 : Using list comprehension
In this, we check for 1st element using conditional statements and, and construct new tuple in list comprehension.
Python3
# Python3 code to demonstrate working of # Cross Pairing in Tuple List# Using list comprehension # initializing liststest_list1 = [(1, 7), (6, 7), (9, 100), (4, 21)]test_list2 = [(1, 3), (2, 1), (9, 7), (2, 17)] # printing original listsprint("The original list 1 : " + str(test_list1))print("The original list 2 : " + str(test_list2)) # corresponding loop in list comprehensionres = [(sub1[1], sub2[1]) for sub2 in test_list2 for sub1 in test_list1 if sub1[0] == sub2[0]] # printing result print("The mapped tuples : " + str(res))
The original list 1 : [(1, 7), (6, 7), (9, 100), (4, 21)]
The original list 2 : [(1, 3), (2, 1), (9, 7), (2, 17)]
The mapped tuples : [(7, 3), (100, 7)]
Method #2 : Using zip() + list comprehension
In this, the task of pairing is done using zip() and conditional check is done inside list comprehension.
Python3
# Python3 code to demonstrate working of # Cross Pairing in Tuple List# Using zip() + list comprehension # initializing liststest_list1 = [(1, 7), (6, 7), (9, 100), (4, 21)]test_list2 = [(1, 3), (2, 1), (9, 7), (2, 17)] # printing original listsprint("The original list 1 : " + str(test_list1))print("The original list 2 : " + str(test_list2)) # zip() is used for pairing res = [(a[1], b[1]) for a, b in zip(test_list1, test_list2) if a[0] == b[0]] # printing result print("The mapped tuples : " + str(res))
The original list 1 : [(1, 7), (6, 7), (9, 100), (4, 21)]
The original list 2 : [(1, 3), (2, 1), (9, 7), (2, 17)]
The mapped tuples : [(7, 3), (100, 7)]
Python list-programs
Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Sep, 2020"
},
{
"code": null,
"e": 153,
"s": 28,
"text": "Given 2 tuples, perform cross pairing of corresponding tuples, convert to single tuple if 1st element of both tuple matches."
},
{
"code": null,
"e": 381,
"s": 153,
"text": "Input : test_list1 = [(1, 7), (6, 7), (8, 100), (4, 21)], test_list2 = [(1, 3), (2, 1), (9, 7), (2, 17)]Output : [(7, 3)]Explanation : 1 occurs as tuple element at pos. 1 in both tuple, its 2nd elements are paired and returned."
},
{
"code": null,
"e": 532,
"s": 381,
"text": "Input : test_list1 = [(10, 7), (6, 7), (8, 100), (4, 21)], test_list2 = [(1, 3), (2, 1), (9, 7), (2, 17)]Output : []Explanation : NO pairing possible."
},
{
"code": null,
"e": 569,
"s": 532,
"text": "Method #1 : Using list comprehension"
},
{
"code": null,
"e": 684,
"s": 569,
"text": "In this, we check for 1st element using conditional statements and, and construct new tuple in list comprehension."
},
{
"code": null,
"e": 692,
"s": 684,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Cross Pairing in Tuple List# Using list comprehension # initializing liststest_list1 = [(1, 7), (6, 7), (9, 100), (4, 21)]test_list2 = [(1, 3), (2, 1), (9, 7), (2, 17)] # printing original listsprint(\"The original list 1 : \" + str(test_list1))print(\"The original list 2 : \" + str(test_list2)) # corresponding loop in list comprehensionres = [(sub1[1], sub2[1]) for sub2 in test_list2 for sub1 in test_list1 if sub1[0] == sub2[0]] # printing result print(\"The mapped tuples : \" + str(res))",
"e": 1228,
"s": 692,
"text": null
},
{
"code": null,
"e": 1382,
"s": 1228,
"text": "The original list 1 : [(1, 7), (6, 7), (9, 100), (4, 21)]\nThe original list 2 : [(1, 3), (2, 1), (9, 7), (2, 17)]\nThe mapped tuples : [(7, 3), (100, 7)]\n"
},
{
"code": null,
"e": 1427,
"s": 1382,
"text": "Method #2 : Using zip() + list comprehension"
},
{
"code": null,
"e": 1533,
"s": 1427,
"text": "In this, the task of pairing is done using zip() and conditional check is done inside list comprehension."
},
{
"code": null,
"e": 1541,
"s": 1533,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Cross Pairing in Tuple List# Using zip() + list comprehension # initializing liststest_list1 = [(1, 7), (6, 7), (9, 100), (4, 21)]test_list2 = [(1, 3), (2, 1), (9, 7), (2, 17)] # printing original listsprint(\"The original list 1 : \" + str(test_list1))print(\"The original list 2 : \" + str(test_list2)) # zip() is used for pairing res = [(a[1], b[1]) for a, b in zip(test_list1, test_list2) if a[0] == b[0]] # printing result print(\"The mapped tuples : \" + str(res))",
"e": 2053,
"s": 1541,
"text": null
},
{
"code": null,
"e": 2207,
"s": 2053,
"text": "The original list 1 : [(1, 7), (6, 7), (9, 100), (4, 21)]\nThe original list 2 : [(1, 3), (2, 1), (9, 7), (2, 17)]\nThe mapped tuples : [(7, 3), (100, 7)]\n"
},
{
"code": null,
"e": 2228,
"s": 2207,
"text": "Python list-programs"
},
{
"code": null,
"e": 2250,
"s": 2228,
"text": "Python tuple-programs"
},
{
"code": null,
"e": 2257,
"s": 2250,
"text": "Python"
},
{
"code": null,
"e": 2273,
"s": 2257,
"text": "Python Programs"
}
]
|
Kernel in Operating System | 08 Mar, 2022
Kernel is central component of an operating system that manages operations of computer and hardware. It basically manages operations of memory and CPU time. It is core component of an operating system. Kernel acts as a bridge between applications and data processing performed at hardware level using inter-process communication and system calls.
Kernel loads first into memory when an operating system is loaded and remains into memory until operating system is shut down again. It is responsible for various tasks such as disk management, task management, and memory management.
It decides which process should be allocated to processor to execute and which process should be kept in main memory to execute. It basically acts as an interface between user applications and hardware. The major aim of kernel is to manage communication between software i.e. user-level applications and hardware i.e., CPU and disk memory.
Objectives of Kernel :
To establish communication between user level application and hardware.
To decide state of incoming processes.
To control disk management.
To control memory management.
To control task management.
Types of Kernel :
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.
1. Monolithic Kernel – It is one of types of kernel where all operating system services operate in kernel space. It has dependencies between systems components. It has huge lines of code which is complex.
Example :
Unix, Linux, Open VMS, XTS-400 etc.
Advantage : It has good performance.
Disadvantage : It has dependencies between system component and lines of code in millions.
2. Micro Kernel – It is kernel types which has minimalist approach. It has virtual memory and thread scheduling. It is more stable with less services in kernel space. It puts rest in user space.
Example :
Mach, L4, AmigaOS, Minix, K42 etc.
Advantage : It is more stable.
Disadvantage : There are lots of system calls and context switches.
3. Hybrid Kernel – It is the combination of both monolithic kernel and microkernel. It has speed and design of monolithic kernel and modularity and stability of microkernel.
Example :
Windows NT, Netware, BeOS etc.
Advantage : It combines both monolithic kernel and microkernel.
Disadvantage : It is still similar to monolithic kernel.
4. Exo Kernel – It is the type of kernel which follows end-to-end principle. It has fewest hardware abstractions as possible. It allocates physical resources to applications.
Example :
Nemesis, ExOS etc.
Advantage : It has fewest hardware abstractions.
Disadvantage : There is more work for application developers.
5. Nano Kernel – It is the type of kernel that offers hardware abstraction but without system services. Micro Kernel also does not have system services therefore the Micro Kernel and Nano Kernel have become analogous.
Example :
EROS etc.
Advantage : It offers hardware abstractions without system services.
Disadvantage : It is quite same as Micro kernel hence it is less used.
ManasChhabra2
GATE CS
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Page Replacement Algorithms in Operating Systems
Inter Process Communication (IPC)
Introduction of Operating System - Set 1
Semaphores in Process Synchronization
Differences between TCP and UDP
Banker's Algorithm in Operating System
Page Replacement Algorithms in Operating Systems
Disk Scheduling Algorithms
File Allocation Methods
Introduction of Deadlock in Operating System | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n08 Mar, 2022"
},
{
"code": null,
"e": 400,
"s": 52,
"text": "Kernel is central component of an operating system that manages operations of computer and hardware. It basically manages operations of memory and CPU time. It is core component of an operating system. Kernel acts as a bridge between applications and data processing performed at hardware level using inter-process communication and system calls. "
},
{
"code": null,
"e": 635,
"s": 400,
"text": "Kernel loads first into memory when an operating system is loaded and remains into memory until operating system is shut down again. It is responsible for various tasks such as disk management, task management, and memory management. "
},
{
"code": null,
"e": 976,
"s": 635,
"text": "It decides which process should be allocated to processor to execute and which process should be kept in main memory to execute. It basically acts as an interface between user applications and hardware. The major aim of kernel is to manage communication between software i.e. user-level applications and hardware i.e., CPU and disk memory. "
},
{
"code": null,
"e": 1001,
"s": 976,
"text": "Objectives of Kernel : "
},
{
"code": null,
"e": 1075,
"s": 1001,
"text": "To establish communication between user level application and hardware. "
},
{
"code": null,
"e": 1118,
"s": 1077,
"text": "To decide state of incoming processes. "
},
{
"code": null,
"e": 1150,
"s": 1120,
"text": "To control disk management. "
},
{
"code": null,
"e": 1184,
"s": 1152,
"text": "To control memory management. "
},
{
"code": null,
"e": 1216,
"s": 1186,
"text": "To control task management. "
},
{
"code": null,
"e": 1237,
"s": 1218,
"text": "Types of Kernel : "
},
{
"code": null,
"e": 1246,
"s": 1237,
"text": "Chapters"
},
{
"code": null,
"e": 1273,
"s": 1246,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 1323,
"s": 1273,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 1346,
"s": 1323,
"text": "captions off, selected"
},
{
"code": null,
"e": 1354,
"s": 1346,
"text": "English"
},
{
"code": null,
"e": 1378,
"s": 1354,
"text": "This is a modal window."
},
{
"code": null,
"e": 1447,
"s": 1378,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 1469,
"s": 1447,
"text": "End of dialog window."
},
{
"code": null,
"e": 1675,
"s": 1469,
"text": "1. Monolithic Kernel – It is one of types of kernel where all operating system services operate in kernel space. It has dependencies between systems components. It has huge lines of code which is complex. "
},
{
"code": null,
"e": 1687,
"s": 1675,
"text": "Example : "
},
{
"code": null,
"e": 1723,
"s": 1687,
"text": "Unix, Linux, Open VMS, XTS-400 etc."
},
{
"code": null,
"e": 1764,
"s": 1725,
"text": "Advantage : It has good performance. "
},
{
"code": null,
"e": 1859,
"s": 1766,
"text": "Disadvantage : It has dependencies between system component and lines of code in millions. "
},
{
"code": null,
"e": 2057,
"s": 1861,
"text": "2. Micro Kernel – It is kernel types which has minimalist approach. It has virtual memory and thread scheduling. It is more stable with less services in kernel space. It puts rest in user space. "
},
{
"code": null,
"e": 2069,
"s": 2057,
"text": "Example : "
},
{
"code": null,
"e": 2104,
"s": 2069,
"text": "Mach, L4, AmigaOS, Minix, K42 etc."
},
{
"code": null,
"e": 2139,
"s": 2106,
"text": "Advantage : It is more stable. "
},
{
"code": null,
"e": 2211,
"s": 2141,
"text": "Disadvantage : There are lots of system calls and context switches. "
},
{
"code": null,
"e": 2388,
"s": 2213,
"text": "3. Hybrid Kernel – It is the combination of both monolithic kernel and microkernel. It has speed and design of monolithic kernel and modularity and stability of microkernel. "
},
{
"code": null,
"e": 2400,
"s": 2388,
"text": "Example : "
},
{
"code": null,
"e": 2431,
"s": 2400,
"text": "Windows NT, Netware, BeOS etc."
},
{
"code": null,
"e": 2499,
"s": 2433,
"text": "Advantage : It combines both monolithic kernel and microkernel. "
},
{
"code": null,
"e": 2560,
"s": 2501,
"text": "Disadvantage : It is still similar to monolithic kernel. "
},
{
"code": null,
"e": 2738,
"s": 2562,
"text": "4. Exo Kernel – It is the type of kernel which follows end-to-end principle. It has fewest hardware abstractions as possible. It allocates physical resources to applications. "
},
{
"code": null,
"e": 2750,
"s": 2738,
"text": "Example : "
},
{
"code": null,
"e": 2769,
"s": 2750,
"text": "Nemesis, ExOS etc."
},
{
"code": null,
"e": 2822,
"s": 2771,
"text": "Advantage : It has fewest hardware abstractions. "
},
{
"code": null,
"e": 2888,
"s": 2824,
"text": "Disadvantage : There is more work for application developers. "
},
{
"code": null,
"e": 3109,
"s": 2890,
"text": "5. Nano Kernel – It is the type of kernel that offers hardware abstraction but without system services. Micro Kernel also does not have system services therefore the Micro Kernel and Nano Kernel have become analogous. "
},
{
"code": null,
"e": 3121,
"s": 3109,
"text": "Example : "
},
{
"code": null,
"e": 3131,
"s": 3121,
"text": "EROS etc."
},
{
"code": null,
"e": 3204,
"s": 3133,
"text": "Advantage : It offers hardware abstractions without system services. "
},
{
"code": null,
"e": 3279,
"s": 3206,
"text": "Disadvantage : It is quite same as Micro kernel hence it is less used. "
},
{
"code": null,
"e": 3297,
"s": 3283,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 3305,
"s": 3297,
"text": "GATE CS"
},
{
"code": null,
"e": 3323,
"s": 3305,
"text": "Operating Systems"
},
{
"code": null,
"e": 3341,
"s": 3323,
"text": "Operating Systems"
},
{
"code": null,
"e": 3439,
"s": 3341,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3488,
"s": 3439,
"text": "Page Replacement Algorithms in Operating Systems"
},
{
"code": null,
"e": 3522,
"s": 3488,
"text": "Inter Process Communication (IPC)"
},
{
"code": null,
"e": 3563,
"s": 3522,
"text": "Introduction of Operating System - Set 1"
},
{
"code": null,
"e": 3601,
"s": 3563,
"text": "Semaphores in Process Synchronization"
},
{
"code": null,
"e": 3633,
"s": 3601,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 3672,
"s": 3633,
"text": "Banker's Algorithm in Operating System"
},
{
"code": null,
"e": 3721,
"s": 3672,
"text": "Page Replacement Algorithms in Operating Systems"
},
{
"code": null,
"e": 3748,
"s": 3721,
"text": "Disk Scheduling Algorithms"
},
{
"code": null,
"e": 3772,
"s": 3748,
"text": "File Allocation Methods"
}
]
|
Lodash _.includes() Method | 09 Sep, 2020
The _.includes() method is used to find the value is in the collection or not. If the collection is a string, it will be tested for a value sub-string, otherwise SameValueZero() method is used for equality comparisons. If the index is given and is negative, the value is tested from the end indexes of the collection as the offset.
Syntax:
_.includes( collection, value, index )
Parameters: This method accepts three parameters as mentioned above and described below:
collection: This parameter holds the collection to inspect. Collection can be an array or object or string.
value: This parameter holds the value to search for.
index: This parameter holds the index to search from.
Return Value: This method returns true if the value is found in the collection, else false.
Example 1:
Javascript
// Requiring the lodash library const _ = require("lodash"); // Collection of stringvar name = [ 'gfg', 'geeks', 'computer', 'science', 'portal' ]; // Check value is found or not by _.includes() methodconsole.log(_.includes(name, 'computer')); // Check value is found or not by _.includes() methodconsole.log(_.includes(name, 'geeeks')); // Check value is found or not by _.includes() methodconsole.log(_.includes(name, 'gfg', 2));
Output:
true
false
false
Example 2:
Javascript
// Requiring the lodash library const _ = require("lodash"); // Collection of integer valuevar name = [ 10, 15, 20, 25, 30 ]; // Check value is found or not by _.includes() methodconsole.log(_.includes(name, 25)); // Check value is found or not by _.includes() methodconsole.log(_.includes(name, 35)); // Check value is found or not by _.includes() methodconsole.log(_.includes(name, 25, 3));
Output:
true
false
true
JavaScript-Lodash
JavaScript
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": "\n09 Sep, 2020"
},
{
"code": null,
"e": 360,
"s": 28,
"text": "The _.includes() method is used to find the value is in the collection or not. If the collection is a string, it will be tested for a value sub-string, otherwise SameValueZero() method is used for equality comparisons. If the index is given and is negative, the value is tested from the end indexes of the collection as the offset."
},
{
"code": null,
"e": 368,
"s": 360,
"text": "Syntax:"
},
{
"code": null,
"e": 408,
"s": 368,
"text": "_.includes( collection, value, index )\n"
},
{
"code": null,
"e": 497,
"s": 408,
"text": "Parameters: This method accepts three parameters as mentioned above and described below:"
},
{
"code": null,
"e": 605,
"s": 497,
"text": "collection: This parameter holds the collection to inspect. Collection can be an array or object or string."
},
{
"code": null,
"e": 658,
"s": 605,
"text": "value: This parameter holds the value to search for."
},
{
"code": null,
"e": 712,
"s": 658,
"text": "index: This parameter holds the index to search from."
},
{
"code": null,
"e": 804,
"s": 712,
"text": "Return Value: This method returns true if the value is found in the collection, else false."
},
{
"code": null,
"e": 815,
"s": 804,
"text": "Example 1:"
},
{
"code": null,
"e": 826,
"s": 815,
"text": "Javascript"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); // Collection of stringvar name = [ 'gfg', 'geeks', 'computer', 'science', 'portal' ]; // Check value is found or not by _.includes() methodconsole.log(_.includes(name, 'computer')); // Check value is found or not by _.includes() methodconsole.log(_.includes(name, 'geeeks')); // Check value is found or not by _.includes() methodconsole.log(_.includes(name, 'gfg', 2));",
"e": 1266,
"s": 826,
"text": null
},
{
"code": null,
"e": 1274,
"s": 1266,
"text": "Output:"
},
{
"code": null,
"e": 1292,
"s": 1274,
"text": "true\nfalse\nfalse\n"
},
{
"code": null,
"e": 1305,
"s": 1292,
"text": "Example 2: "
},
{
"code": null,
"e": 1316,
"s": 1305,
"text": "Javascript"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); // Collection of integer valuevar name = [ 10, 15, 20, 25, 30 ]; // Check value is found or not by _.includes() methodconsole.log(_.includes(name, 25)); // Check value is found or not by _.includes() methodconsole.log(_.includes(name, 35)); // Check value is found or not by _.includes() methodconsole.log(_.includes(name, 25, 3));",
"e": 1717,
"s": 1316,
"text": null
},
{
"code": null,
"e": 1725,
"s": 1717,
"text": "Output:"
},
{
"code": null,
"e": 1742,
"s": 1725,
"text": "true\nfalse\ntrue\n"
},
{
"code": null,
"e": 1760,
"s": 1742,
"text": "JavaScript-Lodash"
},
{
"code": null,
"e": 1771,
"s": 1760,
"text": "JavaScript"
},
{
"code": null,
"e": 1788,
"s": 1771,
"text": "Web Technologies"
}
]
|
Lodash _.exists() Method | 30 Sep, 2020
The Lodash _.exists() method checks whether the given value is Exist or not and returns the corresponding boolean value. Both null and undefined are considered non-existy values. All other values are “Existy”.
Syntax:
_.exists( value );
Parameters: This method accepts single parameter as mentioned above and described below:
value: Given value to be checked for Existy value.
Return Value: This method returns a Boolean value true if the given value is Existy, else false.
Note: This will not work in normal JavaScript because it requires the lidash.js contrib library to be installed. Lodash.js contrib library can be installed using npm install lodash-contrib.
Example 1:
Javascript
// Defining underscore lodash variable var _ = require('lodash-contrib'); var bool = _.exists("Geeks"); console.log("Check the Existenc of Given Value : ", bool);
Output:
Check the Existenc of Given Value : true
Example 2:
Javascript
// Defining underscore lodash variable var _ = require('lodash-contrib'); var bool = _.exists(undefined); console.log("Check the Existenc of Given Value : ", bool);
Output:
Check the Existenc of Given Value : false
Example 3:
Javascript
// Defining underscore lodash variable var _ = require('lodash-contrib'); var bool = _.exists(null); console.log("Check the Existenc of Given Value : ", bool);
Output:
Check the Existenc of Given Value : false
Example 4:
Javascript
// Defining underscore lodash variable var _ = require('lodash-contrib'); var bool = _.exists([1, 12, 2, 3]); console.log("Check the Existenc of Given Value : ", bool);
Output:
Check the Existenc of Given Value : true
JavaScript-Lodash
JavaScript
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": "\n30 Sep, 2020"
},
{
"code": null,
"e": 238,
"s": 28,
"text": "The Lodash _.exists() method checks whether the given value is Exist or not and returns the corresponding boolean value. Both null and undefined are considered non-existy values. All other values are “Existy”."
},
{
"code": null,
"e": 246,
"s": 238,
"text": "Syntax:"
},
{
"code": null,
"e": 266,
"s": 246,
"text": "_.exists( value );\n"
},
{
"code": null,
"e": 355,
"s": 266,
"text": "Parameters: This method accepts single parameter as mentioned above and described below:"
},
{
"code": null,
"e": 406,
"s": 355,
"text": "value: Given value to be checked for Existy value."
},
{
"code": null,
"e": 503,
"s": 406,
"text": "Return Value: This method returns a Boolean value true if the given value is Existy, else false."
},
{
"code": null,
"e": 693,
"s": 503,
"text": "Note: This will not work in normal JavaScript because it requires the lidash.js contrib library to be installed. Lodash.js contrib library can be installed using npm install lodash-contrib."
},
{
"code": null,
"e": 704,
"s": 693,
"text": "Example 1:"
},
{
"code": null,
"e": 715,
"s": 704,
"text": "Javascript"
},
{
"code": "// Defining underscore lodash variable var _ = require('lodash-contrib'); var bool = _.exists(\"Geeks\"); console.log(\"Check the Existenc of Given Value : \", bool);",
"e": 883,
"s": 715,
"text": null
},
{
"code": null,
"e": 891,
"s": 883,
"text": "Output:"
},
{
"code": null,
"e": 933,
"s": 891,
"text": "Check the Existenc of Given Value : true\n"
},
{
"code": null,
"e": 944,
"s": 933,
"text": "Example 2:"
},
{
"code": null,
"e": 955,
"s": 944,
"text": "Javascript"
},
{
"code": "// Defining underscore lodash variable var _ = require('lodash-contrib'); var bool = _.exists(undefined); console.log(\"Check the Existenc of Given Value : \", bool);",
"e": 1126,
"s": 955,
"text": null
},
{
"code": null,
"e": 1134,
"s": 1126,
"text": "Output:"
},
{
"code": null,
"e": 1177,
"s": 1134,
"text": "Check the Existenc of Given Value : false\n"
},
{
"code": null,
"e": 1188,
"s": 1177,
"text": "Example 3:"
},
{
"code": null,
"e": 1199,
"s": 1188,
"text": "Javascript"
},
{
"code": "// Defining underscore lodash variable var _ = require('lodash-contrib'); var bool = _.exists(null); console.log(\"Check the Existenc of Given Value : \", bool);",
"e": 1364,
"s": 1199,
"text": null
},
{
"code": null,
"e": 1372,
"s": 1364,
"text": "Output:"
},
{
"code": null,
"e": 1415,
"s": 1372,
"text": "Check the Existenc of Given Value : false\n"
},
{
"code": null,
"e": 1426,
"s": 1415,
"text": "Example 4:"
},
{
"code": null,
"e": 1437,
"s": 1426,
"text": "Javascript"
},
{
"code": "// Defining underscore lodash variable var _ = require('lodash-contrib'); var bool = _.exists([1, 12, 2, 3]); console.log(\"Check the Existenc of Given Value : \", bool);",
"e": 1611,
"s": 1437,
"text": null
},
{
"code": null,
"e": 1619,
"s": 1611,
"text": "Output:"
},
{
"code": null,
"e": 1661,
"s": 1619,
"text": "Check the Existenc of Given Value : true\n"
},
{
"code": null,
"e": 1679,
"s": 1661,
"text": "JavaScript-Lodash"
},
{
"code": null,
"e": 1690,
"s": 1679,
"text": "JavaScript"
},
{
"code": null,
"e": 1707,
"s": 1690,
"text": "Web Technologies"
}
]
|
Find Prime number just less than and just greater each element of given Array - GeeksforGeeks | 28 Jan, 2022
Given an integer array A[] of size N, the task is to find the prime numbers just less and just greater than A[i] (for all 0<=i<N).
Examples:
Input: A={17, 28}, N=2Output:13 1923 29Explanation:13 is the prime number just less than 17.19 is the prime number just greater than 17.23 is the prime number just less than 28.29 is the prime number just greater than 28.
Input: A={126, 64, 2896, 156}, N=4Output:113 127 61 67 2887 2897 151 157
Naive Approach: Observation: The Maximal Primal Gap for numbers less than 109 is 292.
The Naive Approach would be to check for primality by checking if a number has any factor other than 1 and itself. Follow the steps below to solve the problem:
Traverse the array A, and for each current index i, do the following:
Iterate from A[i]-1 in the descending order, and for each current index j, do the following:Check if j is prime or not by checking if it has any factor other than 1 and itself.If j is prime, print j and terminate the inner loop. This gives the prime number just less than A[i].Iterate from A[i]+1 in the ascending order, and for each current index j, do the following:Check if j is prime or not by checking if it has any factor other than 1 and itself.If j is prime, print j and terminate the inner loop. This gives the prime number just less than A[i],
Iterate from A[i]-1 in the descending order, and for each current index j, do the following:Check if j is prime or not by checking if it has any factor other than 1 and itself.If j is prime, print j and terminate the inner loop. This gives the prime number just less than A[i].
Check if j is prime or not by checking if it has any factor other than 1 and itself.If j is prime, print j and terminate the inner loop. This gives the prime number just less than A[i].
Check if j is prime or not by checking if it has any factor other than 1 and itself.
If j is prime, print j and terminate the inner loop. This gives the prime number just less than A[i].
Iterate from A[i]+1 in the ascending order, and for each current index j, do the following:Check if j is prime or not by checking if it has any factor other than 1 and itself.If j is prime, print j and terminate the inner loop. This gives the prime number just less than A[i],
Check if j is prime or not by checking if it has any factor other than 1 and itself.If j is prime, print j and terminate the inner loop. This gives the prime number just less than A[i],
Check if j is prime or not by checking if it has any factor other than 1 and itself.
If j is prime, print j and terminate the inner loop. This gives the prime number just less than A[i],
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;// Utility function to check// for primality of a number X by// checking whether X haACCs any// factors other than 1 and itself.bool isPrime(int X){ for (int i = 2; i * i <= X; i++) if (X % i == 0) // Factor found return false; return true;}// Function to print primes// just less than and just greater// than of each element in an arrayvoid printPrimes(int A[], int N){ // Traverse the array for (int i = 0; i < N; i++) { // Traverse for finding prime // just less than A[i] for (int j = A[i] - 1;; j--) { // Prime just less than A[i] found if (isPrime(j)) { cout << j << " "; break; } } // Traverse for finding prime // just greater than A[i] for (int j = A[i] + 1;; j++) { // Prime just greater than A[i] found if (isPrime(j)) { cout << j << " "; break; } } cout << endl; }}// Driver codeint main(){ // Input int A[] = { 17, 28 }; int N = sizeof(A) / sizeof(A[0]); // Function call printPrimes(A, N); return 0;}
// Java program for the above approachimport java.io.*; class GFG{ // Utility function to check// for primality of a number X by// checking whether X has any// factors other than 1 and itself.static boolean isPrime(int X){ for(int i = 2; i * i <= X; i++) // Factor found if (X % i == 0) return false; return true;} // Function to print primes// just less than and just greater// than of each element in an arraystatic void printPrimes(int A[], int N){ // Traverse the array for(int i = 0; i < N; i++) { // Traverse for finding prime // just less than A[i] for(int j = A[i] - 1;; j--) { // Prime just less than A[i] found if (isPrime(j)) { System.out.print(j + " "); break; } } // Traverse for finding prime // just greater than A[i] for(int j = A[i] + 1;; j++) { // Prime just greater than A[i] found if (isPrime(j)) { System.out.print( j + " "); break; } } System.out.println(); }} // Driver codepublic static void main(String[] args){ // Input int A[] = { 17, 28 }; int N = A.length; // Function call printPrimes(A, N);}} // This code is contributed by sanjoy_62
# Python3 program for the above approachfrom math import sqrt # Utility function to check# for primality of a number X by# checking whether X haACCs any# factors other than 1 and itself.def isPrime(X): for i in range(2, int(sqrt(X)) + 1, 1): if (X % i == 0): # Factor found return False return True # Function to print primes# just less than and just greater# than of each element in an arraydef printPrimes(A, N): # Traverse the array for i in range(N): # Traverse for finding prime # just less than A[i] j = A[i] - 1 while(1): # Prime just less than A[i] found if (isPrime(j)): print(j, end = " ") break j -= 1 # Traverse for finding prime # just greater than A[i] j = A[i] + 1 while (1): # Prime just greater than A[i] found if (isPrime(j)): print(j, end = " ") break j += 1 print("\n", end = "") # Driver codeif __name__ == '__main__': # Input A = [ 17, 28 ] N = len(A) # Function call printPrimes(A, N) # This code is contributed by SURENDRA_GANGWAR
// C# program for the above approachusing System; class GFG{ // Utility function to check// for primality of a number X by// checking whether X has any// factors other than 1 and itself.static bool isPrime(int X){ for(int i = 2; i * i <= X; i++) // Factor found if (X % i == 0) return false; return true;} // Function to print primes// just less than and just greater// than of each element in an arraystatic void printPrimes(int[] A, int N){ // Traverse the array for(int i = 0; i < N; i++) { // Traverse for finding prime // just less than A[i] for(int j = A[i] - 1;; j--) { // Prime just less than A[i] found if (isPrime(j)) { Console.Write(j + " "); break; } } // Traverse for finding prime // just greater than A[i] for(int j = A[i] + 1;; j++) { // Prime just greater than A[i] found if (isPrime(j)) { Console.Write(j + " "); break; } } Console.WriteLine(); }} // Driver codepublic static void Main(){ // Input int []A = { 17, 28 }; int N = A.Length; // Function call printPrimes(A, N);}} // This code is contributed by subhammahato348
<script>// Javascript program for the above approach // Utility function to check// for primality of a number X by// checking whether X haACCs any// factors other than 1 and itself.function isPrime(X) { for (let i = 2; i * i <= X; i++) if (X % i == 0) // Factor found return false; return true;} // Function to print primes// just less than and just greater// than of each element in an arrayfunction printPrimes(A, N){ // Traverse the array for (let i = 0; i < N; i++) { // Traverse for finding prime // just less than A[i] for (let j = A[i] - 1; ; j--) { // Prime just less than A[i] found if (isPrime(j)) { document.write(j + " "); break; } } // Traverse for finding prime // just greater than A[i] for (let j = A[i] + 1; ; j++) { // Prime just greater than A[i] found if (isPrime(j)) { document.write(j + " "); break; } } document.write("<br>"); }} // Driver code // Inputlet A = [17, 28];let N = A.length; // Function callprintPrimes(A, N); // This code is contributed by _saurabh_jaiswal.</script>
13 19
23 29
Time Complexity: O(N*G*√M), where G is the maximal primal gap and M is the largest element in A.Auxiliary Space: O(1)
Efficient Approach 1: Instead of checking for individual numbers, all primes numbers can be recalculated using the Sieve of Eratosthenes.
Below is the implementation of the above approach:
C++
Java
C#
Javascript
#include <bits/stdc++.h>using namespace std;const int M = 1e6;// Boolean array to store// if a number is prime or notbool isPrime[M];void SieveOfEratosthenes(){ // assigh value false // to the boolean array isprime memset(isPrime, true, sizeof(isPrime)); for (int i = 2; i * i <= M; i++) { // If isPrime[i] is not changed, // then it is a prime if (isPrime[i]) { // Update all multiples of i greater than or // equal to the square of it numbers which are // multiple of i and are less than i^2 are // already been marked. for (int j = i * i; j < M; j += i) isPrime[j] = false; } }}// Function to print primes// just less than and just greater// than of each element in an arrayvoid printPrimes(int A[], int N){ // Precalculating SieveOfEratosthenes(); // Traverse the array for (int i = 0; i < N; i++) { // Traverse for finding // prime just less than A[i] for (int j = A[i] - 1;; j--) { // Prime just less than A[i] found if (isPrime[j]) { cout << j << " "; break; } } // Traverse for finding // prime just greater than A[i] for (int j = A[i] + 1;; j++) { // Prime just greater than A[i] found if (isPrime[j]) { cout << j << " "; break; } } cout << endl; }}// Driver codeint main(){ // Input int A[] = { 17, 28 }; int N = sizeof(A) / sizeof(A[0]); // Function call printPrimes(A, N); return 0;}
import java.util.*; class GFG{ static int M = 1000000; // Boolean array to store// if a number is prime or notstatic boolean isPrime[] = new boolean[M]; static void SieveOfEratosthenes(){ // Assigh value false // to the boolean array isprime Arrays.fill(isPrime, true); for(int i = 2; i * i <= M; i++) { // If isPrime[i] is not changed, // then it is a prime if (isPrime[i]) { // Update all multiples of i greater than or // equal to the square of it numbers which are // multiple of i and are less than i^2 are // already been marked. for(int j = i * i; j < M; j += i) isPrime[j] = false; } }} // Function to print primes// just less than and just greater// than of each element in an arraystatic void printPrimes(int A[], int N){ // Precalculating SieveOfEratosthenes(); // Traverse the array for(int i = 0; i < N; i++) { // Traverse for finding // prime just less than A[i] for(int j = A[i] - 1;; j--) { // Prime just less than A[i] found if (isPrime[j]) { System.out.print( j + " "); break; } } // Traverse for finding // prime just greater than A[i] for(int j = A[i] + 1;; j++) { // Prime just greater than A[i] found if (isPrime[j]) { System.out.print(j + " "); break; } } System.out.println(); }} // Driver codepublic static void main(String[] args){ // Input int A[] = { 17, 28 }; int N = A.length; // Function call printPrimes(A, N);}} // This code is contributed by sanjoy_62
using System; class GFG { static int M = 1000000; // Boolean array to store // if a number is prime or not static bool[] isPrime = new bool[M]; static void SieveOfEratosthenes() { // Assigh value false // to the boolean array isprime Array.Fill(isPrime, true); for (int i = 2; i * i <= M; i++) { // If isPrime[i] is not changed, // then it is a prime if (isPrime[i]) { // Update all multiples of i greater than or // equal to the square of it numbers which // are multiple of i and are less than i^2 // are already been marked. for (int j = i * i; j < M; j += i) isPrime[j] = false; } } } // Function to print primes // just less than and just greater // than of each element in an array static void printPrimes(int[] A, int N) { // Precalculating SieveOfEratosthenes(); // Traverse the array for (int i = 0; i < N; i++) { // Traverse for finding // prime just less than A[i] for (int j = A[i] - 1;; j--) { // Prime just less than A[i] found if (isPrime[j]) { Console.Write(j + " "); break; } } // Traverse for finding // prime just greater than A[i] for (int j = A[i] + 1;; j++) { // Prime just greater than A[i] found if (isPrime[j]) { Console.Write(j + " "); break; } } Console.WriteLine(); } } // Driver code public static void Main() { // Input int[] A = { 17, 28 }; int N = A.Length; // Function call printPrimes(A, N); }} // This code is contributed by subham348.
<script> const M = 1000000;// Boolean array to store// if a number is prime or notlet isPrime = new Array(M).fill(true);function SieveOfEratosthenes(){ for (let i = 2; i * i <= M; i++) { // If isPrime[i] is not changed, // then it is a prime if (isPrime[i]) { // Update all multiples of i greater than or // equal to the square of it numbers which are // multiple of i and are less than i^2 are // already been marked. for (let j = i * i; j < M; j += i) isPrime[j] = false; } }}// Function to print primes// just less than and just greater// than of each element in an arrayfunction printPrimes(A, N){ // Precalculating SieveOfEratosthenes(); // Traverse the array for (let i = 0; i < N; i++) { // Traverse for finding // prime just less than A[i] for (let j = A[i] - 1;; j--) { // Prime just less than A[i] found if (isPrime[j]) { document.write(j + " "); break; } } // Traverse for finding // prime just greater than A[i] for (let j = A[i] + 1;; j++) { // Prime just greater than A[i] found if (isPrime[j]) { document.write(j + " "); break; } } document.write("<br>"); }}// Driver code // Input let A = [ 17, 28 ]; let N = A.length; // Function call printPrimes(A, N); </script>
13 19
23 29
Time Complexity: O(N*G+MLog(Log(M))), where G is the maximal primal gap and M is the largest element in A.Auxiliary Space: O(M)
Efficient Approach 2: The Millar-Rabin primality test can be used.
C++
Java
#include <bits/stdc++.h>using namespace std;// Utility function to do modular exponentiation.// It returns (x^y) % pint power(int x, unsigned int y, int p){ int res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if (y & 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res;} // This function is called for all k trials.// It returns false if n is composite// and returns true if n is probably prime.// d is an odd number such that// d*2<sup>r</sup> = n-1 for some r >= 1bool miillerTest(int d, int n){ // Pick a random number in [2..n-2] // Corner cases make sure that n > 4 int a = 2 + rand() % (n - 4); // Compute a^d % n int x = power(a, d, n); if (x == 1 || x == n - 1) return true; // Keep squaring x while one // of the following doesn't happen // (i) d does not reach n-1 // (ii) (x^2) % n is not 1 // (iii) (x^2) % n is not n-1 while (d != n - 1) { x = (x * x) % n; d *= 2; if (x == 1) return false; if (x == n - 1) return true; } // Return composite return false;} // It returns false if n is// composite and returns true if n// is probably prime.// k determines accuracy level. Higher// value of k indicates more accuracy.bool isPrime(int n){ // number of iterations int k = 4; // Corner cases if (n <= 1 || n == 4) return false; if (n <= 3) return true; // Find r such that // n = 2^d * r + 1 for some r >= 1 int d = n - 1; while (d % 2 == 0) d /= 2; // Iterate given number of 'k' times for (int i = 0; i < k; i++) if (!miillerTest(d, n)) return false; return true;} // Function to print primes// just less than and just greater// than of each element in an arrayvoid printPrimes(int A[], int N){ // Precalculating // Traverse the array for (int i = 0; i < N; i++) { // Traverse for finding // prime just less than A[i] for (int j = A[i] - 1;; j--) { // Prime just less than A[i] found if (isPrime(j)) { cout << j << " "; break; } } // Traverse for finding // prime just greater than A[i] for (int j = A[i] + 1;; j++) { // Prime just greater than A[i] found if (isPrime(j)) { cout << j << " "; break; } } cout << endl; }}// Driver codeint main(){ // Input int A[] = { 17, 28 }; int N = sizeof(A) / sizeof(A[0]); // Function call printPrimes(A, N); return 0;}
import java.util.*; class GFG{ // Utility function to do modular exponentiation.// It returns (x^y) % pstatic int power(int x, int y, int p){ int res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if (y %2==1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res;} // This function is called for all k trials.// It returns false if n is composite// and returns true if n is probably prime.// d is an odd number such that// d*2<sup>r</sup> = n-1 for some r >= 1static boolean miillerTest(int d, int n){ // Pick a random number in [2..n-2] // Corner cases make sure that n > 4 int a = 2 + (int)(Math.random()*100000) % (n - 4); // Compute a^d % n int x = power(a, d, n); if (x == 1 || x == n - 1) return true; // Keep squaring x while one // of the following doesn't happen // (i) d does not reach n-1 // (ii) (x^2) % n is not 1 // (iii) (x^2) % n is not n-1 while (d != n - 1) { x = (x * x) % n; d *= 2; if (x == 1) return false; if (x == n - 1) return true; } // Return composite return false;} // It returns false if n is// composite and returns true if n// is probably prime.// k determines accuracy level. Higher// value of k indicates more accuracy.static boolean isPrime(int n){ // number of iterations int k = 4; // Corner cases if (n <= 1 || n == 4) return false; if (n <= 3) return true; // Find r such that // n = 2^d * r + 1 for some r >= 1 int d = n - 1; while (d % 2 == 0) d /= 2; // Iterate given number of 'k' times for (int i = 0; i < k; i++) if (!miillerTest(d, n)) return false; return true;} // Function to print primes// just less than and just greater// than of each element in an arraystatic void printPrimes(int A[], int N){ // Precalculating // Traverse the array for (int i = 0; i < N; i++) { // Traverse for finding // prime just less than A[i] for (int j = A[i] - 1;; j--) { // Prime just less than A[i] found if (isPrime(j)) { System.out.print(j+ " "); break; } } // Traverse for finding // prime just greater than A[i] for (int j = A[i] + 1;; j++) { // Prime just greater than A[i] found if (isPrime(j)) { System.out.print(j+ " "); break; } } System.out.println(); }} // Driver codepublic static void main(String[] args){ // Input int A[] = { 17, 28 }; int N = A.length; // Function call printPrimes(A, N); }} // This code is contributed by gauravrajput1
13 19
23 29
Time Complexity: O(N*G*KLog3M), where G is the maximal primal gap and M is the largest element in A. Here, K=4Auxiliary Space: O(1)
sanjoy_62
SURENDRA_GANGWAR
subhammahato348
_saurabh_jaiswal
subham348
GauravRajput1
number-theory
Prime Number
sieve
Arrays
Mathematical
Arrays
number-theory
Mathematical
Prime Number
sieve
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Window Sliding Technique
Trapping Rain Water
Reversal algorithm for array rotation
Building Heap from Array
Move all negative numbers to beginning and positive to end with constant extra space
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": 24820,
"s": 24792,
"text": "\n28 Jan, 2022"
},
{
"code": null,
"e": 24951,
"s": 24820,
"text": "Given an integer array A[] of size N, the task is to find the prime numbers just less and just greater than A[i] (for all 0<=i<N)."
},
{
"code": null,
"e": 24961,
"s": 24951,
"text": "Examples:"
},
{
"code": null,
"e": 25183,
"s": 24961,
"text": "Input: A={17, 28}, N=2Output:13 1923 29Explanation:13 is the prime number just less than 17.19 is the prime number just greater than 17.23 is the prime number just less than 28.29 is the prime number just greater than 28."
},
{
"code": null,
"e": 25257,
"s": 25183,
"text": "Input: A={126, 64, 2896, 156}, N=4Output:113 127 61 67 2887 2897 151 157 "
},
{
"code": null,
"e": 25343,
"s": 25257,
"text": "Naive Approach: Observation: The Maximal Primal Gap for numbers less than 109 is 292."
},
{
"code": null,
"e": 25503,
"s": 25343,
"text": "The Naive Approach would be to check for primality by checking if a number has any factor other than 1 and itself. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 25573,
"s": 25503,
"text": "Traverse the array A, and for each current index i, do the following:"
},
{
"code": null,
"e": 26127,
"s": 25573,
"text": "Iterate from A[i]-1 in the descending order, and for each current index j, do the following:Check if j is prime or not by checking if it has any factor other than 1 and itself.If j is prime, print j and terminate the inner loop. This gives the prime number just less than A[i].Iterate from A[i]+1 in the ascending order, and for each current index j, do the following:Check if j is prime or not by checking if it has any factor other than 1 and itself.If j is prime, print j and terminate the inner loop. This gives the prime number just less than A[i],"
},
{
"code": null,
"e": 26405,
"s": 26127,
"text": "Iterate from A[i]-1 in the descending order, and for each current index j, do the following:Check if j is prime or not by checking if it has any factor other than 1 and itself.If j is prime, print j and terminate the inner loop. This gives the prime number just less than A[i]."
},
{
"code": null,
"e": 26591,
"s": 26405,
"text": "Check if j is prime or not by checking if it has any factor other than 1 and itself.If j is prime, print j and terminate the inner loop. This gives the prime number just less than A[i]."
},
{
"code": null,
"e": 26676,
"s": 26591,
"text": "Check if j is prime or not by checking if it has any factor other than 1 and itself."
},
{
"code": null,
"e": 26778,
"s": 26676,
"text": "If j is prime, print j and terminate the inner loop. This gives the prime number just less than A[i]."
},
{
"code": null,
"e": 27055,
"s": 26778,
"text": "Iterate from A[i]+1 in the ascending order, and for each current index j, do the following:Check if j is prime or not by checking if it has any factor other than 1 and itself.If j is prime, print j and terminate the inner loop. This gives the prime number just less than A[i],"
},
{
"code": null,
"e": 27241,
"s": 27055,
"text": "Check if j is prime or not by checking if it has any factor other than 1 and itself.If j is prime, print j and terminate the inner loop. This gives the prime number just less than A[i],"
},
{
"code": null,
"e": 27326,
"s": 27241,
"text": "Check if j is prime or not by checking if it has any factor other than 1 and itself."
},
{
"code": null,
"e": 27428,
"s": 27326,
"text": "If j is prime, print j and terminate the inner loop. This gives the prime number just less than A[i],"
},
{
"code": null,
"e": 27479,
"s": 27428,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 27483,
"s": 27479,
"text": "C++"
},
{
"code": null,
"e": 27488,
"s": 27483,
"text": "Java"
},
{
"code": null,
"e": 27496,
"s": 27488,
"text": "Python3"
},
{
"code": null,
"e": 27499,
"s": 27496,
"text": "C#"
},
{
"code": null,
"e": 27510,
"s": 27499,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std;// Utility function to check// for primality of a number X by// checking whether X haACCs any// factors other than 1 and itself.bool isPrime(int X){ for (int i = 2; i * i <= X; i++) if (X % i == 0) // Factor found return false; return true;}// Function to print primes// just less than and just greater// than of each element in an arrayvoid printPrimes(int A[], int N){ // Traverse the array for (int i = 0; i < N; i++) { // Traverse for finding prime // just less than A[i] for (int j = A[i] - 1;; j--) { // Prime just less than A[i] found if (isPrime(j)) { cout << j << \" \"; break; } } // Traverse for finding prime // just greater than A[i] for (int j = A[i] + 1;; j++) { // Prime just greater than A[i] found if (isPrime(j)) { cout << j << \" \"; break; } } cout << endl; }}// Driver codeint main(){ // Input int A[] = { 17, 28 }; int N = sizeof(A) / sizeof(A[0]); // Function call printPrimes(A, N); return 0;}",
"e": 28748,
"s": 27510,
"text": null
},
{
"code": "// Java program for the above approachimport java.io.*; class GFG{ // Utility function to check// for primality of a number X by// checking whether X has any// factors other than 1 and itself.static boolean isPrime(int X){ for(int i = 2; i * i <= X; i++) // Factor found if (X % i == 0) return false; return true;} // Function to print primes// just less than and just greater// than of each element in an arraystatic void printPrimes(int A[], int N){ // Traverse the array for(int i = 0; i < N; i++) { // Traverse for finding prime // just less than A[i] for(int j = A[i] - 1;; j--) { // Prime just less than A[i] found if (isPrime(j)) { System.out.print(j + \" \"); break; } } // Traverse for finding prime // just greater than A[i] for(int j = A[i] + 1;; j++) { // Prime just greater than A[i] found if (isPrime(j)) { System.out.print( j + \" \"); break; } } System.out.println(); }} // Driver codepublic static void main(String[] args){ // Input int A[] = { 17, 28 }; int N = A.length; // Function call printPrimes(A, N);}} // This code is contributed by sanjoy_62",
"e": 30173,
"s": 28748,
"text": null
},
{
"code": "# Python3 program for the above approachfrom math import sqrt # Utility function to check# for primality of a number X by# checking whether X haACCs any# factors other than 1 and itself.def isPrime(X): for i in range(2, int(sqrt(X)) + 1, 1): if (X % i == 0): # Factor found return False return True # Function to print primes# just less than and just greater# than of each element in an arraydef printPrimes(A, N): # Traverse the array for i in range(N): # Traverse for finding prime # just less than A[i] j = A[i] - 1 while(1): # Prime just less than A[i] found if (isPrime(j)): print(j, end = \" \") break j -= 1 # Traverse for finding prime # just greater than A[i] j = A[i] + 1 while (1): # Prime just greater than A[i] found if (isPrime(j)): print(j, end = \" \") break j += 1 print(\"\\n\", end = \"\") # Driver codeif __name__ == '__main__': # Input A = [ 17, 28 ] N = len(A) # Function call printPrimes(A, N) # This code is contributed by SURENDRA_GANGWAR",
"e": 31512,
"s": 30173,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ // Utility function to check// for primality of a number X by// checking whether X has any// factors other than 1 and itself.static bool isPrime(int X){ for(int i = 2; i * i <= X; i++) // Factor found if (X % i == 0) return false; return true;} // Function to print primes// just less than and just greater// than of each element in an arraystatic void printPrimes(int[] A, int N){ // Traverse the array for(int i = 0; i < N; i++) { // Traverse for finding prime // just less than A[i] for(int j = A[i] - 1;; j--) { // Prime just less than A[i] found if (isPrime(j)) { Console.Write(j + \" \"); break; } } // Traverse for finding prime // just greater than A[i] for(int j = A[i] + 1;; j++) { // Prime just greater than A[i] found if (isPrime(j)) { Console.Write(j + \" \"); break; } } Console.WriteLine(); }} // Driver codepublic static void Main(){ // Input int []A = { 17, 28 }; int N = A.Length; // Function call printPrimes(A, N);}} // This code is contributed by subhammahato348",
"e": 32889,
"s": 31512,
"text": null
},
{
"code": "<script>// Javascript program for the above approach // Utility function to check// for primality of a number X by// checking whether X haACCs any// factors other than 1 and itself.function isPrime(X) { for (let i = 2; i * i <= X; i++) if (X % i == 0) // Factor found return false; return true;} // Function to print primes// just less than and just greater// than of each element in an arrayfunction printPrimes(A, N){ // Traverse the array for (let i = 0; i < N; i++) { // Traverse for finding prime // just less than A[i] for (let j = A[i] - 1; ; j--) { // Prime just less than A[i] found if (isPrime(j)) { document.write(j + \" \"); break; } } // Traverse for finding prime // just greater than A[i] for (let j = A[i] + 1; ; j++) { // Prime just greater than A[i] found if (isPrime(j)) { document.write(j + \" \"); break; } } document.write(\"<br>\"); }} // Driver code // Inputlet A = [17, 28];let N = A.length; // Function callprintPrimes(A, N); // This code is contributed by _saurabh_jaiswal.</script>",
"e": 34165,
"s": 32889,
"text": null
},
{
"code": null,
"e": 34179,
"s": 34165,
"text": "13 19 \n23 29 "
},
{
"code": null,
"e": 34297,
"s": 34179,
"text": "Time Complexity: O(N*G*√M), where G is the maximal primal gap and M is the largest element in A.Auxiliary Space: O(1)"
},
{
"code": null,
"e": 34435,
"s": 34297,
"text": "Efficient Approach 1: Instead of checking for individual numbers, all primes numbers can be recalculated using the Sieve of Eratosthenes."
},
{
"code": null,
"e": 34487,
"s": 34435,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 34491,
"s": 34487,
"text": "C++"
},
{
"code": null,
"e": 34496,
"s": 34491,
"text": "Java"
},
{
"code": null,
"e": 34499,
"s": 34496,
"text": "C#"
},
{
"code": null,
"e": 34510,
"s": 34499,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std;const int M = 1e6;// Boolean array to store// if a number is prime or notbool isPrime[M];void SieveOfEratosthenes(){ // assigh value false // to the boolean array isprime memset(isPrime, true, sizeof(isPrime)); for (int i = 2; i * i <= M; i++) { // If isPrime[i] is not changed, // then it is a prime if (isPrime[i]) { // Update all multiples of i greater than or // equal to the square of it numbers which are // multiple of i and are less than i^2 are // already been marked. for (int j = i * i; j < M; j += i) isPrime[j] = false; } }}// Function to print primes// just less than and just greater// than of each element in an arrayvoid printPrimes(int A[], int N){ // Precalculating SieveOfEratosthenes(); // Traverse the array for (int i = 0; i < N; i++) { // Traverse for finding // prime just less than A[i] for (int j = A[i] - 1;; j--) { // Prime just less than A[i] found if (isPrime[j]) { cout << j << \" \"; break; } } // Traverse for finding // prime just greater than A[i] for (int j = A[i] + 1;; j++) { // Prime just greater than A[i] found if (isPrime[j]) { cout << j << \" \"; break; } } cout << endl; }}// Driver codeint main(){ // Input int A[] = { 17, 28 }; int N = sizeof(A) / sizeof(A[0]); // Function call printPrimes(A, N); return 0;}",
"e": 36143,
"s": 34510,
"text": null
},
{
"code": "import java.util.*; class GFG{ static int M = 1000000; // Boolean array to store// if a number is prime or notstatic boolean isPrime[] = new boolean[M]; static void SieveOfEratosthenes(){ // Assigh value false // to the boolean array isprime Arrays.fill(isPrime, true); for(int i = 2; i * i <= M; i++) { // If isPrime[i] is not changed, // then it is a prime if (isPrime[i]) { // Update all multiples of i greater than or // equal to the square of it numbers which are // multiple of i and are less than i^2 are // already been marked. for(int j = i * i; j < M; j += i) isPrime[j] = false; } }} // Function to print primes// just less than and just greater// than of each element in an arraystatic void printPrimes(int A[], int N){ // Precalculating SieveOfEratosthenes(); // Traverse the array for(int i = 0; i < N; i++) { // Traverse for finding // prime just less than A[i] for(int j = A[i] - 1;; j--) { // Prime just less than A[i] found if (isPrime[j]) { System.out.print( j + \" \"); break; } } // Traverse for finding // prime just greater than A[i] for(int j = A[i] + 1;; j++) { // Prime just greater than A[i] found if (isPrime[j]) { System.out.print(j + \" \"); break; } } System.out.println(); }} // Driver codepublic static void main(String[] args){ // Input int A[] = { 17, 28 }; int N = A.length; // Function call printPrimes(A, N);}} // This code is contributed by sanjoy_62",
"e": 37998,
"s": 36143,
"text": null
},
{
"code": "using System; class GFG { static int M = 1000000; // Boolean array to store // if a number is prime or not static bool[] isPrime = new bool[M]; static void SieveOfEratosthenes() { // Assigh value false // to the boolean array isprime Array.Fill(isPrime, true); for (int i = 2; i * i <= M; i++) { // If isPrime[i] is not changed, // then it is a prime if (isPrime[i]) { // Update all multiples of i greater than or // equal to the square of it numbers which // are multiple of i and are less than i^2 // are already been marked. for (int j = i * i; j < M; j += i) isPrime[j] = false; } } } // Function to print primes // just less than and just greater // than of each element in an array static void printPrimes(int[] A, int N) { // Precalculating SieveOfEratosthenes(); // Traverse the array for (int i = 0; i < N; i++) { // Traverse for finding // prime just less than A[i] for (int j = A[i] - 1;; j--) { // Prime just less than A[i] found if (isPrime[j]) { Console.Write(j + \" \"); break; } } // Traverse for finding // prime just greater than A[i] for (int j = A[i] + 1;; j++) { // Prime just greater than A[i] found if (isPrime[j]) { Console.Write(j + \" \"); break; } } Console.WriteLine(); } } // Driver code public static void Main() { // Input int[] A = { 17, 28 }; int N = A.Length; // Function call printPrimes(A, N); }} // This code is contributed by subham348.",
"e": 39944,
"s": 37998,
"text": null
},
{
"code": "<script> const M = 1000000;// Boolean array to store// if a number is prime or notlet isPrime = new Array(M).fill(true);function SieveOfEratosthenes(){ for (let i = 2; i * i <= M; i++) { // If isPrime[i] is not changed, // then it is a prime if (isPrime[i]) { // Update all multiples of i greater than or // equal to the square of it numbers which are // multiple of i and are less than i^2 are // already been marked. for (let j = i * i; j < M; j += i) isPrime[j] = false; } }}// Function to print primes// just less than and just greater// than of each element in an arrayfunction printPrimes(A, N){ // Precalculating SieveOfEratosthenes(); // Traverse the array for (let i = 0; i < N; i++) { // Traverse for finding // prime just less than A[i] for (let j = A[i] - 1;; j--) { // Prime just less than A[i] found if (isPrime[j]) { document.write(j + \" \"); break; } } // Traverse for finding // prime just greater than A[i] for (let j = A[i] + 1;; j++) { // Prime just greater than A[i] found if (isPrime[j]) { document.write(j + \" \"); break; } } document.write(\"<br>\"); }}// Driver code // Input let A = [ 17, 28 ]; let N = A.length; // Function call printPrimes(A, N); </script>",
"e": 41449,
"s": 39944,
"text": null
},
{
"code": null,
"e": 41463,
"s": 41449,
"text": "13 19 \n23 29 "
},
{
"code": null,
"e": 41591,
"s": 41463,
"text": "Time Complexity: O(N*G+MLog(Log(M))), where G is the maximal primal gap and M is the largest element in A.Auxiliary Space: O(M)"
},
{
"code": null,
"e": 41658,
"s": 41591,
"text": "Efficient Approach 2: The Millar-Rabin primality test can be used."
},
{
"code": null,
"e": 41662,
"s": 41658,
"text": "C++"
},
{
"code": null,
"e": 41667,
"s": 41662,
"text": "Java"
},
{
"code": "#include <bits/stdc++.h>using namespace std;// Utility function to do modular exponentiation.// It returns (x^y) % pint power(int x, unsigned int y, int p){ int res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if (y & 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res;} // This function is called for all k trials.// It returns false if n is composite// and returns true if n is probably prime.// d is an odd number such that// d*2<sup>r</sup> = n-1 for some r >= 1bool miillerTest(int d, int n){ // Pick a random number in [2..n-2] // Corner cases make sure that n > 4 int a = 2 + rand() % (n - 4); // Compute a^d % n int x = power(a, d, n); if (x == 1 || x == n - 1) return true; // Keep squaring x while one // of the following doesn't happen // (i) d does not reach n-1 // (ii) (x^2) % n is not 1 // (iii) (x^2) % n is not n-1 while (d != n - 1) { x = (x * x) % n; d *= 2; if (x == 1) return false; if (x == n - 1) return true; } // Return composite return false;} // It returns false if n is// composite and returns true if n// is probably prime.// k determines accuracy level. Higher// value of k indicates more accuracy.bool isPrime(int n){ // number of iterations int k = 4; // Corner cases if (n <= 1 || n == 4) return false; if (n <= 3) return true; // Find r such that // n = 2^d * r + 1 for some r >= 1 int d = n - 1; while (d % 2 == 0) d /= 2; // Iterate given number of 'k' times for (int i = 0; i < k; i++) if (!miillerTest(d, n)) return false; return true;} // Function to print primes// just less than and just greater// than of each element in an arrayvoid printPrimes(int A[], int N){ // Precalculating // Traverse the array for (int i = 0; i < N; i++) { // Traverse for finding // prime just less than A[i] for (int j = A[i] - 1;; j--) { // Prime just less than A[i] found if (isPrime(j)) { cout << j << \" \"; break; } } // Traverse for finding // prime just greater than A[i] for (int j = A[i] + 1;; j++) { // Prime just greater than A[i] found if (isPrime(j)) { cout << j << \" \"; break; } } cout << endl; }}// Driver codeint main(){ // Input int A[] = { 17, 28 }; int N = sizeof(A) / sizeof(A[0]); // Function call printPrimes(A, N); return 0;}",
"e": 44451,
"s": 41667,
"text": null
},
{
"code": "import java.util.*; class GFG{ // Utility function to do modular exponentiation.// It returns (x^y) % pstatic int power(int x, int y, int p){ int res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if (y %2==1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res;} // This function is called for all k trials.// It returns false if n is composite// and returns true if n is probably prime.// d is an odd number such that// d*2<sup>r</sup> = n-1 for some r >= 1static boolean miillerTest(int d, int n){ // Pick a random number in [2..n-2] // Corner cases make sure that n > 4 int a = 2 + (int)(Math.random()*100000) % (n - 4); // Compute a^d % n int x = power(a, d, n); if (x == 1 || x == n - 1) return true; // Keep squaring x while one // of the following doesn't happen // (i) d does not reach n-1 // (ii) (x^2) % n is not 1 // (iii) (x^2) % n is not n-1 while (d != n - 1) { x = (x * x) % n; d *= 2; if (x == 1) return false; if (x == n - 1) return true; } // Return composite return false;} // It returns false if n is// composite and returns true if n// is probably prime.// k determines accuracy level. Higher// value of k indicates more accuracy.static boolean isPrime(int n){ // number of iterations int k = 4; // Corner cases if (n <= 1 || n == 4) return false; if (n <= 3) return true; // Find r such that // n = 2^d * r + 1 for some r >= 1 int d = n - 1; while (d % 2 == 0) d /= 2; // Iterate given number of 'k' times for (int i = 0; i < k; i++) if (!miillerTest(d, n)) return false; return true;} // Function to print primes// just less than and just greater// than of each element in an arraystatic void printPrimes(int A[], int N){ // Precalculating // Traverse the array for (int i = 0; i < N; i++) { // Traverse for finding // prime just less than A[i] for (int j = A[i] - 1;; j--) { // Prime just less than A[i] found if (isPrime(j)) { System.out.print(j+ \" \"); break; } } // Traverse for finding // prime just greater than A[i] for (int j = A[i] + 1;; j++) { // Prime just greater than A[i] found if (isPrime(j)) { System.out.print(j+ \" \"); break; } } System.out.println(); }} // Driver codepublic static void main(String[] args){ // Input int A[] = { 17, 28 }; int N = A.length; // Function call printPrimes(A, N); }} // This code is contributed by gauravrajput1",
"e": 47420,
"s": 44451,
"text": null
},
{
"code": null,
"e": 47434,
"s": 47420,
"text": "13 19 \n23 29 "
},
{
"code": null,
"e": 47566,
"s": 47434,
"text": "Time Complexity: O(N*G*KLog3M), where G is the maximal primal gap and M is the largest element in A. Here, K=4Auxiliary Space: O(1)"
},
{
"code": null,
"e": 47578,
"s": 47568,
"text": "sanjoy_62"
},
{
"code": null,
"e": 47595,
"s": 47578,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 47611,
"s": 47595,
"text": "subhammahato348"
},
{
"code": null,
"e": 47628,
"s": 47611,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 47638,
"s": 47628,
"text": "subham348"
},
{
"code": null,
"e": 47652,
"s": 47638,
"text": "GauravRajput1"
},
{
"code": null,
"e": 47666,
"s": 47652,
"text": "number-theory"
},
{
"code": null,
"e": 47679,
"s": 47666,
"text": "Prime Number"
},
{
"code": null,
"e": 47685,
"s": 47679,
"text": "sieve"
},
{
"code": null,
"e": 47692,
"s": 47685,
"text": "Arrays"
},
{
"code": null,
"e": 47705,
"s": 47692,
"text": "Mathematical"
},
{
"code": null,
"e": 47712,
"s": 47705,
"text": "Arrays"
},
{
"code": null,
"e": 47726,
"s": 47712,
"text": "number-theory"
},
{
"code": null,
"e": 47739,
"s": 47726,
"text": "Mathematical"
},
{
"code": null,
"e": 47752,
"s": 47739,
"text": "Prime Number"
},
{
"code": null,
"e": 47758,
"s": 47752,
"text": "sieve"
},
{
"code": null,
"e": 47856,
"s": 47758,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 47881,
"s": 47856,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 47901,
"s": 47881,
"text": "Trapping Rain Water"
},
{
"code": null,
"e": 47939,
"s": 47901,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 47964,
"s": 47939,
"text": "Building Heap from Array"
},
{
"code": null,
"e": 48049,
"s": 47964,
"text": "Move all negative numbers to beginning and positive to end with constant extra space"
},
{
"code": null,
"e": 48079,
"s": 48049,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 48139,
"s": 48079,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 48154,
"s": 48139,
"text": "C++ Data Types"
},
{
"code": null,
"e": 48197,
"s": 48154,
"text": "Set in C++ Standard Template Library (STL)"
}
]
|
Explain about add and assignment(+=) operator in detail in javascript? | The add and assignment(+=) operator reduces the code little bit.It may not much influential in small codes whereas coming to long codes it's use can't be ignored.
Live Demo
<html>
<body>
<script>
var tot = 0;
var a = [1,45,78,9,78,40];
for(var i = 0; i<a.length;i++){
tot += a[i]
}
document.write(tot);
</script>
</body>
</html>
251 | [
{
"code": null,
"e": 1226,
"s": 1062,
"text": "The add and assignment(+=) operator reduces the code little bit.It may not much influential in small codes whereas coming to long codes it's use can't be ignored."
},
{
"code": null,
"e": 1237,
"s": 1226,
"text": " Live Demo"
},
{
"code": null,
"e": 1414,
"s": 1237,
"text": "<html>\n<body>\n<script>\n var tot = 0;\n var a = [1,45,78,9,78,40];\n for(var i = 0; i<a.length;i++){\n tot += a[i]\n }\n document.write(tot);\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 1418,
"s": 1414,
"text": "251"
}
]
|
Upload file with php to another php server | The fopen, fread and fwrite functions can be used to open a file stream, read a data stream and write that data to a file respectively.
The file resource doesn't necessarily need to point to a location on the local machine itself.
Below is an example that transfers a file from the local server to ftp server −
$file = "file_name.jpg";
$destination = fopen("ftp://username:[email protected]/" . $file, "wb");
$source = file_get_contents($file);
fwrite($destination, $source, strlen($source));
fclose($destination);
The image needs to be transferred to an FTP server. Hence the server is opened in write mode, and the image is written to that location and the stream is closed.
The curl extension uses Client URL Library (libcurl) to transfer files from one location to the other. The logic of implementing a curl solution follows the below logic −
Initialize a session first.
The desired transfer options can be set.
The transfer can be performed.
The session can be closed.
The curl session can be initialized using the 'curl_init' function. It returns a resource that could be used with other curl functions.
The destination to upload the file and other factors associated with the transfer session can be set using the 'curl_setopt'.
This takes the curl resource, that is a predefined constant which represents the setting and the optional value.
Below is an example demonstrating the same −
$session_begin = curl_init();
curl_setopt($session_begin, CURLOPT_POST, true);
curl_setopt($session_begin, CURLOPT_POSTFIELDS, array('file' => 'path/to/file.txt'));
curl_setopt($session_begin, CURLOPT_URL, 'http://server2/upload.php');
curl_exec($session_begin);
curl_close($session_begin);
The second server can be handled as a regular file upload. | [
{
"code": null,
"e": 1198,
"s": 1062,
"text": "The fopen, fread and fwrite functions can be used to open a file stream, read a data stream and write that data to a file respectively."
},
{
"code": null,
"e": 1293,
"s": 1198,
"text": "The file resource doesn't necessarily need to point to a location on the local machine itself."
},
{
"code": null,
"e": 1373,
"s": 1293,
"text": "Below is an example that transfers a file from the local server to ftp server −"
},
{
"code": null,
"e": 1580,
"s": 1373,
"text": "$file = \"file_name.jpg\";\n$destination = fopen(\"ftp://username:[email protected]/\" . $file, \"wb\");\n$source = file_get_contents($file);\nfwrite($destination, $source, strlen($source));\nfclose($destination);"
},
{
"code": null,
"e": 1742,
"s": 1580,
"text": "The image needs to be transferred to an FTP server. Hence the server is opened in write mode, and the image is written to that location and the stream is closed."
},
{
"code": null,
"e": 1913,
"s": 1742,
"text": "The curl extension uses Client URL Library (libcurl) to transfer files from one location to the other. The logic of implementing a curl solution follows the below logic −"
},
{
"code": null,
"e": 1941,
"s": 1913,
"text": "Initialize a session first."
},
{
"code": null,
"e": 1982,
"s": 1941,
"text": "The desired transfer options can be set."
},
{
"code": null,
"e": 2013,
"s": 1982,
"text": "The transfer can be performed."
},
{
"code": null,
"e": 2040,
"s": 2013,
"text": "The session can be closed."
},
{
"code": null,
"e": 2176,
"s": 2040,
"text": "The curl session can be initialized using the 'curl_init' function. It returns a resource that could be used with other curl functions."
},
{
"code": null,
"e": 2302,
"s": 2176,
"text": "The destination to upload the file and other factors associated with the transfer session can be set using the 'curl_setopt'."
},
{
"code": null,
"e": 2415,
"s": 2302,
"text": "This takes the curl resource, that is a predefined constant which represents the setting and the optional value."
},
{
"code": null,
"e": 2460,
"s": 2415,
"text": "Below is an example demonstrating the same −"
},
{
"code": null,
"e": 2751,
"s": 2460,
"text": "$session_begin = curl_init();\ncurl_setopt($session_begin, CURLOPT_POST, true);\ncurl_setopt($session_begin, CURLOPT_POSTFIELDS, array('file' => 'path/to/file.txt'));\ncurl_setopt($session_begin, CURLOPT_URL, 'http://server2/upload.php');\ncurl_exec($session_begin);\ncurl_close($session_begin);"
},
{
"code": null,
"e": 2810,
"s": 2751,
"text": "The second server can be handled as a regular file upload."
}
]
|
Complete Architectural Details of all EfficientNet Models | by Vardan Agarwal | Towards Data Science | I was scrolling through notebooks in a Kaggle competition and found almost everyone was using EfficientNet as their backbone which I had not heard about till then. It is introduced by Google AI in this paper and they tried to propose a method that is more efficient as suggested by its name while improving the state of the art results. Generally, the models are made too wide, deep, or with a very high resolution. Increasing these characteristics helps the model initially but it quickly saturates and the model made just has more parameters and is therefore not efficient. In EfficientNet they are scaled in a more principled way i.e. gradually everything is increased.
Did not understand what going on? Don’t worry you will once you see the architecture. But first, let’s see the results they got with this.
With considerably fewer numbers of parameters, the family of models are efficient and also provide better results. So now we have seen why these might become the standard pre-trained model but something’s missing. I remember an article by Raimi Karim where he showed the architectures of pre-trained models and that helped me a lot in understanding them and creating similar architectures.
towardsdatascience.com
As I could not find one like this on the net, I decided to understand it and create one for all of you.
The first thing is any network is its stem after which all the experimenting with the architecture starts which is common in all the eight models and the final layers.
After this each of them contains 7 blocks. These blocks further have a varying number of sub-blocks whose number is increased as we move from EfficientNetB0 to EfficientNetB7. To have a look at the layers of the models in Colab write this code:
!pip install tf-nightly-gpuimport tensorflow as tfIMG_SHAPE = (224, 224, 3)model0 = tf.keras.applications.EfficientNetB0(input_shape=IMG_SHAPE, include_top=False, weights="imagenet")tf.keras.utils.plot_model(model0) # to draw and visualizemodel0.summary() # to see the list of layers and parameters
If you count the total number of layers in EfficientNet-B0 the total is 237 and in EfficientNet-B7 the total comes out to 813!! But don’t worry all these layers can be made from 5 modules shown below and the stem above.
Module 1 — This is used as a starting point for the sub-blocks.
Module 2 — This is used as a starting point for the first sub-block of all the 7 main blocks except the 1st one.
Module 3 — This is connected as a skip connection to all the sub-blocks.
Module 4 — This is used for combining the skip connection in the first sub-blocks.
Module 5 — Each sub-block is connected to its previous sub-block in a skip connection and they are combined using this module.
These modules are further combined to form sub-blocks which will be used in a certain way in the blocks.
Sub-block 1 — This is used only used as the first sub-block in the first block.
Sub-block 2 — This is used as the first sub-block in all the other blocks.
Sub-block 3 — This is used for any sub-block except the first one in all the blocks.
Till now we have specified everything that will be combined to create the EfficientNet models so let’s get started.
Its architecture is the same as the above model the only difference between them is that the number of feature maps (channels) is varied that increases the number of parameters.
It’s easy to see the difference among all the models and they gradually increased the number of sub-blocks. If you understood the architectures I will encourage you to take any model and print its summary and have a go through it to know it more thoroughly. The table shown below denotes the kernel size for convolution operations along with the resolution, channels, and layers in EfficientNet-B0.
This table was included in the original paper. The resolution remains the same as for the whole family. I don’t know about whether the kernel size changes or remains the same so if anyone knows leave a reply. The number of layers is already shown above in the figures. The number of channels varies and it is calculated from the information seen from each model’s summary and is presented below (If you are using Mobile device then you will need to view it in landscape mode.)
╔═══════╦══════╦══════╦══════╦══════╦══════╦══════╦══════╗║ Stage ║ B1 ║ B2 ║ B3 ║ B4 ║ B5 ║ B6 ║ B7 ║╠═══════╬══════╬══════╬══════╬══════╬══════╬══════╬══════╣║ 1 ║ 32 ║ 32 ║ 40 ║ 48 ║ 48 ║ 56 ║ 64 ║║ 2 ║ 16 ║ 16 ║ 24 ║ 24 ║ 24 ║ 32 ║ 32 ║║ 3 ║ 24 ║ 24 ║ 32 ║ 32 ║ 40 ║ 40 ║ 48 ║║ 4 ║ 40 ║ 48 ║ 48 ║ 56 ║ 64 ║ 72 ║ 80 ║║ 5 ║ 80 ║ 88 ║ 96 ║ 112 ║ 128 ║ 144 ║ 160 ║║ 6 ║ 112 ║ 120 ║ 136 ║ 160 ║ 176 ║ 200 ║ 224 ║║ 7 ║ 192 ║ 208 ║ 232 ║ 272 ║ 304 ║ 344 ║ 384 ║║ 8 ║ 320 ║ 352 ║ 384 ║ 448 ║ 512 ║ 576 ║ 640 ║║ 9 ║ 1280 ║ 1408 ║ 1536 ║ 1792 ║ 2048 ║ 2304 ║ 2560 ║╚═══════╩══════╩══════╩══════╩══════╩══════╩══════╩══════╝
Medium does not has any format to make tables, so if you want to create tables like the one above you create ASCII tables from this site.
Before ending I have attached another image again from its research paper which shows its performance against the other state of the art techniques and also reduces the number of parameters and the number of FLOPS required.
If you want to create advanced CNN architectures like this or had problems understanding any of the layers or terms used don’t worry, I have written an article that will solve these problems.
towardsdatascience.com
Do you want to see how EfficientNet stacks up against models on a Kaggle challenge you can check this article. | [
{
"code": null,
"e": 845,
"s": 172,
"text": "I was scrolling through notebooks in a Kaggle competition and found almost everyone was using EfficientNet as their backbone which I had not heard about till then. It is introduced by Google AI in this paper and they tried to propose a method that is more efficient as suggested by its name while improving the state of the art results. Generally, the models are made too wide, deep, or with a very high resolution. Increasing these characteristics helps the model initially but it quickly saturates and the model made just has more parameters and is therefore not efficient. In EfficientNet they are scaled in a more principled way i.e. gradually everything is increased."
},
{
"code": null,
"e": 984,
"s": 845,
"text": "Did not understand what going on? Don’t worry you will once you see the architecture. But first, let’s see the results they got with this."
},
{
"code": null,
"e": 1374,
"s": 984,
"text": "With considerably fewer numbers of parameters, the family of models are efficient and also provide better results. So now we have seen why these might become the standard pre-trained model but something’s missing. I remember an article by Raimi Karim where he showed the architectures of pre-trained models and that helped me a lot in understanding them and creating similar architectures."
},
{
"code": null,
"e": 1397,
"s": 1374,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1501,
"s": 1397,
"text": "As I could not find one like this on the net, I decided to understand it and create one for all of you."
},
{
"code": null,
"e": 1669,
"s": 1501,
"text": "The first thing is any network is its stem after which all the experimenting with the architecture starts which is common in all the eight models and the final layers."
},
{
"code": null,
"e": 1914,
"s": 1669,
"text": "After this each of them contains 7 blocks. These blocks further have a varying number of sub-blocks whose number is increased as we move from EfficientNetB0 to EfficientNetB7. To have a look at the layers of the models in Colab write this code:"
},
{
"code": null,
"e": 2213,
"s": 1914,
"text": "!pip install tf-nightly-gpuimport tensorflow as tfIMG_SHAPE = (224, 224, 3)model0 = tf.keras.applications.EfficientNetB0(input_shape=IMG_SHAPE, include_top=False, weights=\"imagenet\")tf.keras.utils.plot_model(model0) # to draw and visualizemodel0.summary() # to see the list of layers and parameters"
},
{
"code": null,
"e": 2433,
"s": 2213,
"text": "If you count the total number of layers in EfficientNet-B0 the total is 237 and in EfficientNet-B7 the total comes out to 813!! But don’t worry all these layers can be made from 5 modules shown below and the stem above."
},
{
"code": null,
"e": 2497,
"s": 2433,
"text": "Module 1 — This is used as a starting point for the sub-blocks."
},
{
"code": null,
"e": 2610,
"s": 2497,
"text": "Module 2 — This is used as a starting point for the first sub-block of all the 7 main blocks except the 1st one."
},
{
"code": null,
"e": 2683,
"s": 2610,
"text": "Module 3 — This is connected as a skip connection to all the sub-blocks."
},
{
"code": null,
"e": 2766,
"s": 2683,
"text": "Module 4 — This is used for combining the skip connection in the first sub-blocks."
},
{
"code": null,
"e": 2893,
"s": 2766,
"text": "Module 5 — Each sub-block is connected to its previous sub-block in a skip connection and they are combined using this module."
},
{
"code": null,
"e": 2998,
"s": 2893,
"text": "These modules are further combined to form sub-blocks which will be used in a certain way in the blocks."
},
{
"code": null,
"e": 3078,
"s": 2998,
"text": "Sub-block 1 — This is used only used as the first sub-block in the first block."
},
{
"code": null,
"e": 3153,
"s": 3078,
"text": "Sub-block 2 — This is used as the first sub-block in all the other blocks."
},
{
"code": null,
"e": 3238,
"s": 3153,
"text": "Sub-block 3 — This is used for any sub-block except the first one in all the blocks."
},
{
"code": null,
"e": 3354,
"s": 3238,
"text": "Till now we have specified everything that will be combined to create the EfficientNet models so let’s get started."
},
{
"code": null,
"e": 3532,
"s": 3354,
"text": "Its architecture is the same as the above model the only difference between them is that the number of feature maps (channels) is varied that increases the number of parameters."
},
{
"code": null,
"e": 3931,
"s": 3532,
"text": "It’s easy to see the difference among all the models and they gradually increased the number of sub-blocks. If you understood the architectures I will encourage you to take any model and print its summary and have a go through it to know it more thoroughly. The table shown below denotes the kernel size for convolution operations along with the resolution, channels, and layers in EfficientNet-B0."
},
{
"code": null,
"e": 4408,
"s": 3931,
"text": "This table was included in the original paper. The resolution remains the same as for the whole family. I don’t know about whether the kernel size changes or remains the same so if anyone knows leave a reply. The number of layers is already shown above in the figures. The number of channels varies and it is calculated from the information seen from each model’s summary and is presented below (If you are using Mobile device then you will need to view it in landscape mode.)"
},
{
"code": null,
"e": 5163,
"s": 4408,
"text": "╔═══════╦══════╦══════╦══════╦══════╦══════╦══════╦══════╗║ Stage ║ B1 ║ B2 ║ B3 ║ B4 ║ B5 ║ B6 ║ B7 ║╠═══════╬══════╬══════╬══════╬══════╬══════╬══════╬══════╣║ 1 ║ 32 ║ 32 ║ 40 ║ 48 ║ 48 ║ 56 ║ 64 ║║ 2 ║ 16 ║ 16 ║ 24 ║ 24 ║ 24 ║ 32 ║ 32 ║║ 3 ║ 24 ║ 24 ║ 32 ║ 32 ║ 40 ║ 40 ║ 48 ║║ 4 ║ 40 ║ 48 ║ 48 ║ 56 ║ 64 ║ 72 ║ 80 ║║ 5 ║ 80 ║ 88 ║ 96 ║ 112 ║ 128 ║ 144 ║ 160 ║║ 6 ║ 112 ║ 120 ║ 136 ║ 160 ║ 176 ║ 200 ║ 224 ║║ 7 ║ 192 ║ 208 ║ 232 ║ 272 ║ 304 ║ 344 ║ 384 ║║ 8 ║ 320 ║ 352 ║ 384 ║ 448 ║ 512 ║ 576 ║ 640 ║║ 9 ║ 1280 ║ 1408 ║ 1536 ║ 1792 ║ 2048 ║ 2304 ║ 2560 ║╚═══════╩══════╩══════╩══════╩══════╩══════╩══════╩══════╝"
},
{
"code": null,
"e": 5301,
"s": 5163,
"text": "Medium does not has any format to make tables, so if you want to create tables like the one above you create ASCII tables from this site."
},
{
"code": null,
"e": 5525,
"s": 5301,
"text": "Before ending I have attached another image again from its research paper which shows its performance against the other state of the art techniques and also reduces the number of parameters and the number of FLOPS required."
},
{
"code": null,
"e": 5717,
"s": 5525,
"text": "If you want to create advanced CNN architectures like this or had problems understanding any of the layers or terms used don’t worry, I have written an article that will solve these problems."
},
{
"code": null,
"e": 5740,
"s": 5717,
"text": "towardsdatascience.com"
}
]
|
Comparison of Exception Handling in C++ and Java - GeeksforGeeks | 08 Dec, 2021
Both languages use to try, catch and throw keywords for exception handling, and their meaning is also the same in both languages.
Following are the differences between Java and C++ exception handling:
Java
C++
The above points have been discussed in detail below:
1) In C++, all types (including primitive and pointer) can be thrown as exceptions. But in Java, only throwable objects (Throwable objects are instances of any subclass of the Throwable class) can be thrown as exceptions. For example, the following type of code works in C++, but similar code doesn’t work in Java.
CPP
// CPP Program to demonstrate all types (including primitive// and pointer) can be thrown as exception.#include <iostream>using namespace std;int main(){ int x = -1; // some other stuff try { // some other stuff if (x < 0) { throw x; } } catch (int x) { cout << "Exception occurred: thrown value is " << x << endl; } getchar(); return 0;}
Exception occurred: thrown value is -1
2) In C++, there is a special catch called “catch all” that can catch all kinds of exceptions.
CPP
// CPP Program to demonstrate catch all#include <iostream>using namespace std;int main(){ int x = -1; char* ptr; ptr = new char[256]; try { if (x < 0) { throw x; } if (ptr == NULL) { throw " ptr is NULL "; } } catch (...) // catch all { cout << "Exception occurred: exiting " << endl; exit(0); } getchar(); return 0;}
Exception occurred: exiting
In Java, for all practical purposes, we can catch Exception objects to catch all kinds of exceptions. Because normally we do not catch Throwable(s) other than Exception(s) (which are Errors)
catch(Exception e){
.......
}
3) In Java, there is a block called finally that is always executed after the try-catch block. This block can be used to do cleanup work. There is no such block in C++.
Java
// Java Program to demonstrate creating an exception typeclass Test extends Exception {} class Main { public static void main(String args[]) { try { throw new Test(); } catch (Test t) { System.out.println("Got the Test Exception"); } finally { System.out.println("Inside finally block "); } }}
Got the Test Exception
Inside finally block
4) In C++, all exceptions are unchecked. In Java, there are two types of exceptions – checked and unchecked. See this for more details on checked vs Unchecked exceptions.
5) In Java, a new keyword throws is used to list exceptions that can be thrown by a function. In C++, there is no throws keyword, the same keyword throw is used for this purpose also.
6) In C++ if the exception isn’t caught then the exception handling subsystem calls the function unexpected(), which terminates the program or an application abnormally. If any exception arises in our C++ program then finding that particular exception is very time-consuming because in C++ unexpected() did not tell us that which type and on which line the exception has occurred. For more details on unexpected() refer to this.
But in Java, if the system-generated exception isn’t caught then the java runtime system(JVM) handover the exception object to the default exception handler, which basically prints the name, description, and on which line the exception has occurred. So, in Java finding and handling the exception is easier than in the C++ language.
For more details on the default exception handler refer to this.
aanuj0110
rohitsharmaofficial42019
anshikajain26
cpp-exception
Java-Exceptions
C++
Difference Between
Java
Java
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inheritance in C++
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
Bitwise Operators in C/C++
Virtual Function in C++
Difference between BFS and DFS
Class method vs Static method in Python
Differences between TCP and UDP
Difference between var, let and const keywords in JavaScript
Differences between IPv4 and IPv6 | [
{
"code": null,
"e": 25483,
"s": 25455,
"text": "\n08 Dec, 2021"
},
{
"code": null,
"e": 25614,
"s": 25483,
"text": "Both languages use to try, catch and throw keywords for exception handling, and their meaning is also the same in both languages. "
},
{
"code": null,
"e": 25685,
"s": 25614,
"text": "Following are the differences between Java and C++ exception handling:"
},
{
"code": null,
"e": 25690,
"s": 25685,
"text": "Java"
},
{
"code": null,
"e": 25694,
"s": 25690,
"text": "C++"
},
{
"code": null,
"e": 25748,
"s": 25694,
"text": "The above points have been discussed in detail below:"
},
{
"code": null,
"e": 26063,
"s": 25748,
"text": "1) In C++, all types (including primitive and pointer) can be thrown as exceptions. But in Java, only throwable objects (Throwable objects are instances of any subclass of the Throwable class) can be thrown as exceptions. For example, the following type of code works in C++, but similar code doesn’t work in Java."
},
{
"code": null,
"e": 26067,
"s": 26063,
"text": "CPP"
},
{
"code": "// CPP Program to demonstrate all types (including primitive// and pointer) can be thrown as exception.#include <iostream>using namespace std;int main(){ int x = -1; // some other stuff try { // some other stuff if (x < 0) { throw x; } } catch (int x) { cout << \"Exception occurred: thrown value is \" << x << endl; } getchar(); return 0;}",
"e": 26483,
"s": 26067,
"text": null
},
{
"code": null,
"e": 26522,
"s": 26483,
"text": "Exception occurred: thrown value is -1"
},
{
"code": null,
"e": 26619,
"s": 26522,
"text": "2) In C++, there is a special catch called “catch all” that can catch all kinds of exceptions. "
},
{
"code": null,
"e": 26623,
"s": 26619,
"text": "CPP"
},
{
"code": "// CPP Program to demonstrate catch all#include <iostream>using namespace std;int main(){ int x = -1; char* ptr; ptr = new char[256]; try { if (x < 0) { throw x; } if (ptr == NULL) { throw \" ptr is NULL \"; } } catch (...) // catch all { cout << \"Exception occurred: exiting \" << endl; exit(0); } getchar(); return 0;}",
"e": 27043,
"s": 26623,
"text": null
},
{
"code": null,
"e": 27072,
"s": 27043,
"text": "Exception occurred: exiting "
},
{
"code": null,
"e": 27264,
"s": 27072,
"text": "In Java, for all practical purposes, we can catch Exception objects to catch all kinds of exceptions. Because normally we do not catch Throwable(s) other than Exception(s) (which are Errors) "
},
{
"code": null,
"e": 27295,
"s": 27264,
"text": "catch(Exception e){\n .......\n}"
},
{
"code": null,
"e": 27465,
"s": 27295,
"text": "3) In Java, there is a block called finally that is always executed after the try-catch block. This block can be used to do cleanup work. There is no such block in C++. "
},
{
"code": null,
"e": 27470,
"s": 27465,
"text": "Java"
},
{
"code": "// Java Program to demonstrate creating an exception typeclass Test extends Exception {} class Main { public static void main(String args[]) { try { throw new Test(); } catch (Test t) { System.out.println(\"Got the Test Exception\"); } finally { System.out.println(\"Inside finally block \"); } }}",
"e": 27851,
"s": 27470,
"text": null
},
{
"code": null,
"e": 27896,
"s": 27851,
"text": "Got the Test Exception\nInside finally block "
},
{
"code": null,
"e": 28067,
"s": 27896,
"text": "4) In C++, all exceptions are unchecked. In Java, there are two types of exceptions – checked and unchecked. See this for more details on checked vs Unchecked exceptions."
},
{
"code": null,
"e": 28251,
"s": 28067,
"text": "5) In Java, a new keyword throws is used to list exceptions that can be thrown by a function. In C++, there is no throws keyword, the same keyword throw is used for this purpose also."
},
{
"code": null,
"e": 28680,
"s": 28251,
"text": "6) In C++ if the exception isn’t caught then the exception handling subsystem calls the function unexpected(), which terminates the program or an application abnormally. If any exception arises in our C++ program then finding that particular exception is very time-consuming because in C++ unexpected() did not tell us that which type and on which line the exception has occurred. For more details on unexpected() refer to this."
},
{
"code": null,
"e": 29014,
"s": 28680,
"text": "But in Java, if the system-generated exception isn’t caught then the java runtime system(JVM) handover the exception object to the default exception handler, which basically prints the name, description, and on which line the exception has occurred. So, in Java finding and handling the exception is easier than in the C++ language. "
},
{
"code": null,
"e": 29079,
"s": 29014,
"text": "For more details on the default exception handler refer to this."
},
{
"code": null,
"e": 29089,
"s": 29079,
"text": "aanuj0110"
},
{
"code": null,
"e": 29114,
"s": 29089,
"text": "rohitsharmaofficial42019"
},
{
"code": null,
"e": 29128,
"s": 29114,
"text": "anshikajain26"
},
{
"code": null,
"e": 29142,
"s": 29128,
"text": "cpp-exception"
},
{
"code": null,
"e": 29158,
"s": 29142,
"text": "Java-Exceptions"
},
{
"code": null,
"e": 29162,
"s": 29158,
"text": "C++"
},
{
"code": null,
"e": 29181,
"s": 29162,
"text": "Difference Between"
},
{
"code": null,
"e": 29186,
"s": 29181,
"text": "Java"
},
{
"code": null,
"e": 29191,
"s": 29186,
"text": "Java"
},
{
"code": null,
"e": 29195,
"s": 29191,
"text": "CPP"
},
{
"code": null,
"e": 29293,
"s": 29195,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29312,
"s": 29293,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 29355,
"s": 29312,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 29379,
"s": 29355,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 29406,
"s": 29379,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 29430,
"s": 29406,
"text": "Virtual Function in C++"
},
{
"code": null,
"e": 29461,
"s": 29430,
"text": "Difference between BFS and DFS"
},
{
"code": null,
"e": 29501,
"s": 29461,
"text": "Class method vs Static method in Python"
},
{
"code": null,
"e": 29533,
"s": 29501,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 29594,
"s": 29533,
"text": "Difference between var, let and const keywords in JavaScript"
}
]
|
Interface 8255 with 8085 microprocessor for addition - GeeksforGeeks | 07 Apr, 2022
Problem – Interface 8255 with 8085 microprocessor and write an assembly program that determines the addition of contents of port A and port B and stores the result in port C.
Example –
Algorithm –
Construct the control word registerInput the data from port A and port BAdd the contents of port A and port BDisplay the result in port C
Construct the control word register
Input the data from port A and port B
Add the contents of port A and port B
Display the result in port C
Program –
Explanation –
MVI A, 92H means that the value of the control register is 92.
D7=1 as it is in I/O mode.
D6=0 & D5=0 as Poet A is in m0 mode.
D4=1 as Port A is taking input.
D3=0 & D0=0 as Port C is not taking part.
D2=0 as mode of Port B is m0.
D1=1as Port B is taking the input.
OUT 83H putting the value of A in 83H which is the port number of the port control register.
IN 80H taking input from 80H which is the port number of port A.
MOV B, A copies the content of A register to B register.
IN 81H takes input from 81H which is the port number of port B.
ADD B add the contents of A register and B register.
OUT 82H displays the result in 81H which is the port number of port C.
RET return
nidhi_biet
roozbehsayadi
avtarkumar719
xineyir106
microprocessor
system-programming
Computer Organization & Architecture
microprocessor
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Logical and Physical Address in Operating System
Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)
Memory Hierarchy Design and its Characteristics
Computer Organization | RISC and CISC
Direct Access Media (DMA) Controller in Computer Architecture
Computer Organization | Instruction Formats (Zero, One, Two and Three Address Instruction)
Interrupts
I/O Interface (Interrupt and DMA Mode)
Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard)
Addressing modes in 8085 microprocessor | [
{
"code": null,
"e": 26521,
"s": 26493,
"text": "\n07 Apr, 2022"
},
{
"code": null,
"e": 26697,
"s": 26521,
"text": "Problem – Interface 8255 with 8085 microprocessor and write an assembly program that determines the addition of contents of port A and port B and stores the result in port C. "
},
{
"code": null,
"e": 26709,
"s": 26697,
"text": "Example – "
},
{
"code": null,
"e": 26722,
"s": 26709,
"text": "Algorithm – "
},
{
"code": null,
"e": 26860,
"s": 26722,
"text": "Construct the control word registerInput the data from port A and port BAdd the contents of port A and port BDisplay the result in port C"
},
{
"code": null,
"e": 26896,
"s": 26860,
"text": "Construct the control word register"
},
{
"code": null,
"e": 26934,
"s": 26896,
"text": "Input the data from port A and port B"
},
{
"code": null,
"e": 26972,
"s": 26934,
"text": "Add the contents of port A and port B"
},
{
"code": null,
"e": 27001,
"s": 26972,
"text": "Display the result in port C"
},
{
"code": null,
"e": 27013,
"s": 27001,
"text": "Program – "
},
{
"code": null,
"e": 27029,
"s": 27013,
"text": "Explanation – "
},
{
"code": null,
"e": 27093,
"s": 27029,
"text": "MVI A, 92H means that the value of the control register is 92. "
},
{
"code": null,
"e": 27296,
"s": 27093,
"text": "D7=1 as it is in I/O mode.\nD6=0 & D5=0 as Poet A is in m0 mode.\nD4=1 as Port A is taking input.\nD3=0 & D0=0 as Port C is not taking part.\nD2=0 as mode of Port B is m0.\nD1=1as Port B is taking the input."
},
{
"code": null,
"e": 27389,
"s": 27296,
"text": "OUT 83H putting the value of A in 83H which is the port number of the port control register."
},
{
"code": null,
"e": 27454,
"s": 27389,
"text": "IN 80H taking input from 80H which is the port number of port A."
},
{
"code": null,
"e": 27511,
"s": 27454,
"text": "MOV B, A copies the content of A register to B register."
},
{
"code": null,
"e": 27575,
"s": 27511,
"text": "IN 81H takes input from 81H which is the port number of port B."
},
{
"code": null,
"e": 27628,
"s": 27575,
"text": "ADD B add the contents of A register and B register."
},
{
"code": null,
"e": 27699,
"s": 27628,
"text": "OUT 82H displays the result in 81H which is the port number of port C."
},
{
"code": null,
"e": 27710,
"s": 27699,
"text": "RET return"
},
{
"code": null,
"e": 27723,
"s": 27712,
"text": "nidhi_biet"
},
{
"code": null,
"e": 27737,
"s": 27723,
"text": "roozbehsayadi"
},
{
"code": null,
"e": 27751,
"s": 27737,
"text": "avtarkumar719"
},
{
"code": null,
"e": 27762,
"s": 27751,
"text": "xineyir106"
},
{
"code": null,
"e": 27777,
"s": 27762,
"text": "microprocessor"
},
{
"code": null,
"e": 27796,
"s": 27777,
"text": "system-programming"
},
{
"code": null,
"e": 27833,
"s": 27796,
"text": "Computer Organization & Architecture"
},
{
"code": null,
"e": 27848,
"s": 27833,
"text": "microprocessor"
},
{
"code": null,
"e": 27946,
"s": 27848,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27995,
"s": 27946,
"text": "Logical and Physical Address in Operating System"
},
{
"code": null,
"e": 28090,
"s": 27995,
"text": "Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)"
},
{
"code": null,
"e": 28138,
"s": 28090,
"text": "Memory Hierarchy Design and its Characteristics"
},
{
"code": null,
"e": 28176,
"s": 28138,
"text": "Computer Organization | RISC and CISC"
},
{
"code": null,
"e": 28238,
"s": 28176,
"text": "Direct Access Media (DMA) Controller in Computer Architecture"
},
{
"code": null,
"e": 28329,
"s": 28238,
"text": "Computer Organization | Instruction Formats (Zero, One, Two and Three Address Instruction)"
},
{
"code": null,
"e": 28340,
"s": 28329,
"text": "Interrupts"
},
{
"code": null,
"e": 28379,
"s": 28340,
"text": "I/O Interface (Interrupt and DMA Mode)"
},
{
"code": null,
"e": 28470,
"s": 28379,
"text": "Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard)"
}
]
|
Working with Image Pixels in OpenCV | by Samuel Ozechi | Towards Data Science | Pixels are important attributes of images in computer vision. They are numerical values that represent the color intensity of light in a particular space in an image and are the smallest units of data in an image.
The total number of pixels in an image is obtained as the product of its height, width and channels.
Since Images in OpenCV are read as Numpy arrays of pixel values, it is then possible to get and process regions of an image as represented by the pixels of that region using array slicing operations.
Slicing operations are used to retrieve subset of sequences such as lists, tuples and arrays and as such can be used to get the pixel values of regions of an image for processing such as editing, formatting or cropping.
Slicing operations
Script : Use slicing operation to get subset of a list.
Notice that I used index values to slice the list of letters. For example, passing a start index of 1 (index for the second letter in the list ) and 4 returns a slice of the list, from the second to fourth values.
As index values are used to retrieve subset of interest in this way, so are they also used to target and retrieve regions of interest in images.
The slice to target a region in an image is defined by the start and end values of both axes (horizontal (X) and vertical(Y)) of the image in the format :
image[startY: endY, startx:endX]
Which returns a Numpy array (of the image pixels) for the desired region of interest.
How then do we determine the start and end values of the X and Y axes for our region of interest?
These values (startX, endX, startY, endY) are coordinate values that maps out the region of interest. These values are not displayed alongside the image when displayed with OpenCV, but we can use other applications (such as Photoshop, Corel Draw, Paint e.t.c) or other python visualization libraries (such as Matplotlib) to display images with their X and Y coordinates values.
As always, this is better understood in practice. Let’s display an image using matplotlib.pyplot from which we can retrieve the coordinates that maps out a targeted region of interest in the image.
I demonstrate this with an image of the National flag of The Republic of Ghana. Here, I target the region that surrounds the black star in the image.
Getting the coordinate values for the region of interest.
Load and display the image using Matplotlib.
Load and display the image using Matplotlib.
As you can see, The plt.imshow function returns the read image along with coordinates values for the x and y axes.
We can then retrieve the values of the start and end coordinates for our region of interest (the black star). Below is a plot of how to trace out the values of the star region.
The image shows how to trace out the coordinates that targets the region around the black star.
From the image we can retrieve the coordinates (startY(y1), endY(y2), startX(x1), endX(x2)). We can then define our start and end coordinates for both axes and crop out the star as:
image[y1: y2, x1:x2]
if we get y1, y2 = [145, 295] and x1, x2 = [245, 400]
Then the region that maps out the black star would be:
black_star = image[145:295, 245:400]
This will return the pixel values (in a Numpy array) that maps the region of interest (the black star in this case).
Now we can employ this technique in targeting and slicing regions of our image for a variety of image processes.
I demonstrate common image processing techniques with slice operations using an image of coal miners statue from Enugu, Nigeria.
Cropping Images using slice operations
1. Load and display the original image
2. Get the Spatial Dimensions of the Image
3. Use the Dimensions to Crop the Image
Cropping out the Top Left Corner of the Image
Cropping out the Top Right Corner of the Image
Cropping out the Bottom Left Corner of the Image
Cropping out the Bottom Right Corner of the Image
4. Using Dimensions to set parts of the image to certain colors.
Summary:
Image pixels are numerical values that represent color intensities in images. The procedures of getting and setting image pixels for different image processing with OpenCV are based on slicing operations of Numpy arrays. Slicing the pixel values is useful in cropping, resetting, duplicating or enhancing images. | [
{
"code": null,
"e": 386,
"s": 172,
"text": "Pixels are important attributes of images in computer vision. They are numerical values that represent the color intensity of light in a particular space in an image and are the smallest units of data in an image."
},
{
"code": null,
"e": 487,
"s": 386,
"text": "The total number of pixels in an image is obtained as the product of its height, width and channels."
},
{
"code": null,
"e": 687,
"s": 487,
"text": "Since Images in OpenCV are read as Numpy arrays of pixel values, it is then possible to get and process regions of an image as represented by the pixels of that region using array slicing operations."
},
{
"code": null,
"e": 907,
"s": 687,
"text": "Slicing operations are used to retrieve subset of sequences such as lists, tuples and arrays and as such can be used to get the pixel values of regions of an image for processing such as editing, formatting or cropping."
},
{
"code": null,
"e": 926,
"s": 907,
"text": "Slicing operations"
},
{
"code": null,
"e": 982,
"s": 926,
"text": "Script : Use slicing operation to get subset of a list."
},
{
"code": null,
"e": 1196,
"s": 982,
"text": "Notice that I used index values to slice the list of letters. For example, passing a start index of 1 (index for the second letter in the list ) and 4 returns a slice of the list, from the second to fourth values."
},
{
"code": null,
"e": 1341,
"s": 1196,
"text": "As index values are used to retrieve subset of interest in this way, so are they also used to target and retrieve regions of interest in images."
},
{
"code": null,
"e": 1496,
"s": 1341,
"text": "The slice to target a region in an image is defined by the start and end values of both axes (horizontal (X) and vertical(Y)) of the image in the format :"
},
{
"code": null,
"e": 1529,
"s": 1496,
"text": "image[startY: endY, startx:endX]"
},
{
"code": null,
"e": 1615,
"s": 1529,
"text": "Which returns a Numpy array (of the image pixels) for the desired region of interest."
},
{
"code": null,
"e": 1713,
"s": 1615,
"text": "How then do we determine the start and end values of the X and Y axes for our region of interest?"
},
{
"code": null,
"e": 2091,
"s": 1713,
"text": "These values (startX, endX, startY, endY) are coordinate values that maps out the region of interest. These values are not displayed alongside the image when displayed with OpenCV, but we can use other applications (such as Photoshop, Corel Draw, Paint e.t.c) or other python visualization libraries (such as Matplotlib) to display images with their X and Y coordinates values."
},
{
"code": null,
"e": 2289,
"s": 2091,
"text": "As always, this is better understood in practice. Let’s display an image using matplotlib.pyplot from which we can retrieve the coordinates that maps out a targeted region of interest in the image."
},
{
"code": null,
"e": 2439,
"s": 2289,
"text": "I demonstrate this with an image of the National flag of The Republic of Ghana. Here, I target the region that surrounds the black star in the image."
},
{
"code": null,
"e": 2497,
"s": 2439,
"text": "Getting the coordinate values for the region of interest."
},
{
"code": null,
"e": 2542,
"s": 2497,
"text": "Load and display the image using Matplotlib."
},
{
"code": null,
"e": 2587,
"s": 2542,
"text": "Load and display the image using Matplotlib."
},
{
"code": null,
"e": 2702,
"s": 2587,
"text": "As you can see, The plt.imshow function returns the read image along with coordinates values for the x and y axes."
},
{
"code": null,
"e": 2879,
"s": 2702,
"text": "We can then retrieve the values of the start and end coordinates for our region of interest (the black star). Below is a plot of how to trace out the values of the star region."
},
{
"code": null,
"e": 2975,
"s": 2879,
"text": "The image shows how to trace out the coordinates that targets the region around the black star."
},
{
"code": null,
"e": 3157,
"s": 2975,
"text": "From the image we can retrieve the coordinates (startY(y1), endY(y2), startX(x1), endX(x2)). We can then define our start and end coordinates for both axes and crop out the star as:"
},
{
"code": null,
"e": 3178,
"s": 3157,
"text": "image[y1: y2, x1:x2]"
},
{
"code": null,
"e": 3232,
"s": 3178,
"text": "if we get y1, y2 = [145, 295] and x1, x2 = [245, 400]"
},
{
"code": null,
"e": 3287,
"s": 3232,
"text": "Then the region that maps out the black star would be:"
},
{
"code": null,
"e": 3324,
"s": 3287,
"text": "black_star = image[145:295, 245:400]"
},
{
"code": null,
"e": 3441,
"s": 3324,
"text": "This will return the pixel values (in a Numpy array) that maps the region of interest (the black star in this case)."
},
{
"code": null,
"e": 3554,
"s": 3441,
"text": "Now we can employ this technique in targeting and slicing regions of our image for a variety of image processes."
},
{
"code": null,
"e": 3683,
"s": 3554,
"text": "I demonstrate common image processing techniques with slice operations using an image of coal miners statue from Enugu, Nigeria."
},
{
"code": null,
"e": 3722,
"s": 3683,
"text": "Cropping Images using slice operations"
},
{
"code": null,
"e": 3761,
"s": 3722,
"text": "1. Load and display the original image"
},
{
"code": null,
"e": 3804,
"s": 3761,
"text": "2. Get the Spatial Dimensions of the Image"
},
{
"code": null,
"e": 3844,
"s": 3804,
"text": "3. Use the Dimensions to Crop the Image"
},
{
"code": null,
"e": 3890,
"s": 3844,
"text": "Cropping out the Top Left Corner of the Image"
},
{
"code": null,
"e": 3937,
"s": 3890,
"text": "Cropping out the Top Right Corner of the Image"
},
{
"code": null,
"e": 3986,
"s": 3937,
"text": "Cropping out the Bottom Left Corner of the Image"
},
{
"code": null,
"e": 4036,
"s": 3986,
"text": "Cropping out the Bottom Right Corner of the Image"
},
{
"code": null,
"e": 4101,
"s": 4036,
"text": "4. Using Dimensions to set parts of the image to certain colors."
},
{
"code": null,
"e": 4110,
"s": 4101,
"text": "Summary:"
}
]
|
JDBC - Insert Records Example | This chapter provides an example on how to insert records in a table using JDBC application. Before executing following example, make sure you have the following in place −
To execute the following example you can replace the username and password with your actual user name and password.
To execute the following example you can replace the username and password with your actual user name and password.
Your MySQL or whatever database you are using is up and running.
Your MySQL or whatever database you are using is up and running.
The following steps are required to create a new Database using JDBC application −
Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice.
Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice.
Register the JDBC driver − Requires that you initialize a driver so you can open a communications channel with the database.
Register the JDBC driver − Requires that you initialize a driver so you can open a communications channel with the database.
Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server.
Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server.
Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to insert records into a table.
Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to insert records into a table.
Clean up the environment try with resources automatically closes the resources.
Clean up the environment try with resources automatically closes the resources.
Copy and paste the following example in JDBCExample.java, compile and run as follows −
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCExample {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
public static void main(String[] args) {
// Open a connection
try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement();
) {
// Execute a query
System.out.println("Inserting records into the table...");
String sql = "INSERT INTO Registration VALUES (100, 'Zara', 'Ali', 18)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Registration VALUES (101, 'Mahnaz', 'Fatma', 25)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Registration VALUES (102, 'Zaid', 'Khan', 30)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Registration VALUES(103, 'Sumit', 'Mittal', 28)";
stmt.executeUpdate(sql);
System.out.println("Inserted records into the table...");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Now let us compile the above example as follows −
C:\>javac JDBCExample.java
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
Inserting records into the table...
Inserted records into the table...
C:\>
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2335,
"s": 2162,
"text": "This chapter provides an example on how to insert records in a table using JDBC application. Before executing following example, make sure you have the following in place −"
},
{
"code": null,
"e": 2451,
"s": 2335,
"text": "To execute the following example you can replace the username and password with your actual user name and password."
},
{
"code": null,
"e": 2567,
"s": 2451,
"text": "To execute the following example you can replace the username and password with your actual user name and password."
},
{
"code": null,
"e": 2632,
"s": 2567,
"text": "Your MySQL or whatever database you are using is up and running."
},
{
"code": null,
"e": 2697,
"s": 2632,
"text": "Your MySQL or whatever database you are using is up and running."
},
{
"code": null,
"e": 2780,
"s": 2697,
"text": "The following steps are required to create a new Database using JDBC application −"
},
{
"code": null,
"e": 2952,
"s": 2780,
"text": "Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice."
},
{
"code": null,
"e": 3124,
"s": 2952,
"text": "Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice."
},
{
"code": null,
"e": 3249,
"s": 3124,
"text": "Register the JDBC driver − Requires that you initialize a driver so you can open a communications channel with the database."
},
{
"code": null,
"e": 3374,
"s": 3249,
"text": "Register the JDBC driver − Requires that you initialize a driver so you can open a communications channel with the database."
},
{
"code": null,
"e": 3544,
"s": 3374,
"text": "Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server."
},
{
"code": null,
"e": 3714,
"s": 3544,
"text": "Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server."
},
{
"code": null,
"e": 3852,
"s": 3714,
"text": "Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to insert records into a table."
},
{
"code": null,
"e": 3990,
"s": 3852,
"text": "Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to insert records into a table."
},
{
"code": null,
"e": 4071,
"s": 3990,
"text": "Clean up the environment try with resources automatically closes the resources.\n"
},
{
"code": null,
"e": 4151,
"s": 4071,
"text": "Clean up the environment try with resources automatically closes the resources."
},
{
"code": null,
"e": 4238,
"s": 4151,
"text": "Copy and paste the following example in JDBCExample.java, compile and run as follows −"
},
{
"code": null,
"e": 5462,
"s": 4238,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.SQLException;\nimport java.sql.Statement;\n\npublic class JDBCExample {\n static final String DB_URL = \"jdbc:mysql://localhost/TUTORIALSPOINT\";\n static final String USER = \"guest\";\n static final String PASS = \"guest123\";\n\n public static void main(String[] args) {\n // Open a connection\n try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);\n Statement stmt = conn.createStatement();\n ) {\t\t \n // Execute a query\n System.out.println(\"Inserting records into the table...\"); \n String sql = \"INSERT INTO Registration VALUES (100, 'Zara', 'Ali', 18)\";\n stmt.executeUpdate(sql);\n sql = \"INSERT INTO Registration VALUES (101, 'Mahnaz', 'Fatma', 25)\";\n stmt.executeUpdate(sql);\n sql = \"INSERT INTO Registration VALUES (102, 'Zaid', 'Khan', 30)\";\n stmt.executeUpdate(sql);\n sql = \"INSERT INTO Registration VALUES(103, 'Sumit', 'Mittal', 28)\";\n stmt.executeUpdate(sql);\n System.out.println(\"Inserted records into the table...\"); \t \n } catch (SQLException e) {\n e.printStackTrace();\n } \n }\n}"
},
{
"code": null,
"e": 5512,
"s": 5462,
"text": "Now let us compile the above example as follows −"
},
{
"code": null,
"e": 5544,
"s": 5512,
"text": "C:\\>javac JDBCExample.java\nC:\\>"
},
{
"code": null,
"e": 5605,
"s": 5544,
"text": "When you run JDBCExample, it produces the following result −"
},
{
"code": null,
"e": 5703,
"s": 5605,
"text": "C:\\>java JDBCExample\nInserting records into the table...\nInserted records into the table...\nC:\\>\n"
},
{
"code": null,
"e": 5736,
"s": 5703,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5752,
"s": 5736,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 5785,
"s": 5752,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 5801,
"s": 5785,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 5836,
"s": 5801,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5850,
"s": 5836,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5884,
"s": 5850,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 5898,
"s": 5884,
"text": " Tushar Kale"
},
{
"code": null,
"e": 5935,
"s": 5898,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 5950,
"s": 5935,
"text": " Monica Mittal"
},
{
"code": null,
"e": 5983,
"s": 5950,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 6002,
"s": 5983,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6009,
"s": 6002,
"text": " Print"
},
{
"code": null,
"e": 6020,
"s": 6009,
"text": " Add Notes"
}
]
|
Kali Linux - Aircrack-ng - GeeksforGeeks | 28 Jul, 2020
Aircrack-ng is a tool that comes pre-installed in Kali Linux and is used for wifi network security and hacking. Aircrack is an all in one packet sniffer, WEP and WPA/WPA2 cracker, analyzing tool and a hash capturing tool. It is a tool used for wifi hacking. It helps in capturing the package and reading the hashes out of them and even cracking those hashes by various attacks like dictionary attacks. It supports almost all the latest wireless interfaces. It mainly focuses on 4 areas:
Monitoring: Captures cap, packet, or hash files.
Attacking: Performs deauthentication or creates fake access points
Testing: Checking the wifi cards or driver capabilities
Cracking: Various security standards like WEP or WPA PSK.
1. To list all network interfaces.
airmon-ng
This command will return all the network interfaces available or connected to the system.
2. Stopping the desired network interface.
airmon-ng stop wlan0mon
To stop a network interface enter the above command and replace “wlan0” with the desired network interface.
3. Starting a network interface at a specific channel.
airmon-ng start wlan0 10
To start a network interface at a specific channel enter the above command and replace “wlan0” with the desired network interface and 10 with the desired channel name.
4. Collecting authentication handshake
airodump-ng -c 10 --bssid 00:15:5D:9C:44:00 -w psk wlan0
To collect the authentication handshake enter the above command in terminal and replace “wlan0” with the desired network interface and 10 with the desired channel name and bssid with the bssid of the wifi.
5. Cracking the captured handshake file by means of a wordlist
aircrack-ng -w wordlist psk*.cap
To run a brute force attack and to crack the password enter the above command in the terminal and replace “wordlist” with the desired wordlist to be used and “wpa.cap” with the desired handshake filename.
6. To get the help section of the tool
aircrack-ng --help
The above command will display the help section of the aircrack-ng command.
7. To display the # of CPUs and SIMD support
aircrack-ng -u
The above command will display the details of the hash of CPUs and SIMD support.
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
TCP Server-Client implementation in C
ZIP command in Linux with examples
tar command in Linux with examples
SORT command in Linux/Unix with examples
curl command in Linux with Examples
UDP Server-Client implementation in C
'crontab' in Linux with Examples
Conditional Statements | Shell Script
diff command in Linux with examples
tee command in Linux with examples | [
{
"code": null,
"e": 24570,
"s": 24542,
"text": "\n28 Jul, 2020"
},
{
"code": null,
"e": 25057,
"s": 24570,
"text": "Aircrack-ng is a tool that comes pre-installed in Kali Linux and is used for wifi network security and hacking. Aircrack is an all in one packet sniffer, WEP and WPA/WPA2 cracker, analyzing tool and a hash capturing tool. It is a tool used for wifi hacking. It helps in capturing the package and reading the hashes out of them and even cracking those hashes by various attacks like dictionary attacks. It supports almost all the latest wireless interfaces. It mainly focuses on 4 areas:"
},
{
"code": null,
"e": 25106,
"s": 25057,
"text": "Monitoring: Captures cap, packet, or hash files."
},
{
"code": null,
"e": 25173,
"s": 25106,
"text": "Attacking: Performs deauthentication or creates fake access points"
},
{
"code": null,
"e": 25229,
"s": 25173,
"text": "Testing: Checking the wifi cards or driver capabilities"
},
{
"code": null,
"e": 25287,
"s": 25229,
"text": "Cracking: Various security standards like WEP or WPA PSK."
},
{
"code": null,
"e": 25322,
"s": 25287,
"text": "1. To list all network interfaces."
},
{
"code": null,
"e": 25333,
"s": 25322,
"text": "airmon-ng\n"
},
{
"code": null,
"e": 25423,
"s": 25333,
"text": "This command will return all the network interfaces available or connected to the system."
},
{
"code": null,
"e": 25466,
"s": 25423,
"text": "2. Stopping the desired network interface."
},
{
"code": null,
"e": 25491,
"s": 25466,
"text": "airmon-ng stop wlan0mon\n"
},
{
"code": null,
"e": 25599,
"s": 25491,
"text": "To stop a network interface enter the above command and replace “wlan0” with the desired network interface."
},
{
"code": null,
"e": 25654,
"s": 25599,
"text": "3. Starting a network interface at a specific channel."
},
{
"code": null,
"e": 25680,
"s": 25654,
"text": "airmon-ng start wlan0 10\n"
},
{
"code": null,
"e": 25848,
"s": 25680,
"text": "To start a network interface at a specific channel enter the above command and replace “wlan0” with the desired network interface and 10 with the desired channel name."
},
{
"code": null,
"e": 25887,
"s": 25848,
"text": "4. Collecting authentication handshake"
},
{
"code": null,
"e": 25945,
"s": 25887,
"text": "airodump-ng -c 10 --bssid 00:15:5D:9C:44:00 -w psk wlan0\n"
},
{
"code": null,
"e": 26151,
"s": 25945,
"text": "To collect the authentication handshake enter the above command in terminal and replace “wlan0” with the desired network interface and 10 with the desired channel name and bssid with the bssid of the wifi."
},
{
"code": null,
"e": 26214,
"s": 26151,
"text": "5. Cracking the captured handshake file by means of a wordlist"
},
{
"code": null,
"e": 26248,
"s": 26214,
"text": "aircrack-ng -w wordlist psk*.cap\n"
},
{
"code": null,
"e": 26453,
"s": 26248,
"text": "To run a brute force attack and to crack the password enter the above command in the terminal and replace “wordlist” with the desired wordlist to be used and “wpa.cap” with the desired handshake filename."
},
{
"code": null,
"e": 26492,
"s": 26453,
"text": "6. To get the help section of the tool"
},
{
"code": null,
"e": 26512,
"s": 26492,
"text": "aircrack-ng --help\n"
},
{
"code": null,
"e": 26588,
"s": 26512,
"text": "The above command will display the help section of the aircrack-ng command."
},
{
"code": null,
"e": 26633,
"s": 26588,
"text": "7. To display the # of CPUs and SIMD support"
},
{
"code": null,
"e": 26649,
"s": 26633,
"text": "aircrack-ng -u\n"
},
{
"code": null,
"e": 26730,
"s": 26649,
"text": "The above command will display the details of the hash of CPUs and SIMD support."
},
{
"code": null,
"e": 26741,
"s": 26730,
"text": "Linux-Unix"
},
{
"code": null,
"e": 26839,
"s": 26741,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26848,
"s": 26839,
"text": "Comments"
},
{
"code": null,
"e": 26861,
"s": 26848,
"text": "Old Comments"
},
{
"code": null,
"e": 26899,
"s": 26861,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 26934,
"s": 26899,
"text": "ZIP command in Linux with examples"
},
{
"code": null,
"e": 26969,
"s": 26934,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 27010,
"s": 26969,
"text": "SORT command in Linux/Unix with examples"
},
{
"code": null,
"e": 27046,
"s": 27010,
"text": "curl command in Linux with Examples"
},
{
"code": null,
"e": 27084,
"s": 27046,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 27117,
"s": 27084,
"text": "'crontab' in Linux with Examples"
},
{
"code": null,
"e": 27155,
"s": 27117,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 27191,
"s": 27155,
"text": "diff command in Linux with examples"
}
]
|
DurationField - Django Models - GeeksforGeeks | 02 Sep, 2021
DurationField is a field for storing periods of time – modeled in Python by timedelta. When used on PostgreSQL, the data type used is an interval and on Oracle the data type is INTERVAL DAY(9) TO SECOND(6). Otherwise, a bigint of microseconds is used. DurationField basically stores a duration, the difference between two dates or times.
Syntax
field_name = models.DurationField(**options)
Illustration of DurationField using an Example. Consider a project named geeksforgeeks having an app named geeks.
Refer to the following articles to check how to create a project and an app in Django.
How to Create a Basic Project using MVT in Django?
How to Create an App in Django ?
Enter the following code into models.py file of geeks app.
Python3
from django.db import modelsfrom django.db.models import Model# Create your models here. class GeeksModel(Model): geeks_field = models.DurationField()
Add the geeks app to INSTALLED_APPS
Python3
# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'geeks',]
Now when we run makemigrations command from the terminal,
Python manage.py makemigrations
A new folder named migrations would be created in geeks directory with a file named 0001_initial.py
Python3
# Generated by Django 2.2.5 on 2019-09-25 06:00 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name ='GeeksModel', fields =[ ('id', models.AutoField( auto_created = True, primary_key = True, serialize = False, verbose_name ='ID' )), ('geeks_field', models.DurationField()), ], ), ]
Now run,
Python manage.py migrate
Thus, an geeks_field DurationField is created when you run migrations on the project. It is a field to store datetime.timedelta python object.
DurationField is used for storing python datetime.timedelta instance in the database. One can store any type of duration based on time or date in the database. To know more about datetime.timedelta, check out Python | datetime.timedelta() function. Let’s try storing a timedelta instance in model created above.
Python3
# importing the model# from geeks appfrom geeks.models import GeeksModel # importing datetime moduleimport datetime # creating an instance of# datetime.timedeltad = datetime.timedelta(days =-1, seconds = 68400) # creating an instance of# GeeksModelgeek_object = GeeksModel.objects.create(geeks_field = d)geek_object.save()
Now let’s check it in admin server. We have created an instance of GeeksModel.
Field Options are the arguments given to each field for applying some constraint or imparting a particular characteristic to a particular Field. For example, adding an argument null = True to DurationField will enable it to store empty values for that table in relational database. Here are the field options and attributes that a DurationField can use.
NaveenArora
simmytarika5
Django-models
Python Django
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
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python | [
{
"code": null,
"e": 23681,
"s": 23653,
"text": "\n02 Sep, 2021"
},
{
"code": null,
"e": 24019,
"s": 23681,
"text": "DurationField is a field for storing periods of time – modeled in Python by timedelta. When used on PostgreSQL, the data type used is an interval and on Oracle the data type is INTERVAL DAY(9) TO SECOND(6). Otherwise, a bigint of microseconds is used. DurationField basically stores a duration, the difference between two dates or times."
},
{
"code": null,
"e": 24026,
"s": 24019,
"text": "Syntax"
},
{
"code": null,
"e": 24071,
"s": 24026,
"text": "field_name = models.DurationField(**options)"
},
{
"code": null,
"e": 24186,
"s": 24071,
"text": "Illustration of DurationField using an Example. Consider a project named geeksforgeeks having an app named geeks. "
},
{
"code": null,
"e": 24274,
"s": 24186,
"text": "Refer to the following articles to check how to create a project and an app in Django. "
},
{
"code": null,
"e": 24325,
"s": 24274,
"text": "How to Create a Basic Project using MVT in Django?"
},
{
"code": null,
"e": 24358,
"s": 24325,
"text": "How to Create an App in Django ?"
},
{
"code": null,
"e": 24419,
"s": 24358,
"text": "Enter the following code into models.py file of geeks app. "
},
{
"code": null,
"e": 24427,
"s": 24419,
"text": "Python3"
},
{
"code": "from django.db import modelsfrom django.db.models import Model# Create your models here. class GeeksModel(Model): geeks_field = models.DurationField()",
"e": 24581,
"s": 24427,
"text": null
},
{
"code": null,
"e": 24618,
"s": 24581,
"text": "Add the geeks app to INSTALLED_APPS "
},
{
"code": null,
"e": 24626,
"s": 24618,
"text": "Python3"
},
{
"code": "# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'geeks',]",
"e": 24863,
"s": 24626,
"text": null
},
{
"code": null,
"e": 24921,
"s": 24863,
"text": "Now when we run makemigrations command from the terminal,"
},
{
"code": null,
"e": 24953,
"s": 24921,
"text": "Python manage.py makemigrations"
},
{
"code": null,
"e": 25054,
"s": 24953,
"text": "A new folder named migrations would be created in geeks directory with a file named 0001_initial.py "
},
{
"code": null,
"e": 25062,
"s": 25054,
"text": "Python3"
},
{
"code": "# Generated by Django 2.2.5 on 2019-09-25 06:00 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name ='GeeksModel', fields =[ ('id', models.AutoField( auto_created = True, primary_key = True, serialize = False, verbose_name ='ID' )), ('geeks_field', models.DurationField()), ], ), ]",
"e": 25645,
"s": 25062,
"text": null
},
{
"code": null,
"e": 25655,
"s": 25645,
"text": "Now run, "
},
{
"code": null,
"e": 25680,
"s": 25655,
"text": "Python manage.py migrate"
},
{
"code": null,
"e": 25823,
"s": 25680,
"text": "Thus, an geeks_field DurationField is created when you run migrations on the project. It is a field to store datetime.timedelta python object."
},
{
"code": null,
"e": 26135,
"s": 25823,
"text": "DurationField is used for storing python datetime.timedelta instance in the database. One can store any type of duration based on time or date in the database. To know more about datetime.timedelta, check out Python | datetime.timedelta() function. Let’s try storing a timedelta instance in model created above."
},
{
"code": null,
"e": 26143,
"s": 26135,
"text": "Python3"
},
{
"code": "# importing the model# from geeks appfrom geeks.models import GeeksModel # importing datetime moduleimport datetime # creating an instance of# datetime.timedeltad = datetime.timedelta(days =-1, seconds = 68400) # creating an instance of# GeeksModelgeek_object = GeeksModel.objects.create(geeks_field = d)geek_object.save()",
"e": 26466,
"s": 26143,
"text": null
},
{
"code": null,
"e": 26546,
"s": 26466,
"text": "Now let’s check it in admin server. We have created an instance of GeeksModel. "
},
{
"code": null,
"e": 26901,
"s": 26546,
"text": "Field Options are the arguments given to each field for applying some constraint or imparting a particular characteristic to a particular Field. For example, adding an argument null = True to DurationField will enable it to store empty values for that table in relational database. Here are the field options and attributes that a DurationField can use. "
},
{
"code": null,
"e": 26915,
"s": 26903,
"text": "NaveenArora"
},
{
"code": null,
"e": 26928,
"s": 26915,
"text": "simmytarika5"
},
{
"code": null,
"e": 26942,
"s": 26928,
"text": "Django-models"
},
{
"code": null,
"e": 26956,
"s": 26942,
"text": "Python Django"
},
{
"code": null,
"e": 26963,
"s": 26956,
"text": "Python"
},
{
"code": null,
"e": 27061,
"s": 26963,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27070,
"s": 27061,
"text": "Comments"
},
{
"code": null,
"e": 27083,
"s": 27070,
"text": "Old Comments"
},
{
"code": null,
"e": 27101,
"s": 27083,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27136,
"s": 27101,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27158,
"s": 27136,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27190,
"s": 27158,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27220,
"s": 27190,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27262,
"s": 27220,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27305,
"s": 27262,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 27331,
"s": 27305,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27375,
"s": 27331,
"text": "Reading and Writing to text files in Python"
}
]
|
Concatenate strings from several rows using Pandas groupby - GeeksforGeeks | 20 Aug, 2020
Pandas Dataframe.groupby() method is used to split the data into groups based on some criteria. The abstract definition of grouping is to provide a mapping of labels to the group name.
To concatenate string from several rows using Dataframe.groupby(), perform the following steps:
Group the data using Dataframe.groupby() method whose attributes you need to concatenate.Concatenate the string by using the join function and transform the value of that column using lambda statement.
Group the data using Dataframe.groupby() method whose attributes you need to concatenate.
Concatenate the string by using the join function and transform the value of that column using lambda statement.
We will use the CSV file having 2 columns, the content of the file is shown in the below image:
Example 1: We will concatenate the data in the branch column having the same name.
Python3
# import pandas libraryimport pandas as pd # read csv filedf = pd.read_csv("Book2.csv") # concatenate the stringdf['branch'] = df.groupby(['Name'])['branch'].transform(lambda x : ' '.join(x)) # drop duplicate datadf = df.drop_duplicates() # show the dataframeprint(df)
Output:
Example 2: We can perform Pandas groupby on multiple columns as well.
We will use the CSV file having 3 columns, the content of the file is shown in the below image:
Apply groupby on Name and year column
Python3
# import pandas libraryimport pandas as pd # read a csv filedf = pd.read_csv("Book1.csv") # concatenate the stringdf['branch'] = df.groupby(['Name', 'year'])['branch'].transform( lambda x: ' '.join(x)) # drop duplicate datadf = df.drop_duplicates() # show the dataframedf
Output:
Python Pandas-exercise
Python pandas-groupby
Python-pandas
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
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
*args and **kwargs in Python | [
{
"code": null,
"e": 25043,
"s": 25015,
"text": "\n20 Aug, 2020"
},
{
"code": null,
"e": 25228,
"s": 25043,
"text": "Pandas Dataframe.groupby() method is used to split the data into groups based on some criteria. The abstract definition of grouping is to provide a mapping of labels to the group name."
},
{
"code": null,
"e": 25324,
"s": 25228,
"text": "To concatenate string from several rows using Dataframe.groupby(), perform the following steps:"
},
{
"code": null,
"e": 25526,
"s": 25324,
"text": "Group the data using Dataframe.groupby() method whose attributes you need to concatenate.Concatenate the string by using the join function and transform the value of that column using lambda statement."
},
{
"code": null,
"e": 25616,
"s": 25526,
"text": "Group the data using Dataframe.groupby() method whose attributes you need to concatenate."
},
{
"code": null,
"e": 25729,
"s": 25616,
"text": "Concatenate the string by using the join function and transform the value of that column using lambda statement."
},
{
"code": null,
"e": 25825,
"s": 25729,
"text": "We will use the CSV file having 2 columns, the content of the file is shown in the below image:"
},
{
"code": null,
"e": 25908,
"s": 25825,
"text": "Example 1: We will concatenate the data in the branch column having the same name."
},
{
"code": null,
"e": 25916,
"s": 25908,
"text": "Python3"
},
{
"code": "# import pandas libraryimport pandas as pd # read csv filedf = pd.read_csv(\"Book2.csv\") # concatenate the stringdf['branch'] = df.groupby(['Name'])['branch'].transform(lambda x : ' '.join(x)) # drop duplicate datadf = df.drop_duplicates() # show the dataframeprint(df)",
"e": 26192,
"s": 25916,
"text": null
},
{
"code": null,
"e": 26200,
"s": 26192,
"text": "Output:"
},
{
"code": null,
"e": 26270,
"s": 26200,
"text": "Example 2: We can perform Pandas groupby on multiple columns as well."
},
{
"code": null,
"e": 26366,
"s": 26270,
"text": "We will use the CSV file having 3 columns, the content of the file is shown in the below image:"
},
{
"code": null,
"e": 26404,
"s": 26366,
"text": "Apply groupby on Name and year column"
},
{
"code": null,
"e": 26412,
"s": 26404,
"text": "Python3"
},
{
"code": "# import pandas libraryimport pandas as pd # read a csv filedf = pd.read_csv(\"Book1.csv\") # concatenate the stringdf['branch'] = df.groupby(['Name', 'year'])['branch'].transform( lambda x: ' '.join(x)) # drop duplicate datadf = df.drop_duplicates() # show the dataframedf",
"e": 26743,
"s": 26412,
"text": null
},
{
"code": null,
"e": 26751,
"s": 26743,
"text": "Output:"
},
{
"code": null,
"e": 26774,
"s": 26751,
"text": "Python Pandas-exercise"
},
{
"code": null,
"e": 26796,
"s": 26774,
"text": "Python pandas-groupby"
},
{
"code": null,
"e": 26810,
"s": 26796,
"text": "Python-pandas"
},
{
"code": null,
"e": 26817,
"s": 26810,
"text": "Python"
},
{
"code": null,
"e": 26915,
"s": 26817,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26933,
"s": 26915,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26968,
"s": 26933,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26990,
"s": 26968,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27022,
"s": 26990,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27052,
"s": 27022,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27094,
"s": 27052,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27131,
"s": 27094,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 27174,
"s": 27131,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 27218,
"s": 27174,
"text": "Reading and Writing to text files in Python"
}
]
|
Priority Queue Introduction in C/C++
| A priority queue is a type of queue in which elements are inserted or deleted according to the priorities assigned to them where priority is an integer value that can range between 0-10 where 0 shows the element with the highest priority and 10 shows the element with the lowest priority. There are two rules that are followed for implementing priority queue −
Data or element with the highest priority will get executed before the data or element with the lowest priority.
If two elements have the same priority than they will be executed in the sequence they are added in the list.
There are multiple data structures available that can be used to implement priority queue like Stack, Queue and Linked List. In this article, we are explaining queue data structure. There are two ways that can used to implement the priority queue like −
Maintain queue for multiple priorities in a single arrayOne way to implement priority queue is to maintain a queue for each priority. We can store these multiple queues in a single array where each queue will have two pointers i.e. Front and Rear. In queue, Front pointer is used to insert the element in a queue and it is incremented by 1 whenever the element is inserted and another pointer is rear which is used to delete or remove the element from the queue which is decremented by 1 whenever the element is removed from the queue. In the end, through the positions of the two pointers we can also determine the number of elements in the queue.
One way to implement priority queue is to maintain a queue for each priority. We can store these multiple queues in a single array where each queue will have two pointers i.e. Front and Rear. In queue, Front pointer is used to insert the element in a queue and it is incremented by 1 whenever the element is inserted and another pointer is rear which is used to delete or remove the element from the queue which is decremented by 1 whenever the element is removed from the queue. In the end, through the positions of the two pointers we can also determine the number of elements in the queue.
In this type of representation, we need to shift the pointers to make space for inserting new elements which will make it complex in terms of time and space both.
Maintain queue for each priority in a single arrayIn this type of method we create separate arrow for each element. Every queue is implemented as a circular array and have two pointer variables .i.e. Front and Rear. The element with give priority number is inserted in the corresponding queue likewise if we want to delete an element from the queue it must be the element from the highest priority queue. Lowest priority integer indicates the highest priority(0).
In this type of method we create separate arrow for each element. Every queue is implemented as a circular array and have two pointer variables .i.e. Front and Rear. The element with give priority number is inserted in the corresponding queue likewise if we want to delete an element from the queue it must be the element from the highest priority queue. Lowest priority integer indicates the highest priority(0).
Note − If the size of each queue is same then we can create a single two dimensional array instead of creating multiple one-dimensional array.
insert(queue, data, priority)
If(queue->Rear[priority] = MAX-1 AND queue->Front[priority] = 0) OR (queue->Rear[priority] +1 =queue->Front[priority])
Print Overflow
End
IF queue->Rear[priority - 1] = MAX-1
Set queue->Rear[priority - 1] = 0
Else
Set queue->Rear[priority] = queue->Rear[priority - 1] +1
End
Set queue->CQueue[priority - 1] [queue->Rear[priority - 1] = data
IF queue->Front[priority - 1] = -1
Set queue->Front[priority - 1] = 0
End
delete(queue)
Set flag = 0, priority = 0
While priority <= MAX-1
IF NOT queue->Front[priority] = -1
Set flag = 1
Set value = queue->CQueue[priority][queue->Front[priority]]
IF queue->Front[priority] = queue->Rear[priority]
Set queue->Front[priority] = queue->Rear[priority] = -1
Else
IF queue->Front[priority] = MAX-1
Set queue->Front[priority] = 0
Else
Set queue->Front[priority] = queue->Front[priority] + 1
End
End
Break
End
Set priority = priority +
End
If flag = 0
Print underflow
Else
Return value
End | [
{
"code": null,
"e": 1423,
"s": 1062,
"text": "A priority queue is a type of queue in which elements are inserted or deleted according to the priorities assigned to them where priority is an integer value that can range between 0-10 where 0 shows the element with the highest priority and 10 shows the element with the lowest priority. There are two rules that are followed for implementing priority queue −"
},
{
"code": null,
"e": 1536,
"s": 1423,
"text": "Data or element with the highest priority will get executed before the data or element with the lowest priority."
},
{
"code": null,
"e": 1646,
"s": 1536,
"text": "If two elements have the same priority than they will be executed in the sequence they are added in the list."
},
{
"code": null,
"e": 1900,
"s": 1646,
"text": "There are multiple data structures available that can be used to implement priority queue like Stack, Queue and Linked List. In this article, we are explaining queue data structure. There are two ways that can used to implement the priority queue like −"
},
{
"code": null,
"e": 2549,
"s": 1900,
"text": "Maintain queue for multiple priorities in a single arrayOne way to implement priority queue is to maintain a queue for each priority. We can store these multiple queues in a single array where each queue will have two pointers i.e. Front and Rear. In queue, Front pointer is used to insert the element in a queue and it is incremented by 1 whenever the element is inserted and another pointer is rear which is used to delete or remove the element from the queue which is decremented by 1 whenever the element is removed from the queue. In the end, through the positions of the two pointers we can also determine the number of elements in the queue."
},
{
"code": null,
"e": 3142,
"s": 2549,
"text": "One way to implement priority queue is to maintain a queue for each priority. We can store these multiple queues in a single array where each queue will have two pointers i.e. Front and Rear. In queue, Front pointer is used to insert the element in a queue and it is incremented by 1 whenever the element is inserted and another pointer is rear which is used to delete or remove the element from the queue which is decremented by 1 whenever the element is removed from the queue. In the end, through the positions of the two pointers we can also determine the number of elements in the queue."
},
{
"code": null,
"e": 3305,
"s": 3142,
"text": "In this type of representation, we need to shift the pointers to make space for inserting new elements which will make it complex in terms of time and space both."
},
{
"code": null,
"e": 3769,
"s": 3305,
"text": "Maintain queue for each priority in a single arrayIn this type of method we create separate arrow for each element. Every queue is implemented as a circular array and have two pointer variables .i.e. Front and Rear. The element with give priority number is inserted in the corresponding queue likewise if we want to delete an element from the queue it must be the element from the highest priority queue. Lowest priority integer indicates the highest priority(0)."
},
{
"code": null,
"e": 4183,
"s": 3769,
"text": "In this type of method we create separate arrow for each element. Every queue is implemented as a circular array and have two pointer variables .i.e. Front and Rear. The element with give priority number is inserted in the corresponding queue likewise if we want to delete an element from the queue it must be the element from the highest priority queue. Lowest priority integer indicates the highest priority(0)."
},
{
"code": null,
"e": 4326,
"s": 4183,
"text": "Note − If the size of each queue is same then we can create a single two dimensional array instead of creating multiple one-dimensional array."
},
{
"code": null,
"e": 4819,
"s": 4326,
"text": "insert(queue, data, priority)\n If(queue->Rear[priority] = MAX-1 AND queue->Front[priority] = 0) OR (queue->Rear[priority] +1 =queue->Front[priority])\n Print Overflow\n End\n IF queue->Rear[priority - 1] = MAX-1\n Set queue->Rear[priority - 1] = 0\n Else\n Set queue->Rear[priority] = queue->Rear[priority - 1] +1\n End\n Set queue->CQueue[priority - 1] [queue->Rear[priority - 1] = data\n IF queue->Front[priority - 1] = -1\n Set queue->Front[priority - 1] = 0\nEnd"
},
{
"code": null,
"e": 5501,
"s": 4819,
"text": "delete(queue)\n Set flag = 0, priority = 0\n While priority <= MAX-1\n IF NOT queue->Front[priority] = -1\n Set flag = 1\n Set value = queue->CQueue[priority][queue->Front[priority]]\n IF queue->Front[priority] = queue->Rear[priority]\n Set queue->Front[priority] = queue->Rear[priority] = -1\n Else\n IF queue->Front[priority] = MAX-1\n Set queue->Front[priority] = 0\n Else\n Set queue->Front[priority] = queue->Front[priority] + 1\n End\n End\n Break\n End\n Set priority = priority +\nEnd\nIf flag = 0\n Print underflow\nElse\n Return value\nEnd"
}
]
|
Explain about concurrent transactions in DBMS | A transaction is a unit of database processing which contains a set of operations. For example, deposit of money, balance enquiry, reservation of tickets etc.
Every transaction starts with delimiters begin transaction and terminates with end transaction delimiters. The set of operations within these two delimiters constitute one transaction.
main()
{
begin transaction
} end transaction
There are three possible ways in which a transaction can be executed. These are as follows −
Serial execution.
Parallel execution.
Concurrent execution.
Concurrent transaction or execution includes multiple transactions which are executed concurrently or simultaneously in the system.
The advantages of the concurrent transactions are as follows −
Increases throughput which is nothing but number of transactions completed per unit time.
Increases throughput which is nothing but number of transactions completed per unit time.
It reduces the waiting time.
It reduces the waiting time.
T1= 90sec
T2= 500sec
T3= 5sec.
If we execute serially by T1->T2->T3 then transaction T3 waits for 590 sec, so we go for non-serial or concurrent transactions to reduce waiting time.
i.e. T3 -> T1 -> T2.
The disadvantage is that the execution of concurrent transactions may result in inconsistency.
The concurrent execution given below is in a consistent state.
The transaction given below is not consistent.
Concurrent schedules do not keep the database in the consistent state. The concurrent execution of the transactions has to be carried out in a controlled environment.
If a system consists of ‘n’ number of transactions, we will have more than ‘n!’ number of concurrent schedules, out of which only a few of them are keeping the database in consistent state. | [
{
"code": null,
"e": 1221,
"s": 1062,
"text": "A transaction is a unit of database processing which contains a set of operations. For example, deposit of money, balance enquiry, reservation of tickets etc."
},
{
"code": null,
"e": 1406,
"s": 1221,
"text": "Every transaction starts with delimiters begin transaction and terminates with end transaction delimiters. The set of operations within these two delimiters constitute one transaction."
},
{
"code": null,
"e": 1454,
"s": 1406,
"text": "main()\n{\n begin transaction\n} end transaction"
},
{
"code": null,
"e": 1547,
"s": 1454,
"text": "There are three possible ways in which a transaction can be executed. These are as follows −"
},
{
"code": null,
"e": 1565,
"s": 1547,
"text": "Serial execution."
},
{
"code": null,
"e": 1585,
"s": 1565,
"text": "Parallel execution."
},
{
"code": null,
"e": 1607,
"s": 1585,
"text": "Concurrent execution."
},
{
"code": null,
"e": 1739,
"s": 1607,
"text": "Concurrent transaction or execution includes multiple transactions which are executed concurrently or simultaneously in the system."
},
{
"code": null,
"e": 1802,
"s": 1739,
"text": "The advantages of the concurrent transactions are as follows −"
},
{
"code": null,
"e": 1892,
"s": 1802,
"text": "Increases throughput which is nothing but number of transactions completed per unit time."
},
{
"code": null,
"e": 1982,
"s": 1892,
"text": "Increases throughput which is nothing but number of transactions completed per unit time."
},
{
"code": null,
"e": 2011,
"s": 1982,
"text": "It reduces the waiting time."
},
{
"code": null,
"e": 2040,
"s": 2011,
"text": "It reduces the waiting time."
},
{
"code": null,
"e": 2071,
"s": 2040,
"text": "T1= 90sec\nT2= 500sec\nT3= 5sec."
},
{
"code": null,
"e": 2222,
"s": 2071,
"text": "If we execute serially by T1->T2->T3 then transaction T3 waits for 590 sec, so we go for non-serial or concurrent transactions to reduce waiting time."
},
{
"code": null,
"e": 2243,
"s": 2222,
"text": "i.e. T3 -> T1 -> T2."
},
{
"code": null,
"e": 2338,
"s": 2243,
"text": "The disadvantage is that the execution of concurrent transactions may result in inconsistency."
},
{
"code": null,
"e": 2401,
"s": 2338,
"text": "The concurrent execution given below is in a consistent state."
},
{
"code": null,
"e": 2448,
"s": 2401,
"text": "The transaction given below is not consistent."
},
{
"code": null,
"e": 2615,
"s": 2448,
"text": "Concurrent schedules do not keep the database in the consistent state. The concurrent execution of the transactions has to be carried out in a controlled environment."
},
{
"code": null,
"e": 2805,
"s": 2615,
"text": "If a system consists of ‘n’ number of transactions, we will have more than ‘n!’ number of concurrent schedules, out of which only a few of them are keeping the database in consistent state."
}
]
|
Comparing Timestamp in Python - Pandas - GeeksforGeeks | 24 Jan, 2021
Pandas timestamp is equivalent to DateTime in Python. The timestamp is used for time series oriented data structures in pandas. Sometimes date and time is provided as a timestamp in pandas or is beneficial to be converted in timestamp. And, it is required to compare timestamps to know the latest entry, entries between two timestamps, the oldest entry, etc. for various tasks. Comparison between pandas timestamp objects is carried out using simple comparison operators: >, <,==,< = , >=. The difference can be calculated using a simple ‘–’ operator.
Given time can be converted to pandas timestamp using pandas.Timestamp() method. This method can take input in various forms such as DateTime-like string (e.g. ‘2017-01-01T12’), Unix epoch in units of seconds (1513393355.5), etc. The values can be taken for a year, month, day, hour, minute, second, etc. separated by commas or using variable names. For example, if we want to write 2018/2/21 11:40:00, we can provide (2018,2,21,11,40) as parameters to Timestamp method or can write ( year=2018,month=2,day=21,hour=11,minute=40). Values not provided will be considered as zero. This approach is used in the following code to create the timestamp column ‘new_time’ using provided date and time information.
Approach:
Create a dataframe with date and time values
Convert date and time values to timestamp values using pandas.timestamp() method
Compare required timestamps using regular comparison operators.
Create a pandas Dataframe with date and time:
Python3
import pandas as pd # Create a dataframedf = pd.DataFrame({ 'year': [2017, 2017, 2017, 2018, 2018], 'month': [11, 11, 12, 1, 2], 'day': [29, 30, 31, 1, 2], 'hour': [10, 10, 10, 11, 11], 'minute': [10, 20, 25, 30, 40]}) def time(rows): return (pd.Timestamp(rows.year, rows.month, rows.day, rows.hour, rows.minute)) # Create new column with entries of date# and time provided in timestamp formatdf['new_time'] = df.apply(time, axis = 'columns')display(df)
Output:
Above df is used in following examples.
Example 1: Here, the first and second timestamp in ‘new_time’ are compared to know the oldest among those.
Python3
# Compare first and second timestampsif df['new_time'][0] <= df['new_time'][1]: print("First entry is old")else: print("Second entry is old")
Output:
First entry is old
Example 2: Here, all timestamps in ‘new_time’ are compared with Timestamp(2018-01-05 12:00:00) and the entries before this timestamp are returned
Python3
# Timestamps satisfying given conditionfor i in range(len(df['year'])): if df['new_time'][i] < pd.Timestamp(2018, 1, 5, 12): print(df['new_time'][i])
Output:
2017-11-29 10:10:00
2017-11-30 10:20:00
2017-12-31 10:25:00
2018-01-01 11:30:00
Example 3: Here again we compared all timestamps with Timestamp(2018-01-05 12:00:00), but returned comparison result as boolean values (True/False) for all timestamps.
Python3
# Boolean value output for given conditionprint(df['new_time'] > pd.Timestamp(2018, 1, 5, 12))
Output:
0 False
1 False
2 False
3 False
4 True
Name: new_time, dtype: bool
Example 4: Here, the max function is used to get the maximum of all timestamps, that is the recent entry in the ‘new_time’ column.
Also, with that, we calculated the time difference between the first and the second timestamp in the ‘new_time’ column.
Python3
# Latest timestampprint("Latest Timestamp: ", max(df['new_time'])) # Get difference between 2 timestampsdiff = abs(df['new_time'][0]-df['new_time'][1])print("Difference: ", diff)
Output:
Latest Timestamp: 2018-02-02 11:40:00
Difference: 1 days 00:10:00
Picked
Python Pandas-Timestamp
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
Defaultdict in Python
Selecting rows in pandas DataFrame based on conditions
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n24 Jan, 2021"
},
{
"code": null,
"e": 24844,
"s": 24292,
"text": "Pandas timestamp is equivalent to DateTime in Python. The timestamp is used for time series oriented data structures in pandas. Sometimes date and time is provided as a timestamp in pandas or is beneficial to be converted in timestamp. And, it is required to compare timestamps to know the latest entry, entries between two timestamps, the oldest entry, etc. for various tasks. Comparison between pandas timestamp objects is carried out using simple comparison operators: >, <,==,< = , >=. The difference can be calculated using a simple ‘–’ operator."
},
{
"code": null,
"e": 25550,
"s": 24844,
"text": "Given time can be converted to pandas timestamp using pandas.Timestamp() method. This method can take input in various forms such as DateTime-like string (e.g. ‘2017-01-01T12’), Unix epoch in units of seconds (1513393355.5), etc. The values can be taken for a year, month, day, hour, minute, second, etc. separated by commas or using variable names. For example, if we want to write 2018/2/21 11:40:00, we can provide (2018,2,21,11,40) as parameters to Timestamp method or can write ( year=2018,month=2,day=21,hour=11,minute=40). Values not provided will be considered as zero. This approach is used in the following code to create the timestamp column ‘new_time’ using provided date and time information."
},
{
"code": null,
"e": 25560,
"s": 25550,
"text": "Approach:"
},
{
"code": null,
"e": 25605,
"s": 25560,
"text": "Create a dataframe with date and time values"
},
{
"code": null,
"e": 25686,
"s": 25605,
"text": "Convert date and time values to timestamp values using pandas.timestamp() method"
},
{
"code": null,
"e": 25750,
"s": 25686,
"text": "Compare required timestamps using regular comparison operators."
},
{
"code": null,
"e": 25796,
"s": 25750,
"text": "Create a pandas Dataframe with date and time:"
},
{
"code": null,
"e": 25804,
"s": 25796,
"text": "Python3"
},
{
"code": "import pandas as pd # Create a dataframedf = pd.DataFrame({ 'year': [2017, 2017, 2017, 2018, 2018], 'month': [11, 11, 12, 1, 2], 'day': [29, 30, 31, 1, 2], 'hour': [10, 10, 10, 11, 11], 'minute': [10, 20, 25, 30, 40]}) def time(rows): return (pd.Timestamp(rows.year, rows.month, rows.day, rows.hour, rows.minute)) # Create new column with entries of date# and time provided in timestamp formatdf['new_time'] = df.apply(time, axis = 'columns')display(df)",
"e": 26303,
"s": 25804,
"text": null
},
{
"code": null,
"e": 26311,
"s": 26303,
"text": "Output:"
},
{
"code": null,
"e": 26351,
"s": 26311,
"text": "Above df is used in following examples."
},
{
"code": null,
"e": 26458,
"s": 26351,
"text": "Example 1: Here, the first and second timestamp in ‘new_time’ are compared to know the oldest among those."
},
{
"code": null,
"e": 26466,
"s": 26458,
"text": "Python3"
},
{
"code": "# Compare first and second timestampsif df['new_time'][0] <= df['new_time'][1]: print(\"First entry is old\")else: print(\"Second entry is old\")",
"e": 26614,
"s": 26466,
"text": null
},
{
"code": null,
"e": 26622,
"s": 26614,
"text": "Output:"
},
{
"code": null,
"e": 26641,
"s": 26622,
"text": "First entry is old"
},
{
"code": null,
"e": 26787,
"s": 26641,
"text": "Example 2: Here, all timestamps in ‘new_time’ are compared with Timestamp(2018-01-05 12:00:00) and the entries before this timestamp are returned"
},
{
"code": null,
"e": 26795,
"s": 26787,
"text": "Python3"
},
{
"code": "# Timestamps satisfying given conditionfor i in range(len(df['year'])): if df['new_time'][i] < pd.Timestamp(2018, 1, 5, 12): print(df['new_time'][i])",
"e": 26955,
"s": 26795,
"text": null
},
{
"code": null,
"e": 26963,
"s": 26955,
"text": "Output:"
},
{
"code": null,
"e": 27043,
"s": 26963,
"text": "2017-11-29 10:10:00\n2017-11-30 10:20:00\n2017-12-31 10:25:00\n2018-01-01 11:30:00"
},
{
"code": null,
"e": 27211,
"s": 27043,
"text": "Example 3: Here again we compared all timestamps with Timestamp(2018-01-05 12:00:00), but returned comparison result as boolean values (True/False) for all timestamps."
},
{
"code": null,
"e": 27219,
"s": 27211,
"text": "Python3"
},
{
"code": "# Boolean value output for given conditionprint(df['new_time'] > pd.Timestamp(2018, 1, 5, 12))",
"e": 27314,
"s": 27219,
"text": null
},
{
"code": null,
"e": 27322,
"s": 27314,
"text": "Output:"
},
{
"code": null,
"e": 27405,
"s": 27322,
"text": "0 False\n1 False\n2 False\n3 False\n4 True\nName: new_time, dtype: bool"
},
{
"code": null,
"e": 27536,
"s": 27405,
"text": "Example 4: Here, the max function is used to get the maximum of all timestamps, that is the recent entry in the ‘new_time’ column."
},
{
"code": null,
"e": 27656,
"s": 27536,
"text": "Also, with that, we calculated the time difference between the first and the second timestamp in the ‘new_time’ column."
},
{
"code": null,
"e": 27664,
"s": 27656,
"text": "Python3"
},
{
"code": "# Latest timestampprint(\"Latest Timestamp: \", max(df['new_time'])) # Get difference between 2 timestampsdiff = abs(df['new_time'][0]-df['new_time'][1])print(\"Difference: \", diff)",
"e": 27844,
"s": 27664,
"text": null
},
{
"code": null,
"e": 27852,
"s": 27844,
"text": "Output:"
},
{
"code": null,
"e": 27920,
"s": 27852,
"text": "Latest Timestamp: 2018-02-02 11:40:00\nDifference: 1 days 00:10:00"
},
{
"code": null,
"e": 27927,
"s": 27920,
"text": "Picked"
},
{
"code": null,
"e": 27951,
"s": 27927,
"text": "Python Pandas-Timestamp"
},
{
"code": null,
"e": 27965,
"s": 27951,
"text": "Python-pandas"
},
{
"code": null,
"e": 27972,
"s": 27965,
"text": "Python"
},
{
"code": null,
"e": 28070,
"s": 27972,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28102,
"s": 28070,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28144,
"s": 28102,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28200,
"s": 28144,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28242,
"s": 28200,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28273,
"s": 28242,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28295,
"s": 28273,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28350,
"s": 28295,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 28389,
"s": 28350,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28418,
"s": 28389,
"text": "Create a directory in Python"
}
]
|
Java program to reverse bits of a positive integer number | The bits of an integer number can be reversed to obtain another number. An example of this is given as follows −
Number = 11
Binary representation = 1011
Reversed binary representation = 1101
Reversed number = 13
A program that demonstrates this is given as follows −
Live Demo
public class Example {
public static void main(String[] args) {
int num = 14;
int n = num;
int rev = 0;
while (num > 0) {
rev <<= 1;
if ((int)(num & 1) == 1)
rev ^= 1;
num >>= 1;
}
System.out.println("The original number is: " + n);
System.out.println("The number with reversed bits is: " + rev);
}
}
The original number is: 14
The number with reversed bits is: 7
Now let us understand the above program.
The number is defined. Then a while loop is used to reverse the bits of the number. The code snippet that demonstrates this is given as follows −
int num = 14;
int n = num;
int rev = 0;
while (num > 0) {
rev <<= 1;
if ((int)(num & 1) == 1)
rev ^= 1;
num >>= 1;
}
Finally, the number, as well as the reversed number, are displayed. The code snippet that demonstrates this is given as follows −
System.out.println("The original number is: " + n);
System.out.println("The number with reversed bits is: " + rev); | [
{
"code": null,
"e": 1175,
"s": 1062,
"text": "The bits of an integer number can be reversed to obtain another number. An example of this is given as follows −"
},
{
"code": null,
"e": 1275,
"s": 1175,
"text": "Number = 11\nBinary representation = 1011\nReversed binary representation = 1101\nReversed number = 13"
},
{
"code": null,
"e": 1330,
"s": 1275,
"text": "A program that demonstrates this is given as follows −"
},
{
"code": null,
"e": 1341,
"s": 1330,
"text": " Live Demo"
},
{
"code": null,
"e": 1726,
"s": 1341,
"text": "public class Example {\n public static void main(String[] args) {\n int num = 14;\n int n = num;\n int rev = 0;\n while (num > 0) {\n rev <<= 1;\n if ((int)(num & 1) == 1)\n rev ^= 1;\n num >>= 1;\n }\n System.out.println(\"The original number is: \" + n);\n System.out.println(\"The number with reversed bits is: \" + rev);\n }\n}"
},
{
"code": null,
"e": 1789,
"s": 1726,
"text": "The original number is: 14\nThe number with reversed bits is: 7"
},
{
"code": null,
"e": 1830,
"s": 1789,
"text": "Now let us understand the above program."
},
{
"code": null,
"e": 1976,
"s": 1830,
"text": "The number is defined. Then a while loop is used to reverse the bits of the number. The code snippet that demonstrates this is given as follows −"
},
{
"code": null,
"e": 2105,
"s": 1976,
"text": "int num = 14;\nint n = num;\nint rev = 0;\nwhile (num > 0) {\n rev <<= 1;\n if ((int)(num & 1) == 1)\n rev ^= 1;\n num >>= 1;\n}"
},
{
"code": null,
"e": 2235,
"s": 2105,
"text": "Finally, the number, as well as the reversed number, are displayed. The code snippet that demonstrates this is given as follows −"
},
{
"code": null,
"e": 2351,
"s": 2235,
"text": "System.out.println(\"The original number is: \" + n);\nSystem.out.println(\"The number with reversed bits is: \" + rev);"
}
]
|
Integrating Airflow with Slack for Daily Reporting | by Mandy Gu | Towards Data Science | Tech Stack: Python 3.7, Airflow (1.10.10), Docker
GitHub link: All of the code can be found here.
Slack is an increasingly popular chat app used in the workplace. Apache Airflow is an open source platform for orchestrating workflows. One of the biggest advantages to using Airflow is the versatility around its hooks and operators. Hooks are interfaces to external platforms, databases and also serve as the basic building blocks of Operators.
The Slack Webhook Operator can be used to integrate Airflow with Slack. This operator is typically used for reporting and alerting purposes by scheduling incoming messages to Slack channels when some trigger condition is met.
I’m going to show you how to leverage these tools to perform some very simple reporting in your Slack workspace: send daily weather forecasts to a channel.
These foundations can be expanded to create more complex Airflow + Slack integrations. Let’s get started!
If you are interested in learning more about data engineering foundations, here’s a course to get started.
click.linksynergy.com
Note: if you are already familiar with setting up apps on Slack and with the Slack webhook, skip to “Airflow + Docker”
A workspace is a shared hub of channels where teammates and collaborators can communicate together. I created a workspace called weather-enthusiasts.
From our workspace, we need:
a channel to accept these messages
webhook url
Let’s have Airflow post to a public channel called #daily-weather-feed. If the message contents are sensitive, consider changing this to a private channel.
Next, we want to create an Airflow app for the workspace. Go to https://api.slack.com/apps and click Create New App
This should lead you to a modal where you can set the App name. Airflow will post messages under the name you select. For simplicity, I named my app airflow.
Exiting the modal leads to a page where you can add “Incoming Webhooks” as an app feature.
Make sure that incoming webhooks are turned on.
Scroll to the bottom of the page and click on “Add New Webhook to Workspace”.
This generates a WebHook URL, which can be used as authentication for Airflow.
The WebHook URL also allows you to programmatically send messages to Slack. Here’s a very simple POST request you can try in the terminal. Don’t forget to replace my redacted URL with yours.
curl -X POST -H 'Content-type: application/json' --data '{"text":"Hi, this is an automated message!"}' https://hooks.slack.com/services/XXXX
Check your channel to see the automated message.
If you are interested in learning more about using APIs and Python in the context of software engineering, this is a Coursera specialization well suited for beginners.
click.linksynergy.com
I’m going to show you how to set up Airflow with Docker to properly containerize your application. I am using part of the setup from puckel/docker-airflow.
Airflow comes with a lot of configurations which can be complex to set up. Using Docker makes it easier to get started with reproducible results.
What is Docker? Docker is a way of packaging individual applications independent of your local set up. Each application is in its own Docker container. Here are some helpful resources about Docker, including one that I have written about Docker commands.
docker-curriculum.com
towardsdatascience.com
For more advanced Docker applications with AWS services:
click.linksynergy.com
The entire Airflow platform can be broken into four parts: the scheduler, the executor, the metadata database and the webserver.
scheduler decides which jobs to run and at what time/order
executor executes the instructions for each job
the database stores Airflow states (did this job succeed or fail? how long did it take to run?)
the webserver is the user interface that makes it easier to interface with Airflow; the webserver is a Flask app under the hood
DAGs are a very important concept in Airflow. Each DAG is a collection of similar tasks organized in a way that reflects their dependencies and relationships. These graphs cannot have directed cycles, or in other words, mutually dependent jobs.
DAGs are defined in Python scripts and they help the scheduler determine which jobs to run. A downstream job cannot run until all upstream jobs have finished successfully.
Create a repository for your Airflow server. I will name mine slack-airflow. Once again, my repository is hosted here. These are the components in the directory:
requirements.txt
Dockerfile
Airflow sub-directory to manage configurations
docker-compose.yml
shell script for starting Airflow
a DAG file (we will get more to this later)
requirements.txt
This is for installing the required Airflow libraries (plus any other required libraries).
apache-airflow[crypto,celery,postgres,jdbc,ssh,statsd,slack]==1.10.10
airflow/config/airflow.cfg
The Airflow configuration file is typically downloaded as a part of the Airflow installation (added bonus of using Docker: you don’t need to go through the installation process). The default configurations are fine on their own, but settings can be tweaked for your particular use case.
Here is a comprehensive list indicating what every field corresponds to: https://airflow.apache.org/docs/stable/configurations-ref.html
This is the only file you need in the airflow directory.
Dockerfile
This contains the instructions for your Docker image. We specify some environment variables, more dependencies and instructions for running pip install and define the image entrypoint with our entrypoint.sh shell script. The last line also launches the webserver.
I am also using Dockerfile to store secrets to Slack and to the Open Weather API. Ideally, secrets should be stored in their own environment file and baked into the Docker container at build time. The environment file should be added to .gitignore so that it will not be surfaced in the codebase.
At the risk of over complicating this set up, we’ll leave the secrets in the Dockerfile.
Please fill these two lines accordingly with your secrets. Keep in mind when sharing your code that these are sensitive credentials! The weather_api_key is used to get daily weather forecasts — the next section covers how we can obtain this token. For now, feel free to leave it empty.
ENV weather_api_key=ENV slack_webhook_url=
docker-compose.yml
docker-compose is an organized way of handling Docker settings. It’s especially helpful if you are working with multiple containers that are dependent on each other.
The first service postgres creates the Postgres database responsible for storing the Airflow states. The credentials are set in the Dockerfile, which can be used to connect to the database on your local network.
This is the full database URL. The credential components are scattered across the Dockerfile and start up script. You can use this URL to connect to and query the Airflow database from your local network.
postgresql+psycopg2://airflow:airflow@postgres:5432/airflow
To learn more about how to connect to the DBAPI, check out my other article on Postgres DBs.
towardsdatascience.com
Here is a helpful Coursera course for those who want to explore Pythonic connections to databases in more detail:
click.linksynergy.com
The second part defines the webserver, which will be hosted on port 8080 in your local network.
We can utilize the Open Weather API to get daily forecasts. Create an account and generate an API token for your account.
Go back to the Dockerfile and set this environment variable with your token:
ENV weather_api_key=
Here is the link to my weather DAG. I placed it in a folder called dags.
I added myself as the owner of this DAG. This is a required argument for every DAG. If depends_on_past is set to True, subsequent tasks will not run unless the previous run was successful. Pick a start_date from the past. I picked yesterday’s date for mine.retries being set to 0 means that Airflow will not try to rerun failed tasks.
We send a GET request to Open Weather to get the weather details for Toronto. The payload is parsed and the description field is used to describe the forecast.
The API key is fetched from the environment variable instantiated in the Dockerfile.
We are using the SlackWebhookOperator in our DAG. Feel free to name the http_conn_id anything you want, but the same connection needs to be set on the Airflow server (this is covered in the section: Setting up your Slack connection on Airflow). The webhook token is fetched from the environment variables.
The default arguments are referenced here in addition to the scheduled interval and catchup=False (this prevents Airflow from running backfills).
The schedule_interval is a cron syntax that determines the cadence to run your DAG. The arguments correspond to (in order): minute, hour, day, month and day of the week.
I usually use this website to decipher Cron syntax: https://crontab.guru/
Run these two commands in your root directory.
This builds the image and tags it as airflow . It’s important that you don’t change the tag name as it is referenced in the start up script.
docker build . -t airflow
This spins up the relevant Docker containers based on the instructions in docker-compose.
docker-compose -f docker-compose.yml up -d
The first time running these steps will take a few minutes. After it is done, the web server will be exposed to your local 8080 port.
You can access it from your local network at localhost:8080. This is what mine looks like.
We are almost done.
The last thing we need to do is set up slack_connection in Airflow (this name needs to match the http_conn_id specified in the DAG file).
Go to localhost:8080 to access the webserver and click on Admin > Connections.
Hit Create and fill the fields accordingly. For the Slack connection, you will only need the Conn id and Host
conn_id = slack_connection
host = your webhook URL
If you don’t want to wait for the scheduled interval to observe the results, manually trigger a DAG run by hitting the Trigger DAG button.
After the task runs successfully, this message appears in Slack. Today’s forecast is clear sk(ies), which sounds about right ☀️
Awesome! Say goodbye to weather networks and hello to programmatic forecasts 😃
To get the weather forecast every single day, leave the Airflow server running.
I hope you found this article helpful. For additional Airflow resources, check out the official documentation which is a very comprehensive guide.
airflow.readthedocs.io
Follow me on Medium for the latest updates. 😃
I am also building a comprehensive set of free Data Science lessons and practice problems at www.dscrashcourse.com as a hobby project.
Thank you again for reading! 📕 | [
{
"code": null,
"e": 221,
"s": 171,
"text": "Tech Stack: Python 3.7, Airflow (1.10.10), Docker"
},
{
"code": null,
"e": 269,
"s": 221,
"text": "GitHub link: All of the code can be found here."
},
{
"code": null,
"e": 615,
"s": 269,
"text": "Slack is an increasingly popular chat app used in the workplace. Apache Airflow is an open source platform for orchestrating workflows. One of the biggest advantages to using Airflow is the versatility around its hooks and operators. Hooks are interfaces to external platforms, databases and also serve as the basic building blocks of Operators."
},
{
"code": null,
"e": 841,
"s": 615,
"text": "The Slack Webhook Operator can be used to integrate Airflow with Slack. This operator is typically used for reporting and alerting purposes by scheduling incoming messages to Slack channels when some trigger condition is met."
},
{
"code": null,
"e": 997,
"s": 841,
"text": "I’m going to show you how to leverage these tools to perform some very simple reporting in your Slack workspace: send daily weather forecasts to a channel."
},
{
"code": null,
"e": 1103,
"s": 997,
"text": "These foundations can be expanded to create more complex Airflow + Slack integrations. Let’s get started!"
},
{
"code": null,
"e": 1210,
"s": 1103,
"text": "If you are interested in learning more about data engineering foundations, here’s a course to get started."
},
{
"code": null,
"e": 1232,
"s": 1210,
"text": "click.linksynergy.com"
},
{
"code": null,
"e": 1351,
"s": 1232,
"text": "Note: if you are already familiar with setting up apps on Slack and with the Slack webhook, skip to “Airflow + Docker”"
},
{
"code": null,
"e": 1501,
"s": 1351,
"text": "A workspace is a shared hub of channels where teammates and collaborators can communicate together. I created a workspace called weather-enthusiasts."
},
{
"code": null,
"e": 1530,
"s": 1501,
"text": "From our workspace, we need:"
},
{
"code": null,
"e": 1565,
"s": 1530,
"text": "a channel to accept these messages"
},
{
"code": null,
"e": 1577,
"s": 1565,
"text": "webhook url"
},
{
"code": null,
"e": 1733,
"s": 1577,
"text": "Let’s have Airflow post to a public channel called #daily-weather-feed. If the message contents are sensitive, consider changing this to a private channel."
},
{
"code": null,
"e": 1849,
"s": 1733,
"text": "Next, we want to create an Airflow app for the workspace. Go to https://api.slack.com/apps and click Create New App"
},
{
"code": null,
"e": 2007,
"s": 1849,
"text": "This should lead you to a modal where you can set the App name. Airflow will post messages under the name you select. For simplicity, I named my app airflow."
},
{
"code": null,
"e": 2098,
"s": 2007,
"text": "Exiting the modal leads to a page where you can add “Incoming Webhooks” as an app feature."
},
{
"code": null,
"e": 2146,
"s": 2098,
"text": "Make sure that incoming webhooks are turned on."
},
{
"code": null,
"e": 2224,
"s": 2146,
"text": "Scroll to the bottom of the page and click on “Add New Webhook to Workspace”."
},
{
"code": null,
"e": 2303,
"s": 2224,
"text": "This generates a WebHook URL, which can be used as authentication for Airflow."
},
{
"code": null,
"e": 2494,
"s": 2303,
"text": "The WebHook URL also allows you to programmatically send messages to Slack. Here’s a very simple POST request you can try in the terminal. Don’t forget to replace my redacted URL with yours."
},
{
"code": null,
"e": 2635,
"s": 2494,
"text": "curl -X POST -H 'Content-type: application/json' --data '{\"text\":\"Hi, this is an automated message!\"}' https://hooks.slack.com/services/XXXX"
},
{
"code": null,
"e": 2684,
"s": 2635,
"text": "Check your channel to see the automated message."
},
{
"code": null,
"e": 2852,
"s": 2684,
"text": "If you are interested in learning more about using APIs and Python in the context of software engineering, this is a Coursera specialization well suited for beginners."
},
{
"code": null,
"e": 2874,
"s": 2852,
"text": "click.linksynergy.com"
},
{
"code": null,
"e": 3030,
"s": 2874,
"text": "I’m going to show you how to set up Airflow with Docker to properly containerize your application. I am using part of the setup from puckel/docker-airflow."
},
{
"code": null,
"e": 3176,
"s": 3030,
"text": "Airflow comes with a lot of configurations which can be complex to set up. Using Docker makes it easier to get started with reproducible results."
},
{
"code": null,
"e": 3431,
"s": 3176,
"text": "What is Docker? Docker is a way of packaging individual applications independent of your local set up. Each application is in its own Docker container. Here are some helpful resources about Docker, including one that I have written about Docker commands."
},
{
"code": null,
"e": 3453,
"s": 3431,
"text": "docker-curriculum.com"
},
{
"code": null,
"e": 3476,
"s": 3453,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 3533,
"s": 3476,
"text": "For more advanced Docker applications with AWS services:"
},
{
"code": null,
"e": 3555,
"s": 3533,
"text": "click.linksynergy.com"
},
{
"code": null,
"e": 3684,
"s": 3555,
"text": "The entire Airflow platform can be broken into four parts: the scheduler, the executor, the metadata database and the webserver."
},
{
"code": null,
"e": 3743,
"s": 3684,
"text": "scheduler decides which jobs to run and at what time/order"
},
{
"code": null,
"e": 3791,
"s": 3743,
"text": "executor executes the instructions for each job"
},
{
"code": null,
"e": 3887,
"s": 3791,
"text": "the database stores Airflow states (did this job succeed or fail? how long did it take to run?)"
},
{
"code": null,
"e": 4015,
"s": 3887,
"text": "the webserver is the user interface that makes it easier to interface with Airflow; the webserver is a Flask app under the hood"
},
{
"code": null,
"e": 4260,
"s": 4015,
"text": "DAGs are a very important concept in Airflow. Each DAG is a collection of similar tasks organized in a way that reflects their dependencies and relationships. These graphs cannot have directed cycles, or in other words, mutually dependent jobs."
},
{
"code": null,
"e": 4432,
"s": 4260,
"text": "DAGs are defined in Python scripts and they help the scheduler determine which jobs to run. A downstream job cannot run until all upstream jobs have finished successfully."
},
{
"code": null,
"e": 4594,
"s": 4432,
"text": "Create a repository for your Airflow server. I will name mine slack-airflow. Once again, my repository is hosted here. These are the components in the directory:"
},
{
"code": null,
"e": 4611,
"s": 4594,
"text": "requirements.txt"
},
{
"code": null,
"e": 4622,
"s": 4611,
"text": "Dockerfile"
},
{
"code": null,
"e": 4669,
"s": 4622,
"text": "Airflow sub-directory to manage configurations"
},
{
"code": null,
"e": 4688,
"s": 4669,
"text": "docker-compose.yml"
},
{
"code": null,
"e": 4722,
"s": 4688,
"text": "shell script for starting Airflow"
},
{
"code": null,
"e": 4766,
"s": 4722,
"text": "a DAG file (we will get more to this later)"
},
{
"code": null,
"e": 4783,
"s": 4766,
"text": "requirements.txt"
},
{
"code": null,
"e": 4874,
"s": 4783,
"text": "This is for installing the required Airflow libraries (plus any other required libraries)."
},
{
"code": null,
"e": 4944,
"s": 4874,
"text": "apache-airflow[crypto,celery,postgres,jdbc,ssh,statsd,slack]==1.10.10"
},
{
"code": null,
"e": 4971,
"s": 4944,
"text": "airflow/config/airflow.cfg"
},
{
"code": null,
"e": 5258,
"s": 4971,
"text": "The Airflow configuration file is typically downloaded as a part of the Airflow installation (added bonus of using Docker: you don’t need to go through the installation process). The default configurations are fine on their own, but settings can be tweaked for your particular use case."
},
{
"code": null,
"e": 5394,
"s": 5258,
"text": "Here is a comprehensive list indicating what every field corresponds to: https://airflow.apache.org/docs/stable/configurations-ref.html"
},
{
"code": null,
"e": 5451,
"s": 5394,
"text": "This is the only file you need in the airflow directory."
},
{
"code": null,
"e": 5462,
"s": 5451,
"text": "Dockerfile"
},
{
"code": null,
"e": 5726,
"s": 5462,
"text": "This contains the instructions for your Docker image. We specify some environment variables, more dependencies and instructions for running pip install and define the image entrypoint with our entrypoint.sh shell script. The last line also launches the webserver."
},
{
"code": null,
"e": 6023,
"s": 5726,
"text": "I am also using Dockerfile to store secrets to Slack and to the Open Weather API. Ideally, secrets should be stored in their own environment file and baked into the Docker container at build time. The environment file should be added to .gitignore so that it will not be surfaced in the codebase."
},
{
"code": null,
"e": 6112,
"s": 6023,
"text": "At the risk of over complicating this set up, we’ll leave the secrets in the Dockerfile."
},
{
"code": null,
"e": 6398,
"s": 6112,
"text": "Please fill these two lines accordingly with your secrets. Keep in mind when sharing your code that these are sensitive credentials! The weather_api_key is used to get daily weather forecasts — the next section covers how we can obtain this token. For now, feel free to leave it empty."
},
{
"code": null,
"e": 6441,
"s": 6398,
"text": "ENV weather_api_key=ENV slack_webhook_url="
},
{
"code": null,
"e": 6460,
"s": 6441,
"text": "docker-compose.yml"
},
{
"code": null,
"e": 6626,
"s": 6460,
"text": "docker-compose is an organized way of handling Docker settings. It’s especially helpful if you are working with multiple containers that are dependent on each other."
},
{
"code": null,
"e": 6838,
"s": 6626,
"text": "The first service postgres creates the Postgres database responsible for storing the Airflow states. The credentials are set in the Dockerfile, which can be used to connect to the database on your local network."
},
{
"code": null,
"e": 7043,
"s": 6838,
"text": "This is the full database URL. The credential components are scattered across the Dockerfile and start up script. You can use this URL to connect to and query the Airflow database from your local network."
},
{
"code": null,
"e": 7103,
"s": 7043,
"text": "postgresql+psycopg2://airflow:airflow@postgres:5432/airflow"
},
{
"code": null,
"e": 7196,
"s": 7103,
"text": "To learn more about how to connect to the DBAPI, check out my other article on Postgres DBs."
},
{
"code": null,
"e": 7219,
"s": 7196,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 7333,
"s": 7219,
"text": "Here is a helpful Coursera course for those who want to explore Pythonic connections to databases in more detail:"
},
{
"code": null,
"e": 7355,
"s": 7333,
"text": "click.linksynergy.com"
},
{
"code": null,
"e": 7451,
"s": 7355,
"text": "The second part defines the webserver, which will be hosted on port 8080 in your local network."
},
{
"code": null,
"e": 7573,
"s": 7451,
"text": "We can utilize the Open Weather API to get daily forecasts. Create an account and generate an API token for your account."
},
{
"code": null,
"e": 7650,
"s": 7573,
"text": "Go back to the Dockerfile and set this environment variable with your token:"
},
{
"code": null,
"e": 7671,
"s": 7650,
"text": "ENV weather_api_key="
},
{
"code": null,
"e": 7744,
"s": 7671,
"text": "Here is the link to my weather DAG. I placed it in a folder called dags."
},
{
"code": null,
"e": 8079,
"s": 7744,
"text": "I added myself as the owner of this DAG. This is a required argument for every DAG. If depends_on_past is set to True, subsequent tasks will not run unless the previous run was successful. Pick a start_date from the past. I picked yesterday’s date for mine.retries being set to 0 means that Airflow will not try to rerun failed tasks."
},
{
"code": null,
"e": 8239,
"s": 8079,
"text": "We send a GET request to Open Weather to get the weather details for Toronto. The payload is parsed and the description field is used to describe the forecast."
},
{
"code": null,
"e": 8324,
"s": 8239,
"text": "The API key is fetched from the environment variable instantiated in the Dockerfile."
},
{
"code": null,
"e": 8630,
"s": 8324,
"text": "We are using the SlackWebhookOperator in our DAG. Feel free to name the http_conn_id anything you want, but the same connection needs to be set on the Airflow server (this is covered in the section: Setting up your Slack connection on Airflow). The webhook token is fetched from the environment variables."
},
{
"code": null,
"e": 8776,
"s": 8630,
"text": "The default arguments are referenced here in addition to the scheduled interval and catchup=False (this prevents Airflow from running backfills)."
},
{
"code": null,
"e": 8946,
"s": 8776,
"text": "The schedule_interval is a cron syntax that determines the cadence to run your DAG. The arguments correspond to (in order): minute, hour, day, month and day of the week."
},
{
"code": null,
"e": 9020,
"s": 8946,
"text": "I usually use this website to decipher Cron syntax: https://crontab.guru/"
},
{
"code": null,
"e": 9067,
"s": 9020,
"text": "Run these two commands in your root directory."
},
{
"code": null,
"e": 9208,
"s": 9067,
"text": "This builds the image and tags it as airflow . It’s important that you don’t change the tag name as it is referenced in the start up script."
},
{
"code": null,
"e": 9234,
"s": 9208,
"text": "docker build . -t airflow"
},
{
"code": null,
"e": 9324,
"s": 9234,
"text": "This spins up the relevant Docker containers based on the instructions in docker-compose."
},
{
"code": null,
"e": 9367,
"s": 9324,
"text": "docker-compose -f docker-compose.yml up -d"
},
{
"code": null,
"e": 9501,
"s": 9367,
"text": "The first time running these steps will take a few minutes. After it is done, the web server will be exposed to your local 8080 port."
},
{
"code": null,
"e": 9592,
"s": 9501,
"text": "You can access it from your local network at localhost:8080. This is what mine looks like."
},
{
"code": null,
"e": 9612,
"s": 9592,
"text": "We are almost done."
},
{
"code": null,
"e": 9750,
"s": 9612,
"text": "The last thing we need to do is set up slack_connection in Airflow (this name needs to match the http_conn_id specified in the DAG file)."
},
{
"code": null,
"e": 9829,
"s": 9750,
"text": "Go to localhost:8080 to access the webserver and click on Admin > Connections."
},
{
"code": null,
"e": 9939,
"s": 9829,
"text": "Hit Create and fill the fields accordingly. For the Slack connection, you will only need the Conn id and Host"
},
{
"code": null,
"e": 9966,
"s": 9939,
"text": "conn_id = slack_connection"
},
{
"code": null,
"e": 9990,
"s": 9966,
"text": "host = your webhook URL"
},
{
"code": null,
"e": 10129,
"s": 9990,
"text": "If you don’t want to wait for the scheduled interval to observe the results, manually trigger a DAG run by hitting the Trigger DAG button."
},
{
"code": null,
"e": 10257,
"s": 10129,
"text": "After the task runs successfully, this message appears in Slack. Today’s forecast is clear sk(ies), which sounds about right ☀️"
},
{
"code": null,
"e": 10336,
"s": 10257,
"text": "Awesome! Say goodbye to weather networks and hello to programmatic forecasts 😃"
},
{
"code": null,
"e": 10416,
"s": 10336,
"text": "To get the weather forecast every single day, leave the Airflow server running."
},
{
"code": null,
"e": 10563,
"s": 10416,
"text": "I hope you found this article helpful. For additional Airflow resources, check out the official documentation which is a very comprehensive guide."
},
{
"code": null,
"e": 10586,
"s": 10563,
"text": "airflow.readthedocs.io"
},
{
"code": null,
"e": 10632,
"s": 10586,
"text": "Follow me on Medium for the latest updates. 😃"
},
{
"code": null,
"e": 10767,
"s": 10632,
"text": "I am also building a comprehensive set of free Data Science lessons and practice problems at www.dscrashcourse.com as a hobby project."
}
]
|
How to update all the entries except a single value in a particular column using MySQL? | To update all the entries while ignoring a single value, you need to use IF().
Let us first create a table −
mysql> create table DemoTable736 (
CustomerId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
CustomerName varchar(100),
isMarried boolean
);
Query OK, 0 rows affected (0.53 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable736(CustomerName,isMarried) values('Chris',0);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable736(CustomerName,isMarried) values('Robert',0);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable736(CustomerName,isMarried) values('David',0);
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable736(CustomerName,isMarried) values('Mike',0);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable736(CustomerName,isMarried) values('Carol',1);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable736(CustomerName,isMarried) values('Bob',0);
Query OK, 1 row affected (0.20 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable736;
This will produce the following output -
+------------+--------------+-----------+
| CustomerId | CustomerName | isMarried |
+------------+--------------+-----------+
| 1 | Chris | 0 |
| 2 | Robert | 0 |
| 3 | David | 0 |
| 4 | Mike | 0 |
| 5 | Carol | 1 |
| 6 | Bob | 0 |
+------------+--------------+-----------+
6 rows in set (0.00 sec)
Following is the query to update all the entries except a single value in a particular column using MySQL. Here, we are updating the “isMarried” column −
mysql> update DemoTable736 set isMarried=if(CustomerId=5,1,1);
Query OK, 5 rows affected (0.13 sec)
Rows matched: 6 Changed: 5 Warnings: 0
Let us check table records once again −
mysql> select *from DemoTable736;
This will produce the following output -
+------------+--------------+-----------+
| CustomerId | CustomerName | isMarried |
+------------+--------------+-----------+
| 1 | Chris | 1 |
| 2 | Robert | 1 |
| 3 | David | 1 |
| 4 | Mike | 1 |
| 5 | Carol | 1 |
| 6 | Bob | 1 |
+------------+--------------+-----------+
6 rows in set (0.00 sec) | [
{
"code": null,
"e": 1141,
"s": 1062,
"text": "To update all the entries while ignoring a single value, you need to use IF()."
},
{
"code": null,
"e": 1171,
"s": 1141,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1352,
"s": 1171,
"text": "mysql> create table DemoTable736 (\n CustomerId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n CustomerName varchar(100),\n isMarried boolean\n);\nQuery OK, 0 rows affected (0.53 sec)"
},
{
"code": null,
"e": 1408,
"s": 1352,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 2072,
"s": 1408,
"text": "mysql> insert into DemoTable736(CustomerName,isMarried) values('Chris',0);\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into DemoTable736(CustomerName,isMarried) values('Robert',0);\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable736(CustomerName,isMarried) values('David',0);\nQuery OK, 1 row affected (0.24 sec)\nmysql> insert into DemoTable736(CustomerName,isMarried) values('Mike',0);\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into DemoTable736(CustomerName,isMarried) values('Carol',1);\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into DemoTable736(CustomerName,isMarried) values('Bob',0);\nQuery OK, 1 row affected (0.20 sec)"
},
{
"code": null,
"e": 2132,
"s": 2072,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 2166,
"s": 2132,
"text": "mysql> select *from DemoTable736;"
},
{
"code": null,
"e": 2207,
"s": 2166,
"text": "This will produce the following output -"
},
{
"code": null,
"e": 2652,
"s": 2207,
"text": "+------------+--------------+-----------+\n| CustomerId | CustomerName | isMarried |\n+------------+--------------+-----------+\n| 1 | Chris | 0 |\n| 2 | Robert | 0 |\n| 3 | David | 0 |\n| 4 | Mike | 0 |\n| 5 | Carol | 1 |\n| 6 | Bob | 0 |\n+------------+--------------+-----------+\n6 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2806,
"s": 2652,
"text": "Following is the query to update all the entries except a single value in a particular column using MySQL. Here, we are updating the “isMarried” column −"
},
{
"code": null,
"e": 2945,
"s": 2806,
"text": "mysql> update DemoTable736 set isMarried=if(CustomerId=5,1,1);\nQuery OK, 5 rows affected (0.13 sec)\nRows matched: 6 Changed: 5 Warnings: 0"
},
{
"code": null,
"e": 2985,
"s": 2945,
"text": "Let us check table records once again −"
},
{
"code": null,
"e": 3019,
"s": 2985,
"text": "mysql> select *from DemoTable736;"
},
{
"code": null,
"e": 3060,
"s": 3019,
"text": "This will produce the following output -"
},
{
"code": null,
"e": 3505,
"s": 3060,
"text": "+------------+--------------+-----------+\n| CustomerId | CustomerName | isMarried |\n+------------+--------------+-----------+\n| 1 | Chris | 1 |\n| 2 | Robert | 1 |\n| 3 | David | 1 |\n| 4 | Mike | 1 |\n| 5 | Carol | 1 |\n| 6 | Bob | 1 |\n+------------+--------------+-----------+\n6 rows in set (0.00 sec)"
}
]
|
Final variables in C# | Java has a final keyword, but C# does not have its implementation. Use the sealed or readonly keyword in C# for the same implementation.
The readonly would allow the variables to be assigned a value only once. A field marked "read-only", can only be set once during the construction of an object. It cannot be changed.
class Employee {
readonly int age;
Employee(int age) {
this.age = age;
}
void ChangeAge() {
//age = 27; // Compile error
}
}
Above, we have set the age field as readonly, which once assigned cannot be changed. | [
{
"code": null,
"e": 1199,
"s": 1062,
"text": "Java has a final keyword, but C# does not have its implementation. Use the sealed or readonly keyword in C# for the same implementation."
},
{
"code": null,
"e": 1381,
"s": 1199,
"text": "The readonly would allow the variables to be assigned a value only once. A field marked \"read-only\", can only be set once during the construction of an object. It cannot be changed."
},
{
"code": null,
"e": 1538,
"s": 1381,
"text": "class Employee {\n readonly int age;\n\n Employee(int age) {\n this.age = age;\n }\n\n void ChangeAge() {\n //age = 27; // Compile error\n }\n}"
},
{
"code": null,
"e": 1623,
"s": 1538,
"text": "Above, we have set the age field as readonly, which once assigned cannot be changed."
}
]
|
Rat in a Maze Problem - I | Practice | GeeksforGeeks | Consider a rat placed at (0, 0) in a square matrix of order N * N. It has to reach the destination at (N - 1, N - 1). Find all possible paths that the rat can take to reach from source to destination. The directions in which the rat can move are 'U'(up), 'D'(down), 'L' (left), 'R' (right). Value 0 at a cell in the matrix represents that it is blocked and rat cannot move to it while value 1 at a cell in the matrix represents that rat can be travel through it.
Note: In a path, no cell can be visited more than one time. If the source cell is 0, the rat cannot move to any other cell.
Example 1:
Input:
N = 4
m[][] = {{1, 0, 0, 0},
{1, 1, 0, 1},
{1, 1, 0, 0},
{0, 1, 1, 1}}
Output:
DDRDRR DRDDRR
Explanation:
The rat can reach the destination at
(3, 3) from (0, 0) by two paths - DRDDRR
and DDRDRR, when printed in sorted order
we get DDRDRR DRDDRR.
Input:
N = 2
m[][] = {{1, 0},
{1, 0}}
Output:
-1
Explanation:
No path exists and destination cell is
blocked.
Your Task:
You don't need to read input or print anything. Complete the function printPath() which takes N and 2D array m[ ][ ] as input parameters and returns the list of paths in lexicographically increasing order.
Note: In case of no path, return an empty list. The driver will output "-1" automatically.
Expected Time Complexity: O((3N^2)).
Expected Auxiliary Space: O(L * X), L = length of the path, X = number of paths.
Constraints:
2 ≤ N ≤ 5
0 ≤ m[i][j] ≤ 1
0
bhattpawan19973 hours ago
Please let m know why this solution is not passing:
// { Driver Code Starts// Initial Template for Java
import java.util.*;class Rat { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt();
while (t-- > 0) { int n = sc.nextInt(); int[][] a = new int[n][n]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) a[i][j] = sc.nextInt();
Solution obj = new Solution(); ArrayList<String> res = obj.findPath(a, n); Collections.sort(res); if (res.size() > 0) { for (int i = 0; i < res.size(); i++) System.out.print(res.get(i) + " "); System.out.println(); } else { System.out.println(-1); } } }}// } Driver Code Ends
// User function Template for Java
// m is the given matrix and n is the order of matrixclass Solution { static ArrayList<String> res = new ArrayList<>(); private static void findPathHelper(int[][]m, int row, int col, int n, String path, boolean[][] visited){ if(row < 0 || col < 0 || row == n || col == n || m[row][col] == 0 || visited[row][col] == true){ return; } if(row == n-1 && col == n-1){ res.add(path); return; } visited[row][col] = true; findPathHelper(m,row+1,col,n,path+'D',visited); findPathHelper(m,row,col-1,n,path+'L',visited); findPathHelper(m,row,col+1,n,path+'R',visited); findPathHelper(m,row-1,col,n,path+'U',visited); visited[row][col] = false; } public static ArrayList<String> findPath(int[][] m, int n) { boolean[][] visited = new boolean[n][n]; findPathHelper(m,0,0,n,"",visited); return res; }}
+1
jainmuskan5656 days ago
void solve(int i,int j,string move,vector<string>&res,vector<vector<int>> &m,vector<vector<int>>&visited,int n){
if(i==n-1 && j==n-1){
res.push_back(move);
return;
}
if(i<0 || j<0 || i>n-1 ||j>n-1){
return;
}
// base cases
if(visited[i][j]==1 || m[i][j]==0){
return;
}
// down left right up (sorted order traversal)
visited[i][j]=1;
solve(i+1,j,move+"D",res,m,visited,n);
solve(i,j-1,move+"L",res,m,visited,n);
solve(i,j+1,move+"R",res,m,visited,n);
solve(i-1,j,move+"U",res,m,visited,n);
// backtracking step unvisit the position
visited[i][j]=0;
}
vector<string> findPath(vector<vector<int>> &m, int n) {
vector<vector<int>> visited(n,vector<int>(n,0));
vector<string> res;
if(m[0][0]==0 || m[n-1][n-1]==0){
return res;
}
solve(0,0,"",res,m,visited,n);
return res;
}
0
harshmaheshwari1 week ago
simple recursion and backtracking
vector<string> findPath(vector<vector<int>> &m, int n) {
// Your code goes here
vector<string> ans;
findans(m,n,0,0,ans,"");
if(ans.size()==0) return {"-1"};
return ans;
}
void findans(vector<vector<int>> &m,int n, int i,int j, vector<string> &ans,string temp)
{
if(i>n-1 )
return;
if(j>n-1)
return;
if(j<0)
return;
if(i<0)
return;
if(m[i][j]==0)
return ;
if(i==n-1 && j==n-1)
{
ans.push_back(temp);
return ;
}
if(m[i][j]==1)
{
m[i][j]=0;
findans(m, n, i+1,j ,ans, temp+"D");
findans(m, n, i,j+1 ,ans, temp+"R");
findans(m, n, i-1,j,ans, temp+"U");
findans(m, n, i,j-1, ans, temp+"L");
m[i][j] =1;
}
}
-1
shashank28931 week ago
#Python Working Code: Basic backtracking, if any neighbor is #1, move to the next neighbor and color the current neighbor #as -1.
class Solution:
def findPath(self, m, n):
# code here
# Edge case, the starting point is zero, not clear in question
if m[0][0] == 0:
return ['-1']
self.ans, self.n = [], n
self.dirs = {'R':[0,1],
'D': [1,0],
'L': [0, -1],
'U':[-1, 0]
}
self.helper(m, 0, 0, '')
if self.ans:
return self.ans
else:
return ['-1']
def helper(self, m, x, y, path):
if x == self.n - 1 and y == self.n - 1:
self.ans.append(path)
m[x][y] = 1
return
for d, val in self.dirs.items():
x_next, y_next = x+val[0], y+val[1]
if 0 <= x_next < self.n and 0<= y_next < self.n and m[x_next][y_next] == 1:
m[x][y] = -1
self.helper(m, x_next, y_next, path + d)
if m[x][y] == -1:
m[x][y] = 1
0
shubhamkavia19981 week ago
Can you tell the error
Thank You!
class Solution{
public:
vector<string>res;string str="";
void dfs(vector<vector<int>> &m,int i,int j,int row,int col)
{
if(i==(row-1) && j==(col-1)){ res.push_back(str); str=""; return;}
if(valid(m,i,j,row,col))
{ m[i][j]=2;
dfs(m,i,j+1,row,col);str+='R';
dfs(m,i,j-1,row,col);str+='L';
dfs(m,i+1,j,row,col);str+='D';
dfs(m,i-1,j,row,col);str+='U';
m[i][j]=1;
int p=str.size();
str = str.substr(0,p-2);
}
}
bool valid(vector<vector<int>> &m,int i,int j,int row,int col)
{
if(i<0||j<0||i>=row||j>=col)return false;
else
{
if(m[i][j]==1)
return true;
else if(m[i][j]==0 || m[i][j]==2)
return false;
}
}
vector<string> findPath(vector<vector<int>> &m, int n) {
vector<string>gas;
gas.push_back("-1");
int row= m.size();int col=m[0].size();
dfs(m,0,0,row,col);
sort(res.begin(),res.end());
if(res.empty()==0)
return gas;
return res;
}
};
0
shubhamkavia1998
This comment was deleted.
+1
himanshu0719cse192 weeks ago
public static void helper(int[][] m,int n,String s,ArrayList<String>ans,int row,int col,boolean[][]visited) { //System.out.println(s); if(row==n-1&&col==n-1) { ans.add(s); return; } visited[row][col]=true; int[]x={0,0,1,-1}; int[]y={1,-1,0,0}; char[]dir={'R','L','D','U'}; for(int i=0;i<4;i++) { int row1=row+x[i]; int col1=col+y[i]; boolean valid=row1>=0&&row1<n&&col1>=0&&col1<n&&!visited[row1][col1]&&m[row1][col1]!=0; if(valid) { helper(m,n,s+dir[i],ans,row1,col1,visited); } } visited[row][col]=false; } public static ArrayList<String> findPath(int[][] m, int n) { ArrayList<String>ans=new ArrayList<>(); if(m[0][0]==0) { return ans; } boolean[][]visited=new boolean[n][n]; String s=""; helper(m,n,s,ans,0,0,visited); return ans; }
0
psadv
This comment was deleted.
+4
soniwalsushil242 weeks ago
JAVA MOST SIMPLE SOLUTION WITH COMMENTS.
class Solution {
static ArrayList<String> res = new ArrayList<>(); // Static arrayList. static ArrayList<String> findPath(int[][] maze, int n) { res.clear(); // If source or destination is a obstacle. if (maze[0][0] == 0 || maze[n - 1][n - 1] == 0) { return res; } printPath("", maze, 0, 0, n); return res; } static void printPath(String ans, int[][] maze, int row, int col, int n) { // Base Condition. if (row == n - 1 && col == n - 1) { res.add(ans); return; } // Can't go. if (maze[row][col] == 0) { return; } // Consider This Cell In My Path. maze[row][col] = 0; // To Travel Down. if (row < n - 1) { printPath(ans + 'D', maze, row + 1, col, n); } // To Travel Right. if (col < n - 1) { printPath(ans + 'R', maze, row, col + 1, n); } // To Travel Up. if (row > 0) { printPath(ans + 'U', maze, row - 1, col, n); } // To Travel Left. if (col > 0) { printPath(ans + 'L', maze, row, col - 1, n); } // BackTrack:- Remove The Changes That We Were Made. maze[row][col] = 1; }}
+1
moaslam8263 weeks ago
c++ soln
void fun(vector<vector<int>>&m,vector<string> &ans,int row,int col,int max_row,int max_col,string str){
if(row==max_row-1 && col==max_col-1){
ans.push_back(str);
return;
}
//upward validaton
if(row-1>=0 &&m[row-1][col]!=0){
string t=str;
t.push_back('U');
m[row][col]=0;
fun(m,ans,row-1,col,max_row,max_col,t);
m[row][col]=1;
}
//dowanward validation
if(row+1<max_row && m[row+1][col]!=0){
string t=str;
t.push_back('D');
m[row][col]=0;
fun(m,ans,row+1,col,max_row,max_col,t);
m[row][col]=1;
}
//for left validation
if(col-1>=0 && m[row][col-1]!=0){
string t=str;
t.push_back('L');
m[row][col]=0;
fun(m,ans,row,col-1,max_row,max_col,t);
m[row][col]=1;
}
//for right validation
if(col+1<max_col && m[row][col+1]!=0){
string t=str;
t.push_back('R');
m[row][col]=0;
fun(m,ans,row,col+1,max_row,max_col,t);
m[row][col]=1;
}
}
vector<string> findPath(vector<vector<int>> &m, int n) {
if(m[n-1][n-1]==0) return {"-1"};
if(m[0][0]==0) return {"-1"};
vector<string> s;
fun(m,s,0,0,n,n,"");
if(s.size()==0) return {"-1"};
return s;
}
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": 825,
"s": 238,
"text": "Consider a rat placed at (0, 0) in a square matrix of order N * N. It has to reach the destination at (N - 1, N - 1). Find all possible paths that the rat can take to reach from source to destination. The directions in which the rat can move are 'U'(up), 'D'(down), 'L' (left), 'R' (right). Value 0 at a cell in the matrix represents that it is blocked and rat cannot move to it while value 1 at a cell in the matrix represents that rat can be travel through it.\nNote: In a path, no cell can be visited more than one time. If the source cell is 0, the rat cannot move to any other cell."
},
{
"code": null,
"e": 836,
"s": 825,
"text": "Example 1:"
},
{
"code": null,
"e": 1121,
"s": 836,
"text": "Input:\nN = 4\nm[][] = {{1, 0, 0, 0},\n {1, 1, 0, 1}, \n {1, 1, 0, 0},\n {0, 1, 1, 1}}\nOutput:\nDDRDRR DRDDRR\nExplanation:\nThe rat can reach the destination at \n(3, 3) from (0, 0) by two paths - DRDDRR \nand DDRDRR, when printed in sorted order \nwe get DDRDRR DRDDRR."
},
{
"code": null,
"e": 1242,
"s": 1121,
"text": "Input:\nN = 2\nm[][] = {{1, 0},\n {1, 0}}\nOutput:\n-1\nExplanation:\nNo path exists and destination cell is \nblocked.\n"
},
{
"code": null,
"e": 1553,
"s": 1242,
"text": "Your Task: \nYou don't need to read input or print anything. Complete the function printPath() which takes N and 2D array m[ ][ ] as input parameters and returns the list of paths in lexicographically increasing order. \nNote: In case of no path, return an empty list. The driver will output \"-1\" automatically."
},
{
"code": null,
"e": 1671,
"s": 1553,
"text": "Expected Time Complexity: O((3N^2)).\nExpected Auxiliary Space: O(L * X), L = length of the path, X = number of paths."
},
{
"code": null,
"e": 1710,
"s": 1671,
"text": "Constraints:\n2 ≤ N ≤ 5\n0 ≤ m[i][j] ≤ 1"
},
{
"code": null,
"e": 1712,
"s": 1710,
"text": "0"
},
{
"code": null,
"e": 1738,
"s": 1712,
"text": "bhattpawan19973 hours ago"
},
{
"code": null,
"e": 1790,
"s": 1738,
"text": "Please let m know why this solution is not passing:"
},
{
"code": null,
"e": 1844,
"s": 1792,
"text": "// { Driver Code Starts// Initial Template for Java"
},
{
"code": null,
"e": 1989,
"s": 1844,
"text": "import java.util.*;class Rat { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt();"
},
{
"code": null,
"e": 2187,
"s": 1989,
"text": " while (t-- > 0) { int n = sc.nextInt(); int[][] a = new int[n][n]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) a[i][j] = sc.nextInt();"
},
{
"code": null,
"e": 2592,
"s": 2187,
"text": " Solution obj = new Solution(); ArrayList<String> res = obj.findPath(a, n); Collections.sort(res); if (res.size() > 0) { for (int i = 0; i < res.size(); i++) System.out.print(res.get(i) + \" \"); System.out.println(); } else { System.out.println(-1); } } }}// } Driver Code Ends"
},
{
"code": null,
"e": 2627,
"s": 2592,
"text": "// User function Template for Java"
},
{
"code": null,
"e": 3583,
"s": 2627,
"text": "// m is the given matrix and n is the order of matrixclass Solution { static ArrayList<String> res = new ArrayList<>(); private static void findPathHelper(int[][]m, int row, int col, int n, String path, boolean[][] visited){ if(row < 0 || col < 0 || row == n || col == n || m[row][col] == 0 || visited[row][col] == true){ return; } if(row == n-1 && col == n-1){ res.add(path); return; } visited[row][col] = true; findPathHelper(m,row+1,col,n,path+'D',visited); findPathHelper(m,row,col-1,n,path+'L',visited); findPathHelper(m,row,col+1,n,path+'R',visited); findPathHelper(m,row-1,col,n,path+'U',visited); visited[row][col] = false; } public static ArrayList<String> findPath(int[][] m, int n) { boolean[][] visited = new boolean[n][n]; findPathHelper(m,0,0,n,\"\",visited); return res; }}"
},
{
"code": null,
"e": 3586,
"s": 3583,
"text": "+1"
},
{
"code": null,
"e": 3610,
"s": 3586,
"text": "jainmuskan5656 days ago"
},
{
"code": null,
"e": 4620,
"s": 3610,
"text": "void solve(int i,int j,string move,vector<string>&res,vector<vector<int>> &m,vector<vector<int>>&visited,int n){\n if(i==n-1 && j==n-1){\n res.push_back(move);\n return;\n }\n if(i<0 || j<0 || i>n-1 ||j>n-1){\n return;\n }\n // base cases \n if(visited[i][j]==1 || m[i][j]==0){\n return;\n }\n // down left right up (sorted order traversal)\n visited[i][j]=1;\n solve(i+1,j,move+\"D\",res,m,visited,n);\n solve(i,j-1,move+\"L\",res,m,visited,n);\n solve(i,j+1,move+\"R\",res,m,visited,n);\n solve(i-1,j,move+\"U\",res,m,visited,n);\n // backtracking step unvisit the position\n visited[i][j]=0;\n }\n vector<string> findPath(vector<vector<int>> &m, int n) {\n vector<vector<int>> visited(n,vector<int>(n,0));\n vector<string> res;\n if(m[0][0]==0 || m[n-1][n-1]==0){\n return res;\n }\n solve(0,0,\"\",res,m,visited,n);\n return res;\n }"
},
{
"code": null,
"e": 4622,
"s": 4620,
"text": "0"
},
{
"code": null,
"e": 4648,
"s": 4622,
"text": "harshmaheshwari1 week ago"
},
{
"code": null,
"e": 4682,
"s": 4648,
"text": "simple recursion and backtracking"
},
{
"code": null,
"e": 5625,
"s": 4682,
"text": " vector<string> findPath(vector<vector<int>> &m, int n) {\n // Your code goes here\n vector<string> ans;\n findans(m,n,0,0,ans,\"\");\n if(ans.size()==0) return {\"-1\"};\n return ans;\n \n }\n void findans(vector<vector<int>> &m,int n, int i,int j, vector<string> &ans,string temp)\n {\n \n \n if(i>n-1 )\n return;\n if(j>n-1)\n return;\n if(j<0)\n return;\n if(i<0)\n return;\n \n if(m[i][j]==0)\n return ;\n \n if(i==n-1 && j==n-1)\n {\n ans.push_back(temp);\n return ;\n }\n \n if(m[i][j]==1)\n {\n m[i][j]=0;\n findans(m, n, i+1,j ,ans, temp+\"D\");\n findans(m, n, i,j+1 ,ans, temp+\"R\");\n findans(m, n, i-1,j,ans, temp+\"U\");\n findans(m, n, i,j-1, ans, temp+\"L\");\n m[i][j] =1;\n }\n \n }"
},
{
"code": null,
"e": 5628,
"s": 5625,
"text": "-1"
},
{
"code": null,
"e": 5651,
"s": 5628,
"text": "shashank28931 week ago"
},
{
"code": null,
"e": 6771,
"s": 5651,
"text": "#Python Working Code: Basic backtracking, if any neighbor is #1, move to the next neighbor and color the current neighbor #as -1. \n\nclass Solution:\n def findPath(self, m, n):\n # code here\n # Edge case, the starting point is zero, not clear in question\n if m[0][0] == 0:\n return ['-1']\n \n self.ans, self.n = [], n\n \n self.dirs = {'R':[0,1], \n 'D': [1,0], \n 'L': [0, -1], \n 'U':[-1, 0]\n \n }\n \n self.helper(m, 0, 0, '')\n if self.ans:\n return self.ans\n else:\n return ['-1']\n \n def helper(self, m, x, y, path):\n if x == self.n - 1 and y == self.n - 1:\n self.ans.append(path)\n m[x][y] = 1\n return\n \n for d, val in self.dirs.items():\n x_next, y_next = x+val[0], y+val[1]\n if 0 <= x_next < self.n and 0<= y_next < self.n and m[x_next][y_next] == 1:\n m[x][y] = -1\n self.helper(m, x_next, y_next, path + d)\n \n if m[x][y] == -1:\n m[x][y] = 1"
},
{
"code": null,
"e": 6773,
"s": 6771,
"text": "0"
},
{
"code": null,
"e": 6800,
"s": 6773,
"text": "shubhamkavia19981 week ago"
},
{
"code": null,
"e": 6823,
"s": 6800,
"text": "Can you tell the error"
},
{
"code": null,
"e": 6834,
"s": 6823,
"text": "Thank You!"
},
{
"code": null,
"e": 7988,
"s": 6836,
"text": "class Solution{\n public:\n vector<string>res;string str=\"\";\n\n void dfs(vector<vector<int>> &m,int i,int j,int row,int col)\n { \n if(i==(row-1) && j==(col-1)){ res.push_back(str); str=\"\"; return;}\n if(valid(m,i,j,row,col))\n { m[i][j]=2;\n dfs(m,i,j+1,row,col);str+='R';\n dfs(m,i,j-1,row,col);str+='L';\n dfs(m,i+1,j,row,col);str+='D';\n dfs(m,i-1,j,row,col);str+='U';\n m[i][j]=1;\n int p=str.size();\n str = str.substr(0,p-2);\n }\n }\n \n bool valid(vector<vector<int>> &m,int i,int j,int row,int col)\n {\n if(i<0||j<0||i>=row||j>=col)return false;\n else \n {\n if(m[i][j]==1)\n return true;\n else if(m[i][j]==0 || m[i][j]==2)\n return false;\n }\n }\n vector<string> findPath(vector<vector<int>> &m, int n) {\n vector<string>gas;\n gas.push_back(\"-1\");\n int row= m.size();int col=m[0].size();\n dfs(m,0,0,row,col);\n sort(res.begin(),res.end());\n if(res.empty()==0)\n return gas;\n return res;\n \n }\n};"
},
{
"code": null,
"e": 7990,
"s": 7988,
"text": "0"
},
{
"code": null,
"e": 8007,
"s": 7990,
"text": "shubhamkavia1998"
},
{
"code": null,
"e": 8033,
"s": 8007,
"text": "This comment was deleted."
},
{
"code": null,
"e": 8036,
"s": 8033,
"text": "+1"
},
{
"code": null,
"e": 8065,
"s": 8036,
"text": "himanshu0719cse192 weeks ago"
},
{
"code": null,
"e": 9034,
"s": 8065,
"text": "public static void helper(int[][] m,int n,String s,ArrayList<String>ans,int row,int col,boolean[][]visited) { //System.out.println(s); if(row==n-1&&col==n-1) { ans.add(s); return; } visited[row][col]=true; int[]x={0,0,1,-1}; int[]y={1,-1,0,0}; char[]dir={'R','L','D','U'}; for(int i=0;i<4;i++) { int row1=row+x[i]; int col1=col+y[i]; boolean valid=row1>=0&&row1<n&&col1>=0&&col1<n&&!visited[row1][col1]&&m[row1][col1]!=0; if(valid) { helper(m,n,s+dir[i],ans,row1,col1,visited); } } visited[row][col]=false; } public static ArrayList<String> findPath(int[][] m, int n) { ArrayList<String>ans=new ArrayList<>(); if(m[0][0]==0) { return ans; } boolean[][]visited=new boolean[n][n]; String s=\"\"; helper(m,n,s,ans,0,0,visited); return ans; }"
},
{
"code": null,
"e": 9036,
"s": 9034,
"text": "0"
},
{
"code": null,
"e": 9042,
"s": 9036,
"text": "psadv"
},
{
"code": null,
"e": 9068,
"s": 9042,
"text": "This comment was deleted."
},
{
"code": null,
"e": 9071,
"s": 9068,
"text": "+4"
},
{
"code": null,
"e": 9098,
"s": 9071,
"text": "soniwalsushil242 weeks ago"
},
{
"code": null,
"e": 9139,
"s": 9098,
"text": "JAVA MOST SIMPLE SOLUTION WITH COMMENTS."
},
{
"code": null,
"e": 9158,
"s": 9141,
"text": "class Solution {"
},
{
"code": null,
"e": 10411,
"s": 9158,
"text": "static ArrayList<String> res = new ArrayList<>(); // Static arrayList. static ArrayList<String> findPath(int[][] maze, int n) { res.clear(); // If source or destination is a obstacle. if (maze[0][0] == 0 || maze[n - 1][n - 1] == 0) { return res; } printPath(\"\", maze, 0, 0, n); return res; } static void printPath(String ans, int[][] maze, int row, int col, int n) { // Base Condition. if (row == n - 1 && col == n - 1) { res.add(ans); return; } // Can't go. if (maze[row][col] == 0) { return; } // Consider This Cell In My Path. maze[row][col] = 0; // To Travel Down. if (row < n - 1) { printPath(ans + 'D', maze, row + 1, col, n); } // To Travel Right. if (col < n - 1) { printPath(ans + 'R', maze, row, col + 1, n); } // To Travel Up. if (row > 0) { printPath(ans + 'U', maze, row - 1, col, n); } // To Travel Left. if (col > 0) { printPath(ans + 'L', maze, row, col - 1, n); } // BackTrack:- Remove The Changes That We Were Made. maze[row][col] = 1; }}"
},
{
"code": null,
"e": 10414,
"s": 10411,
"text": "+1"
},
{
"code": null,
"e": 10436,
"s": 10414,
"text": "moaslam8263 weeks ago"
},
{
"code": null,
"e": 10445,
"s": 10436,
"text": "c++ soln"
},
{
"code": null,
"e": 11696,
"s": 10445,
"text": "void fun(vector<vector<int>>&m,vector<string> &ans,int row,int col,int max_row,int max_col,string str){\n\n\tif(row==max_row-1 && col==max_col-1){\n ans.push_back(str);\n return;\n\t}\n //upward validaton\n if(row-1>=0 &&m[row-1][col]!=0){\n \t\n \tstring t=str;\n \tt.push_back('U');\n \tm[row][col]=0;\n \tfun(m,ans,row-1,col,max_row,max_col,t);\n \tm[row][col]=1;\n }\n //dowanward validation\n if(row+1<max_row && m[row+1][col]!=0){\n \tstring t=str;\n \tt.push_back('D');\n \tm[row][col]=0;\n \tfun(m,ans,row+1,col,max_row,max_col,t);\n \tm[row][col]=1;\n }\n //for left validation\n if(col-1>=0 && m[row][col-1]!=0){\n\n \tstring t=str;\n \tt.push_back('L');\n \tm[row][col]=0;\n \tfun(m,ans,row,col-1,max_row,max_col,t);\n \tm[row][col]=1;\n }\n //for right validation \n if(col+1<max_col && m[row][col+1]!=0){\n \tstring t=str;\n \tt.push_back('R');\n \tm[row][col]=0;\n \tfun(m,ans,row,col+1,max_row,max_col,t);\n \tm[row][col]=1;\n }\n}\n\n vector<string> findPath(vector<vector<int>> &m, int n) {\n if(m[n-1][n-1]==0) return {\"-1\"};\n if(m[0][0]==0) return {\"-1\"};\n vector<string> s;\n fun(m,s,0,0,n,n,\"\");\n if(s.size()==0) return {\"-1\"};\n return s;\n }"
},
{
"code": null,
"e": 11842,
"s": 11696,
"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": 11878,
"s": 11842,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 11888,
"s": 11878,
"text": "\nProblem\n"
},
{
"code": null,
"e": 11898,
"s": 11888,
"text": "\nContest\n"
},
{
"code": null,
"e": 11961,
"s": 11898,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 12109,
"s": 11961,
"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": 12317,
"s": 12109,
"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": 12423,
"s": 12317,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
]
|
Maximum frequency of any array element possible by at most K increments - GeeksforGeeks | 13 Jul, 2021
Given an array arr[] of size N and an integer K, the task is to find the maximum possible frequency of any array element by at most K increments.
Examples:
Input: arr[] = {1, 4, 8, 13}, N = 4, K = 5 Output: 2 Explanation: Incrementing arr[0] twice modifies arr[] to {4, 4, 8, 13}. Maximum frequency = 2. Incrementing arr[1] four times modifies arr[] to {1, 8, 8, 13}. Maximum frequency = 2. Incrementing arr[2] five times modifies arr[] to {1, 4, 13, 13}. Maximum frequency = 2. Therefore, the maximum possible frequency of any array element that can be obtained by at most 5 increments is 2.
Input: arr[] = {2, 4, 5}, N = 3, K = 4 Output: 3
Approach: This problem can be solved by using Sliding Window Technique and Sorting. Follow the steps to solve this problem.
Sort the array arr[].
Initialize variables sum = 0, start = 0 and resultant frequency res = 0.
Traverse the array over the range of indices [0, N – 1] and perform the following steps:Increment sum by arr[end].Iterate a loop until the value of [(end – start + 1) * arr[end] – sum] is less than K and perform the following operatiosn: Decrement the value of sum by arr[start].Increment the value of start by 1.After completing the above steps, all the elements over the range [start, end] can be made equal by using at most K operations. Therefore, update the value of res as the maximum of res and (end – start + 1).
Increment sum by arr[end].
Iterate a loop until the value of [(end – start + 1) * arr[end] – sum] is less than K and perform the following operatiosn: Decrement the value of sum by arr[start].Increment the value of start by 1.
Decrement the value of sum by arr[start].
Increment the value of start by 1.
After completing the above steps, all the elements over the range [start, end] can be made equal by using at most K operations. Therefore, update the value of res as the maximum of res and (end – start + 1).
Finally, print the value of res as frequency of most frequent element after performing Koperations.
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; // Function to find the maximum possible// frequency of a most frequent element// after at most K increment operationsvoid maxFrequency(int arr[], int N, int K){ // Sort the input array sort(arr, arr + N); int start = 0, end = 0; // Stores the sum of sliding // window and the maximum possible // frequency of any array element int sum = 0, res = 0; // Traverse the array for (end = 0; end < N; end++) { // Add the current element // to the window sum += arr[end]; // Decrease the window size // If it is not possible to make the // array elements in the window equal while ((end - start + 1) * arr[end] - sum > K) { // Update the value of sum sum -= arr[start]; // Increment the value of start start++; } // Update the maximum possible frequency res = max(res, end - start + 1); } // Print the frequency of // the most frequent array // element after K increments cout << res << endl;} // Driver codeint main(){ int arr[] = { 1, 4, 8, 13 }; int N = 4; int K = 5; maxFrequency(arr, N, K); return 0;}
// Java program for the above approachimport java.util.Arrays; class GFG{ // Function to find the maximum possible// frequency of a most frequent element// after at most K increment operationsstatic void maxFrequency(int arr[], int N, int K){ // Sort the input array Arrays.sort(arr); int start = 0, end = 0; // Stores the sum of sliding // window and the maximum possible // frequency of any array element int sum = 0, res = 0; // Traverse the array for(end = 0; end < N; end++) { // Add the current element // to the window sum += arr[end]; // Decrease the window size // If it is not possible to make the // array elements in the window equal while ((end - start + 1) * arr[end] - sum > K) { // Update the value of sum sum -= arr[start]; // Increment the value of start start++; } // Update the maximum possible frequency res = Math.max(res, end - start + 1); } // Print the frequency of // the most frequent array // element after K increments System.out.println(res);} // Driver codepublic static void main(String[] args){ int arr[] = { 1, 4, 8, 13 }; int N = 4; int K = 5; maxFrequency(arr, N, K);}} // This code is contributed by abhinavjain194
# Python3 program for the above approach # Function to find the maximum possible# frequency of a most frequent element# after at most K increment operationsdef maxFrequency(arr, N, K): # Sort the input array arr.sort() start = 0 end = 0 # Stores the sum of sliding # window and the maximum possible # frequency of any array element sum = 0 res = 0 # Traverse the array for end in range(N): # Add the current element # to the window sum += arr[end] # Decrease the window size # If it is not possible to make the # array elements in the window equal while ((end - start + 1) * arr[end] - sum > K): # Update the value of sum sum -= arr[start] # Increment the value of start start += 1 # Update the maximum possible frequency res = max(res, end - start + 1) # Print the frequency of # the most frequent array # element after K increments print(res) # Driver codeif __name__ == '__main__': arr = [ 1, 4, 8, 13 ] N = 4 K = 5 maxFrequency(arr, N, K) # This code is contributed by ipg2016107
// C# program for the above approachusing System; class GFG{ // Function to find the maximum possible// frequency of a most frequent element// after at most K increment operationsstatic void maxFrequency(int[] arr, int N, int K){ // Sort the input array Array.Sort(arr); int start = 0, end = 0; // Stores the sum of sliding // window and the maximum possible // frequency of any array element int sum = 0, res = 0; // Traverse the array for(end = 0; end < N; end++) { // Add the current element // to the window sum += arr[end]; // Decrease the window size // If it is not possible to make the // array elements in the window equal while ((end - start + 1) * arr[end] - sum > K) { // Update the value of sum sum -= arr[start]; // Increment the value of start start++; } // Update the maximum possible frequency res = Math.Max(res, end - start + 1); } // Print the frequency of // the most frequent array // element after K increments Console.WriteLine(res);} // Driver Codepublic static void Main(){ int[] arr = { 1, 4, 8, 13 }; int N = 4; int K = 5; maxFrequency(arr, N, K);}} // This code is contributed by code_hunt
<script> // JavaScript program for the above approach // Function to find the maximum possible// frequency of a most frequent element// after at most K increment operationsfunction maxFrequency(arr, N, K) { // Sort the input array arr.sort((a, b) => a - b); let start = 0, end = 0; // Stores the sum of sliding // window and the maximum possible // frequency of any array element let sum = 0, res = 0; // Traverse the array for (end = 0; end < N; end++) { // Add the current element // to the window sum += arr[end]; // Decrease the window size // If it is not possible to make the // array elements in the window equal while ((end - start + 1) * arr[end] - sum > K) { // Update the value of sum sum -= arr[start]; // Increment the value of start start++; } // Update the maximum possible frequency res = Math.max(res, end - start + 1); } // Print the frequency of // the most frequent array // element after K increments document.write(res + "<br>");} // Driver code let arr = [1, 4, 8, 13];let N = 4;let K = 5;maxFrequency(arr, N, K); </script>
2
Time Complexity: O(NlogN) Auxiliary Space: O(1)
abhinavjain194
code_hunt
ipg2016107
_saurabh_jaiswal
frequency-counting
Picked
sliding-window
Arrays
Mathematical
sliding-window
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Multidimensional Arrays in Java
Queue | Set 1 (Introduction and Array Implementation)
Linear Search
Python | Using 2D arrays/lists the right way
Maximum and minimum of an array using minimum number of comparisons
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": 24981,
"s": 24953,
"text": "\n13 Jul, 2021"
},
{
"code": null,
"e": 25127,
"s": 24981,
"text": "Given an array arr[] of size N and an integer K, the task is to find the maximum possible frequency of any array element by at most K increments."
},
{
"code": null,
"e": 25137,
"s": 25127,
"text": "Examples:"
},
{
"code": null,
"e": 25574,
"s": 25137,
"text": "Input: arr[] = {1, 4, 8, 13}, N = 4, K = 5 Output: 2 Explanation: Incrementing arr[0] twice modifies arr[] to {4, 4, 8, 13}. Maximum frequency = 2. Incrementing arr[1] four times modifies arr[] to {1, 8, 8, 13}. Maximum frequency = 2. Incrementing arr[2] five times modifies arr[] to {1, 4, 13, 13}. Maximum frequency = 2. Therefore, the maximum possible frequency of any array element that can be obtained by at most 5 increments is 2."
},
{
"code": null,
"e": 25623,
"s": 25574,
"text": "Input: arr[] = {2, 4, 5}, N = 3, K = 4 Output: 3"
},
{
"code": null,
"e": 25747,
"s": 25623,
"text": "Approach: This problem can be solved by using Sliding Window Technique and Sorting. Follow the steps to solve this problem."
},
{
"code": null,
"e": 25769,
"s": 25747,
"text": "Sort the array arr[]."
},
{
"code": null,
"e": 25842,
"s": 25769,
"text": "Initialize variables sum = 0, start = 0 and resultant frequency res = 0."
},
{
"code": null,
"e": 26363,
"s": 25842,
"text": "Traverse the array over the range of indices [0, N – 1] and perform the following steps:Increment sum by arr[end].Iterate a loop until the value of [(end – start + 1) * arr[end] – sum] is less than K and perform the following operatiosn: Decrement the value of sum by arr[start].Increment the value of start by 1.After completing the above steps, all the elements over the range [start, end] can be made equal by using at most K operations. Therefore, update the value of res as the maximum of res and (end – start + 1)."
},
{
"code": null,
"e": 26390,
"s": 26363,
"text": "Increment sum by arr[end]."
},
{
"code": null,
"e": 26590,
"s": 26390,
"text": "Iterate a loop until the value of [(end – start + 1) * arr[end] – sum] is less than K and perform the following operatiosn: Decrement the value of sum by arr[start].Increment the value of start by 1."
},
{
"code": null,
"e": 26632,
"s": 26590,
"text": "Decrement the value of sum by arr[start]."
},
{
"code": null,
"e": 26667,
"s": 26632,
"text": "Increment the value of start by 1."
},
{
"code": null,
"e": 26875,
"s": 26667,
"text": "After completing the above steps, all the elements over the range [start, end] can be made equal by using at most K operations. Therefore, update the value of res as the maximum of res and (end – start + 1)."
},
{
"code": null,
"e": 26975,
"s": 26875,
"text": "Finally, print the value of res as frequency of most frequent element after performing Koperations."
},
{
"code": null,
"e": 27026,
"s": 26975,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 27030,
"s": 27026,
"text": "C++"
},
{
"code": null,
"e": 27035,
"s": 27030,
"text": "Java"
},
{
"code": null,
"e": 27043,
"s": 27035,
"text": "Python3"
},
{
"code": null,
"e": 27046,
"s": 27043,
"text": "C#"
},
{
"code": null,
"e": 27057,
"s": 27046,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the maximum possible// frequency of a most frequent element// after at most K increment operationsvoid maxFrequency(int arr[], int N, int K){ // Sort the input array sort(arr, arr + N); int start = 0, end = 0; // Stores the sum of sliding // window and the maximum possible // frequency of any array element int sum = 0, res = 0; // Traverse the array for (end = 0; end < N; end++) { // Add the current element // to the window sum += arr[end]; // Decrease the window size // If it is not possible to make the // array elements in the window equal while ((end - start + 1) * arr[end] - sum > K) { // Update the value of sum sum -= arr[start]; // Increment the value of start start++; } // Update the maximum possible frequency res = max(res, end - start + 1); } // Print the frequency of // the most frequent array // element after K increments cout << res << endl;} // Driver codeint main(){ int arr[] = { 1, 4, 8, 13 }; int N = 4; int K = 5; maxFrequency(arr, N, K); return 0;}",
"e": 28320,
"s": 27057,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.Arrays; class GFG{ // Function to find the maximum possible// frequency of a most frequent element// after at most K increment operationsstatic void maxFrequency(int arr[], int N, int K){ // Sort the input array Arrays.sort(arr); int start = 0, end = 0; // Stores the sum of sliding // window and the maximum possible // frequency of any array element int sum = 0, res = 0; // Traverse the array for(end = 0; end < N; end++) { // Add the current element // to the window sum += arr[end]; // Decrease the window size // If it is not possible to make the // array elements in the window equal while ((end - start + 1) * arr[end] - sum > K) { // Update the value of sum sum -= arr[start]; // Increment the value of start start++; } // Update the maximum possible frequency res = Math.max(res, end - start + 1); } // Print the frequency of // the most frequent array // element after K increments System.out.println(res);} // Driver codepublic static void main(String[] args){ int arr[] = { 1, 4, 8, 13 }; int N = 4; int K = 5; maxFrequency(arr, N, K);}} // This code is contributed by abhinavjain194",
"e": 29708,
"s": 28320,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to find the maximum possible# frequency of a most frequent element# after at most K increment operationsdef maxFrequency(arr, N, K): # Sort the input array arr.sort() start = 0 end = 0 # Stores the sum of sliding # window and the maximum possible # frequency of any array element sum = 0 res = 0 # Traverse the array for end in range(N): # Add the current element # to the window sum += arr[end] # Decrease the window size # If it is not possible to make the # array elements in the window equal while ((end - start + 1) * arr[end] - sum > K): # Update the value of sum sum -= arr[start] # Increment the value of start start += 1 # Update the maximum possible frequency res = max(res, end - start + 1) # Print the frequency of # the most frequent array # element after K increments print(res) # Driver codeif __name__ == '__main__': arr = [ 1, 4, 8, 13 ] N = 4 K = 5 maxFrequency(arr, N, K) # This code is contributed by ipg2016107",
"e": 30885,
"s": 29708,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ // Function to find the maximum possible// frequency of a most frequent element// after at most K increment operationsstatic void maxFrequency(int[] arr, int N, int K){ // Sort the input array Array.Sort(arr); int start = 0, end = 0; // Stores the sum of sliding // window and the maximum possible // frequency of any array element int sum = 0, res = 0; // Traverse the array for(end = 0; end < N; end++) { // Add the current element // to the window sum += arr[end]; // Decrease the window size // If it is not possible to make the // array elements in the window equal while ((end - start + 1) * arr[end] - sum > K) { // Update the value of sum sum -= arr[start]; // Increment the value of start start++; } // Update the maximum possible frequency res = Math.Max(res, end - start + 1); } // Print the frequency of // the most frequent array // element after K increments Console.WriteLine(res);} // Driver Codepublic static void Main(){ int[] arr = { 1, 4, 8, 13 }; int N = 4; int K = 5; maxFrequency(arr, N, K);}} // This code is contributed by code_hunt",
"e": 32244,
"s": 30885,
"text": null
},
{
"code": "<script> // JavaScript program for the above approach // Function to find the maximum possible// frequency of a most frequent element// after at most K increment operationsfunction maxFrequency(arr, N, K) { // Sort the input array arr.sort((a, b) => a - b); let start = 0, end = 0; // Stores the sum of sliding // window and the maximum possible // frequency of any array element let sum = 0, res = 0; // Traverse the array for (end = 0; end < N; end++) { // Add the current element // to the window sum += arr[end]; // Decrease the window size // If it is not possible to make the // array elements in the window equal while ((end - start + 1) * arr[end] - sum > K) { // Update the value of sum sum -= arr[start]; // Increment the value of start start++; } // Update the maximum possible frequency res = Math.max(res, end - start + 1); } // Print the frequency of // the most frequent array // element after K increments document.write(res + \"<br>\");} // Driver code let arr = [1, 4, 8, 13];let N = 4;let K = 5;maxFrequency(arr, N, K); </script>",
"e": 33458,
"s": 32244,
"text": null
},
{
"code": null,
"e": 33460,
"s": 33458,
"text": "2"
},
{
"code": null,
"e": 33510,
"s": 33462,
"text": "Time Complexity: O(NlogN) Auxiliary Space: O(1)"
},
{
"code": null,
"e": 33525,
"s": 33510,
"text": "abhinavjain194"
},
{
"code": null,
"e": 33535,
"s": 33525,
"text": "code_hunt"
},
{
"code": null,
"e": 33546,
"s": 33535,
"text": "ipg2016107"
},
{
"code": null,
"e": 33563,
"s": 33546,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 33582,
"s": 33563,
"text": "frequency-counting"
},
{
"code": null,
"e": 33589,
"s": 33582,
"text": "Picked"
},
{
"code": null,
"e": 33604,
"s": 33589,
"text": "sliding-window"
},
{
"code": null,
"e": 33611,
"s": 33604,
"text": "Arrays"
},
{
"code": null,
"e": 33624,
"s": 33611,
"text": "Mathematical"
},
{
"code": null,
"e": 33639,
"s": 33624,
"text": "sliding-window"
},
{
"code": null,
"e": 33646,
"s": 33639,
"text": "Arrays"
},
{
"code": null,
"e": 33659,
"s": 33646,
"text": "Mathematical"
},
{
"code": null,
"e": 33757,
"s": 33659,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33766,
"s": 33757,
"text": "Comments"
},
{
"code": null,
"e": 33779,
"s": 33766,
"text": "Old Comments"
},
{
"code": null,
"e": 33811,
"s": 33779,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 33865,
"s": 33811,
"text": "Queue | Set 1 (Introduction and Array Implementation)"
},
{
"code": null,
"e": 33879,
"s": 33865,
"text": "Linear Search"
},
{
"code": null,
"e": 33924,
"s": 33879,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 33992,
"s": 33924,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 34022,
"s": 33992,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 34082,
"s": 34022,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 34097,
"s": 34082,
"text": "C++ Data Types"
},
{
"code": null,
"e": 34140,
"s": 34097,
"text": "Set in C++ Standard Template Library (STL)"
}
]
|
How to Sort CSV by multiple columns in Python ? - GeeksforGeeks | 21 Apr, 2021
In this article, we are going to discuss how to sort a CSV file by multiple columns. First, we will convert the CSV file into a data frame then we will sort the data frame by using the sort_values() method.
Syntax: DataFrame.sort_values(by, axis=0, ascending=True, inplace=False, kind=’quicksort’, na_position=’last’)
Return Type: Returns a sorted Data Frame with same dimensions as of the function caller Data Frame.
After converting the CSV file into a data frame, we need to add two or more column names of the CSV file as by parameter in sort_values() method with axis assigned to 0 like below:
sort_values(‘column1’, ‘column2’...’columnn’, axis=0)
CSV file in use:
Below are various examples that depict how to sort a CSV file by multiple columns:
Example 1:
In the below program, we first convert the CSV file into a dataframe, then we sort the dataframe by a single column in ascending order.
Python3
# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv("diamonds.csv") # sorting data frame by a columndata.sort_values("carat", axis=0, ascending=True, inplace=True, na_position='first') # displaydata.head(10)
Output:
Example 2:
Here, after converting into a data frame, the CSV file is sorted by multiple columns, the depth column is sorted first in ascending order, then the table column is sorted in ascending order for every depth.
Python3
# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv("diamonds.csv") # sorting data frame by multiple columnsdata.sort_values(["depth", "table"], axis=0, ascending=True, inplace=True) # displaydata.head(10)
Output:
Example 3:
In the below example, the CSV file is sorted in descending order by the depth and then in ascending order by the table for every depth.
Python3
# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv("diamonds.csv") # sorting data frame by multiple columnsdata.sort_values(["depth", "table"], axis=0, ascending=[False, True], inplace=True) # displaydata.head(10)
Output:
Example 4:
Here is another example where the CSV file is sorted by multiple columns.
Python3
# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv("diamonds.csv") # sorting data frame by multiple columnsdata.sort_values(["depth", "table", "carat"], axis=0, ascending=[False, True, False], inplace=True) # displaydata.head(10)
Output:
Picked
python-csv
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
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
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n21 Apr, 2021"
},
{
"code": null,
"e": 24500,
"s": 24292,
"text": "In this article, we are going to discuss how to sort a CSV file by multiple columns. First, we will convert the CSV file into a data frame then we will sort the data frame by using the sort_values() method. "
},
{
"code": null,
"e": 24611,
"s": 24500,
"text": "Syntax: DataFrame.sort_values(by, axis=0, ascending=True, inplace=False, kind=’quicksort’, na_position=’last’)"
},
{
"code": null,
"e": 24711,
"s": 24611,
"text": "Return Type: Returns a sorted Data Frame with same dimensions as of the function caller Data Frame."
},
{
"code": null,
"e": 24892,
"s": 24711,
"text": "After converting the CSV file into a data frame, we need to add two or more column names of the CSV file as by parameter in sort_values() method with axis assigned to 0 like below:"
},
{
"code": null,
"e": 24946,
"s": 24892,
"text": "sort_values(‘column1’, ‘column2’...’columnn’, axis=0)"
},
{
"code": null,
"e": 24963,
"s": 24946,
"text": "CSV file in use:"
},
{
"code": null,
"e": 25046,
"s": 24963,
"text": "Below are various examples that depict how to sort a CSV file by multiple columns:"
},
{
"code": null,
"e": 25057,
"s": 25046,
"text": "Example 1:"
},
{
"code": null,
"e": 25193,
"s": 25057,
"text": "In the below program, we first convert the CSV file into a dataframe, then we sort the dataframe by a single column in ascending order."
},
{
"code": null,
"e": 25201,
"s": 25193,
"text": "Python3"
},
{
"code": "# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv(\"diamonds.csv\") # sorting data frame by a columndata.sort_values(\"carat\", axis=0, ascending=True, inplace=True, na_position='first') # displaydata.head(10)",
"e": 25474,
"s": 25201,
"text": null
},
{
"code": null,
"e": 25482,
"s": 25474,
"text": "Output:"
},
{
"code": null,
"e": 25493,
"s": 25482,
"text": "Example 2:"
},
{
"code": null,
"e": 25700,
"s": 25493,
"text": "Here, after converting into a data frame, the CSV file is sorted by multiple columns, the depth column is sorted first in ascending order, then the table column is sorted in ascending order for every depth."
},
{
"code": null,
"e": 25708,
"s": 25700,
"text": "Python3"
},
{
"code": "# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv(\"diamonds.csv\") # sorting data frame by multiple columnsdata.sort_values([\"depth\", \"table\"], axis=0, ascending=True, inplace=True) # displaydata.head(10)",
"e": 25979,
"s": 25708,
"text": null
},
{
"code": null,
"e": 25987,
"s": 25979,
"text": "Output:"
},
{
"code": null,
"e": 25999,
"s": 25987,
"text": "Example 3: "
},
{
"code": null,
"e": 26136,
"s": 25999,
"text": "In the below example, the CSV file is sorted in descending order by the depth and then in ascending order by the table for every depth. "
},
{
"code": null,
"e": 26144,
"s": 26136,
"text": "Python3"
},
{
"code": "# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv(\"diamonds.csv\") # sorting data frame by multiple columnsdata.sort_values([\"depth\", \"table\"], axis=0, ascending=[False, True], inplace=True) # displaydata.head(10)",
"e": 26424,
"s": 26144,
"text": null
},
{
"code": null,
"e": 26432,
"s": 26424,
"text": "Output:"
},
{
"code": null,
"e": 26443,
"s": 26432,
"text": "Example 4:"
},
{
"code": null,
"e": 26517,
"s": 26443,
"text": "Here is another example where the CSV file is sorted by multiple columns."
},
{
"code": null,
"e": 26525,
"s": 26517,
"text": "Python3"
},
{
"code": "# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv(\"diamonds.csv\") # sorting data frame by multiple columnsdata.sort_values([\"depth\", \"table\", \"carat\"], axis=0, ascending=[False, True, False], inplace=True) # displaydata.head(10)",
"e": 26821,
"s": 26525,
"text": null
},
{
"code": null,
"e": 26829,
"s": 26821,
"text": "Output:"
},
{
"code": null,
"e": 26836,
"s": 26829,
"text": "Picked"
},
{
"code": null,
"e": 26847,
"s": 26836,
"text": "python-csv"
},
{
"code": null,
"e": 26861,
"s": 26847,
"text": "Python-pandas"
},
{
"code": null,
"e": 26868,
"s": 26861,
"text": "Python"
},
{
"code": null,
"e": 26966,
"s": 26868,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26998,
"s": 26966,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27054,
"s": 26998,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27096,
"s": 27054,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27138,
"s": 27096,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27160,
"s": 27138,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27199,
"s": 27160,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27230,
"s": 27199,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27285,
"s": 27230,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 27314,
"s": 27285,
"text": "Create a directory in Python"
}
]
|
Data Pipelines — Design Patterns for Reusability, Extensibility | by Mukul Sood | Towards Data Science | Designing extensible, modular, reusable Data Pipelines is a larger topic and very relevant in Data Engineering as the type of work involves dealing with constant change across different layers such as data sources, ingest, validation, processing, security, logging, monitoring. The changes happen at varying rates across these layers and they impact the data pipelines differently based on the level of abstraction and design of the pipeline. In this post, we will discuss Cross Cutting Concerns, specifically Logging and Monitoring and discuss some use cases and patterns that may provide the ground to build modularity and reusability into the pipelines
To get some context into layers of a Data Pipeline and to start to map the config, here’s a conceptual view:
This is a simplified view, as the layers could be represented in many different ways however in a distilled form the pipeline can be thought of as Ingest, Processing and Result layers. For each layer, we can think in terms of functions, as the image shows the functional blocks. The content of the blocks change depending on the layer requirements. This helps us think in terms of templates and config that could represent the Pipeline DAG. As an example, the yaml config below:
The Ingest, Processing and Result layers could be mapped to different loggers and monitors based on requirements. For example, at the Ingest layer the file log could be S3 and event log could be custom and monitors could be Stackdriver and Redash. However, the Results layer could be mapped to event log DataDog and event monitor as DataDog.
If we take a generic pipeline, specifically looking at Logging and Monitoring, this representation would get implemented as Dag methods where loggers and monitors would be coupled with Dag code. This involves more coding, it is brittle, difficult to reuse and a violation of design principles SRP, DRY, Open Closed making the overall pipeline unstable and unreliable. If we extend this problem statement beyond Monitoring and Logging, we will see similar problems in different functional blocks — Data Quality/Validation, Security/Privacy etc.
When we see similarities in problems, that is an indicator to recognize the common themes. For example, here we have DAG specific and function specific (Logging, Monitoring) responsibilities. In addition, we want to remove the coupling between these and increase cohesion within these. This gives us enough context to start thinking in terms of Design Patterns. Refer Design Patterns: Elements of Reusable Object-Oriented Software by the “Gang of Four” (Gamma et al.). For our context, we will show how these patterns play a role in our design. Schematic below shows a high level view of Pipeline DAG with the patterns applicable to different layers:
The first set of patterns are Creational or Structural. They allow us to separate creation and structure of cross cutting concerns such as Logging, Monitoring from Dag specific areas. The Factory and AbstractFactory help in abstracting and decoupling the different Loggers and Monitors from the Dag code allowing the Dag codebase to evolve without dependencies on Logging, Monitoring code base
from loglib import LogConfigConstfrom abc import ABC, abstractmethodfrom boto3 import Sessionclass Logger(metaclass=ABC.ABCMeta): @abstractmethod def log(self,message): passclass S3Logger(Logger): """ log to AWS S3 """ _initialized = False _instance = None _s3session = None def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = super(S3Logger, cls).__new__(cls, *args, **kwargs) return cls._instance def __init__(self, *args, **kwargs): if self._initialized: return super(S3Logger, self).__init__(*args, **kwargs) #get the kwarg config that has details of S3 connection params -- Region, Public Key, Secret Key logconfig=kwargs["logconfig"] logConfigConst=LogConfigConst() #establish s3 session, use boto3 self.__class__._s3session=Session(aws_access_key_id=logconfig[logConfigConst.AWS_ACCESS_KEY_ID], aws_secret_access_key=logconfig[logConfigConst.AWS_SECRET_ACCESS_KEY], region_name=logconfig[logConfigConst.AWS_REGION]) self.__class__._initialized = True @classmethod def log(cls, message): #log to S3 return
Code sample showing an example of Logger and LogFactory classes:
class LogFactory: _dictlogger={} @classmethod def create_logger(config): logger=None if config.name == LogConfigConst.filelog.names.S3: logger=S3Logger(logconfig=config) elif config.name == LogConfigConst.eventlog.names.DataDog: logger=DataDogLogger(logconfig=config) elif config.name == LogConfigConst.databaselog.names.PostGresDB: logger=PostGresDBLogger(logconfig=config) return logger @classmethod def get_logger(cls,config): if cls._dictlogger[config.name] is None: cls.dict_logger[config.name] = cls.create_logger(config) return cls.dict_logger[config.name]
The second set of patterns are Behavioral. They allow us to specify behavior while maintaining SRP, DRY and SOLID principles. The Decorator pattern is widely used to modify or add behavior to existing functions. Logging and Monitoring are immediately applicable as we see below.
import functools,sys,tracebackfrom loglib import LoggingFacadeclass LoggingDecorator: def __init__(self,config): self.logFacade=LoggingFacade(config_template=config) def log_error(self,func=None): def error_log(func): @functools.wraps(func) def wrapper(*args, **kwargs): try: # Execute the called function return func(*args, **kwargs) except Exception as e: error_msg = 'And error has occurred in '.join(func.__name__) self.logFacade.log_filestore(error_msg) raise e return wrapper return [email protected]_errordef push_exception_to_xcom(kwargs): """To push exception occuring from dag task to xcom ; this will be used in alert/reporting""" exc_type, exc_value, exc_traceback = sys.exc_info() exception_details= ''.join(traceback.format_exception(etype=type(exc_type),value=exc_value, tb=exc_traceback)) kwargs['ti'].xcom_push(key='exception_details', value=exception_details)
Code sample showing an example of LoggingDecorator:
The Facade pattern is useful when a narrower or specific api is needed for client or consumer. For example, the broad set of api’s or methods exposed by the different Loggers and Monitors do not need to be exposed to the Dag layer. The Facade pattern helps define an access or interface to the Logging, Monitoring layer, as we see below
from loglib import LogConfigConstfrom loglib.LoggerFactory import LogFactoryclass LoggingFacade: _file_logger, _event_logger, _database_logger = None _initialized = False def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = super(LoggingFacade, cls).__new__(cls, *args, **kwargs) return cls._instance def __init__(self, *args, **kwargs): if self._initialized: return super(LoggingFacade, self).__init__(*args, **kwargs) #get the kwarg config that has config for all the loggers config=kwargs["config_template"] logconfig=LogConfigConst() for conf in config.loggers: if conf.type == logconfig.FILELOG: self.__class__._file_logger = LogFactory().get_logger(conf) elif conf.type == logconfig.EVENTLOG: self.__class__._event_logger = LogFactory().get_logger(conf) elif conf.type == logconfig.DATABASELOG: self.__class__._database_logger = LogFactory().get_logger(conf) self.__class__._initialized = True #filestore could be S3 or other providers @classmethod def log_filestore(cls,message): cls._file_logger.log(message) #event logger could be DataDog or other providers @classmethod def log_event(cls,message): cls.event_logger.log(message) @classmethod def log_database(cls,message): cls.database_logger.log(message)
Code sample showing an example of LoggingFacade:
When we combine these patterns, we realize the benefits of design principles as the separation of responsibilities allows the modularization of code base at multiple levels: Dag level, Cross Cutting Concerns level (separate packages for Monitoring, Logging), Cross Dag level (common templates could be abstracted for example domain specific). What this provides is building blocks for generalizing the Data pipelines to move away from writing custom code to more generic modules, templates, config. The different pieces follow their development cycles and deployment packages completely decoupled from Dag codebase. While adding these design principles does increase the abstraction and some level of complexity however that is a small price to pay for scaling up the pipeline development while maintaining quality and velocity
While the world of Data Engineering is continuously evolving and DAG Pipeline design and architecture has its own set of challenges, there are some key principles that can be applied to increase stability, reliability, maintainability of the pipelines. I hope you enjoyed reading this article and found some useful information to apply in your Data Engineering initiatives. I look forward to your comments and feedback. | [
{
"code": null,
"e": 828,
"s": 172,
"text": "Designing extensible, modular, reusable Data Pipelines is a larger topic and very relevant in Data Engineering as the type of work involves dealing with constant change across different layers such as data sources, ingest, validation, processing, security, logging, monitoring. The changes happen at varying rates across these layers and they impact the data pipelines differently based on the level of abstraction and design of the pipeline. In this post, we will discuss Cross Cutting Concerns, specifically Logging and Monitoring and discuss some use cases and patterns that may provide the ground to build modularity and reusability into the pipelines"
},
{
"code": null,
"e": 937,
"s": 828,
"text": "To get some context into layers of a Data Pipeline and to start to map the config, here’s a conceptual view:"
},
{
"code": null,
"e": 1416,
"s": 937,
"text": "This is a simplified view, as the layers could be represented in many different ways however in a distilled form the pipeline can be thought of as Ingest, Processing and Result layers. For each layer, we can think in terms of functions, as the image shows the functional blocks. The content of the blocks change depending on the layer requirements. This helps us think in terms of templates and config that could represent the Pipeline DAG. As an example, the yaml config below:"
},
{
"code": null,
"e": 1758,
"s": 1416,
"text": "The Ingest, Processing and Result layers could be mapped to different loggers and monitors based on requirements. For example, at the Ingest layer the file log could be S3 and event log could be custom and monitors could be Stackdriver and Redash. However, the Results layer could be mapped to event log DataDog and event monitor as DataDog."
},
{
"code": null,
"e": 2302,
"s": 1758,
"text": "If we take a generic pipeline, specifically looking at Logging and Monitoring, this representation would get implemented as Dag methods where loggers and monitors would be coupled with Dag code. This involves more coding, it is brittle, difficult to reuse and a violation of design principles SRP, DRY, Open Closed making the overall pipeline unstable and unreliable. If we extend this problem statement beyond Monitoring and Logging, we will see similar problems in different functional blocks — Data Quality/Validation, Security/Privacy etc."
},
{
"code": null,
"e": 2953,
"s": 2302,
"text": "When we see similarities in problems, that is an indicator to recognize the common themes. For example, here we have DAG specific and function specific (Logging, Monitoring) responsibilities. In addition, we want to remove the coupling between these and increase cohesion within these. This gives us enough context to start thinking in terms of Design Patterns. Refer Design Patterns: Elements of Reusable Object-Oriented Software by the “Gang of Four” (Gamma et al.). For our context, we will show how these patterns play a role in our design. Schematic below shows a high level view of Pipeline DAG with the patterns applicable to different layers:"
},
{
"code": null,
"e": 3347,
"s": 2953,
"text": "The first set of patterns are Creational or Structural. They allow us to separate creation and structure of cross cutting concerns such as Logging, Monitoring from Dag specific areas. The Factory and AbstractFactory help in abstracting and decoupling the different Loggers and Monitors from the Dag code allowing the Dag codebase to evolve without dependencies on Logging, Monitoring code base"
},
{
"code": null,
"e": 4605,
"s": 3347,
"text": "from loglib import LogConfigConstfrom abc import ABC, abstractmethodfrom boto3 import Sessionclass Logger(metaclass=ABC.ABCMeta): @abstractmethod def log(self,message): passclass S3Logger(Logger): \"\"\" log to AWS S3 \"\"\" _initialized = False _instance = None _s3session = None def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = super(S3Logger, cls).__new__(cls, *args, **kwargs) return cls._instance def __init__(self, *args, **kwargs): if self._initialized: return super(S3Logger, self).__init__(*args, **kwargs) #get the kwarg config that has details of S3 connection params -- Region, Public Key, Secret Key logconfig=kwargs[\"logconfig\"] logConfigConst=LogConfigConst() #establish s3 session, use boto3 self.__class__._s3session=Session(aws_access_key_id=logconfig[logConfigConst.AWS_ACCESS_KEY_ID], aws_secret_access_key=logconfig[logConfigConst.AWS_SECRET_ACCESS_KEY], region_name=logconfig[logConfigConst.AWS_REGION]) self.__class__._initialized = True @classmethod def log(cls, message): #log to S3 return"
},
{
"code": null,
"e": 4670,
"s": 4605,
"text": "Code sample showing an example of Logger and LogFactory classes:"
},
{
"code": null,
"e": 5342,
"s": 4670,
"text": "class LogFactory: _dictlogger={} @classmethod def create_logger(config): logger=None if config.name == LogConfigConst.filelog.names.S3: logger=S3Logger(logconfig=config) elif config.name == LogConfigConst.eventlog.names.DataDog: logger=DataDogLogger(logconfig=config) elif config.name == LogConfigConst.databaselog.names.PostGresDB: logger=PostGresDBLogger(logconfig=config) return logger @classmethod def get_logger(cls,config): if cls._dictlogger[config.name] is None: cls.dict_logger[config.name] = cls.create_logger(config) return cls.dict_logger[config.name]"
},
{
"code": null,
"e": 5621,
"s": 5342,
"text": "The second set of patterns are Behavioral. They allow us to specify behavior while maintaining SRP, DRY and SOLID principles. The Decorator pattern is widely used to modify or add behavior to existing functions. Logging and Monitoring are immediately applicable as we see below."
},
{
"code": null,
"e": 6709,
"s": 5621,
"text": "import functools,sys,tracebackfrom loglib import LoggingFacadeclass LoggingDecorator: def __init__(self,config): self.logFacade=LoggingFacade(config_template=config) def log_error(self,func=None): def error_log(func): @functools.wraps(func) def wrapper(*args, **kwargs): try: # Execute the called function return func(*args, **kwargs) except Exception as e: error_msg = 'And error has occurred in '.join(func.__name__) self.logFacade.log_filestore(error_msg) raise e return wrapper return [email protected]_errordef push_exception_to_xcom(kwargs): \"\"\"To push exception occuring from dag task to xcom ; this will be used in alert/reporting\"\"\" exc_type, exc_value, exc_traceback = sys.exc_info() exception_details= ''.join(traceback.format_exception(etype=type(exc_type),value=exc_value, tb=exc_traceback)) kwargs['ti'].xcom_push(key='exception_details', value=exception_details)"
},
{
"code": null,
"e": 6761,
"s": 6709,
"text": "Code sample showing an example of LoggingDecorator:"
},
{
"code": null,
"e": 7098,
"s": 6761,
"text": "The Facade pattern is useful when a narrower or specific api is needed for client or consumer. For example, the broad set of api’s or methods exposed by the different Loggers and Monitors do not need to be exposed to the Dag layer. The Facade pattern helps define an access or interface to the Logging, Monitoring layer, as we see below"
},
{
"code": null,
"e": 8553,
"s": 7098,
"text": "from loglib import LogConfigConstfrom loglib.LoggerFactory import LogFactoryclass LoggingFacade: _file_logger, _event_logger, _database_logger = None _initialized = False def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = super(LoggingFacade, cls).__new__(cls, *args, **kwargs) return cls._instance def __init__(self, *args, **kwargs): if self._initialized: return super(LoggingFacade, self).__init__(*args, **kwargs) #get the kwarg config that has config for all the loggers config=kwargs[\"config_template\"] logconfig=LogConfigConst() for conf in config.loggers: if conf.type == logconfig.FILELOG: self.__class__._file_logger = LogFactory().get_logger(conf) elif conf.type == logconfig.EVENTLOG: self.__class__._event_logger = LogFactory().get_logger(conf) elif conf.type == logconfig.DATABASELOG: self.__class__._database_logger = LogFactory().get_logger(conf) self.__class__._initialized = True #filestore could be S3 or other providers @classmethod def log_filestore(cls,message): cls._file_logger.log(message) #event logger could be DataDog or other providers @classmethod def log_event(cls,message): cls.event_logger.log(message) @classmethod def log_database(cls,message): cls.database_logger.log(message)"
},
{
"code": null,
"e": 8602,
"s": 8553,
"text": "Code sample showing an example of LoggingFacade:"
},
{
"code": null,
"e": 9430,
"s": 8602,
"text": "When we combine these patterns, we realize the benefits of design principles as the separation of responsibilities allows the modularization of code base at multiple levels: Dag level, Cross Cutting Concerns level (separate packages for Monitoring, Logging), Cross Dag level (common templates could be abstracted for example domain specific). What this provides is building blocks for generalizing the Data pipelines to move away from writing custom code to more generic modules, templates, config. The different pieces follow their development cycles and deployment packages completely decoupled from Dag codebase. While adding these design principles does increase the abstraction and some level of complexity however that is a small price to pay for scaling up the pipeline development while maintaining quality and velocity"
}
]
|
Aptitude | GATE CS 1998 | Question 52 - GeeksforGeeks | 06 Sep, 2018
Consider n processes sharing the CPU in a round-robin fashion. Assuming that each process switch takes s seconds, what must be the quantum size q such that the overhead resulting from process switching is minimized but, at the same time, each process is guaranteed to get its turn at the CPU at least every t seconds ?
(A) a(B) b(C) c(D) dAnswer: (A)Explanation: Each process will get CPU for q seconds and each process wants CPU again after t seconds.Thus, there will be (n-1) processes once after current process gets CPU again. Each process takes s seconds for context switch.
(Qp1)(s)(Qp2)(s)(Qp3)(s)(Qp1)
It can be seen that since P1 left and arrived again, there have been n context switches and (n-1) processes. Thus, equation will be:
q*(n-1) + n*s <= t
q*(n-1) <= t - n*s
q <= (t-n.s) / (n-1)
So, option (A) is correct.Quiz of this Question
parthendo
Aptitude
Aptitude-GATE CS 1998
GATE CS 1998
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-IT-2004 | Question 71
GATE | GATE CS 2011 | Question 7
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE CS 2018 | Question 37
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-IT-2004 | Question 83
GATE | GATE-CS-2016 (Set 1) | Question 63
GATE | GATE-CS-2014-(Set-2) | Question 65 | [
{
"code": null,
"e": 24226,
"s": 24198,
"text": "\n06 Sep, 2018"
},
{
"code": null,
"e": 24545,
"s": 24226,
"text": "Consider n processes sharing the CPU in a round-robin fashion. Assuming that each process switch takes s seconds, what must be the quantum size q such that the overhead resulting from process switching is minimized but, at the same time, each process is guaranteed to get its turn at the CPU at least every t seconds ?"
},
{
"code": null,
"e": 24807,
"s": 24545,
"text": " (A) a(B) b(C) c(D) dAnswer: (A)Explanation: Each process will get CPU for q seconds and each process wants CPU again after t seconds.Thus, there will be (n-1) processes once after current process gets CPU again. Each process takes s seconds for context switch."
},
{
"code": null,
"e": 24838,
"s": 24807,
"text": "(Qp1)(s)(Qp2)(s)(Qp3)(s)(Qp1) "
},
{
"code": null,
"e": 24971,
"s": 24838,
"text": "It can be seen that since P1 left and arrived again, there have been n context switches and (n-1) processes. Thus, equation will be:"
},
{
"code": null,
"e": 25031,
"s": 24971,
"text": "q*(n-1) + n*s <= t\nq*(n-1) <= t - n*s\nq <= (t-n.s) / (n-1) "
},
{
"code": null,
"e": 25079,
"s": 25031,
"text": "So, option (A) is correct.Quiz of this Question"
},
{
"code": null,
"e": 25089,
"s": 25079,
"text": "parthendo"
},
{
"code": null,
"e": 25098,
"s": 25089,
"text": "Aptitude"
},
{
"code": null,
"e": 25120,
"s": 25098,
"text": "Aptitude-GATE CS 1998"
},
{
"code": null,
"e": 25133,
"s": 25120,
"text": "GATE CS 1998"
},
{
"code": null,
"e": 25138,
"s": 25133,
"text": "GATE"
},
{
"code": null,
"e": 25236,
"s": 25138,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25245,
"s": 25236,
"text": "Comments"
},
{
"code": null,
"e": 25258,
"s": 25245,
"text": "Old Comments"
},
{
"code": null,
"e": 25292,
"s": 25258,
"text": "GATE | GATE-IT-2004 | Question 71"
},
{
"code": null,
"e": 25325,
"s": 25292,
"text": "GATE | GATE CS 2011 | Question 7"
},
{
"code": null,
"e": 25367,
"s": 25325,
"text": "GATE | GATE-CS-2015 (Set 3) | Question 65"
},
{
"code": null,
"e": 25409,
"s": 25367,
"text": "GATE | GATE-CS-2016 (Set 2) | Question 48"
},
{
"code": null,
"e": 25451,
"s": 25409,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 38"
},
{
"code": null,
"e": 25485,
"s": 25451,
"text": "GATE | GATE CS 2018 | Question 37"
},
{
"code": null,
"e": 25527,
"s": 25485,
"text": "GATE | GATE-CS-2016 (Set 1) | Question 65"
},
{
"code": null,
"e": 25561,
"s": 25527,
"text": "GATE | GATE-IT-2004 | Question 83"
},
{
"code": null,
"e": 25603,
"s": 25561,
"text": "GATE | GATE-CS-2016 (Set 1) | Question 63"
}
]
|
4 Bit Binary Incrementer - GeeksforGeeks | 29 Apr, 2021
What is 4 Bit Binary Incrementer ?It adds 1 binary value to the existing binary value stored in the register or in other words we can simply say that it increases the value stored in the register by 1.For any n-bit binary incrementer ,‘n’ refers to the storage capacity of the register which needs to be incremented by 1. So we require ‘n’ number of half adders . Thus, in case of 4 bit binary incrementer we require 4 half adders.
Working:
The half adders are connected one after the other , as it has 2 inputs and 2 outputs , so for the LSB ( least significant bit) half adder or the right most half adder is given 1 as direct input( first input) and A0 which is the first bit of the register (second input) , so we get the two output : sum (S0) and carry (C).
The carry(C) from previous half adder is propagated to the next half adder, so the carry output of the previous half adder becomes the input of the next higher order half adder.
So considering the case for 4 half adders the circuit gets in total 4 bits (A0, A1, A2, A3), 1 is added and we get an incremented output.
Examples:
(Refer to the circuit diagram from right to left for better understanding)
1. Input: 1010 ----> After using 4 bit binary incrementer ----> Output: 1011
1 0 1 0 (Comparing from the circuit 1 0 1 0 is A3, A2, A1, A0 respectively)
+ 1 (1 is added as seen in the diagram also, in the first half adder, 1 is taken as input)
_________
1 0 1 1 ( 1 0 1 1 , in the diagram are S3, S2, S1, S0 respectively)
_________
2. Input: 0010 ---> After using 4 bit binary incrementer ----> Output: 0011
0 0 1 0
+ 1
_________
0 0 1 1
_________
3. Input: 0011 ---> After using 4 bit binary incrementer ----> Output: 0100
0 0 1 1
+ 1
________
0 1 0 0
_________
Computer Organization and Architecture
Digital Electronics & Logic Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Maximum mode configuration of 8086 microprocessor (Max mode)
Minimum mode configuration of 8086 microprocessor (Min mode)
Microprocessor | 8254 programmable interval timer
Subroutine in 8085
8086 program to convert an 8 bit BCD number into hexadecimal number
Full Adder in Digital Logic
Program for Decimal to Binary Conversion
Introduction of K-Map (Karnaugh Map)
Program for Binary To Decimal Conversion
4-bit binary Adder-Subtractor | [
{
"code": null,
"e": 24442,
"s": 24414,
"text": "\n29 Apr, 2021"
},
{
"code": null,
"e": 24874,
"s": 24442,
"text": "What is 4 Bit Binary Incrementer ?It adds 1 binary value to the existing binary value stored in the register or in other words we can simply say that it increases the value stored in the register by 1.For any n-bit binary incrementer ,‘n’ refers to the storage capacity of the register which needs to be incremented by 1. So we require ‘n’ number of half adders . Thus, in case of 4 bit binary incrementer we require 4 half adders."
},
{
"code": null,
"e": 24883,
"s": 24874,
"text": "Working:"
},
{
"code": null,
"e": 25205,
"s": 24883,
"text": "The half adders are connected one after the other , as it has 2 inputs and 2 outputs , so for the LSB ( least significant bit) half adder or the right most half adder is given 1 as direct input( first input) and A0 which is the first bit of the register (second input) , so we get the two output : sum (S0) and carry (C)."
},
{
"code": null,
"e": 25383,
"s": 25205,
"text": "The carry(C) from previous half adder is propagated to the next half adder, so the carry output of the previous half adder becomes the input of the next higher order half adder."
},
{
"code": null,
"e": 25522,
"s": 25383,
"text": "So considering the case for 4 half adders the circuit gets in total 4 bits (A0, A1, A2, A3), 1 is added and we get an incremented output. "
},
{
"code": null,
"e": 25532,
"s": 25522,
"text": "Examples:"
},
{
"code": null,
"e": 25984,
"s": 25532,
"text": "(Refer to the circuit diagram from right to left for better understanding)\n \n\n1. Input: 1010 ----> After using 4 bit binary incrementer ----> Output: 1011\n\n\n 1 0 1 0 (Comparing from the circuit 1 0 1 0 is A3, A2, A1, A0 respectively)\n + 1 (1 is added as seen in the diagram also, in the first half adder, 1 is taken as input)\n _________\n 1 0 1 1 ( 1 0 1 1 , in the diagram are S3, S2, S1, S0 respectively)\n _________"
},
{
"code": null,
"e": 26119,
"s": 25984,
"text": "2. Input: 0010 ---> After using 4 bit binary incrementer ----> Output: 0011\n\n 0 0 1 0\n + 1\n _________\n 0 0 1 1\n _________"
},
{
"code": null,
"e": 26254,
"s": 26119,
"text": "3. Input: 0011 ---> After using 4 bit binary incrementer ----> Output: 0100\n\n 0 0 1 1\n + 1\n ________\n 0 1 0 0\n _________"
},
{
"code": null,
"e": 26293,
"s": 26254,
"text": "Computer Organization and Architecture"
},
{
"code": null,
"e": 26328,
"s": 26293,
"text": "Digital Electronics & Logic Design"
},
{
"code": null,
"e": 26426,
"s": 26328,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26435,
"s": 26426,
"text": "Comments"
},
{
"code": null,
"e": 26448,
"s": 26435,
"text": "Old Comments"
},
{
"code": null,
"e": 26509,
"s": 26448,
"text": "Maximum mode configuration of 8086 microprocessor (Max mode)"
},
{
"code": null,
"e": 26570,
"s": 26509,
"text": "Minimum mode configuration of 8086 microprocessor (Min mode)"
},
{
"code": null,
"e": 26620,
"s": 26570,
"text": "Microprocessor | 8254 programmable interval timer"
},
{
"code": null,
"e": 26639,
"s": 26620,
"text": "Subroutine in 8085"
},
{
"code": null,
"e": 26707,
"s": 26639,
"text": "8086 program to convert an 8 bit BCD number into hexadecimal number"
},
{
"code": null,
"e": 26735,
"s": 26707,
"text": "Full Adder in Digital Logic"
},
{
"code": null,
"e": 26776,
"s": 26735,
"text": "Program for Decimal to Binary Conversion"
},
{
"code": null,
"e": 26813,
"s": 26776,
"text": "Introduction of K-Map (Karnaugh Map)"
},
{
"code": null,
"e": 26854,
"s": 26813,
"text": "Program for Binary To Decimal Conversion"
}
]
|
Bokeh - Quick Guide | Bokeh is a data visualization library for Python. Unlike Matplotlib and Seaborn, they are also Python packages for data visualization, Bokeh renders its plots using HTML and JavaScript. Hence, it proves to be extremely useful for developing web based dashboards.
The Bokeh project is sponsored by NumFocus https://numfocus.org/. NumFocus also supports PyData, an educational program, involved in development of other important tools such as NumPy, Pandas and more. Bokeh can easily connect with these tools and produce interactive plots, dashboards and data applications.
Bokeh primarily converts the data source into a JSON file which is used as input for BokehJS, a JavaScript library, which in turn is written in TypeScript and renders the visualizations in modern browsers.
Some of the important features of Bokeh are as follows −
Bokeh is useful for common plotting requirements as well as custom and complex use-cases.
Bokeh can easily interact with other popular Pydata tools such as Pandas and Jupyter notebook.
This is an important advantage of Bokeh over Matplotlib and Seaborn, both produce static plots. Bokeh creates interactive plots that change when the user interacts with them. You can give your audience a wide range of options and tools for inferring and looking at data from various angles so that user can perform “what if” analysis.
By adding custom JavaScript, it is possible to generate visualizations for specialised use-cases.
Plots can be embedded in output of Flask or Django enabled web applications. They can also be rendered in
Jupyter
Bokeh is an open source project. It is distributed under Berkeley Source Distribution (BSD) license. Its source code is available on https://github.com/bokeh/bokeh.
Bokeh can be installed on CPython versions 2.7 and 3.5+ only both with Standard distribution and Anaconda distribution. Current version of Bokeh at the time of writing this tutorial is ver. 1.3.4. Bokeh package has the following dependencies −
jinja2 >= 2.7
numpy >= 1.7.1
packaging >= 16.8
pillow >= 4.0
python-dateutil >= 2.1
pyyaml >= 3.10
six >= 1.5.2
tornado >= 4.3
Generally, above packages are installed automatically when Bokeh is installed using Python’s built-in Package manager PIP as shown below −
pip3 install bokeh
If you are using Anaconda distribution, use conda package manager as follows −
conda install bokeh
In addition to the above dependencies, you may require additional packages such as pandas, psutil, etc., for specific purposes.
To verify if Bokeh has been successfully installed, import bokeh package in Python terminal and check its version −
>>> import bokeh
>>> bokeh.__version__
'1.3.4'
Creating a simple line plot between two numpy arrays is very simple. To begin with, import following functions from bokeh.plotting modules −
from bokeh.plotting import figure, output_file, show
The figure() function creates a new figure for plotting.
The output_file() function is used to specify a HTML file to store output.
The show() function displays the Bokeh figure in browser on in notebook.
Next, set up two numpy arrays where second array is sine value of first.
import numpy as np
import math
x = np.arange(0, math.pi*2, 0.05)
y = np.sin(x)
To obtain a Bokeh Figure object, specify the title and x and y axis labels as below −
p = figure(title = "sine wave example", x_axis_label = 'x', y_axis_label = 'y')
The Figure object contains a line() method that adds a line glyph to the figure. It needs data series for x and y axes.
p.line(x, y, legend = "sine", line_width = 2)
Finally, set the output file and call show() function.
output_file("sine.html")
show(p)
This will render the line plot in ‘sine.html’ and will be displayed in browser.
from bokeh.plotting import figure, output_file, show
import numpy as np
import math
x = np.arange(0, math.pi*2, 0.05)
y = np.sin(x)
output_file("sine.html")
p = figure(title = "sine wave example", x_axis_label = 'x', y_axis_label = 'y')
p.line(x, y, legend = "sine", line_width = 2)
show(p)
Displaying Bokeh figure in Jupyter notebook is very similar to the above. The only change you need to make is to import output_notebook instead of output_file from bokeh.plotting module.
from bokeh.plotting import figure, output_notebook, show
Call to output_notebook() function sets Jupyter notebook’s output cell as the destination for show() function as shown below −
output_notebook()
show(p)
Enter the code in a notebook cell and run it. The sine wave will be displayed inside the notebook.
Bokeh package offers two interfaces using which various plotting operations can be performed.
This module is a low level interface. It provides great deal of flexibility to the application developer in developing visualizations. A Bokeh plot results in an object containing visual and data aspects of a scene which is used by BokehJS library. The low-level objects that comprise a Bokeh scene graph are called Models.
This is a higher level interface that has functionality for composing visual glyphs. This module contains definition of Figure class. It actually is a subclass of plot class defined in bokeh.models module.
Figure class simplifies plot creation. It contains various methods to draw different vectorized graphical glyphs. Glyphs are the building blocks of Bokeh plot such as lines, circles, rectangles, and other shapes.
Bokeh package Application class which is a lightweight factory for creating Bokeh Documents. A Document is a container for Bokeh Models to be reflected to the client side BokehJS library.
It provides customizable Bokeh Server Tornadocore application. Server is used to share and publish interactive plots and apps to an audience of your choice.
Any plot is usually made up of one or many geometrical shapes such as line, circle, rectangle, etc. These shapes have visual information about the corresponding set of data. In Bokeh terminology, these geometrical shapes are called gylphs. Bokeh plots constructed using bokeh.plotting interface use a default set of tools and styles. However, it is possible to customize the styles using available plotting tools.
Different types of plots created using glyphs are as given below −
This type of plot is useful for visualizing the movements of points along the x-and y-axes in the form of a line. It is used to perform time series analytics.
This is typically useful for indicating the count of each category of a particular column or field in your dataset.
This plot indicates a region of points in a particular shade of color. This type of plot is used to distinguish different groups within the same dataset.
This type of plot is used to visualize relationship between two variables and to indicate the strength of correlation between them.
Different glyph plots are formed by calling appropriate method of Figure class. The Figure object is obtained by following constructor −
from bokeh.plotting import figure
figure(**kwargs)
The Figure object can be customised by various keyword arguments.
The line() method of Figure object adds a line glyph to the Bokeh figure. It needs x and y parameters as data arrays for showing their linear relationship.
from bokeh.plotting import figure, show
fig = figure()
fig.line(x,y)
show(fig)
Following code renders a simple line plot between two sets of values in the form Python list objects −
from bokeh.plotting import figure, output_file, show
x = [1,2,3,4,5]
y = [2,4,6,8,10]
output_file('line.html')
fig = figure(title = 'Line Plot example', x_axis_label = 'x', y_axis_label = 'y')
fig.line(x,y)
show(fig)
The figure object has two different methods for constructing bar plot
The bars are shown horizontally across plot width. The hbar() method has the following parameters −
Following code is an example of horizontal bar using Bokeh.
from bokeh.plotting import figure, output_file, show
fig = figure(plot_width = 400, plot_height = 200)
fig.hbar(y = [2,4,6], height = 1, left = 0, right = [1,2,3], color = "Cyan")
output_file('bar.html')
show(fig)
The bars are shown vertically across plot height. The vbar() method has following parameters −
Following code displays vertical bar plot −
from bokeh.plotting import figure, output_file, show
fig = figure(plot_width = 200, plot_height = 400)
fig.vbar(x = [1,2,3], width = 0.5, bottom = 0, top = [2,4,6], color = "Cyan")
output_file('bar.html')
show(fig)
A plot which shades a region of space in a specific color to show a region or a group having similar properties is termed as a patch plot in Bokeh. Figure object has patch() and patches() methods for this purpose.
This method adds patch glyph to given figure. The method has the following arguments −
A simple patch plot is obtained by the following Python code −
from bokeh.plotting import figure, output_file, show
p = figure(plot_width = 300, plot_height = 300)
p.patch(x = [1, 3,2,4], y = [2,3,5,7], color = "green")
output_file('patch.html')
show(p)
This method is used to draw multiple polygonal patches. It needs following arguments −
As an example of patches() method, run the following code −
from bokeh.plotting import figure, output_file, show
xs = [[5,3,4], [2,4,3], [2,3,5,4]]
ys = [[6,4,2], [3,6,7], [2,4,7,8]]
fig = figure()
fig.patches(xs, ys, fill_color = ['red', 'blue', 'black'], line_color = 'white')
output_file('patch_plot.html')
show(fig)
Scatter plots are very commonly used to determine the bi-variate relationship between two variables. The enhanced interactivity is added to them using Bokeh. Scatter plot is obtained by calling scatter() method of Figure object. It uses the following parameters −
Following marker type constants are defined in Bokeh: −
Asterisk
Circle
CircleCross
CircleX
Cross
Dash
Diamond
DiamondCross
Hex
InvertedTriangle
Square
SquareCross
SquareX
Triangle
X
Following Python code generates scatter plot with circle marks.
from bokeh.plotting import figure, output_file, show
fig = figure()
fig.scatter([1, 4, 3, 2, 5], [6, 5, 2, 4, 7], marker = "circle", size = 20, fill_color = "grey")
output_file('scatter.html')
show(fig)
Area plots are filled regions between two series that share a common index. Bokeh's Figure class has two methods as follows −
Output of the varea() method is a vertical directed area that has one x coordinate array, and two y coordinate arrays, y1 and y2, which will be filled between.
from bokeh.plotting import figure, output_file, show
fig = figure()
x = [1, 2, 3, 4, 5]
y1 = [2, 6, 4, 3, 5]
y2 = [1, 4, 2, 2, 3]
fig.varea(x = x,y1 = y1,y2 = y2)
output_file('area.html')
show(fig)
The harea() method on the other hand needs x1, x2 and y parameters.
from bokeh.plotting import figure, output_file, show
fig = figure()
y = [1, 2, 3, 4, 5]
x1 = [2, 6, 4, 3, 5]
x2 = [1, 4, 2, 2, 3]
fig.harea(x1 = x1,x2 = x2,y = y)
output_file('area.html')
show(fig)
The figure object has many methods using which vectorised glyphs of different shapes such as circle, rectangle, polygon, etc. can, be drawn.
Following methods are available for drawing circle glyphs −
The circle() method adds a circle glyph to the figure and needs x and y coordinates of its center. Additionally, it can be configured with the help of parameters such as fill_color, line-color, line_width etc.
The circle_cross() method adds circle glyph with a ‘+’ cross through the center.
The circle_x() method adds circle with an ‘X’ cross through the center.
Following example shows use of various circle glyphs added to Bokeh figure −
from bokeh.plotting import figure, output_file, show
plot = figure(plot_width = 300, plot_height = 300)
plot.circle(x = [1, 2, 3], y = [3,7,5], size = 20, fill_color = 'red')
plot.circle_cross(x = [2,4,6], y = [5,8,9], size = 20, fill_color = 'blue',fill_alpha = 0.2, line_width = 2)
plot.circle_x(x = [5,7,2], y = [2,4,9], size = 20, fill_color = 'green',fill_alpha = 0.6, line_width = 2)
show(plot)
It is possible to render rectangle, ellipse and polygons in a Bokeh figure. The rect() method of Figure class adds a rectangle glyph based on x and y coordinates of center, width and height. The square() method on the other hand has size parameter to decide dimensions.
The ellipse() and oval() methods adds an ellipse and oval glyph. They use similar signature to that of rect() having x, y,w and h parameters. Additionally, angle parameter determines rotation from horizontal.
Following code shows use of different shape glyph methods −
from bokeh.plotting import figure, output_file, show
fig = figure(plot_width = 300, plot_height = 300)
fig.rect(x = 10,y = 10,width = 100, height = 50, width_units = 'screen', height_units = 'screen')
fig.square(x = 2,y = 3,size = 80, color = 'red')
fig.ellipse(x = 7,y = 6, width = 30, height = 10, fill_color = None, line_width = 2)
fig.oval(x = 6,y = 6,width = 2, height = 1, angle = -0.4)
show(fig)
The arc() method draws a simple line arc based on x and y coordinates, start and end angles and radius. Angles are given in radians whereas radius may be in screen units or data units. The wedge is a filled arc.
The wedge() method has same properties as arc() method. Both methods have provision of optional direction property which may be clock or anticlock that determines the direction of arc/wedge rendering. The annular_wedge() function renders a filled area between to arcs of inner and outer radius.
Here is an example of arc and wedge glyphs added to Bokeh figure −
from bokeh.plotting import figure, output_file, show
import math
fig = figure(plot_width = 300, plot_height = 300)
fig.arc(x = 3, y = 3, radius = 50, radius_units = 'screen', start_angle = 0.0, end_angle = math.pi/2)
fig.wedge(x = 3, y = 3, radius = 30, radius_units = 'screen',
start_angle = 0, end_angle = math.pi, direction = 'clock')
fig.annular_wedge(x = 3,y = 3, inner_radius = 100, outer_radius = 75,outer_radius_units = 'screen',
inner_radius_units = 'screen',start_angle = 0.4, end_angle = 4.5,color = "green", alpha = 0.6)
show(fig)
The bokeh.plotting API supports methods for rendering following specialised curves −
This method adds a Bézier curve to the figure object. A Bézier curve is a parametric curve used in computer graphics. Other uses include the design of computer fonts and animation, user interface design and for smoothing cursor trajectory.
In vector graphics, Bézier curves are used to model smooth curves that can be scaled indefinitely. A "Path" is combination of linked Bézier curves.
The beizer() method has following parameters which are defined −
Default value for all parameters is None.
Following code generates a HTML page showing a Bézier curve and parabola in Bokeh plot −
x = 2
y = 4
xp02 = x+0.4
xp01 = x+0.1
xm01 = x-0.1
yp01 = y+0.2
ym01 = y-0.2
fig = figure(plot_width = 300, plot_height = 300)
fig.bezier(x0 = x, y0 = y, x1 = xp02, y1 = y, cx0 = xp01, cy0 = yp01,
cx1 = xm01, cy1 = ym01, line_color = "red", line_width = 2)
This method adds a parabola glyph to bokeh figure. The function has same parameters as beizer(), except cx0 and cx1.
The code given below generates a quadratic curve.
x = 2
y = 4
xp02 = x + 0.3
xp01 = x + 0.2
xm01 = x - 0.4
yp01 = y + 0.1
ym01 = y - 0.2
x = x,
y = y,
xp02 = x + 0.4,
xp01 = x + 0.1,
yp01 = y + 0.2,
fig.quadratic(x0 = x, y0 = y, x1 = x + 0.4, y1 = y + 0.01, cx = x + 0.1,
cy = y + 0.2, line_color = "blue", line_width = 3)
Numeric ranges of data axes of a plot are automatically set by Bokeh taking into consideration the dataset under process. However, sometimes you may want to define the range of values on x and y axis explicitly. This is done by assigning x_range and y_range properties to a figure() function.
These ranges are defined with the help of range1d() function.
xrange = range1d(0,10)
To use this range object as x_range property, use the below code −
fig = figure(x,y,x_range = xrange)
In this chapter, we shall discuss about various types of axes.
In the examples so far, the Bokeh plots show numerical data along both x and y axes. In order to use categorical data along either of axes, we need to specify a FactorRange to specify categorical dimensions for one of them. For example, to use strings in the given list for x axis −
langs = ['C', 'C++', 'Java', 'Python', 'PHP']
fig = figure(x_range = langs, plot_width = 300, plot_height = 300)
With following example, a simple bar plot is displayed showing number of students enrolled for various courses offered.
from bokeh.plotting import figure, output_file, show
langs = ['C', 'C++', 'Java', 'Python', 'PHP']
students = [23,17,35,29,12]
fig = figure(x_range = langs, plot_width = 300, plot_height = 300)
fig.vbar(x = langs, top = students, width = 0.5)
show(fig)
To show each bar in different colour, set color property of vbar() function to list of color values.
cols = ['red','green','orange','navy', 'cyan']
fig.vbar(x = langs, top = students, color = cols,width=0.5)
To render a vertical (or horizontal) stacked bar using vbar_stack() or hbar_stack() function, set stackers property to list of fields to stack successively and source property to a dict object containing values corresponding to each field.
In following example, sales is a dictionary showing sales figures of three products in three months.
from bokeh.plotting import figure, output_file, show
products = ['computer','mobile','printer']
months = ['Jan','Feb','Mar']
sales = {'products':products,
'Jan':[10,40,5],
'Feb':[8,45,10],
'Mar':[25,60,22]}
cols = ['red','green','blue']#,'navy', 'cyan']
fig = figure(x_range = products, plot_width = 300, plot_height = 300)
fig.vbar_stack(months, x = 'products', source = sales, color = cols,width = 0.5)
show(fig)
A grouped bar plot is obtained by specifying a visual displacement for the bars with the help of dodge() function in bokeh.transform module.
The dodge() function introduces a relative offset for each bar plot thereby achieving a visual impression of group. In following example, vbar() glyph is separated by an offset of 0.25 for each group of bars for a particular month.
from bokeh.plotting import figure, output_file, show
from bokeh.transform import dodge
products = ['computer','mobile','printer']
months = ['Jan','Feb','Mar']
sales = {'products':products,
'Jan':[10,40,5],
'Feb':[8,45,10],
'Mar':[25,60,22]}
fig = figure(x_range = products, plot_width = 300, plot_height = 300)
fig.vbar(x = dodge('products', -0.25, range = fig.x_range), top = 'Jan',
width = 0.2,source = sales, color = "red")
fig.vbar(x = dodge('products', 0.0, range = fig.x_range), top = 'Feb',
width = 0.2, source = sales,color = "green")
fig.vbar(x = dodge('products', 0.25, range = fig.x_range), top = 'Mar',
width = 0.2,source = sales,color = "blue")
show(fig)
When values on one of the axes of a plot grow exponentially with linearly increasing values of another, it is often necessary to have the data on former axis be displayed on a log scale. For example, if there exists a power law relationship between x and y data series, it is desirable to use log scales on both axes.
Bokeh.plotting API's figure() function accepts x_axis_type and y_axis_type as arguments which may be specified as log axis by passing "log" for the value of either of these parameters.
First figure shows plot between x and 10x on a linear scale. In second figure y_axis_type is set to 'log'
from bokeh.plotting import figure, output_file, show
x = [0.1, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0]
y = [10**i for i in x]
fig = figure(title = 'Linear scale example',plot_width = 400, plot_height = 400)
fig.line(x, y, line_width = 2)
show(fig)
Now change figure() function to configure y_axis_type=’log’
fig = figure(title = 'Linear scale example',plot_width = 400, plot_height = 400, y_axis_type = "log")
In certain situations, it may be needed to show multiple axes representing varying ranges on a single plot figure. The figure object can be so configured by defining extra_x_range and extra_y_range properties. While adding new glyph to the figure, these named ranges are used.
We try to display a sine curve and a straight line in same plot. Both glyphs have y axes with different ranges. The x and y data series for sine curve and line are obtained by the following −
from numpy import pi, arange, sin, linspace
x = arange(-2*pi, 2*pi, 0.1)
y = sin(x)
y2 = linspace(0, 100, len(y))
Here, plot between x and y represents sine relation and plot between x and y2 is a straight line. The Figure object is defined with explicit y_range and a line glyph representing sine curve is added as follows −
fig = figure(title = 'Twin Axis Example', y_range = (-1.1, 1.1))
fig.line(x, y, color = "red")
We need an extra y range. It is defined as −
fig.extra_y_ranges = {"y2": Range1d(start = 0, end = 100)}
To add additional y axis on right side, use add_layout() method. Add a new line glyph representing x and y2 to the figure.
fig.add_layout(LinearAxis(y_range_name = "y2"), 'right')
fig.line(x, y2, color = "blue", y_range_name = "y2")
This will result in a plot with twin y axes. Complete code and the output is as follows −
from numpy import pi, arange, sin, linspace
x = arange(-2*pi, 2*pi, 0.1)
y = sin(x)
y2 = linspace(0, 100, len(y))
from bokeh.plotting import output_file, figure, show
from bokeh.models import LinearAxis, Range1d
fig = figure(title='Twin Axis Example', y_range = (-1.1, 1.1))
fig.line(x, y, color = "red")
fig.extra_y_ranges = {"y2": Range1d(start = 0, end = 100)}
fig.add_layout(LinearAxis(y_range_name = "y2"), 'right')
fig.line(x, y2, color = "blue", y_range_name = "y2")
show(fig)
Annotations are pieces of explanatory text added to the diagram. Bokeh plot can be annotated by way of specifying plot title, labels for x and y axes as well as inserting text labels anywhere in the plot area.
Plot title as well as x and y axis labels can be provided in the Figure constructor itself.
fig = figure(title, x_axis_label, y_axis_label)
In the following plot, these properties are set as shown below −
from bokeh.plotting import figure, output_file, show
import numpy as np
import math
x = np.arange(0, math.pi*2, 0.05)
y = np.sin(x)
fig = figure(title = "sine wave example", x_axis_label = 'angle', y_axis_label = 'sin')
fig.line(x, y,line_width = 2)
show(p)
The title’s text and axis labels can also be specified by assigning appropriate string values to corresponding properties of figure object.
fig.title.text = "sine wave example"
fig.xaxis.axis_label = 'angle'
fig.yaxis.axis_label = 'sin'
It is also possible to specify location, alignment, font and color of title.
fig.title.align = "right"
fig.title.text_color = "orange"
fig.title.text_font_size = "25px"
fig.title.background_fill_color = "blue"
Adding legends to the plot figure is very easy. We have to use legend property of any glyph method.
Below we have three glyph curves in the plot with three different legends −
from bokeh.plotting import figure, output_file, show
import numpy as np
import math
x = np.arange(0, math.pi*2, 0.05)
fig = figure()
fig.line(x, np.sin(x),line_width = 2, line_color = 'navy', legend = 'sine')
fig.circle(x,np.cos(x), line_width = 2, line_color = 'orange', legend = 'cosine')
fig.square(x,-np.sin(x),line_width = 2, line_color = 'grey', legend = '-sine')
show(fig)
In all the examples above, the data to be plotted has been provided in the form of Python lists or numpy arrays. It is also possible to provide the data source in the form of pandas DataFrame object.
DataFrame is a two-dimensional data structure. Columns in the dataframe can be of different data types. The Pandas library has functions to create dataframe from various sources such as CSV file, Excel worksheet, SQL table, etc.
For the purpose of following example, we are using a CSV file consisting of two columns representing a number x and 10x. The test.csv file is as below −
x,pow
0.0,1.0
0.5263157894736842,3.3598182862837818
1.0526315789473684,11.28837891684689
1.5789473684210527,37.926901907322495
2.1052631578947367,127.42749857031335
2.631578947368421,428.1332398719391
3.1578947368421053,1438.449888287663
3.6842105263157894,4832.930238571752
4.2105263157894735,16237.76739188721
4.7368421052631575,54555.947811685146
We shall read this file in a dataframe object using read_csv() function in pandas.
import pandas as pd
df = pd.read_csv('test.csv')
print (df)
The dataframe appears as below −
x pow
0 0.000000 1.000000
1 0.526316 3.359818
2 1.052632 11.288379
3 1.578947 37.926902
4 2.105263 127.427499
5 2.631579 428.133240
6 3.157895 1438.449888
7 3.684211 4832.930239
8 4.210526 16237.767392
9 4.736842 54555.947812
The ‘x’ and ‘pow’ columns are used as data series for line glyph in bokeh plot figure.
from bokeh.plotting import figure, output_file, show
p = figure()
x = df['x']
y = df['pow']
p.line(x,y,line_width = 2)
p.circle(x, y,size = 20)
show(p)
Most of the plotting methods in Bokeh API are able to receive data source parameters through ColumnDatasource object. It makes sharing data between plots and ‘DataTables’.
A ColumnDatasource can be considered as a mapping between column name and list of data. A Python dict object with one or more string keys and lists or numpy arrays as values is passed to ColumnDataSource constructor.
Below is the example
from bokeh.models import ColumnDataSource
data = {'x':[1, 4, 3, 2, 5],
'y':[6, 5, 2, 4, 7]}
cds = ColumnDataSource(data = data)
This object is then used as value of source property in a glyph method. Following code generates a scatter plot using ColumnDataSource.
from bokeh.plotting import figure, output_file, show
from bokeh.models import ColumnDataSource
data = {'x':[1, 4, 3, 2, 5],
'y':[6, 5, 2, 4, 7]}
cds = ColumnDataSource(data = data)
fig = figure()
fig.scatter(x = 'x', y = 'y',source = cds, marker = "circle", size = 20, fill_color = "grey")
show(fig)
Instead of assigning a Python dictionary to ColumnDataSource, we can use a Pandas DataFrame for it.
Let us use ‘test.csv’ (used earlier in this section) to obtain a DataFrame and use it for getting ColumnDataSource and rendering line plot.
from bokeh.plotting import figure, output_file, show
import pandas as pd
from bokeh.models import ColumnDataSource
df = pd.read_csv('test.csv')
cds = ColumnDataSource(df)
fig = figure(y_axis_type = 'log')
fig.line(x = 'x', y = 'pow',source = cds, line_color = "grey")
show(fig)
Often, you may want to obtain a plot pertaining to a part of data that satisfies certain conditions instead of the entire dataset. Object of the CDSView class defined in bokeh.models module returns a subset of ColumnDatasource under consideration by applying one or more filters over it.
IndexFilter is the simplest type of filter. You have to specify indices of only those rows from the dataset that you want to use while plotting the figure.
Following example demonstrates use of IndexFilter to set up a CDSView. The resultant figure shows a line glyph between x and y data series of the ColumnDataSource. A view object is obtained by applying index filter over it. The view is used to plot circle glyph as a result of IndexFilter.
from bokeh.models import ColumnDataSource, CDSView, IndexFilter
from bokeh.plotting import figure, output_file, show
source = ColumnDataSource(data = dict(x = list(range(1,11)), y = list(range(2,22,2))))
view = CDSView(source=source, filters = [IndexFilter([0, 2, 4,6])])
fig = figure(title = 'Line Plot example', x_axis_label = 'x', y_axis_label = 'y')
fig.circle(x = "x", y = "y", size = 10, source = source, view = view, legend = 'filtered')
fig.line(source.data['x'],source.data['y'], legend = 'unfiltered')
show(fig)
To choose only those rows from the data source, that satisfy a certain Boolean condition, apply a BooleanFilter.
A typical Bokeh installation consists of a number of sample data sets in sampledata directory. For following example, we use unemployment1948 dataset provided in the form of unemployment1948.csv. It stores year wise percentage of unemployment in USA since 1948. We want to generate a plot only for year 1980 onwards. For that purpose, a CDSView object is obtained by applying BooleanFilter over the given data source.
from bokeh.models import ColumnDataSource, CDSView, BooleanFilter
from bokeh.plotting import figure, show
from bokeh.sampledata.unemployment1948 import data
source = ColumnDataSource(data)
booleans = [True if int(year) >= 1980 else False for year in
source.data['Year']]
print (booleans)
view1 = CDSView(source = source, filters=[BooleanFilter(booleans)])
p = figure(title = "Unemployment data", x_range = (1980,2020), x_axis_label = 'Year', y_axis_label='Percentage')
p.line(x = 'Year', y = 'Annual', source = source, view = view1, color = 'red', line_width = 2)
show(p)
To add more flexibility in applying filter, Bokeh provides a CustomJSFilter class with the help of which the data source can be filtered with a user defined JavaScript function.
The example given below uses the same USA unemployment data. Defining a CustomJSFilter to plot unemployment figures of year 1980 and after.
from bokeh.models import ColumnDataSource, CDSView, CustomJSFilter
from bokeh.plotting import figure, show
from bokeh.sampledata.unemployment1948 import data
source = ColumnDataSource(data)
custom_filter = CustomJSFilter(code = '''
var indices = [];
for (var i = 0; i < source.get_length(); i++){
if (parseInt(source.data['Year'][i]) > = 1980){
indices.push(true);
} else {
indices.push(false);
}
}
return indices;
''')
view1 = CDSView(source = source, filters = [custom_filter])
p = figure(title = "Unemployment data", x_range = (1980,2020), x_axis_label = 'Year', y_axis_label = 'Percentage')
p.line(x = 'Year', y = 'Annual', source = source, view = view1, color = 'red', line_width = 2)
show(p)
Bokeh visualizations can be suitably arranged in different layout options. These layouts as well as sizing modes result in plots and widgets resizing automatically as per the size of browser window. For consistent appearance, all items in a layout must have same sizing mode. The widgets (buttons, menus, etc.) are kept in a separate widget box and not in plot figure.
First type of layout is Column layout which displays plot figures vertically. The column() function is defined in bokeh.layouts module and takes following signature −
from bokeh.layouts import column
col = column(children, sizing_mode)
children − List of plots and/or widgets.
sizing_mode − determines how items in the layout resize. Possible values are "fixed", "stretch_both", "scale_width", "scale_height", "scale_both". Default is “fixed”.
Following code produces two Bokeh figures and places them in a column layout so that they are displayed vertically. Line glyphs representing sine and cos relationship between x and y data series is displayed in Each figure.
from bokeh.plotting import figure, output_file, show
from bokeh.layouts import column
import numpy as np
import math
x = np.arange(0, math.pi*2, 0.05)
y1 = np.sin(x)
y2 = np.cos(x)
fig1 = figure(plot_width = 200, plot_height = 200)
fig1.line(x, y1,line_width = 2, line_color = 'blue')
fig2 = figure(plot_width = 200, plot_height = 200)
fig2.line(x, y2,line_width = 2, line_color = 'red')
c = column(children = [fig1, fig2], sizing_mode = 'stretch_both')
show(c)
Similarly, Row layout arranges plots horizontally, for which row() function as defined in bokeh.layouts module is used. As you would think, it also takes two arguments (similar to column() function) – children and sizing_mode.
The sine and cos curves as shown vertically in above diagram are now displayed horizontally in row layout with following code
from bokeh.plotting import figure, output_file, show
from bokeh.layouts import row
import numpy as np
import math
x = np.arange(0, math.pi*2, 0.05)
y1 = np.sin(x)
y2 = np.cos(x)
fig1 = figure(plot_width = 200, plot_height = 200)
fig1.line(x, y1,line_width = 2, line_color = 'blue')
fig2 = figure(plot_width = 200, plot_height = 200)
fig2.line(x, y2,line_width = 2, line_color = 'red')
r = row(children = [fig1, fig2], sizing_mode = 'stretch_both')
show(r)
The Bokeh package also has grid layout. It holds multiple plot figures (as well as widgets) in a two dimensional grid of rows and columns. The gridplot() function in bokeh.layouts module returns a grid and a single unified toolbar which may be positioned with the help of toolbar_location property.
This is unlike row or column layout where each plot shows its own toolbar. The grid() function too uses children and sizing_mode parameters where children is a list of lists. Ensure that each sublist is of same dimensions.
In the following code, four different relationships between x and y data series are plotted in a grid of two rows and two columns.
from bokeh.plotting import figure, output_file, show
from bokeh.layouts import gridplot
import math
x = list(range(1,11))
y1 = x
y2 =[11-i for i in x]
y3 = [i*i for i in x]
y4 = [math.log10(i) for i in x]
fig1 = figure(plot_width = 200, plot_height = 200)
fig1.line(x, y1,line_width = 2, line_color = 'blue')
fig2 = figure(plot_width = 200, plot_height = 200)
fig2.circle(x, y2,size = 10, color = 'green')
fig3 = figure(plot_width = 200, plot_height = 200)
fig3.circle(x,y3, size = 10, color = 'grey')
fig4 = figure(plot_width = 200, plot_height = 200, y_axis_type = 'log')
fig4.line(x,y4, line_width = 2, line_color = 'red')
grid = gridplot(children = [[fig1, fig2], [fig3,fig4]], sizing_mode = 'stretch_both')
show(grid)
When a Bokeh plot is rendered, normally a tool bar appears on the right side of the figure. It contains a default set of tools. First of all, the position of toolbar can be configured by toolbar_location property in figure() function. This property can take one of the following values −
"above"
"below"
"left"
"right"
"None"
For example, following statement will cause toolbar to be displayed below the plot −
Fig = figure(toolbar_location = "below")
This toolbar can be configured according to the requirement by adding required from various tools defined in bokeh.models module. For example −
Fig.add_tools(WheelZoomTool())
The tools can be classified under following categories −
Pan/Drag Tools
Click/Tap Tools
Scroll/Pinch Tools
BoxSelectTool
Name : 'box_select'
LassoSelectTool
name: 'lasso_select
PanTool
name: 'pan', 'xpan', 'ypan',
TapTool
name: 'tap
WheelZoomTool
name: 'wheel_zoom', 'xwheel_zoom', 'ywheel_zoom'
WheelPanTool
name: 'xwheel_pan', 'ywheel_pan'
ResetTool
name: 'reset'
SaveTool
name: 'save'
ZoomInTool
name: 'zoom_in', 'xzoom_in', 'yzoom_in'
ZoomOutTool
name: 'zoom_out', 'xzoom_out', 'yzoom_out'
CrosshairTool
name: 'crosshair'
The default appearance of a Bokeh plot can be customised by setting various properties to desired value. These properties are mainly of three types −
Following table lists various properties related to line glyph.
Various fill properties are listed below −
There are many text related properties as listed in the following table −
Various glyphs in a plot can be identified by legend property appear as a label by default at top-right position of the plot area. This legend can be customised by following attributes −
Example code for legend customisation is as follows −
from bokeh.plotting import figure, output_file, show
import math
x2 = list(range(1,11))
y4 = [math.pow(i,2) for i in x2]
y2 = [math.log10(pow(10,i)) for i in x2]
fig = figure(y_axis_type = 'log')
fig.circle(x2, y2,size = 5, color = 'blue', legend = 'blue circle')
fig.line(x2,y4, line_width = 2, line_color = 'red', legend = 'red line')
fig.legend.location = 'top_left'
fig.legend.title = 'Legend Title'
fig.legend.title_text_font = 'Arial'
fig.legend.title_text_font_size = '20pt'
show(fig)
The bokeh.models.widgets module contains definitions of GUI objects similar to HTML form elements, such as button, slider, checkbox, radio button, etc. These controls provide interactive interface to a plot. Invoking processing such as modifying plot data, changing plot parameters, etc., can be performed by custom JavaScript functions executed on corresponding events.
Bokeh allows call back functionality to be defined with two methods −
Use the CustomJS callback so that the interactivity will work in standalone HTML documents.
Use the CustomJS callback so that the interactivity will work in standalone HTML documents.
Use Bokeh server and set up event handlers.
Use Bokeh server and set up event handlers.
In this section, we shall see how to add Bokeh widgets and assign JavaScript callbacks.
This widget is a clickable button generally used to invoke a user defined call back handler. The constructor takes following parameters −
Button(label, icon, callback)
The label parameter is a string used as button’s caption and callback is the custom JavaScript function to be called when clicked.
In the following example, a plot and Button widget are displayed in Column layout. The plot itself renders a line glyph between x and y data series.
A custom JavaScript function named ‘callback’ has been defined using CutomJS() function. It receives reference to the object that triggered callback (in this case the button) in the form variable cb_obj.
This function alters the source ColumnDataSource data and finally emits this update in source data.
from bokeh.layouts import column
from bokeh.models import CustomJS, ColumnDataSource
from bokeh.plotting import Figure, output_file, show
from bokeh.models.widgets import Button
x = [x*0.05 for x in range(0, 200)]
y = x
source = ColumnDataSource(data=dict(x=x, y=y))
plot = Figure(plot_width=400, plot_height=400)
plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6)
callback = CustomJS(args=dict(source=source), code="""
var data = source.data;
x = data['x']
y = data['y']
for (i = 0; i < x.length; i++) {
y[i] = Math.pow(x[i], 4)
}
source.change.emit();
""")
btn = Button(label="click here", callback=callback, name="1")
layout = column(btn , plot)
show(layout)
Click on the button on top of the plot and see the updated plot figure which looks as follows −
With the help of a slider control it is possible to select a number between start and end properties assigned to it.
Slider(start, end, step, value)
In the following example, we register a callback function on slider’s on_change event. Slider’s instantaneous numeric value is available to the handler in the form of cb_obj.value which is used to modify the ColumnDatasource data. The plot figure continuously updates as you slide the position.
from bokeh.layouts import column
from bokeh.models import CustomJS, ColumnDataSource
from bokeh.plotting import Figure, output_file, show
from bokeh.models.widgets import Slider
x = [x*0.05 for x in range(0, 200)]
y = x
source = ColumnDataSource(data=dict(x=x, y=y))
plot = Figure(plot_width=400, plot_height=400)
plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6)
handler = CustomJS(args=dict(source=source), code="""
var data = source.data;
var f = cb_obj.value
var x = data['x']
var y = data['y']
for (var i = 0; i < x.length; i++) {
y[i] = Math.pow(x[i], f)
}
source.change.emit();
""")
slider = Slider(start=0.0, end=5, value=1, step=.25, title="Slider Value")
slider.js_on_change('value', handler)
layout = column(slider, plot)
show(layout)
This widget presents a collection of mutually exclusive toggle buttons showing circular buttons to the left of caption.
RadioGroup(labels, active)
Where, labels is a list of captions and active is the index of selected option.
This widget is a simple dropdown list of string items, one of which can be selected. Selected string appears at the top window and it is the value parameter.
Select(options, value)
The list of string elements in the dropdown is given in the form of options list object.
Following is a combined example of radio button and select widgets, both providing three different relationships between x and y data series. The RadioGroup and Select widgets are registered with respective handlers through on_change() method.
from bokeh.layouts import column
from bokeh.models import CustomJS, ColumnDataSource
from bokeh.plotting import Figure, output_file, show
from bokeh.models.widgets import RadioGroup, Select
x = [x*0.05 for x in range(0, 200)]
y = x
source = ColumnDataSource(data=dict(x=x, y=y))
plot = Figure(plot_width=400, plot_height=400)
plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6)
radiohandler = CustomJS(args=dict(source=source), code="""
var data = source.data;
console.log('Tap event occurred at x-position: ' + cb_obj.active);
//plot.title.text=cb_obj.value;
x = data['x']
y = data['y']
if (cb_obj.active==0){
for (i = 0; i < x.length; i++) {
y[i] = x[i];
}
}
if (cb_obj.active==1){
for (i = 0; i < x.length; i++) {
y[i] = Math.pow(x[i], 2)
}
}
if (cb_obj.active==2){
for (i = 0; i < x.length; i++) {
y[i] = Math.pow(x[i], 4)
}
}
source.change.emit();
""")
selecthandler = CustomJS(args=dict(source=source), code="""
var data = source.data;
console.log('Tap event occurred at x-position: ' + cb_obj.value);
//plot.title.text=cb_obj.value;
x = data['x']
y = data['y']
if (cb_obj.value=="line"){
for (i = 0; i < x.length; i++) {
y[i] = x[i];
}
}
if (cb_obj.value=="SquareCurve"){
for (i = 0; i < x.length; i++) {
y[i] = Math.pow(x[i], 2)
}
}
if (cb_obj.value=="CubeCurve"){
for (i = 0; i < x.length; i++) {
y[i] = Math.pow(x[i], 4)
}
}
source.change.emit();
""")
radio = RadioGroup(
labels=["line", "SqureCurve", "CubeCurve"], active=0)
radio.js_on_change('active', radiohandler)
select = Select(title="Select:", value='line', options=["line", "SquareCurve", "CubeCurve"])
select.js_on_change('value', selecthandler)
layout = column(radio, select, plot)
show(layout)
Just as in a browser, each tab can show different web page, the Tab widget is Bokeh model providing different view to each figure. In the following example, two plot figures of sine and cosine curves are rendered in two different tabs −
from bokeh.plotting import figure, output_file, show
from bokeh.models import Panel, Tabs
import numpy as np
import math
x=np.arange(0, math.pi*2, 0.05)
fig1=figure(plot_width=300, plot_height=300)
fig1.line(x, np.sin(x),line_width=2, line_color='navy')
tab1 = Panel(child=fig1, title="sine")
fig2=figure(plot_width=300, plot_height=300)
fig2.line(x,np.cos(x), line_width=2, line_color='orange')
tab2 = Panel(child=fig2, title="cos")
tabs = Tabs(tabs=[ tab1, tab2 ])
show(tabs)
Bokeh architecture has a decouple design in which objects such as plots and glyphs are created using Python and converted in JSON to be consumed by BokehJS client library.
However, it is possible to keep the objects in python and in the browser in sync with one another with the help of Bokeh Server. It enables response to User Interface (UI) events generated in a browser with the full power of python. It also helps automatically push server-side updates to the widgets or plots in a browser.
A Bokeh server uses Application code written in Python to create Bokeh Documents. Every new connection from a client browser results in the Bokeh server creating a new document, just for that session.
First, we have to develop an application code to be served to client browser. Following code renders a sine wave line glyph. Along with the plot, a slider control is also rendered to control the frequency of sine wave. The callback function update_data() updates ColumnDataSource data taking the instantaneous value of slider as current frequency.
import numpy as np
from bokeh.io import curdoc
from bokeh.layouts import row, column
from bokeh.models import ColumnDataSource
from bokeh.models.widgets import Slider, TextInput
from bokeh.plotting import figure
N = 200
x = np.linspace(0, 4*np.pi, N)
y = np.sin(x)
source = ColumnDataSource(data = dict(x = x, y = y))
plot = figure(plot_height = 400, plot_width = 400, title = "sine wave")
plot.line('x', 'y', source = source, line_width = 3, line_alpha = 0.6)
freq = Slider(title = "frequency", value = 1.0, start = 0.1, end = 5.1, step = 0.1)
def update_data(attrname, old, new):
a = 1
b = 0
w = 0
k = freq.value
x = np.linspace(0, 4*np.pi, N)
y = a*np.sin(k*x + w) + b
source.data = dict(x = x, y = y)
freq.on_change('value', update_data)
curdoc().add_root(row(freq, plot, width = 500))
curdoc().title = "Sliders"
Next, start Bokeh server by following command line −
Bokeh serve –show sliders.py
Bokeh server starts running and serving the application at localhost:5006/sliders. The console log shows the following display −
C:\Users\User>bokeh serve --show scripts\sliders.py
2019-09-29 00:21:35,855 Starting Bokeh server version 1.3.4 (running on Tornado 6.0.3)
2019-09-29 00:21:35,875 Bokeh app running at: http://localhost:5006/sliders
2019-09-29 00:21:35,875 Starting Bokeh server with process id: 3776
2019-09-29 00:21:37,330 200 GET /sliders (::1) 699.99ms
2019-09-29 00:21:38,033 101 GET /sliders/ws?bokeh-protocol-version=1.0&bokeh-session-id=VDxLKOzI5Ppl9kDvEMRzZgDVyqnXzvDWsAO21bRCKRZZ (::1) 4.00ms
2019-09-29 00:21:38,045 WebSocket connection opened
2019-09-29 00:21:38,049 ServerConnection created
Open your favourite browser and enter above address. The Sine wave plot is displayed as follows −
You can try and change the frequency to 2 by rolling the slider.
The Bokeh application provides a number of subcommands to be executed from command line. Following table shows the subcommands −
Following command generates a HTML file for Python script having a Bokeh figure.
C:\python37>bokeh html -o app.html app.py
Adding show option automatically opens the HTML file in browser. Likewise, Python script is converted to PNG, SVG, JSON files with corresponding subcommand.
To display information of Bokeh server, use info subcommand as follows −
C:\python37>bokeh info
Python version : 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)]
IPython version : (not installed)
Tornado version : 6.0.3
Bokeh version : 1.3.4
BokehJS static path : c:\python37\lib\site-packages\bokeh\server\static
node.js version : (not installed)
npm version : (not installed)
In order to experiment with various types of plots, Bokeh website https://bokeh.pydata.org makes available sample datasets. They can be downloaded to local machine by sampledata subcommand.
C:\python37>bokeh info
Following datasets are downloaded in C:\Users\User\.bokeh\data folder −
AAPL.csv airports.csv
airports.json CGM.csv
FB.csv gapminder_fertility.csv
gapminder_life_expectancy.csv gapminder_population.csv
gapminder_regions.csv GOOG.csv
haarcascade_frontalface_default.xml IBM.csv
movies.db MSFT.csv
routes.csv unemployment09.csv
us_cities.json US_Counties.csv
world_cities.csv
WPP2012_SA_DB03_POPULATION_QUINQUENNIAL.csv
The secret subcommand generates a secret key to be used along with serve subcommand with SECRET_KEY environment variable.
In addition to subcommands described above, Bokeh plots can be exported to PNG and SVG file format using export() function. For that purpose, local Python installation should have following dependency libraries.
PhantomJS is a JavaScript API that enables automated navigation, screenshots, user behavior and assertions. It is used to run browser-based unit tests. PhantomJS is based on WebKit providing a similar browsing environment for different browsers and provides fast and native support for various web standards: DOM handling, CSS selector, JSON, Canvas, and SVG. In other words, PhantomJS is a web browser without a graphical user interface.
Pillow, a Python Imaging Library (earlier known as PIL) is a free library for the Python programming language that provides support for opening, manipulating, and saving many different image file formats. (including PPM, PNG, JPEG, GIF, TIFF, and BMP.) Some of its features are per-pixel manipulations, masking and transparency handling, image filtering, image enhancing, etc.
The export_png() function generates RGBA-format PNG image from layout. This function uses Webkit headless browser to render the layout in memory and then capture a screenshot. The generated image will be of the same dimensions as the source layout. Make sure that the Plot.background_fill_color and Plot.border_fill_color are properties to None.
from bokeh.io import export_png
export_png(plot, filename = "file.png")
It is possible that HTML5 Canvas plot output with a SVG element that can be edited using programs such as Adobe Illustrator. The SVG objects can also be converted to PDFs. Here, canvas2svg, a JavaScript library is used to mock the normal Canvas element and its methods with an SVG element. Like PNGs, in order to create a SVG with a transparent background,the Plot.background_fill_color and Plot.border_fill_color properties should be to None.
The SVG backend is first activated by setting the Plot.output_backend attribute to "svg".
plot.output_backend = "svg"
For headless export, Bokeh has a utility function, export_svgs(). This function will download all of SVG-enabled plots within a layout as distinct SVG files.
from bokeh.io import export_svgs
plot.output_backend = "svg"
export_svgs(plot, filename = "plot.svg")
Plots and data in the form of standalone documents as well as Bokeh applications can be embedded in HTML documents.
Standalone document is a Bokeh plot or document not backed by Bokeh server. The interactions in such a plot is purely in the form of custom JS and not Pure Python callbacks.
Bokeh plots and documents backed by Bokeh server can also be embedded. Such documents contain Python callbacks that run on the server.
In case of standalone documents, a raw HTML code representing a Bokeh plot is obtained by file_html() function.
from bokeh.plotting import figure
from bokeh.resources import CDN
from bokeh.embed import file_html
fig = figure()
fig.line([1,2,3,4,5], [3,4,5,2,3])
string = file_html(plot, CDN, "my plot")
Return value of file_html() function may be saved as HTML file or may be used to render through URL routes in Flask app.
In case of standalone document, its JSON representation can be obtained by json_item() function.
from bokeh.plotting import figure
from bokeh.embed import file_html
import json
fig = figure()
fig.line([1,2,3,4,5], [3,4,5,2,3])
item_text = json.dumps(json_item(fig, "myplot"))
This output can be used by the Bokeh.embed.embed_item function on a webpage −
item = JSON.parse(item_text);
Bokeh.embed.embed_item(item);
Bokeh applications on Bokeh Server may also be embedded so that a new session and Document is created on every page load so that a specific, existing session is loaded. This can be accomplished with the server_document() function. It accepts the URL to a Bokeh server application, and returns a script that will embed new sessions from that server any time the script is executed.
The server_document() function accepts URL parameter. If it is set to ‘default’, the default URL http://localhost:5006/ will be used.
from bokeh.embed import server_document
script = server_document("http://localhost:5006/sliders")
The server_document() function returns a script tag as follows −
<script
src="http://localhost:5006/sliders/autoload.js?bokeh-autoload-element=1000&bokeh-app-path=/sliders&bokeh-absolute-url=https://localhost:5006/sliders"
id="1000">
</script>
Bokeh integrates well with a wide variety of other libraries, allowing you to use the most appropriate tool for each task. The fact that Bokeh generates JavaScript, makes it possible to combine Bokeh output with a wide variety of JavaScript libraries, such as PhosphorJS.
Datashader (https://github.com/bokeh/datashader) is another library with which Bokeh output can be extended. It is a Python library that pre-renders large datasets as a large-sized raster image. This ability overcomes limitation of browser when it comes to very large data. Datashader includes tools to build interactive Bokeh plots that dynamically re-render these images when zooming and panning in Bokeh, making it practical to work with arbitrarily large datasets in a web browser.
Another library is Holoviews ((http://holoviews.org/) that provides a concise declarative interface for building Bokeh plots, especially in Jupyter notebook. It facilitates quick prototyping of figures for data analysis.
When one has to use large datasets for creating visualizations with the help of Bokeh, the interaction can be very slow. For that purpose, one can enable Web Graphics Library (WebGL) support.
WebGL is a JavaScript API that renders content in the browser using GPU (graphics processing unit). This standardized plugin is available in all modern browsers.
To enable WebGL, all you have to do is set output_backend property of Bokeh Figure object to ‘webgl’.
fig = figure(output_backend="webgl")
In the following example, we plot a scatter glyph consisting of 10,000 points with the help of WebGL support.
import numpy as np
from bokeh.plotting import figure, show, output_file
N = 10000
x = np.random.normal(0, np.pi, N)
y = np.sin(x) + np.random.normal(0, 0.2, N)
output_file("scatterWebGL.html")
p = figure(output_backend="webgl")
p.scatter(x, y, alpha=0.1)
show(p)
The Bokeh Python library, and libraries for Other Languages such as R, Scala, and Julia, primarily interacts with BokehJS at a high level. A Python programmer does not have to worry about JavaScript or web development. However, one can use BokehJS API, to do pure JavaScript development using BokehJS directly.
BokehJS objects such as glyphs and widgets are built more or less similarly as in Bokeh Python API. Typically, any Python ClassName is available as Bokeh.ClassName from JavaScript. For example, a Range1d object as obtained in Python.
xrange = Range1d(start=-0.5, end=20.5)
It is equivalently obtained with BokehJS as −
var xrange = new Bokeh.Range1d({ start: -0.5, end: 20.5 });
Following JavaScript code when embedded in a HTML file renders a simple line plot in the browser.
First include all BokehJS libraries in <head>..</head> secion of web page as below
<head>
<script type="text/javascript" src="https://cdn.pydata.org/bokeh/release/bokeh-1.3.4.min.js"></script>
<script type="text/javascript" src="https://cdn.pydata.org/bokeh/release/bokeh-widgets-1.3.4.min.js"></script>
<script type="text/javascript" src="https://cdn.pydata.org/bokeh/release/bokeh-tables-1.3.4.min.js"></script>
<script type="text/javascript" src="https://cdn.pydata.org/bokeh/release/bokeh-gl-1.3.4.min.js"></script>
<script type="text/javascript" src="https://cdn.pydata.org/bokeh/release/bokeh-api-1.3.4.min.js"></script>
<script type="text/javascript" src="https://cdn.pydata.org/bokeh/release/bokeh-api-1.3.4.min.js"></script>
</head>
In the body section following snippets of JavaScript construct various parts of a Bokeh Plot.
<script>
// create some data and a ColumnDataSource
var x = Bokeh.LinAlg.linspace(-0.5, 20.5, 10);
var y = x.map(function (v) { return v * 0.5 + 3.0; });
var source = new Bokeh.ColumnDataSource({ data: { x: x, y: y } });
// make the plot
var plot = new Bokeh.Plot({
title: "BokehJS Plot",
plot_width: 400,
plot_height: 400
});
// add axes to the plot
var xaxis = new Bokeh.LinearAxis({ axis_line_color: null });
var yaxis = new Bokeh.LinearAxis({ axis_line_color: null });
plot.add_layout(xaxis, "below");
plot.add_layout(yaxis, "left");
// add a Line glyph
var line = new Bokeh.Line({
x: { field: "x" },
y: { field: "y" },
line_color: "#666699",
line_width: 2
});
plot.add_glyph(line, source);
Bokeh.Plotting.show(plot);
</script>
Save above code as a web page and open it in a browser of your choice.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2533,
"s": 2270,
"text": "Bokeh is a data visualization library for Python. Unlike Matplotlib and Seaborn, they are also Python packages for data visualization, Bokeh renders its plots using HTML and JavaScript. Hence, it proves to be extremely useful for developing web based dashboards."
},
{
"code": null,
"e": 2842,
"s": 2533,
"text": "The Bokeh project is sponsored by NumFocus https://numfocus.org/. NumFocus also supports PyData, an educational program, involved in development of other important tools such as NumPy, Pandas and more. Bokeh can easily connect with these tools and produce interactive plots, dashboards and data applications."
},
{
"code": null,
"e": 3048,
"s": 2842,
"text": "Bokeh primarily converts the data source into a JSON file which is used as input for BokehJS, a JavaScript library, which in turn is written in TypeScript and renders the visualizations in modern browsers."
},
{
"code": null,
"e": 3105,
"s": 3048,
"text": "Some of the important features of Bokeh are as follows −"
},
{
"code": null,
"e": 3195,
"s": 3105,
"text": "Bokeh is useful for common plotting requirements as well as custom and complex use-cases."
},
{
"code": null,
"e": 3290,
"s": 3195,
"text": "Bokeh can easily interact with other popular Pydata tools such as Pandas and Jupyter notebook."
},
{
"code": null,
"e": 3625,
"s": 3290,
"text": "This is an important advantage of Bokeh over Matplotlib and Seaborn, both produce static plots. Bokeh creates interactive plots that change when the user interacts with them. You can give your audience a wide range of options and tools for inferring and looking at data from various angles so that user can perform “what if” analysis."
},
{
"code": null,
"e": 3723,
"s": 3625,
"text": "By adding custom JavaScript, it is possible to generate visualizations for specialised use-cases."
},
{
"code": null,
"e": 3830,
"s": 3723,
"text": "Plots can be embedded in output of Flask or Django enabled web applications. They can also be rendered in "
},
{
"code": null,
"e": 3838,
"s": 3830,
"text": "Jupyter"
},
{
"code": null,
"e": 4003,
"s": 3838,
"text": "Bokeh is an open source project. It is distributed under Berkeley Source Distribution (BSD) license. Its source code is available on https://github.com/bokeh/bokeh."
},
{
"code": null,
"e": 4247,
"s": 4003,
"text": "Bokeh can be installed on CPython versions 2.7 and 3.5+ only both with Standard distribution and Anaconda distribution. Current version of Bokeh at the time of writing this tutorial is ver. 1.3.4. Bokeh package has the following dependencies −"
},
{
"code": null,
"e": 4261,
"s": 4247,
"text": "jinja2 >= 2.7"
},
{
"code": null,
"e": 4276,
"s": 4261,
"text": "numpy >= 1.7.1"
},
{
"code": null,
"e": 4294,
"s": 4276,
"text": "packaging >= 16.8"
},
{
"code": null,
"e": 4308,
"s": 4294,
"text": "pillow >= 4.0"
},
{
"code": null,
"e": 4331,
"s": 4308,
"text": "python-dateutil >= 2.1"
},
{
"code": null,
"e": 4346,
"s": 4331,
"text": "pyyaml >= 3.10"
},
{
"code": null,
"e": 4359,
"s": 4346,
"text": "six >= 1.5.2"
},
{
"code": null,
"e": 4374,
"s": 4359,
"text": "tornado >= 4.3"
},
{
"code": null,
"e": 4513,
"s": 4374,
"text": "Generally, above packages are installed automatically when Bokeh is installed using Python’s built-in Package manager PIP as shown below −"
},
{
"code": null,
"e": 4533,
"s": 4513,
"text": "pip3 install bokeh\n"
},
{
"code": null,
"e": 4612,
"s": 4533,
"text": "If you are using Anaconda distribution, use conda package manager as follows −"
},
{
"code": null,
"e": 4633,
"s": 4612,
"text": "conda install bokeh\n"
},
{
"code": null,
"e": 4761,
"s": 4633,
"text": "In addition to the above dependencies, you may require additional packages such as pandas, psutil, etc., for specific purposes."
},
{
"code": null,
"e": 4877,
"s": 4761,
"text": "To verify if Bokeh has been successfully installed, import bokeh package in Python terminal and check its version −"
},
{
"code": null,
"e": 4925,
"s": 4877,
"text": ">>> import bokeh\n>>> bokeh.__version__\n'1.3.4'\n"
},
{
"code": null,
"e": 5066,
"s": 4925,
"text": "Creating a simple line plot between two numpy arrays is very simple. To begin with, import following functions from bokeh.plotting modules −"
},
{
"code": null,
"e": 5120,
"s": 5066,
"text": "from bokeh.plotting import figure, output_file, show\n"
},
{
"code": null,
"e": 5177,
"s": 5120,
"text": "The figure() function creates a new figure for plotting."
},
{
"code": null,
"e": 5252,
"s": 5177,
"text": "The output_file() function is used to specify a HTML file to store output."
},
{
"code": null,
"e": 5325,
"s": 5252,
"text": "The show() function displays the Bokeh figure in browser on in notebook."
},
{
"code": null,
"e": 5398,
"s": 5325,
"text": "Next, set up two numpy arrays where second array is sine value of first."
},
{
"code": null,
"e": 5478,
"s": 5398,
"text": "import numpy as np\nimport math\nx = np.arange(0, math.pi*2, 0.05)\ny = np.sin(x)\n"
},
{
"code": null,
"e": 5564,
"s": 5478,
"text": "To obtain a Bokeh Figure object, specify the title and x and y axis labels as below −"
},
{
"code": null,
"e": 5645,
"s": 5564,
"text": "p = figure(title = \"sine wave example\", x_axis_label = 'x', y_axis_label = 'y')\n"
},
{
"code": null,
"e": 5765,
"s": 5645,
"text": "The Figure object contains a line() method that adds a line glyph to the figure. It needs data series for x and y axes."
},
{
"code": null,
"e": 5812,
"s": 5765,
"text": "p.line(x, y, legend = \"sine\", line_width = 2)\n"
},
{
"code": null,
"e": 5867,
"s": 5812,
"text": "Finally, set the output file and call show() function."
},
{
"code": null,
"e": 5901,
"s": 5867,
"text": "output_file(\"sine.html\")\nshow(p)\n"
},
{
"code": null,
"e": 5981,
"s": 5901,
"text": "This will render the line plot in ‘sine.html’ and will be displayed in browser."
},
{
"code": null,
"e": 6272,
"s": 5981,
"text": "from bokeh.plotting import figure, output_file, show\nimport numpy as np\nimport math\nx = np.arange(0, math.pi*2, 0.05)\ny = np.sin(x)\noutput_file(\"sine.html\")\np = figure(title = \"sine wave example\", x_axis_label = 'x', y_axis_label = 'y')\np.line(x, y, legend = \"sine\", line_width = 2)\nshow(p)"
},
{
"code": null,
"e": 6459,
"s": 6272,
"text": "Displaying Bokeh figure in Jupyter notebook is very similar to the above. The only change you need to make is to import output_notebook instead of output_file from bokeh.plotting module."
},
{
"code": null,
"e": 6517,
"s": 6459,
"text": "from bokeh.plotting import figure, output_notebook, show\n"
},
{
"code": null,
"e": 6644,
"s": 6517,
"text": "Call to output_notebook() function sets Jupyter notebook’s output cell as the destination for show() function as shown below −"
},
{
"code": null,
"e": 6671,
"s": 6644,
"text": "output_notebook()\nshow(p)\n"
},
{
"code": null,
"e": 6770,
"s": 6671,
"text": "Enter the code in a notebook cell and run it. The sine wave will be displayed inside the notebook."
},
{
"code": null,
"e": 6864,
"s": 6770,
"text": "Bokeh package offers two interfaces using which various plotting operations can be performed."
},
{
"code": null,
"e": 7188,
"s": 6864,
"text": "This module is a low level interface. It provides great deal of flexibility to the application developer in developing visualizations. A Bokeh plot results in an object containing visual and data aspects of a scene which is used by BokehJS library. The low-level objects that comprise a Bokeh scene graph are called Models."
},
{
"code": null,
"e": 7394,
"s": 7188,
"text": "This is a higher level interface that has functionality for composing visual glyphs. This module contains definition of Figure class. It actually is a subclass of plot class defined in bokeh.models module."
},
{
"code": null,
"e": 7607,
"s": 7394,
"text": "Figure class simplifies plot creation. It contains various methods to draw different vectorized graphical glyphs. Glyphs are the building blocks of Bokeh plot such as lines, circles, rectangles, and other shapes."
},
{
"code": null,
"e": 7795,
"s": 7607,
"text": "Bokeh package Application class which is a lightweight factory for creating Bokeh Documents. A Document is a container for Bokeh Models to be reflected to the client side BokehJS library."
},
{
"code": null,
"e": 7952,
"s": 7795,
"text": "It provides customizable Bokeh Server Tornadocore application. Server is used to share and publish interactive plots and apps to an audience of your choice."
},
{
"code": null,
"e": 8366,
"s": 7952,
"text": "Any plot is usually made up of one or many geometrical shapes such as line, circle, rectangle, etc. These shapes have visual information about the corresponding set of data. In Bokeh terminology, these geometrical shapes are called gylphs. Bokeh plots constructed using bokeh.plotting interface use a default set of tools and styles. However, it is possible to customize the styles using available plotting tools."
},
{
"code": null,
"e": 8433,
"s": 8366,
"text": "Different types of plots created using glyphs are as given below −"
},
{
"code": null,
"e": 8592,
"s": 8433,
"text": "This type of plot is useful for visualizing the movements of points along the x-and y-axes in the form of a line. It is used to perform time series analytics."
},
{
"code": null,
"e": 8708,
"s": 8592,
"text": "This is typically useful for indicating the count of each category of a particular column or field in your dataset."
},
{
"code": null,
"e": 8862,
"s": 8708,
"text": "This plot indicates a region of points in a particular shade of color. This type of plot is used to distinguish different groups within the same dataset."
},
{
"code": null,
"e": 8994,
"s": 8862,
"text": "This type of plot is used to visualize relationship between two variables and to indicate the strength of correlation between them."
},
{
"code": null,
"e": 9131,
"s": 8994,
"text": "Different glyph plots are formed by calling appropriate method of Figure class. The Figure object is obtained by following constructor −"
},
{
"code": null,
"e": 9183,
"s": 9131,
"text": "from bokeh.plotting import figure\nfigure(**kwargs)\n"
},
{
"code": null,
"e": 9249,
"s": 9183,
"text": "The Figure object can be customised by various keyword arguments."
},
{
"code": null,
"e": 9405,
"s": 9249,
"text": "The line() method of Figure object adds a line glyph to the Bokeh figure. It needs x and y parameters as data arrays for showing their linear relationship."
},
{
"code": null,
"e": 9485,
"s": 9405,
"text": "from bokeh.plotting import figure, show\nfig = figure()\nfig.line(x,y)\nshow(fig)\n"
},
{
"code": null,
"e": 9588,
"s": 9485,
"text": "Following code renders a simple line plot between two sets of values in the form Python list objects −"
},
{
"code": null,
"e": 9806,
"s": 9588,
"text": "from bokeh.plotting import figure, output_file, show\nx = [1,2,3,4,5]\ny = [2,4,6,8,10]\noutput_file('line.html')\nfig = figure(title = 'Line Plot example', x_axis_label = 'x', y_axis_label = 'y')\nfig.line(x,y)\nshow(fig)\n"
},
{
"code": null,
"e": 9876,
"s": 9806,
"text": "The figure object has two different methods for constructing bar plot"
},
{
"code": null,
"e": 9976,
"s": 9876,
"text": "The bars are shown horizontally across plot width. The hbar() method has the following parameters −"
},
{
"code": null,
"e": 10036,
"s": 9976,
"text": "Following code is an example of horizontal bar using Bokeh."
},
{
"code": null,
"e": 10250,
"s": 10036,
"text": "from bokeh.plotting import figure, output_file, show\nfig = figure(plot_width = 400, plot_height = 200)\nfig.hbar(y = [2,4,6], height = 1, left = 0, right = [1,2,3], color = \"Cyan\")\noutput_file('bar.html')\nshow(fig)"
},
{
"code": null,
"e": 10345,
"s": 10250,
"text": "The bars are shown vertically across plot height. The vbar() method has following parameters −"
},
{
"code": null,
"e": 10389,
"s": 10345,
"text": "Following code displays vertical bar plot −"
},
{
"code": null,
"e": 10605,
"s": 10389,
"text": "from bokeh.plotting import figure, output_file, show\nfig = figure(plot_width = 200, plot_height = 400)\nfig.vbar(x = [1,2,3], width = 0.5, bottom = 0, top = [2,4,6], color = \"Cyan\")\noutput_file('bar.html')\nshow(fig)\n"
},
{
"code": null,
"e": 10819,
"s": 10605,
"text": "A plot which shades a region of space in a specific color to show a region or a group having similar properties is termed as a patch plot in Bokeh. Figure object has patch() and patches() methods for this purpose."
},
{
"code": null,
"e": 10906,
"s": 10819,
"text": "This method adds patch glyph to given figure. The method has the following arguments −"
},
{
"code": null,
"e": 10969,
"s": 10906,
"text": "A simple patch plot is obtained by the following Python code −"
},
{
"code": null,
"e": 11160,
"s": 10969,
"text": "from bokeh.plotting import figure, output_file, show\np = figure(plot_width = 300, plot_height = 300)\np.patch(x = [1, 3,2,4], y = [2,3,5,7], color = \"green\")\noutput_file('patch.html')\nshow(p)"
},
{
"code": null,
"e": 11247,
"s": 11160,
"text": "This method is used to draw multiple polygonal patches. It needs following arguments −"
},
{
"code": null,
"e": 11307,
"s": 11247,
"text": "As an example of patches() method, run the following code −"
},
{
"code": null,
"e": 11567,
"s": 11307,
"text": "from bokeh.plotting import figure, output_file, show\nxs = [[5,3,4], [2,4,3], [2,3,5,4]]\nys = [[6,4,2], [3,6,7], [2,4,7,8]]\nfig = figure()\nfig.patches(xs, ys, fill_color = ['red', 'blue', 'black'], line_color = 'white')\noutput_file('patch_plot.html')\nshow(fig)"
},
{
"code": null,
"e": 11831,
"s": 11567,
"text": "Scatter plots are very commonly used to determine the bi-variate relationship between two variables. The enhanced interactivity is added to them using Bokeh. Scatter plot is obtained by calling scatter() method of Figure object. It uses the following parameters −"
},
{
"code": null,
"e": 11887,
"s": 11831,
"text": "Following marker type constants are defined in Bokeh: −"
},
{
"code": null,
"e": 11896,
"s": 11887,
"text": "Asterisk"
},
{
"code": null,
"e": 11903,
"s": 11896,
"text": "Circle"
},
{
"code": null,
"e": 11915,
"s": 11903,
"text": "CircleCross"
},
{
"code": null,
"e": 11923,
"s": 11915,
"text": "CircleX"
},
{
"code": null,
"e": 11929,
"s": 11923,
"text": "Cross"
},
{
"code": null,
"e": 11934,
"s": 11929,
"text": "Dash"
},
{
"code": null,
"e": 11942,
"s": 11934,
"text": "Diamond"
},
{
"code": null,
"e": 11955,
"s": 11942,
"text": "DiamondCross"
},
{
"code": null,
"e": 11959,
"s": 11955,
"text": "Hex"
},
{
"code": null,
"e": 11976,
"s": 11959,
"text": "InvertedTriangle"
},
{
"code": null,
"e": 11983,
"s": 11976,
"text": "Square"
},
{
"code": null,
"e": 11995,
"s": 11983,
"text": "SquareCross"
},
{
"code": null,
"e": 12003,
"s": 11995,
"text": "SquareX"
},
{
"code": null,
"e": 12012,
"s": 12003,
"text": "Triangle"
},
{
"code": null,
"e": 12014,
"s": 12012,
"text": "X"
},
{
"code": null,
"e": 12078,
"s": 12014,
"text": "Following Python code generates scatter plot with circle marks."
},
{
"code": null,
"e": 12281,
"s": 12078,
"text": "from bokeh.plotting import figure, output_file, show\nfig = figure()\nfig.scatter([1, 4, 3, 2, 5], [6, 5, 2, 4, 7], marker = \"circle\", size = 20, fill_color = \"grey\")\noutput_file('scatter.html')\nshow(fig)"
},
{
"code": null,
"e": 12407,
"s": 12281,
"text": "Area plots are filled regions between two series that share a common index. Bokeh's Figure class has two methods as follows −"
},
{
"code": null,
"e": 12567,
"s": 12407,
"text": "Output of the varea() method is a vertical directed area that has one x coordinate array, and two y coordinate arrays, y1 and y2, which will be filled between."
},
{
"code": null,
"e": 12765,
"s": 12567,
"text": "from bokeh.plotting import figure, output_file, show\nfig = figure()\nx = [1, 2, 3, 4, 5]\ny1 = [2, 6, 4, 3, 5]\ny2 = [1, 4, 2, 2, 3]\nfig.varea(x = x,y1 = y1,y2 = y2)\noutput_file('area.html')\nshow(fig)"
},
{
"code": null,
"e": 12833,
"s": 12765,
"text": "The harea() method on the other hand needs x1, x2 and y parameters."
},
{
"code": null,
"e": 13031,
"s": 12833,
"text": "from bokeh.plotting import figure, output_file, show\nfig = figure()\ny = [1, 2, 3, 4, 5]\nx1 = [2, 6, 4, 3, 5]\nx2 = [1, 4, 2, 2, 3]\nfig.harea(x1 = x1,x2 = x2,y = y)\noutput_file('area.html')\nshow(fig)"
},
{
"code": null,
"e": 13172,
"s": 13031,
"text": "The figure object has many methods using which vectorised glyphs of different shapes such as circle, rectangle, polygon, etc. can, be drawn."
},
{
"code": null,
"e": 13232,
"s": 13172,
"text": "Following methods are available for drawing circle glyphs −"
},
{
"code": null,
"e": 13442,
"s": 13232,
"text": "The circle() method adds a circle glyph to the figure and needs x and y coordinates of its center. Additionally, it can be configured with the help of parameters such as fill_color, line-color, line_width etc."
},
{
"code": null,
"e": 13523,
"s": 13442,
"text": "The circle_cross() method adds circle glyph with a ‘+’ cross through the center."
},
{
"code": null,
"e": 13595,
"s": 13523,
"text": "The circle_x() method adds circle with an ‘X’ cross through the center."
},
{
"code": null,
"e": 13672,
"s": 13595,
"text": "Following example shows use of various circle glyphs added to Bokeh figure −"
},
{
"code": null,
"e": 14073,
"s": 13672,
"text": "from bokeh.plotting import figure, output_file, show\nplot = figure(plot_width = 300, plot_height = 300)\nplot.circle(x = [1, 2, 3], y = [3,7,5], size = 20, fill_color = 'red')\nplot.circle_cross(x = [2,4,6], y = [5,8,9], size = 20, fill_color = 'blue',fill_alpha = 0.2, line_width = 2)\nplot.circle_x(x = [5,7,2], y = [2,4,9], size = 20, fill_color = 'green',fill_alpha = 0.6, line_width = 2)\nshow(plot)"
},
{
"code": null,
"e": 14343,
"s": 14073,
"text": "It is possible to render rectangle, ellipse and polygons in a Bokeh figure. The rect() method of Figure class adds a rectangle glyph based on x and y coordinates of center, width and height. The square() method on the other hand has size parameter to decide dimensions."
},
{
"code": null,
"e": 14552,
"s": 14343,
"text": "The ellipse() and oval() methods adds an ellipse and oval glyph. They use similar signature to that of rect() having x, y,w and h parameters. Additionally, angle parameter determines rotation from horizontal."
},
{
"code": null,
"e": 14612,
"s": 14552,
"text": "Following code shows use of different shape glyph methods −"
},
{
"code": null,
"e": 15015,
"s": 14612,
"text": "from bokeh.plotting import figure, output_file, show\nfig = figure(plot_width = 300, plot_height = 300)\nfig.rect(x = 10,y = 10,width = 100, height = 50, width_units = 'screen', height_units = 'screen')\nfig.square(x = 2,y = 3,size = 80, color = 'red')\nfig.ellipse(x = 7,y = 6, width = 30, height = 10, fill_color = None, line_width = 2)\nfig.oval(x = 6,y = 6,width = 2, height = 1, angle = -0.4)\nshow(fig)"
},
{
"code": null,
"e": 15227,
"s": 15015,
"text": "The arc() method draws a simple line arc based on x and y coordinates, start and end angles and radius. Angles are given in radians whereas radius may be in screen units or data units. The wedge is a filled arc."
},
{
"code": null,
"e": 15522,
"s": 15227,
"text": "The wedge() method has same properties as arc() method. Both methods have provision of optional direction property which may be clock or anticlock that determines the direction of arc/wedge rendering. The annular_wedge() function renders a filled area between to arcs of inner and outer radius."
},
{
"code": null,
"e": 15589,
"s": 15522,
"text": "Here is an example of arc and wedge glyphs added to Bokeh figure −"
},
{
"code": null,
"e": 16132,
"s": 15589,
"text": "from bokeh.plotting import figure, output_file, show\nimport math\nfig = figure(plot_width = 300, plot_height = 300)\nfig.arc(x = 3, y = 3, radius = 50, radius_units = 'screen', start_angle = 0.0, end_angle = math.pi/2)\nfig.wedge(x = 3, y = 3, radius = 30, radius_units = 'screen',\nstart_angle = 0, end_angle = math.pi, direction = 'clock')\nfig.annular_wedge(x = 3,y = 3, inner_radius = 100, outer_radius = 75,outer_radius_units = 'screen',\ninner_radius_units = 'screen',start_angle = 0.4, end_angle = 4.5,color = \"green\", alpha = 0.6)\nshow(fig)"
},
{
"code": null,
"e": 16217,
"s": 16132,
"text": "The bokeh.plotting API supports methods for rendering following specialised curves −"
},
{
"code": null,
"e": 16459,
"s": 16217,
"text": "This method adds a Bézier curve to the figure object. A Bézier curve is a parametric curve used in computer graphics. Other uses include the design of computer fonts and animation, user interface design and for smoothing cursor trajectory."
},
{
"code": null,
"e": 16609,
"s": 16459,
"text": "In vector graphics, Bézier curves are used to model smooth curves that can be scaled indefinitely. A \"Path\" is combination of linked Bézier curves."
},
{
"code": null,
"e": 16674,
"s": 16609,
"text": "The beizer() method has following parameters which are defined −"
},
{
"code": null,
"e": 16716,
"s": 16674,
"text": "Default value for all parameters is None."
},
{
"code": null,
"e": 16806,
"s": 16716,
"text": "Following code generates a HTML page showing a Bézier curve and parabola in Bokeh plot −"
},
{
"code": null,
"e": 17063,
"s": 16806,
"text": "x = 2\ny = 4\nxp02 = x+0.4\nxp01 = x+0.1\nxm01 = x-0.1\nyp01 = y+0.2\nym01 = y-0.2\nfig = figure(plot_width = 300, plot_height = 300)\nfig.bezier(x0 = x, y0 = y, x1 = xp02, y1 = y, cx0 = xp01, cy0 = yp01,\ncx1 = xm01, cy1 = ym01, line_color = \"red\", line_width = 2)"
},
{
"code": null,
"e": 17180,
"s": 17063,
"text": "This method adds a parabola glyph to bokeh figure. The function has same parameters as beizer(), except cx0 and cx1."
},
{
"code": null,
"e": 17230,
"s": 17180,
"text": "The code given below generates a quadratic curve."
},
{
"code": null,
"e": 17503,
"s": 17230,
"text": "x = 2\ny = 4\nxp02 = x + 0.3\nxp01 = x + 0.2\nxm01 = x - 0.4\nyp01 = y + 0.1\nym01 = y - 0.2\nx = x,\ny = y,\nxp02 = x + 0.4,\nxp01 = x + 0.1,\nyp01 = y + 0.2,\nfig.quadratic(x0 = x, y0 = y, x1 = x + 0.4, y1 = y + 0.01, cx = x + 0.1,\ncy = y + 0.2, line_color = \"blue\", line_width = 3)"
},
{
"code": null,
"e": 17796,
"s": 17503,
"text": "Numeric ranges of data axes of a plot are automatically set by Bokeh taking into consideration the dataset under process. However, sometimes you may want to define the range of values on x and y axis explicitly. This is done by assigning x_range and y_range properties to a figure() function."
},
{
"code": null,
"e": 17858,
"s": 17796,
"text": "These ranges are defined with the help of range1d() function."
},
{
"code": null,
"e": 17882,
"s": 17858,
"text": "xrange = range1d(0,10)\n"
},
{
"code": null,
"e": 17949,
"s": 17882,
"text": "To use this range object as x_range property, use the below code −"
},
{
"code": null,
"e": 17985,
"s": 17949,
"text": "fig = figure(x,y,x_range = xrange)\n"
},
{
"code": null,
"e": 18048,
"s": 17985,
"text": "In this chapter, we shall discuss about various types of axes."
},
{
"code": null,
"e": 18331,
"s": 18048,
"text": "In the examples so far, the Bokeh plots show numerical data along both x and y axes. In order to use categorical data along either of axes, we need to specify a FactorRange to specify categorical dimensions for one of them. For example, to use strings in the given list for x axis −"
},
{
"code": null,
"e": 18445,
"s": 18331,
"text": "langs = ['C', 'C++', 'Java', 'Python', 'PHP']\nfig = figure(x_range = langs, plot_width = 300, plot_height = 300)\n"
},
{
"code": null,
"e": 18565,
"s": 18445,
"text": "With following example, a simple bar plot is displayed showing number of students enrolled for various courses offered."
},
{
"code": null,
"e": 18818,
"s": 18565,
"text": "from bokeh.plotting import figure, output_file, show\nlangs = ['C', 'C++', 'Java', 'Python', 'PHP']\nstudents = [23,17,35,29,12]\nfig = figure(x_range = langs, plot_width = 300, plot_height = 300)\nfig.vbar(x = langs, top = students, width = 0.5)\nshow(fig)"
},
{
"code": null,
"e": 18919,
"s": 18818,
"text": "To show each bar in different colour, set color property of vbar() function to list of color values."
},
{
"code": null,
"e": 19026,
"s": 18919,
"text": "cols = ['red','green','orange','navy', 'cyan']\nfig.vbar(x = langs, top = students, color = cols,width=0.5)"
},
{
"code": null,
"e": 19266,
"s": 19026,
"text": "To render a vertical (or horizontal) stacked bar using vbar_stack() or hbar_stack() function, set stackers property to list of fields to stack successively and source property to a dict object containing values corresponding to each field."
},
{
"code": null,
"e": 19367,
"s": 19266,
"text": "In following example, sales is a dictionary showing sales figures of three products in three months."
},
{
"code": null,
"e": 19791,
"s": 19367,
"text": "from bokeh.plotting import figure, output_file, show\nproducts = ['computer','mobile','printer']\nmonths = ['Jan','Feb','Mar']\nsales = {'products':products,\n 'Jan':[10,40,5],\n 'Feb':[8,45,10],\n 'Mar':[25,60,22]}\ncols = ['red','green','blue']#,'navy', 'cyan']\nfig = figure(x_range = products, plot_width = 300, plot_height = 300)\nfig.vbar_stack(months, x = 'products', source = sales, color = cols,width = 0.5)\nshow(fig)"
},
{
"code": null,
"e": 19932,
"s": 19791,
"text": "A grouped bar plot is obtained by specifying a visual displacement for the bars with the help of dodge() function in bokeh.transform module."
},
{
"code": null,
"e": 20164,
"s": 19932,
"text": "The dodge() function introduces a relative offset for each bar plot thereby achieving a visual impression of group. In following example, vbar() glyph is separated by an offset of 0.25 for each group of bars for a particular month."
},
{
"code": null,
"e": 20850,
"s": 20164,
"text": "from bokeh.plotting import figure, output_file, show\nfrom bokeh.transform import dodge\nproducts = ['computer','mobile','printer']\nmonths = ['Jan','Feb','Mar']\nsales = {'products':products,\n 'Jan':[10,40,5],\n 'Feb':[8,45,10],\n 'Mar':[25,60,22]}\nfig = figure(x_range = products, plot_width = 300, plot_height = 300)\nfig.vbar(x = dodge('products', -0.25, range = fig.x_range), top = 'Jan',\n width = 0.2,source = sales, color = \"red\")\nfig.vbar(x = dodge('products', 0.0, range = fig.x_range), top = 'Feb',\n width = 0.2, source = sales,color = \"green\")\nfig.vbar(x = dodge('products', 0.25, range = fig.x_range), top = 'Mar',\n width = 0.2,source = sales,color = \"blue\")\nshow(fig)"
},
{
"code": null,
"e": 21168,
"s": 20850,
"text": "When values on one of the axes of a plot grow exponentially with linearly increasing values of another, it is often necessary to have the data on former axis be displayed on a log scale. For example, if there exists a power law relationship between x and y data series, it is desirable to use log scales on both axes."
},
{
"code": null,
"e": 21353,
"s": 21168,
"text": "Bokeh.plotting API's figure() function accepts x_axis_type and y_axis_type as arguments which may be specified as log axis by passing \"log\" for the value of either of these parameters."
},
{
"code": null,
"e": 21459,
"s": 21353,
"text": "First figure shows plot between x and 10x on a linear scale. In second figure y_axis_type is set to 'log'"
},
{
"code": null,
"e": 21697,
"s": 21459,
"text": "from bokeh.plotting import figure, output_file, show\nx = [0.1, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0]\ny = [10**i for i in x]\nfig = figure(title = 'Linear scale example',plot_width = 400, plot_height = 400)\nfig.line(x, y, line_width = 2)\nshow(fig)"
},
{
"code": null,
"e": 21757,
"s": 21697,
"text": "Now change figure() function to configure y_axis_type=’log’"
},
{
"code": null,
"e": 21859,
"s": 21757,
"text": "fig = figure(title = 'Linear scale example',plot_width = 400, plot_height = 400, y_axis_type = \"log\")"
},
{
"code": null,
"e": 22136,
"s": 21859,
"text": "In certain situations, it may be needed to show multiple axes representing varying ranges on a single plot figure. The figure object can be so configured by defining extra_x_range and extra_y_range properties. While adding new glyph to the figure, these named ranges are used."
},
{
"code": null,
"e": 22328,
"s": 22136,
"text": "We try to display a sine curve and a straight line in same plot. Both glyphs have y axes with different ranges. The x and y data series for sine curve and line are obtained by the following −"
},
{
"code": null,
"e": 22442,
"s": 22328,
"text": "from numpy import pi, arange, sin, linspace\nx = arange(-2*pi, 2*pi, 0.1)\ny = sin(x)\ny2 = linspace(0, 100, len(y))"
},
{
"code": null,
"e": 22654,
"s": 22442,
"text": "Here, plot between x and y represents sine relation and plot between x and y2 is a straight line. The Figure object is defined with explicit y_range and a line glyph representing sine curve is added as follows −"
},
{
"code": null,
"e": 22749,
"s": 22654,
"text": "fig = figure(title = 'Twin Axis Example', y_range = (-1.1, 1.1))\nfig.line(x, y, color = \"red\")"
},
{
"code": null,
"e": 22794,
"s": 22749,
"text": "We need an extra y range. It is defined as −"
},
{
"code": null,
"e": 22853,
"s": 22794,
"text": "fig.extra_y_ranges = {\"y2\": Range1d(start = 0, end = 100)}"
},
{
"code": null,
"e": 22976,
"s": 22853,
"text": "To add additional y axis on right side, use add_layout() method. Add a new line glyph representing x and y2 to the figure."
},
{
"code": null,
"e": 23086,
"s": 22976,
"text": "fig.add_layout(LinearAxis(y_range_name = \"y2\"), 'right')\nfig.line(x, y2, color = \"blue\", y_range_name = \"y2\")"
},
{
"code": null,
"e": 23176,
"s": 23086,
"text": "This will result in a plot with twin y axes. Complete code and the output is as follows −"
},
{
"code": null,
"e": 23660,
"s": 23176,
"text": "from numpy import pi, arange, sin, linspace\nx = arange(-2*pi, 2*pi, 0.1)\ny = sin(x)\ny2 = linspace(0, 100, len(y))\nfrom bokeh.plotting import output_file, figure, show\nfrom bokeh.models import LinearAxis, Range1d\nfig = figure(title='Twin Axis Example', y_range = (-1.1, 1.1))\nfig.line(x, y, color = \"red\")\nfig.extra_y_ranges = {\"y2\": Range1d(start = 0, end = 100)}\nfig.add_layout(LinearAxis(y_range_name = \"y2\"), 'right')\nfig.line(x, y2, color = \"blue\", y_range_name = \"y2\")\nshow(fig)"
},
{
"code": null,
"e": 23870,
"s": 23660,
"text": "Annotations are pieces of explanatory text added to the diagram. Bokeh plot can be annotated by way of specifying plot title, labels for x and y axes as well as inserting text labels anywhere in the plot area."
},
{
"code": null,
"e": 23962,
"s": 23870,
"text": "Plot title as well as x and y axis labels can be provided in the Figure constructor itself."
},
{
"code": null,
"e": 24011,
"s": 23962,
"text": "fig = figure(title, x_axis_label, y_axis_label)\n"
},
{
"code": null,
"e": 24076,
"s": 24011,
"text": "In the following plot, these properties are set as shown below −"
},
{
"code": null,
"e": 24334,
"s": 24076,
"text": "from bokeh.plotting import figure, output_file, show\nimport numpy as np\nimport math\nx = np.arange(0, math.pi*2, 0.05)\ny = np.sin(x)\nfig = figure(title = \"sine wave example\", x_axis_label = 'angle', y_axis_label = 'sin')\nfig.line(x, y,line_width = 2)\nshow(p)"
},
{
"code": null,
"e": 24474,
"s": 24334,
"text": "The title’s text and axis labels can also be specified by assigning appropriate string values to corresponding properties of figure object."
},
{
"code": null,
"e": 24571,
"s": 24474,
"text": "fig.title.text = \"sine wave example\"\nfig.xaxis.axis_label = 'angle'\nfig.yaxis.axis_label = 'sin'"
},
{
"code": null,
"e": 24648,
"s": 24571,
"text": "It is also possible to specify location, alignment, font and color of title."
},
{
"code": null,
"e": 24781,
"s": 24648,
"text": "fig.title.align = \"right\"\nfig.title.text_color = \"orange\"\nfig.title.text_font_size = \"25px\"\nfig.title.background_fill_color = \"blue\""
},
{
"code": null,
"e": 24881,
"s": 24781,
"text": "Adding legends to the plot figure is very easy. We have to use legend property of any glyph method."
},
{
"code": null,
"e": 24957,
"s": 24881,
"text": "Below we have three glyph curves in the plot with three different legends −"
},
{
"code": null,
"e": 25337,
"s": 24957,
"text": "from bokeh.plotting import figure, output_file, show\nimport numpy as np\nimport math\nx = np.arange(0, math.pi*2, 0.05)\nfig = figure()\nfig.line(x, np.sin(x),line_width = 2, line_color = 'navy', legend = 'sine')\nfig.circle(x,np.cos(x), line_width = 2, line_color = 'orange', legend = 'cosine')\nfig.square(x,-np.sin(x),line_width = 2, line_color = 'grey', legend = '-sine')\nshow(fig)"
},
{
"code": null,
"e": 25537,
"s": 25337,
"text": "In all the examples above, the data to be plotted has been provided in the form of Python lists or numpy arrays. It is also possible to provide the data source in the form of pandas DataFrame object."
},
{
"code": null,
"e": 25766,
"s": 25537,
"text": "DataFrame is a two-dimensional data structure. Columns in the dataframe can be of different data types. The Pandas library has functions to create dataframe from various sources such as CSV file, Excel worksheet, SQL table, etc."
},
{
"code": null,
"e": 25919,
"s": 25766,
"text": "For the purpose of following example, we are using a CSV file consisting of two columns representing a number x and 10x. The test.csv file is as below −"
},
{
"code": null,
"e": 26269,
"s": 25919,
"text": "x,pow\n0.0,1.0\n0.5263157894736842,3.3598182862837818\n1.0526315789473684,11.28837891684689\n1.5789473684210527,37.926901907322495\n2.1052631578947367,127.42749857031335\n2.631578947368421,428.1332398719391\n3.1578947368421053,1438.449888287663\n3.6842105263157894,4832.930238571752\n4.2105263157894735,16237.76739188721\n4.7368421052631575,54555.947811685146"
},
{
"code": null,
"e": 26352,
"s": 26269,
"text": "We shall read this file in a dataframe object using read_csv() function in pandas."
},
{
"code": null,
"e": 26412,
"s": 26352,
"text": "import pandas as pd\ndf = pd.read_csv('test.csv')\nprint (df)"
},
{
"code": null,
"e": 26445,
"s": 26412,
"text": "The dataframe appears as below −"
},
{
"code": null,
"e": 26679,
"s": 26445,
"text": "x pow\n0 0.000000 1.000000\n1 0.526316 3.359818\n2 1.052632 11.288379\n3 1.578947 37.926902\n4 2.105263 127.427499\n5 2.631579 428.133240\n6 3.157895 1438.449888\n7 3.684211 4832.930239\n8 4.210526 16237.767392\n9 4.736842 54555.947812\n"
},
{
"code": null,
"e": 26766,
"s": 26679,
"text": "The ‘x’ and ‘pow’ columns are used as data series for line glyph in bokeh plot figure."
},
{
"code": null,
"e": 26918,
"s": 26766,
"text": "from bokeh.plotting import figure, output_file, show\np = figure()\nx = df['x']\ny = df['pow']\np.line(x,y,line_width = 2)\np.circle(x, y,size = 20)\nshow(p)"
},
{
"code": null,
"e": 27090,
"s": 26918,
"text": "Most of the plotting methods in Bokeh API are able to receive data source parameters through ColumnDatasource object. It makes sharing data between plots and ‘DataTables’."
},
{
"code": null,
"e": 27307,
"s": 27090,
"text": "A ColumnDatasource can be considered as a mapping between column name and list of data. A Python dict object with one or more string keys and lists or numpy arrays as values is passed to ColumnDataSource constructor."
},
{
"code": null,
"e": 27328,
"s": 27307,
"text": "Below is the example"
},
{
"code": null,
"e": 27459,
"s": 27328,
"text": "from bokeh.models import ColumnDataSource\ndata = {'x':[1, 4, 3, 2, 5],\n 'y':[6, 5, 2, 4, 7]}\ncds = ColumnDataSource(data = data)"
},
{
"code": null,
"e": 27595,
"s": 27459,
"text": "This object is then used as value of source property in a glyph method. Following code generates a scatter plot using ColumnDataSource."
},
{
"code": null,
"e": 27898,
"s": 27595,
"text": "from bokeh.plotting import figure, output_file, show\nfrom bokeh.models import ColumnDataSource\ndata = {'x':[1, 4, 3, 2, 5],\n 'y':[6, 5, 2, 4, 7]}\ncds = ColumnDataSource(data = data)\nfig = figure()\nfig.scatter(x = 'x', y = 'y',source = cds, marker = \"circle\", size = 20, fill_color = \"grey\")\nshow(fig)"
},
{
"code": null,
"e": 27998,
"s": 27898,
"text": "Instead of assigning a Python dictionary to ColumnDataSource, we can use a Pandas DataFrame for it."
},
{
"code": null,
"e": 28138,
"s": 27998,
"text": "Let us use ‘test.csv’ (used earlier in this section) to obtain a DataFrame and use it for getting ColumnDataSource and rendering line plot."
},
{
"code": null,
"e": 28416,
"s": 28138,
"text": "from bokeh.plotting import figure, output_file, show\nimport pandas as pd\nfrom bokeh.models import ColumnDataSource\ndf = pd.read_csv('test.csv')\ncds = ColumnDataSource(df)\nfig = figure(y_axis_type = 'log')\nfig.line(x = 'x', y = 'pow',source = cds, line_color = \"grey\")\nshow(fig)"
},
{
"code": null,
"e": 28704,
"s": 28416,
"text": "Often, you may want to obtain a plot pertaining to a part of data that satisfies certain conditions instead of the entire dataset. Object of the CDSView class defined in bokeh.models module returns a subset of ColumnDatasource under consideration by applying one or more filters over it."
},
{
"code": null,
"e": 28860,
"s": 28704,
"text": "IndexFilter is the simplest type of filter. You have to specify indices of only those rows from the dataset that you want to use while plotting the figure."
},
{
"code": null,
"e": 29150,
"s": 28860,
"text": "Following example demonstrates use of IndexFilter to set up a CDSView. The resultant figure shows a line glyph between x and y data series of the ColumnDataSource. A view object is obtained by applying index filter over it. The view is used to plot circle glyph as a result of IndexFilter."
},
{
"code": null,
"e": 29672,
"s": 29150,
"text": "from bokeh.models import ColumnDataSource, CDSView, IndexFilter\nfrom bokeh.plotting import figure, output_file, show\nsource = ColumnDataSource(data = dict(x = list(range(1,11)), y = list(range(2,22,2))))\nview = CDSView(source=source, filters = [IndexFilter([0, 2, 4,6])])\nfig = figure(title = 'Line Plot example', x_axis_label = 'x', y_axis_label = 'y')\nfig.circle(x = \"x\", y = \"y\", size = 10, source = source, view = view, legend = 'filtered')\nfig.line(source.data['x'],source.data['y'], legend = 'unfiltered')\nshow(fig)"
},
{
"code": null,
"e": 29785,
"s": 29672,
"text": "To choose only those rows from the data source, that satisfy a certain Boolean condition, apply a BooleanFilter."
},
{
"code": null,
"e": 30203,
"s": 29785,
"text": "A typical Bokeh installation consists of a number of sample data sets in sampledata directory. For following example, we use unemployment1948 dataset provided in the form of unemployment1948.csv. It stores year wise percentage of unemployment in USA since 1948. We want to generate a plot only for year 1980 onwards. For that purpose, a CDSView object is obtained by applying BooleanFilter over the given data source."
},
{
"code": null,
"e": 30775,
"s": 30203,
"text": "from bokeh.models import ColumnDataSource, CDSView, BooleanFilter\nfrom bokeh.plotting import figure, show\nfrom bokeh.sampledata.unemployment1948 import data\nsource = ColumnDataSource(data)\nbooleans = [True if int(year) >= 1980 else False for year in\nsource.data['Year']]\nprint (booleans)\nview1 = CDSView(source = source, filters=[BooleanFilter(booleans)])\np = figure(title = \"Unemployment data\", x_range = (1980,2020), x_axis_label = 'Year', y_axis_label='Percentage')\np.line(x = 'Year', y = 'Annual', source = source, view = view1, color = 'red', line_width = 2)\nshow(p)"
},
{
"code": null,
"e": 30953,
"s": 30775,
"text": "To add more flexibility in applying filter, Bokeh provides a CustomJSFilter class with the help of which the data source can be filtered with a user defined JavaScript function."
},
{
"code": null,
"e": 31093,
"s": 30953,
"text": "The example given below uses the same USA unemployment data. Defining a CustomJSFilter to plot unemployment figures of year 1980 and after."
},
{
"code": null,
"e": 31840,
"s": 31093,
"text": "from bokeh.models import ColumnDataSource, CDSView, CustomJSFilter\nfrom bokeh.plotting import figure, show\nfrom bokeh.sampledata.unemployment1948 import data\nsource = ColumnDataSource(data)\ncustom_filter = CustomJSFilter(code = '''\n var indices = [];\n\n for (var i = 0; i < source.get_length(); i++){\n if (parseInt(source.data['Year'][i]) > = 1980){\n indices.push(true);\n } else {\n indices.push(false);\n }\n }\n return indices;\n''')\nview1 = CDSView(source = source, filters = [custom_filter])\np = figure(title = \"Unemployment data\", x_range = (1980,2020), x_axis_label = 'Year', y_axis_label = 'Percentage')\np.line(x = 'Year', y = 'Annual', source = source, view = view1, color = 'red', line_width = 2)\nshow(p)"
},
{
"code": null,
"e": 32209,
"s": 31840,
"text": "Bokeh visualizations can be suitably arranged in different layout options. These layouts as well as sizing modes result in plots and widgets resizing automatically as per the size of browser window. For consistent appearance, all items in a layout must have same sizing mode. The widgets (buttons, menus, etc.) are kept in a separate widget box and not in plot figure."
},
{
"code": null,
"e": 32376,
"s": 32209,
"text": "First type of layout is Column layout which displays plot figures vertically. The column() function is defined in bokeh.layouts module and takes following signature −"
},
{
"code": null,
"e": 32445,
"s": 32376,
"text": "from bokeh.layouts import column\ncol = column(children, sizing_mode)"
},
{
"code": null,
"e": 32486,
"s": 32445,
"text": "children − List of plots and/or widgets."
},
{
"code": null,
"e": 32653,
"s": 32486,
"text": "sizing_mode − determines how items in the layout resize. Possible values are \"fixed\", \"stretch_both\", \"scale_width\", \"scale_height\", \"scale_both\". Default is “fixed”."
},
{
"code": null,
"e": 32877,
"s": 32653,
"text": "Following code produces two Bokeh figures and places them in a column layout so that they are displayed vertically. Line glyphs representing sine and cos relationship between x and y data series is displayed in Each figure."
},
{
"code": null,
"e": 33339,
"s": 32877,
"text": "from bokeh.plotting import figure, output_file, show\nfrom bokeh.layouts import column\nimport numpy as np\nimport math\nx = np.arange(0, math.pi*2, 0.05)\ny1 = np.sin(x)\ny2 = np.cos(x)\nfig1 = figure(plot_width = 200, plot_height = 200)\nfig1.line(x, y1,line_width = 2, line_color = 'blue')\nfig2 = figure(plot_width = 200, plot_height = 200)\nfig2.line(x, y2,line_width = 2, line_color = 'red')\nc = column(children = [fig1, fig2], sizing_mode = 'stretch_both')\nshow(c)"
},
{
"code": null,
"e": 33566,
"s": 33339,
"text": "Similarly, Row layout arranges plots horizontally, for which row() function as defined in bokeh.layouts module is used. As you would think, it also takes two arguments (similar to column() function) – children and sizing_mode."
},
{
"code": null,
"e": 33692,
"s": 33566,
"text": "The sine and cos curves as shown vertically in above diagram are now displayed horizontally in row layout with following code"
},
{
"code": null,
"e": 34148,
"s": 33692,
"text": "from bokeh.plotting import figure, output_file, show\nfrom bokeh.layouts import row\nimport numpy as np\nimport math\nx = np.arange(0, math.pi*2, 0.05)\ny1 = np.sin(x)\ny2 = np.cos(x)\nfig1 = figure(plot_width = 200, plot_height = 200)\nfig1.line(x, y1,line_width = 2, line_color = 'blue')\nfig2 = figure(plot_width = 200, plot_height = 200)\nfig2.line(x, y2,line_width = 2, line_color = 'red')\nr = row(children = [fig1, fig2], sizing_mode = 'stretch_both')\nshow(r)"
},
{
"code": null,
"e": 34447,
"s": 34148,
"text": "The Bokeh package also has grid layout. It holds multiple plot figures (as well as widgets) in a two dimensional grid of rows and columns. The gridplot() function in bokeh.layouts module returns a grid and a single unified toolbar which may be positioned with the help of toolbar_location property."
},
{
"code": null,
"e": 34670,
"s": 34447,
"text": "This is unlike row or column layout where each plot shows its own toolbar. The grid() function too uses children and sizing_mode parameters where children is a list of lists. Ensure that each sublist is of same dimensions."
},
{
"code": null,
"e": 34801,
"s": 34670,
"text": "In the following code, four different relationships between x and y data series are plotted in a grid of two rows and two columns."
},
{
"code": null,
"e": 35526,
"s": 34801,
"text": "from bokeh.plotting import figure, output_file, show\nfrom bokeh.layouts import gridplot\nimport math\nx = list(range(1,11))\n\ny1 = x\ny2 =[11-i for i in x]\ny3 = [i*i for i in x]\ny4 = [math.log10(i) for i in x]\n\nfig1 = figure(plot_width = 200, plot_height = 200)\nfig1.line(x, y1,line_width = 2, line_color = 'blue')\nfig2 = figure(plot_width = 200, plot_height = 200)\nfig2.circle(x, y2,size = 10, color = 'green')\nfig3 = figure(plot_width = 200, plot_height = 200)\nfig3.circle(x,y3, size = 10, color = 'grey')\nfig4 = figure(plot_width = 200, plot_height = 200, y_axis_type = 'log')\nfig4.line(x,y4, line_width = 2, line_color = 'red')\ngrid = gridplot(children = [[fig1, fig2], [fig3,fig4]], sizing_mode = 'stretch_both')\nshow(grid)"
},
{
"code": null,
"e": 35814,
"s": 35526,
"text": "When a Bokeh plot is rendered, normally a tool bar appears on the right side of the figure. It contains a default set of tools. First of all, the position of toolbar can be configured by toolbar_location property in figure() function. This property can take one of the following values −"
},
{
"code": null,
"e": 35822,
"s": 35814,
"text": "\"above\""
},
{
"code": null,
"e": 35830,
"s": 35822,
"text": "\"below\""
},
{
"code": null,
"e": 35837,
"s": 35830,
"text": "\"left\""
},
{
"code": null,
"e": 35845,
"s": 35837,
"text": "\"right\""
},
{
"code": null,
"e": 35852,
"s": 35845,
"text": "\"None\""
},
{
"code": null,
"e": 35937,
"s": 35852,
"text": "For example, following statement will cause toolbar to be displayed below the plot −"
},
{
"code": null,
"e": 35978,
"s": 35937,
"text": "Fig = figure(toolbar_location = \"below\")"
},
{
"code": null,
"e": 36122,
"s": 35978,
"text": "This toolbar can be configured according to the requirement by adding required from various tools defined in bokeh.models module. For example −"
},
{
"code": null,
"e": 36153,
"s": 36122,
"text": "Fig.add_tools(WheelZoomTool())"
},
{
"code": null,
"e": 36210,
"s": 36153,
"text": "The tools can be classified under following categories −"
},
{
"code": null,
"e": 36225,
"s": 36210,
"text": "Pan/Drag Tools"
},
{
"code": null,
"e": 36241,
"s": 36225,
"text": "Click/Tap Tools"
},
{
"code": null,
"e": 36260,
"s": 36241,
"text": "Scroll/Pinch Tools"
},
{
"code": null,
"e": 36274,
"s": 36260,
"text": "BoxSelectTool"
},
{
"code": null,
"e": 36294,
"s": 36274,
"text": "Name : 'box_select'"
},
{
"code": null,
"e": 36310,
"s": 36294,
"text": "LassoSelectTool"
},
{
"code": null,
"e": 36330,
"s": 36310,
"text": "name: 'lasso_select"
},
{
"code": null,
"e": 36338,
"s": 36330,
"text": "PanTool"
},
{
"code": null,
"e": 36367,
"s": 36338,
"text": "name: 'pan', 'xpan', 'ypan',"
},
{
"code": null,
"e": 36375,
"s": 36367,
"text": "TapTool"
},
{
"code": null,
"e": 36386,
"s": 36375,
"text": "name: 'tap"
},
{
"code": null,
"e": 36400,
"s": 36386,
"text": "WheelZoomTool"
},
{
"code": null,
"e": 36449,
"s": 36400,
"text": "name: 'wheel_zoom', 'xwheel_zoom', 'ywheel_zoom'"
},
{
"code": null,
"e": 36462,
"s": 36449,
"text": "WheelPanTool"
},
{
"code": null,
"e": 36495,
"s": 36462,
"text": "name: 'xwheel_pan', 'ywheel_pan'"
},
{
"code": null,
"e": 36505,
"s": 36495,
"text": "ResetTool"
},
{
"code": null,
"e": 36519,
"s": 36505,
"text": "name: 'reset'"
},
{
"code": null,
"e": 36528,
"s": 36519,
"text": "SaveTool"
},
{
"code": null,
"e": 36541,
"s": 36528,
"text": "name: 'save'"
},
{
"code": null,
"e": 36552,
"s": 36541,
"text": "ZoomInTool"
},
{
"code": null,
"e": 36592,
"s": 36552,
"text": "name: 'zoom_in', 'xzoom_in', 'yzoom_in'"
},
{
"code": null,
"e": 36604,
"s": 36592,
"text": "ZoomOutTool"
},
{
"code": null,
"e": 36647,
"s": 36604,
"text": "name: 'zoom_out', 'xzoom_out', 'yzoom_out'"
},
{
"code": null,
"e": 36661,
"s": 36647,
"text": "CrosshairTool"
},
{
"code": null,
"e": 36679,
"s": 36661,
"text": "name: 'crosshair'"
},
{
"code": null,
"e": 36829,
"s": 36679,
"text": "The default appearance of a Bokeh plot can be customised by setting various properties to desired value. These properties are mainly of three types −"
},
{
"code": null,
"e": 36893,
"s": 36829,
"text": "Following table lists various properties related to line glyph."
},
{
"code": null,
"e": 36936,
"s": 36893,
"text": "Various fill properties are listed below −"
},
{
"code": null,
"e": 37010,
"s": 36936,
"text": "There are many text related properties as listed in the following table −"
},
{
"code": null,
"e": 37197,
"s": 37010,
"text": "Various glyphs in a plot can be identified by legend property appear as a label by default at top-right position of the plot area. This legend can be customised by following attributes −"
},
{
"code": null,
"e": 37251,
"s": 37197,
"text": "Example code for legend customisation is as follows −"
},
{
"code": null,
"e": 37743,
"s": 37251,
"text": "from bokeh.plotting import figure, output_file, show\nimport math\nx2 = list(range(1,11))\ny4 = [math.pow(i,2) for i in x2]\ny2 = [math.log10(pow(10,i)) for i in x2]\nfig = figure(y_axis_type = 'log')\nfig.circle(x2, y2,size = 5, color = 'blue', legend = 'blue circle')\nfig.line(x2,y4, line_width = 2, line_color = 'red', legend = 'red line')\nfig.legend.location = 'top_left'\nfig.legend.title = 'Legend Title'\nfig.legend.title_text_font = 'Arial'\nfig.legend.title_text_font_size = '20pt'\nshow(fig)"
},
{
"code": null,
"e": 38114,
"s": 37743,
"text": "The bokeh.models.widgets module contains definitions of GUI objects similar to HTML form elements, such as button, slider, checkbox, radio button, etc. These controls provide interactive interface to a plot. Invoking processing such as modifying plot data, changing plot parameters, etc., can be performed by custom JavaScript functions executed on corresponding events."
},
{
"code": null,
"e": 38184,
"s": 38114,
"text": "Bokeh allows call back functionality to be defined with two methods −"
},
{
"code": null,
"e": 38276,
"s": 38184,
"text": "Use the CustomJS callback so that the interactivity will work in standalone HTML documents."
},
{
"code": null,
"e": 38368,
"s": 38276,
"text": "Use the CustomJS callback so that the interactivity will work in standalone HTML documents."
},
{
"code": null,
"e": 38412,
"s": 38368,
"text": "Use Bokeh server and set up event handlers."
},
{
"code": null,
"e": 38456,
"s": 38412,
"text": "Use Bokeh server and set up event handlers."
},
{
"code": null,
"e": 38544,
"s": 38456,
"text": "In this section, we shall see how to add Bokeh widgets and assign JavaScript callbacks."
},
{
"code": null,
"e": 38682,
"s": 38544,
"text": "This widget is a clickable button generally used to invoke a user defined call back handler. The constructor takes following parameters −"
},
{
"code": null,
"e": 38713,
"s": 38682,
"text": "Button(label, icon, callback)\n"
},
{
"code": null,
"e": 38844,
"s": 38713,
"text": "The label parameter is a string used as button’s caption and callback is the custom JavaScript function to be called when clicked."
},
{
"code": null,
"e": 38993,
"s": 38844,
"text": "In the following example, a plot and Button widget are displayed in Column layout. The plot itself renders a line glyph between x and y data series."
},
{
"code": null,
"e": 39197,
"s": 38993,
"text": "A custom JavaScript function named ‘callback’ has been defined using CutomJS() function. It receives reference to the object that triggered callback (in this case the button) in the form variable cb_obj."
},
{
"code": null,
"e": 39297,
"s": 39197,
"text": "This function alters the source ColumnDataSource data and finally emits this update in source data."
},
{
"code": null,
"e": 40002,
"s": 39297,
"text": "from bokeh.layouts import column\nfrom bokeh.models import CustomJS, ColumnDataSource\nfrom bokeh.plotting import Figure, output_file, show\nfrom bokeh.models.widgets import Button\n\nx = [x*0.05 for x in range(0, 200)]\ny = x\n\nsource = ColumnDataSource(data=dict(x=x, y=y))\nplot = Figure(plot_width=400, plot_height=400)\nplot.line('x', 'y', source=source, line_width=3, line_alpha=0.6)\n\ncallback = CustomJS(args=dict(source=source), code=\"\"\"\n var data = source.data;\n x = data['x']\n y = data['y']\n for (i = 0; i < x.length; i++) {\n y[i] = Math.pow(x[i], 4)\n }\n source.change.emit();\n\"\"\")\n\nbtn = Button(label=\"click here\", callback=callback, name=\"1\")\n\nlayout = column(btn , plot)\nshow(layout)"
},
{
"code": null,
"e": 40098,
"s": 40002,
"text": "Click on the button on top of the plot and see the updated plot figure which looks as follows −"
},
{
"code": null,
"e": 40215,
"s": 40098,
"text": "With the help of a slider control it is possible to select a number between start and end properties assigned to it."
},
{
"code": null,
"e": 40248,
"s": 40215,
"text": "Slider(start, end, step, value)\n"
},
{
"code": null,
"e": 40543,
"s": 40248,
"text": "In the following example, we register a callback function on slider’s on_change event. Slider’s instantaneous numeric value is available to the handler in the form of cb_obj.value which is used to modify the ColumnDatasource data. The plot figure continuously updates as you slide the position."
},
{
"code": null,
"e": 41336,
"s": 40543,
"text": "from bokeh.layouts import column\nfrom bokeh.models import CustomJS, ColumnDataSource\nfrom bokeh.plotting import Figure, output_file, show\nfrom bokeh.models.widgets import Slider\n\nx = [x*0.05 for x in range(0, 200)]\ny = x\n\nsource = ColumnDataSource(data=dict(x=x, y=y))\nplot = Figure(plot_width=400, plot_height=400)\nplot.line('x', 'y', source=source, line_width=3, line_alpha=0.6)\n\nhandler = CustomJS(args=dict(source=source), code=\"\"\"\n var data = source.data;\n var f = cb_obj.value\n var x = data['x']\n var y = data['y']\n for (var i = 0; i < x.length; i++) {\n y[i] = Math.pow(x[i], f)\n }\n source.change.emit();\n\"\"\")\n\nslider = Slider(start=0.0, end=5, value=1, step=.25, title=\"Slider Value\")\n\nslider.js_on_change('value', handler)\nlayout = column(slider, plot)\nshow(layout)"
},
{
"code": null,
"e": 41456,
"s": 41336,
"text": "This widget presents a collection of mutually exclusive toggle buttons showing circular buttons to the left of caption."
},
{
"code": null,
"e": 41484,
"s": 41456,
"text": "RadioGroup(labels, active)\n"
},
{
"code": null,
"e": 41564,
"s": 41484,
"text": "Where, labels is a list of captions and active is the index of selected option."
},
{
"code": null,
"e": 41722,
"s": 41564,
"text": "This widget is a simple dropdown list of string items, one of which can be selected. Selected string appears at the top window and it is the value parameter."
},
{
"code": null,
"e": 41746,
"s": 41722,
"text": "Select(options, value)\n"
},
{
"code": null,
"e": 41835,
"s": 41746,
"text": "The list of string elements in the dropdown is given in the form of options list object."
},
{
"code": null,
"e": 42079,
"s": 41835,
"text": "Following is a combined example of radio button and select widgets, both providing three different relationships between x and y data series. The RadioGroup and Select widgets are registered with respective handlers through on_change() method."
},
{
"code": null,
"e": 43966,
"s": 42079,
"text": "from bokeh.layouts import column\nfrom bokeh.models import CustomJS, ColumnDataSource\nfrom bokeh.plotting import Figure, output_file, show\nfrom bokeh.models.widgets import RadioGroup, Select\n\nx = [x*0.05 for x in range(0, 200)]\ny = x\n\nsource = ColumnDataSource(data=dict(x=x, y=y))\n\nplot = Figure(plot_width=400, plot_height=400)\nplot.line('x', 'y', source=source, line_width=3, line_alpha=0.6)\n\nradiohandler = CustomJS(args=dict(source=source), code=\"\"\"\n var data = source.data;\n console.log('Tap event occurred at x-position: ' + cb_obj.active);\n //plot.title.text=cb_obj.value;\n x = data['x']\n y = data['y']\n if (cb_obj.active==0){\n for (i = 0; i < x.length; i++) {\n y[i] = x[i];\n }\n }\n if (cb_obj.active==1){\n for (i = 0; i < x.length; i++) {\n y[i] = Math.pow(x[i], 2)\n }\n }\n if (cb_obj.active==2){\n for (i = 0; i < x.length; i++) {\n y[i] = Math.pow(x[i], 4)\n }\n }\n source.change.emit();\n\"\"\")\n\nselecthandler = CustomJS(args=dict(source=source), code=\"\"\"\n var data = source.data;\n console.log('Tap event occurred at x-position: ' + cb_obj.value);\n //plot.title.text=cb_obj.value;\n x = data['x']\n y = data['y']\n if (cb_obj.value==\"line\"){\n for (i = 0; i < x.length; i++) {\n y[i] = x[i];\n }\n }\n if (cb_obj.value==\"SquareCurve\"){\n for (i = 0; i < x.length; i++) {\n y[i] = Math.pow(x[i], 2)\n }\n }\n if (cb_obj.value==\"CubeCurve\"){\n for (i = 0; i < x.length; i++) {\n y[i] = Math.pow(x[i], 4)\n }\n }\n source.change.emit();\n\"\"\")\n\nradio = RadioGroup(\n labels=[\"line\", \"SqureCurve\", \"CubeCurve\"], active=0)\nradio.js_on_change('active', radiohandler)\nselect = Select(title=\"Select:\", value='line', options=[\"line\", \"SquareCurve\", \"CubeCurve\"])\nselect.js_on_change('value', selecthandler)\n\nlayout = column(radio, select, plot)\nshow(layout)"
},
{
"code": null,
"e": 44203,
"s": 43966,
"text": "Just as in a browser, each tab can show different web page, the Tab widget is Bokeh model providing different view to each figure. In the following example, two plot figures of sine and cosine curves are rendered in two different tabs −"
},
{
"code": null,
"e": 44685,
"s": 44203,
"text": "from bokeh.plotting import figure, output_file, show\nfrom bokeh.models import Panel, Tabs\nimport numpy as np\nimport math\nx=np.arange(0, math.pi*2, 0.05)\nfig1=figure(plot_width=300, plot_height=300)\n\nfig1.line(x, np.sin(x),line_width=2, line_color='navy')\n\ntab1 = Panel(child=fig1, title=\"sine\")\nfig2=figure(plot_width=300, plot_height=300)\nfig2.line(x,np.cos(x), line_width=2, line_color='orange')\ntab2 = Panel(child=fig2, title=\"cos\")\n\ntabs = Tabs(tabs=[ tab1, tab2 ])\n\nshow(tabs)"
},
{
"code": null,
"e": 44857,
"s": 44685,
"text": "Bokeh architecture has a decouple design in which objects such as plots and glyphs are created using Python and converted in JSON to be consumed by BokehJS client library."
},
{
"code": null,
"e": 45181,
"s": 44857,
"text": "However, it is possible to keep the objects in python and in the browser in sync with one another with the help of Bokeh Server. It enables response to User Interface (UI) events generated in a browser with the full power of python. It also helps automatically push server-side updates to the widgets or plots in a browser."
},
{
"code": null,
"e": 45382,
"s": 45181,
"text": "A Bokeh server uses Application code written in Python to create Bokeh Documents. Every new connection from a client browser results in the Bokeh server creating a new document, just for that session."
},
{
"code": null,
"e": 45730,
"s": 45382,
"text": "First, we have to develop an application code to be served to client browser. Following code renders a sine wave line glyph. Along with the plot, a slider control is also rendered to control the frequency of sine wave. The callback function update_data() updates ColumnDataSource data taking the instantaneous value of slider as current frequency."
},
{
"code": null,
"e": 46568,
"s": 45730,
"text": "import numpy as np\nfrom bokeh.io import curdoc\nfrom bokeh.layouts import row, column\nfrom bokeh.models import ColumnDataSource\nfrom bokeh.models.widgets import Slider, TextInput\nfrom bokeh.plotting import figure\nN = 200\nx = np.linspace(0, 4*np.pi, N)\ny = np.sin(x)\nsource = ColumnDataSource(data = dict(x = x, y = y))\nplot = figure(plot_height = 400, plot_width = 400, title = \"sine wave\")\nplot.line('x', 'y', source = source, line_width = 3, line_alpha = 0.6)\nfreq = Slider(title = \"frequency\", value = 1.0, start = 0.1, end = 5.1, step = 0.1)\ndef update_data(attrname, old, new):\n a = 1\n b = 0\n w = 0\n k = freq.value\n x = np.linspace(0, 4*np.pi, N)\n y = a*np.sin(k*x + w) + b\n source.data = dict(x = x, y = y)\nfreq.on_change('value', update_data)\ncurdoc().add_root(row(freq, plot, width = 500))\ncurdoc().title = \"Sliders\""
},
{
"code": null,
"e": 46621,
"s": 46568,
"text": "Next, start Bokeh server by following command line −"
},
{
"code": null,
"e": 46651,
"s": 46621,
"text": "Bokeh serve –show sliders.py\n"
},
{
"code": null,
"e": 46780,
"s": 46651,
"text": "Bokeh server starts running and serving the application at localhost:5006/sliders. The console log shows the following display −"
},
{
"code": null,
"e": 47367,
"s": 46780,
"text": "C:\\Users\\User>bokeh serve --show scripts\\sliders.py\n2019-09-29 00:21:35,855 Starting Bokeh server version 1.3.4 (running on Tornado 6.0.3)\n2019-09-29 00:21:35,875 Bokeh app running at: http://localhost:5006/sliders\n2019-09-29 00:21:35,875 Starting Bokeh server with process id: 3776\n2019-09-29 00:21:37,330 200 GET /sliders (::1) 699.99ms\n2019-09-29 00:21:38,033 101 GET /sliders/ws?bokeh-protocol-version=1.0&bokeh-session-id=VDxLKOzI5Ppl9kDvEMRzZgDVyqnXzvDWsAO21bRCKRZZ (::1) 4.00ms\n2019-09-29 00:21:38,045 WebSocket connection opened\n2019-09-29 00:21:38,049 ServerConnection created\n"
},
{
"code": null,
"e": 47465,
"s": 47367,
"text": "Open your favourite browser and enter above address. The Sine wave plot is displayed as follows −"
},
{
"code": null,
"e": 47530,
"s": 47465,
"text": "You can try and change the frequency to 2 by rolling the slider."
},
{
"code": null,
"e": 47659,
"s": 47530,
"text": "The Bokeh application provides a number of subcommands to be executed from command line. Following table shows the subcommands −"
},
{
"code": null,
"e": 47740,
"s": 47659,
"text": "Following command generates a HTML file for Python script having a Bokeh figure."
},
{
"code": null,
"e": 47783,
"s": 47740,
"text": "C:\\python37>bokeh html -o app.html app.py\n"
},
{
"code": null,
"e": 47940,
"s": 47783,
"text": "Adding show option automatically opens the HTML file in browser. Likewise, Python script is converted to PNG, SVG, JSON files with corresponding subcommand."
},
{
"code": null,
"e": 48013,
"s": 47940,
"text": "To display information of Bokeh server, use info subcommand as follows −"
},
{
"code": null,
"e": 48351,
"s": 48013,
"text": "C:\\python37>bokeh info\nPython version : 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)]\nIPython version : (not installed)\nTornado version : 6.0.3\nBokeh version : 1.3.4\nBokehJS static path : c:\\python37\\lib\\site-packages\\bokeh\\server\\static\nnode.js version : (not installed)\nnpm version : (not installed)\n"
},
{
"code": null,
"e": 48541,
"s": 48351,
"text": "In order to experiment with various types of plots, Bokeh website https://bokeh.pydata.org makes available sample datasets. They can be downloaded to local machine by sampledata subcommand."
},
{
"code": null,
"e": 48565,
"s": 48541,
"text": "C:\\python37>bokeh info\n"
},
{
"code": null,
"e": 48637,
"s": 48565,
"text": "Following datasets are downloaded in C:\\Users\\User\\.bokeh\\data folder −"
},
{
"code": null,
"e": 49235,
"s": 48637,
"text": "AAPL.csv airports.csv\nairports.json CGM.csv\nFB.csv gapminder_fertility.csv\ngapminder_life_expectancy.csv gapminder_population.csv\ngapminder_regions.csv GOOG.csv\nhaarcascade_frontalface_default.xml IBM.csv\nmovies.db MSFT.csv\nroutes.csv unemployment09.csv\nus_cities.json US_Counties.csv\nworld_cities.csv\nWPP2012_SA_DB03_POPULATION_QUINQUENNIAL.csv\n"
},
{
"code": null,
"e": 49357,
"s": 49235,
"text": "The secret subcommand generates a secret key to be used along with serve subcommand with SECRET_KEY environment variable."
},
{
"code": null,
"e": 49569,
"s": 49357,
"text": "In addition to subcommands described above, Bokeh plots can be exported to PNG and SVG file format using export() function. For that purpose, local Python installation should have following dependency libraries."
},
{
"code": null,
"e": 50008,
"s": 49569,
"text": "PhantomJS is a JavaScript API that enables automated navigation, screenshots, user behavior and assertions. It is used to run browser-based unit tests. PhantomJS is based on WebKit providing a similar browsing environment for different browsers and provides fast and native support for various web standards: DOM handling, CSS selector, JSON, Canvas, and SVG. In other words, PhantomJS is a web browser without a graphical user interface."
},
{
"code": null,
"e": 50385,
"s": 50008,
"text": "Pillow, a Python Imaging Library (earlier known as PIL) is a free library for the Python programming language that provides support for opening, manipulating, and saving many different image file formats. (including PPM, PNG, JPEG, GIF, TIFF, and BMP.) Some of its features are per-pixel manipulations, masking and transparency handling, image filtering, image enhancing, etc."
},
{
"code": null,
"e": 50731,
"s": 50385,
"text": "The export_png() function generates RGBA-format PNG image from layout. This function uses Webkit headless browser to render the layout in memory and then capture a screenshot. The generated image will be of the same dimensions as the source layout. Make sure that the Plot.background_fill_color and Plot.border_fill_color are properties to None."
},
{
"code": null,
"e": 50804,
"s": 50731,
"text": "from bokeh.io import export_png\nexport_png(plot, filename = \"file.png\")\n"
},
{
"code": null,
"e": 51248,
"s": 50804,
"text": "It is possible that HTML5 Canvas plot output with a SVG element that can be edited using programs such as Adobe Illustrator. The SVG objects can also be converted to PDFs. Here, canvas2svg, a JavaScript library is used to mock the normal Canvas element and its methods with an SVG element. Like PNGs, in order to create a SVG with a transparent background,the Plot.background_fill_color and Plot.border_fill_color properties should be to None."
},
{
"code": null,
"e": 51338,
"s": 51248,
"text": "The SVG backend is first activated by setting the Plot.output_backend attribute to \"svg\"."
},
{
"code": null,
"e": 51367,
"s": 51338,
"text": "plot.output_backend = \"svg\"\n"
},
{
"code": null,
"e": 51525,
"s": 51367,
"text": "For headless export, Bokeh has a utility function, export_svgs(). This function will download all of SVG-enabled plots within a layout as distinct SVG files."
},
{
"code": null,
"e": 51628,
"s": 51525,
"text": "from bokeh.io import export_svgs\nplot.output_backend = \"svg\"\nexport_svgs(plot, filename = \"plot.svg\")\n"
},
{
"code": null,
"e": 51744,
"s": 51628,
"text": "Plots and data in the form of standalone documents as well as Bokeh applications can be embedded in HTML documents."
},
{
"code": null,
"e": 51918,
"s": 51744,
"text": "Standalone document is a Bokeh plot or document not backed by Bokeh server. The interactions in such a plot is purely in the form of custom JS and not Pure Python callbacks."
},
{
"code": null,
"e": 52053,
"s": 51918,
"text": "Bokeh plots and documents backed by Bokeh server can also be embedded. Such documents contain Python callbacks that run on the server."
},
{
"code": null,
"e": 52165,
"s": 52053,
"text": "In case of standalone documents, a raw HTML code representing a Bokeh plot is obtained by file_html() function."
},
{
"code": null,
"e": 52357,
"s": 52165,
"text": "from bokeh.plotting import figure\nfrom bokeh.resources import CDN\nfrom bokeh.embed import file_html\nfig = figure()\nfig.line([1,2,3,4,5], [3,4,5,2,3])\nstring = file_html(plot, CDN, \"my plot\")\n"
},
{
"code": null,
"e": 52478,
"s": 52357,
"text": "Return value of file_html() function may be saved as HTML file or may be used to render through URL routes in Flask app."
},
{
"code": null,
"e": 52575,
"s": 52478,
"text": "In case of standalone document, its JSON representation can be obtained by json_item() function."
},
{
"code": null,
"e": 52755,
"s": 52575,
"text": "from bokeh.plotting import figure\nfrom bokeh.embed import file_html\nimport json\nfig = figure()\nfig.line([1,2,3,4,5], [3,4,5,2,3])\nitem_text = json.dumps(json_item(fig, \"myplot\"))\n"
},
{
"code": null,
"e": 52833,
"s": 52755,
"text": "This output can be used by the Bokeh.embed.embed_item function on a webpage −"
},
{
"code": null,
"e": 52894,
"s": 52833,
"text": "item = JSON.parse(item_text);\nBokeh.embed.embed_item(item);\n"
},
{
"code": null,
"e": 53275,
"s": 52894,
"text": "Bokeh applications on Bokeh Server may also be embedded so that a new session and Document is created on every page load so that a specific, existing session is loaded. This can be accomplished with the server_document() function. It accepts the URL to a Bokeh server application, and returns a script that will embed new sessions from that server any time the script is executed."
},
{
"code": null,
"e": 53409,
"s": 53275,
"text": "The server_document() function accepts URL parameter. If it is set to ‘default’, the default URL http://localhost:5006/ will be used."
},
{
"code": null,
"e": 53508,
"s": 53409,
"text": "from bokeh.embed import server_document\nscript = server_document(\"http://localhost:5006/sliders\")\n"
},
{
"code": null,
"e": 53573,
"s": 53508,
"text": "The server_document() function returns a script tag as follows −"
},
{
"code": null,
"e": 53759,
"s": 53573,
"text": "<script\n src=\"http://localhost:5006/sliders/autoload.js?bokeh-autoload-element=1000&bokeh-app-path=/sliders&bokeh-absolute-url=https://localhost:5006/sliders\"\n id=\"1000\">\n</script>\n"
},
{
"code": null,
"e": 54031,
"s": 53759,
"text": "Bokeh integrates well with a wide variety of other libraries, allowing you to use the most appropriate tool for each task. The fact that Bokeh generates JavaScript, makes it possible to combine Bokeh output with a wide variety of JavaScript libraries, such as PhosphorJS."
},
{
"code": null,
"e": 54517,
"s": 54031,
"text": "Datashader (https://github.com/bokeh/datashader) is another library with which Bokeh output can be extended. It is a Python library that pre-renders large datasets as a large-sized raster image. This ability overcomes limitation of browser when it comes to very large data. Datashader includes tools to build interactive Bokeh plots that dynamically re-render these images when zooming and panning in Bokeh, making it practical to work with arbitrarily large datasets in a web browser."
},
{
"code": null,
"e": 54738,
"s": 54517,
"text": "Another library is Holoviews ((http://holoviews.org/) that provides a concise declarative interface for building Bokeh plots, especially in Jupyter notebook. It facilitates quick prototyping of figures for data analysis."
},
{
"code": null,
"e": 54930,
"s": 54738,
"text": "When one has to use large datasets for creating visualizations with the help of Bokeh, the interaction can be very slow. For that purpose, one can enable Web Graphics Library (WebGL) support."
},
{
"code": null,
"e": 55092,
"s": 54930,
"text": "WebGL is a JavaScript API that renders content in the browser using GPU (graphics processing unit). This standardized plugin is available in all modern browsers."
},
{
"code": null,
"e": 55194,
"s": 55092,
"text": "To enable WebGL, all you have to do is set output_backend property of Bokeh Figure object to ‘webgl’."
},
{
"code": null,
"e": 55232,
"s": 55194,
"text": "fig = figure(output_backend=\"webgl\")\n"
},
{
"code": null,
"e": 55342,
"s": 55232,
"text": "In the following example, we plot a scatter glyph consisting of 10,000 points with the help of WebGL support."
},
{
"code": null,
"e": 55605,
"s": 55342,
"text": "import numpy as np\nfrom bokeh.plotting import figure, show, output_file\nN = 10000\nx = np.random.normal(0, np.pi, N)\ny = np.sin(x) + np.random.normal(0, 0.2, N)\noutput_file(\"scatterWebGL.html\")\np = figure(output_backend=\"webgl\")\np.scatter(x, y, alpha=0.1)\nshow(p)"
},
{
"code": null,
"e": 55916,
"s": 55605,
"text": "The Bokeh Python library, and libraries for Other Languages such as R, Scala, and Julia, primarily interacts with BokehJS at a high level. A Python programmer does not have to worry about JavaScript or web development. However, one can use BokehJS API, to do pure JavaScript development using BokehJS directly."
},
{
"code": null,
"e": 56150,
"s": 55916,
"text": "BokehJS objects such as glyphs and widgets are built more or less similarly as in Bokeh Python API. Typically, any Python ClassName is available as Bokeh.ClassName from JavaScript. For example, a Range1d object as obtained in Python."
},
{
"code": null,
"e": 56190,
"s": 56150,
"text": "xrange = Range1d(start=-0.5, end=20.5)\n"
},
{
"code": null,
"e": 56236,
"s": 56190,
"text": "It is equivalently obtained with BokehJS as −"
},
{
"code": null,
"e": 56297,
"s": 56236,
"text": "var xrange = new Bokeh.Range1d({ start: -0.5, end: 20.5 });\n"
},
{
"code": null,
"e": 56395,
"s": 56297,
"text": "Following JavaScript code when embedded in a HTML file renders a simple line plot in the browser."
},
{
"code": null,
"e": 56478,
"s": 56395,
"text": "First include all BokehJS libraries in <head>..</head> secion of web page as below"
},
{
"code": null,
"e": 57137,
"s": 56478,
"text": "<head>\n<script type=\"text/javascript\" src=\"https://cdn.pydata.org/bokeh/release/bokeh-1.3.4.min.js\"></script>\n<script type=\"text/javascript\" src=\"https://cdn.pydata.org/bokeh/release/bokeh-widgets-1.3.4.min.js\"></script>\n<script type=\"text/javascript\" src=\"https://cdn.pydata.org/bokeh/release/bokeh-tables-1.3.4.min.js\"></script>\n<script type=\"text/javascript\" src=\"https://cdn.pydata.org/bokeh/release/bokeh-gl-1.3.4.min.js\"></script>\n<script type=\"text/javascript\" src=\"https://cdn.pydata.org/bokeh/release/bokeh-api-1.3.4.min.js\"></script>\n<script type=\"text/javascript\" src=\"https://cdn.pydata.org/bokeh/release/bokeh-api-1.3.4.min.js\"></script>\n</head>"
},
{
"code": null,
"e": 57231,
"s": 57137,
"text": "In the body section following snippets of JavaScript construct various parts of a Bokeh Plot."
},
{
"code": null,
"e": 57987,
"s": 57231,
"text": "<script>\n// create some data and a ColumnDataSource\nvar x = Bokeh.LinAlg.linspace(-0.5, 20.5, 10);\nvar y = x.map(function (v) { return v * 0.5 + 3.0; });\nvar source = new Bokeh.ColumnDataSource({ data: { x: x, y: y } });\n// make the plot\nvar plot = new Bokeh.Plot({\n title: \"BokehJS Plot\",\n plot_width: 400,\n plot_height: 400\n});\n\n// add axes to the plot\nvar xaxis = new Bokeh.LinearAxis({ axis_line_color: null });\nvar yaxis = new Bokeh.LinearAxis({ axis_line_color: null });\nplot.add_layout(xaxis, \"below\");\nplot.add_layout(yaxis, \"left\");\n\n// add a Line glyph\nvar line = new Bokeh.Line({\n x: { field: \"x\" },\n y: { field: \"y\" },\n line_color: \"#666699\",\n line_width: 2\n});\nplot.add_glyph(line, source);\n\nBokeh.Plotting.show(plot);\n</script>"
},
{
"code": null,
"e": 58058,
"s": 57987,
"text": "Save above code as a web page and open it in a browser of your choice."
},
{
"code": null,
"e": 58065,
"s": 58058,
"text": " Print"
},
{
"code": null,
"e": 58076,
"s": 58065,
"text": " Add Notes"
}
]
|
Working on Git for GUI - GeeksforGeeks | 21 Apr, 2020
Git has its native environment within the terminal. All the new features are updated first at the command line, and only there is the full power of Git. But plain text isn’t the simplest choice for all tasks; sometimes some users are much more comfortable with a point-and-click interface, a visual representation is what they need.
Note: There’s nothing these graphical clients can do that the command-line client can’t; the command-line is still where you’ll have the most power and control when working with your repositories.
Git GUI is Tcl/Tk based graphical user interface to Git. It focuses on allowing users to make changes to their repository by making new commits, amending existing ones, creating branches, performing local merges, and fetching/pushing to remote repositories.
The first thing we need to do is install Git on Windows; you can do so with the following steps:Step 1: Download and install the latest version of Git for Windows.Step 2: Use the default options for each step in the installation.Step 3: Remove Git Bash Desktop Icon.Step 4: Go to Start > All Programs > Git > Git GUI and make a Desktop Shortcut.
Step 1: Create Remote RepositoryNow, we need a Git repository, and we’ll create a new remote repository on Github.
Step 2: Create a Local RepositoryFor creating a local repository: in our Git GUI, click on “Create New Repository”.Select the location you wish to store your repository in. It is important to note that the selected repository location MUST NOT exist.In order for this new repository to be initialized, you must first create a file, any file, in your local repo.Then, you must Commit and Push to the remote Git repository location.
Step 3: Clone a Remote Repository to a Local RepositoryIn order to clone a repository, click on the “Clone Existing Repository” link in the Git GUI window. An existing repository is one that is already initialized and/or has commits pushed to it.
Note: In the Source Location field, fill in the Git remote repository location. The target directory works as same in the case of creating a local repository. Git will attempt to create it, and it will fail if it already exists.
The Git GUI makes it easier to perform Git-related tasks, such as staging changes, commits, and pushes.
When we move files to a Git directory, you will see all the files in the “Unstaged Changes” window. This basically means that new files have been added, removed, updated, etc. When we click the “Stage Changed” button, it will attempt to add all the new files to the Git index.
Git Equivalent Command:
git add file_name
git status
After we’ve staged your changes, we need to commit them to your local repository. Type a Commit Message that makes sense to the changes that were made. When we are done, press the Commit button.
Git Equivalent Command:
git commit -m "message"
After we have committed all the codes in the local repository, we need to push these changes to our remote repository on GitHub. Without pushing the changes, others would not be able to access the code.Before we can proceed to push, we need set up a location to push to. Most folks refer to this location as “origin”. In Git, “origin” is a shorthand name for the remote repository that a project was originally cloned from. More precisely, it is used instead of that original repository’s URL – and thereby makes referencing much easier.
Git Equivalent Command:
git push -u origin master
This way GUI makes it a lot easier to work with GIT for the users that do not prefer the command line.
Picked
Git
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Set Git Username and Password in GitBash?
Difference Between Git Push Origin and Git Push Origin Master
How to Undo a Commit in Git ?
How to Push Git Branch to Remote?
Deleting a Local GitHub Repository
Using GitHub with SSH (Secure Shell)
How to Export Eclipse projects to GitHub?
How to Clone Android Project from GitHub in Android Studio?
Difference Between Git and GitHub
How to Install, Configure and Use GIT on Ubuntu? | [
{
"code": null,
"e": 24318,
"s": 24290,
"text": "\n21 Apr, 2020"
},
{
"code": null,
"e": 24651,
"s": 24318,
"text": "Git has its native environment within the terminal. All the new features are updated first at the command line, and only there is the full power of Git. But plain text isn’t the simplest choice for all tasks; sometimes some users are much more comfortable with a point-and-click interface, a visual representation is what they need."
},
{
"code": null,
"e": 24848,
"s": 24651,
"text": "Note: There’s nothing these graphical clients can do that the command-line client can’t; the command-line is still where you’ll have the most power and control when working with your repositories."
},
{
"code": null,
"e": 25106,
"s": 24848,
"text": "Git GUI is Tcl/Tk based graphical user interface to Git. It focuses on allowing users to make changes to their repository by making new commits, amending existing ones, creating branches, performing local merges, and fetching/pushing to remote repositories."
},
{
"code": null,
"e": 25452,
"s": 25106,
"text": "The first thing we need to do is install Git on Windows; you can do so with the following steps:Step 1: Download and install the latest version of Git for Windows.Step 2: Use the default options for each step in the installation.Step 3: Remove Git Bash Desktop Icon.Step 4: Go to Start > All Programs > Git > Git GUI and make a Desktop Shortcut."
},
{
"code": null,
"e": 25567,
"s": 25452,
"text": "Step 1: Create Remote RepositoryNow, we need a Git repository, and we’ll create a new remote repository on Github."
},
{
"code": null,
"e": 25998,
"s": 25567,
"text": "Step 2: Create a Local RepositoryFor creating a local repository: in our Git GUI, click on “Create New Repository”.Select the location you wish to store your repository in. It is important to note that the selected repository location MUST NOT exist.In order for this new repository to be initialized, you must first create a file, any file, in your local repo.Then, you must Commit and Push to the remote Git repository location."
},
{
"code": null,
"e": 26245,
"s": 25998,
"text": "Step 3: Clone a Remote Repository to a Local RepositoryIn order to clone a repository, click on the “Clone Existing Repository” link in the Git GUI window. An existing repository is one that is already initialized and/or has commits pushed to it."
},
{
"code": null,
"e": 26474,
"s": 26245,
"text": "Note: In the Source Location field, fill in the Git remote repository location. The target directory works as same in the case of creating a local repository. Git will attempt to create it, and it will fail if it already exists."
},
{
"code": null,
"e": 26578,
"s": 26474,
"text": "The Git GUI makes it easier to perform Git-related tasks, such as staging changes, commits, and pushes."
},
{
"code": null,
"e": 26855,
"s": 26578,
"text": "When we move files to a Git directory, you will see all the files in the “Unstaged Changes” window. This basically means that new files have been added, removed, updated, etc. When we click the “Stage Changed” button, it will attempt to add all the new files to the Git index."
},
{
"code": null,
"e": 26909,
"s": 26855,
"text": "Git Equivalent Command:\ngit add file_name\ngit status\n"
},
{
"code": null,
"e": 27104,
"s": 26909,
"text": "After we’ve staged your changes, we need to commit them to your local repository. Type a Commit Message that makes sense to the changes that were made. When we are done, press the Commit button."
},
{
"code": null,
"e": 27153,
"s": 27104,
"text": "Git Equivalent Command:\ngit commit -m \"message\"\n"
},
{
"code": null,
"e": 27691,
"s": 27153,
"text": "After we have committed all the codes in the local repository, we need to push these changes to our remote repository on GitHub. Without pushing the changes, others would not be able to access the code.Before we can proceed to push, we need set up a location to push to. Most folks refer to this location as “origin”. In Git, “origin” is a shorthand name for the remote repository that a project was originally cloned from. More precisely, it is used instead of that original repository’s URL – and thereby makes referencing much easier."
},
{
"code": null,
"e": 27742,
"s": 27691,
"text": "Git Equivalent Command:\ngit push -u origin master\n"
},
{
"code": null,
"e": 27845,
"s": 27742,
"text": "This way GUI makes it a lot easier to work with GIT for the users that do not prefer the command line."
},
{
"code": null,
"e": 27852,
"s": 27845,
"text": "Picked"
},
{
"code": null,
"e": 27856,
"s": 27852,
"text": "Git"
},
{
"code": null,
"e": 27954,
"s": 27856,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27963,
"s": 27954,
"text": "Comments"
},
{
"code": null,
"e": 27976,
"s": 27963,
"text": "Old Comments"
},
{
"code": null,
"e": 28025,
"s": 27976,
"text": "How to Set Git Username and Password in GitBash?"
},
{
"code": null,
"e": 28087,
"s": 28025,
"text": "Difference Between Git Push Origin and Git Push Origin Master"
},
{
"code": null,
"e": 28117,
"s": 28087,
"text": "How to Undo a Commit in Git ?"
},
{
"code": null,
"e": 28151,
"s": 28117,
"text": "How to Push Git Branch to Remote?"
},
{
"code": null,
"e": 28186,
"s": 28151,
"text": "Deleting a Local GitHub Repository"
},
{
"code": null,
"e": 28223,
"s": 28186,
"text": "Using GitHub with SSH (Secure Shell)"
},
{
"code": null,
"e": 28265,
"s": 28223,
"text": "How to Export Eclipse projects to GitHub?"
},
{
"code": null,
"e": 28325,
"s": 28265,
"text": "How to Clone Android Project from GitHub in Android Studio?"
},
{
"code": null,
"e": 28359,
"s": 28325,
"text": "Difference Between Git and GitHub"
}
]
|
Python | Numpy.dsplit() method - GeeksforGeeks | 17 Sep, 2019
With the help of Numpy.dsplit()() method, we can get the splitted dimensions of an array by using Numpy.dsplit()() method.
Syntax : Numpy.dsplit(numpy.array(), split_size)
Return : Return the array having splitted dimensions.
Example #1 :
In this example we can see that using Numpy.expand_dims() method, we are able to get the splitted dimensions using this method.
# import numpyimport numpy as np # using Numpy.dsplit() methodgfg = np.array([[1, 2, 5], [3, 4, 10], [5, 6, 15], [7, 8, 20]]) gfg = gfg.reshape(1, 2, 6)print(gfg) gfg = np.dsplit(gfg, 2)print(gfg)
Output :
[[[ 1 2 5 3 4 10][ 5 6 15 7 8 20]]]
[array([[[ 1, 2, 5],[ 5, 6, 15]]]),array([[[ 3, 4, 10],[ 7, 8, 20]]])]
Example #2 :
# import numpyimport numpy as np # using Numpy.expand_dims() methodgfg = np.array([[1, 2], [7, 8], [5, 10]])gfg = gfg.reshape(1, 2, 3)print(gfg) gfg = np.dsplit(gfg, 3)print(gfg)
Output :
[[[ 1 2 7][ 8 5 10]]]
[array([[[1],[8]]]), array([[[2],[5]]]), array([[[ 7],[10]]])]
Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
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
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n17 Sep, 2019"
},
{
"code": null,
"e": 24415,
"s": 24292,
"text": "With the help of Numpy.dsplit()() method, we can get the splitted dimensions of an array by using Numpy.dsplit()() method."
},
{
"code": null,
"e": 24464,
"s": 24415,
"text": "Syntax : Numpy.dsplit(numpy.array(), split_size)"
},
{
"code": null,
"e": 24518,
"s": 24464,
"text": "Return : Return the array having splitted dimensions."
},
{
"code": null,
"e": 24531,
"s": 24518,
"text": "Example #1 :"
},
{
"code": null,
"e": 24659,
"s": 24531,
"text": "In this example we can see that using Numpy.expand_dims() method, we are able to get the splitted dimensions using this method."
},
{
"code": "# import numpyimport numpy as np # using Numpy.dsplit() methodgfg = np.array([[1, 2, 5], [3, 4, 10], [5, 6, 15], [7, 8, 20]]) gfg = gfg.reshape(1, 2, 6)print(gfg) gfg = np.dsplit(gfg, 2)print(gfg)",
"e": 24904,
"s": 24659,
"text": null
},
{
"code": null,
"e": 24913,
"s": 24904,
"text": "Output :"
},
{
"code": null,
"e": 24949,
"s": 24913,
"text": "[[[ 1 2 5 3 4 10][ 5 6 15 7 8 20]]]"
},
{
"code": null,
"e": 25020,
"s": 24949,
"text": "[array([[[ 1, 2, 5],[ 5, 6, 15]]]),array([[[ 3, 4, 10],[ 7, 8, 20]]])]"
},
{
"code": null,
"e": 25033,
"s": 25020,
"text": "Example #2 :"
},
{
"code": "# import numpyimport numpy as np # using Numpy.expand_dims() methodgfg = np.array([[1, 2], [7, 8], [5, 10]])gfg = gfg.reshape(1, 2, 3)print(gfg) gfg = np.dsplit(gfg, 3)print(gfg)",
"e": 25214,
"s": 25033,
"text": null
},
{
"code": null,
"e": 25223,
"s": 25214,
"text": "Output :"
},
{
"code": null,
"e": 25245,
"s": 25223,
"text": "[[[ 1 2 7][ 8 5 10]]]"
},
{
"code": null,
"e": 25308,
"s": 25245,
"text": "[array([[[1],[8]]]), array([[[2],[5]]]), array([[[ 7],[10]]])]"
},
{
"code": null,
"e": 25339,
"s": 25308,
"text": "Python numpy-arrayManipulation"
},
{
"code": null,
"e": 25352,
"s": 25339,
"text": "Python-numpy"
},
{
"code": null,
"e": 25359,
"s": 25352,
"text": "Python"
},
{
"code": null,
"e": 25457,
"s": 25359,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25489,
"s": 25457,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25545,
"s": 25489,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 25587,
"s": 25545,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 25629,
"s": 25587,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 25651,
"s": 25629,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 25690,
"s": 25651,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 25721,
"s": 25690,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 25776,
"s": 25721,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 25805,
"s": 25776,
"text": "Create a directory in Python"
}
]
|
Arithmetic Operations on Images using OpenCV in Python | In this tutorial, we are going to learn about the arithmetic operations on Images using OpenCV. We can apply operations like addition, subtraction, Bitwise Operations, etc.., Let's see how we can perform operations on images.
We need the OpenCV module to perform operations on images. Install the OpenCV module using the following command in the terminal or command line.
pip install opencv-python==4.1.1.26
If you run the above command, you will get the following successful message.
Collecting opencv-python==4.1.1.26
Downloading https://files.pythonhosted.org/packages/1f/51/e0b9cef23098bc31c77b0e0
6221dd8d05119b9782d4c2b1d1482e22b5f5e/opencv_python-4.1.1.26-cp37-cp37m-win_amd64.w
hl (39.0MB)
Requirement already satisfied: numpy>=1.14.5 in c:\users\hafeezulkareem\anaconda3\l
ib\site-packages (from opencv-python==4.1.1.26) (1.16.2)
Installing collected packages: opencv-python
Successfully installed opencv-python-4.1.1.26
We can add two images using the cv2.addWeighted(). It takes five arguments, two images, and the weight of the final image from both and the light value for the final image.
Now we are going to add those two images into one image.
# importing cv2 module
import cv2
# reading the images and storing in variables
image_one = cv2.imread('_1.jpg')
image_two = cv2.imread('_2.jpg')
# adding two images
result_image = cv2.addWeighted(image_one, 0.5, image_two, 0.5, 0)
# displaying the final image
cv2.imshow('Final Image', result_image)
# deallocating the memory
if cv2.waitKey(0) & 0xff == 27:
cv2.destroyAllWindows()
Final Image
We have a method called cv2.substract(image_one, image_two) to perform subtraction on two images. We are going to use the same images as an addition. Let's see the code.
# importing cv2 module
import cv2
# reading the images and storing in variables
image_one = cv2.imread('_1.jpg')
image_two = cv2.imread('_2.jpg')
# substracting two images
result_image = cv2.subtract(image_one, image_two)
# displaying the final image
cv2.imshow('Final Image', result_image)
# deallocating the memory
if cv2.waitKey(0) & 0xff == 27:
cv2.destroyAllWindows()
Final Image
If you have any doubts regarding the tutorial, mention them in the comment section. | [
{
"code": null,
"e": 1288,
"s": 1062,
"text": "In this tutorial, we are going to learn about the arithmetic operations on Images using OpenCV. We can apply operations like addition, subtraction, Bitwise Operations, etc.., Let's see how we can perform operations on images."
},
{
"code": null,
"e": 1434,
"s": 1288,
"text": "We need the OpenCV module to perform operations on images. Install the OpenCV module using the following command in the terminal or command line."
},
{
"code": null,
"e": 1470,
"s": 1434,
"text": "pip install opencv-python==4.1.1.26"
},
{
"code": null,
"e": 1547,
"s": 1470,
"text": "If you run the above command, you will get the following successful message."
},
{
"code": null,
"e": 1992,
"s": 1547,
"text": "Collecting opencv-python==4.1.1.26\nDownloading https://files.pythonhosted.org/packages/1f/51/e0b9cef23098bc31c77b0e0\n6221dd8d05119b9782d4c2b1d1482e22b5f5e/opencv_python-4.1.1.26-cp37-cp37m-win_amd64.w\nhl (39.0MB)\nRequirement already satisfied: numpy>=1.14.5 in c:\\users\\hafeezulkareem\\anaconda3\\l\nib\\site-packages (from opencv-python==4.1.1.26) (1.16.2)\nInstalling collected packages: opencv-python\nSuccessfully installed opencv-python-4.1.1.26"
},
{
"code": null,
"e": 2165,
"s": 1992,
"text": "We can add two images using the cv2.addWeighted(). It takes five arguments, two images, and the weight of the final image from both and the light value for the final image."
},
{
"code": null,
"e": 2222,
"s": 2165,
"text": "Now we are going to add those two images into one image."
},
{
"code": null,
"e": 2608,
"s": 2222,
"text": "# importing cv2 module\nimport cv2\n# reading the images and storing in variables\nimage_one = cv2.imread('_1.jpg')\nimage_two = cv2.imread('_2.jpg')\n# adding two images\nresult_image = cv2.addWeighted(image_one, 0.5, image_two, 0.5, 0)\n# displaying the final image\ncv2.imshow('Final Image', result_image)\n# deallocating the memory\nif cv2.waitKey(0) & 0xff == 27:\n cv2.destroyAllWindows()"
},
{
"code": null,
"e": 2620,
"s": 2608,
"text": "Final Image"
},
{
"code": null,
"e": 2790,
"s": 2620,
"text": "We have a method called cv2.substract(image_one, image_two) to perform subtraction on two images. We are going to use the same images as an addition. Let's see the code."
},
{
"code": null,
"e": 3166,
"s": 2790,
"text": "# importing cv2 module\nimport cv2\n# reading the images and storing in variables\nimage_one = cv2.imread('_1.jpg')\nimage_two = cv2.imread('_2.jpg')\n# substracting two images\nresult_image = cv2.subtract(image_one, image_two)\n# displaying the final image\ncv2.imshow('Final Image', result_image)\n# deallocating the memory\nif cv2.waitKey(0) & 0xff == 27:\n cv2.destroyAllWindows()"
},
{
"code": null,
"e": 3178,
"s": 3166,
"text": "Final Image"
},
{
"code": null,
"e": 3262,
"s": 3178,
"text": "If you have any doubts regarding the tutorial, mention them in the comment section."
}
]
|
Redis - Backup | Redis SAVE command is used to create a backup of the current Redis database.
Following is the basic syntax of redis SAVE command.
127.0.0.1:6379> SAVE
Following example creates a backup of the current database.
127.0.0.1:6379> SAVE
OK
This command will create a dump.rdb file in your Redis directory.
To restore Redis data, move Redis backup file (dump.rdb) into your Redis directory and start the server. To get your Redis directory, use CONFIG command of Redis as shown below.
127.0.0.1:6379> CONFIG get dir
1) "dir"
2) "/user/tutorialspoint/redis-2.8.13/src"
In the output of the above command /user/tutorialspoint/redis-2.8.13/src is the directory, where Redis server is installed.
To create Redis backup, an alternate command BGSAVE is also available. This command will start the backup process and run this in the background.
127.0.0.1:6379> BGSAVE
Background saving started
22 Lectures
40 mins
Skillbakerystudios
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2122,
"s": 2045,
"text": "Redis SAVE command is used to create a backup of the current Redis database."
},
{
"code": null,
"e": 2175,
"s": 2122,
"text": "Following is the basic syntax of redis SAVE command."
},
{
"code": null,
"e": 2198,
"s": 2175,
"text": "127.0.0.1:6379> SAVE \n"
},
{
"code": null,
"e": 2258,
"s": 2198,
"text": "Following example creates a backup of the current database."
},
{
"code": null,
"e": 2286,
"s": 2258,
"text": "127.0.0.1:6379> SAVE \nOK \n"
},
{
"code": null,
"e": 2352,
"s": 2286,
"text": "This command will create a dump.rdb file in your Redis directory."
},
{
"code": null,
"e": 2530,
"s": 2352,
"text": "To restore Redis data, move Redis backup file (dump.rdb) into your Redis directory and start the server. To get your Redis directory, use CONFIG command of Redis as shown below."
},
{
"code": null,
"e": 2618,
"s": 2530,
"text": "127.0.0.1:6379> CONFIG get dir \n1) \"dir\" \n2) \"/user/tutorialspoint/redis-2.8.13/src\" \n"
},
{
"code": null,
"e": 2742,
"s": 2618,
"text": "In the output of the above command /user/tutorialspoint/redis-2.8.13/src is the directory, where Redis server is installed."
},
{
"code": null,
"e": 2888,
"s": 2742,
"text": "To create Redis backup, an alternate command BGSAVE is also available. This command will start the backup process and run this in the background."
},
{
"code": null,
"e": 2940,
"s": 2888,
"text": "127.0.0.1:6379> BGSAVE \nBackground saving started\n"
},
{
"code": null,
"e": 2972,
"s": 2940,
"text": "\n 22 Lectures \n 40 mins\n"
},
{
"code": null,
"e": 2992,
"s": 2972,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 2999,
"s": 2992,
"text": " Print"
},
{
"code": null,
"e": 3010,
"s": 2999,
"text": " Add Notes"
}
]
|
How to filter rows that contain a certain string in R? | We can do this by using filter and grepl function of dplyr package.
Consider the mtcars data set.
> data(mtcars)
> head(mtcars)
mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
type
Mazda RX4 Mazda RX4
Mazda RX4 Wag Mazda RX4 Wag
Datsun 710 Datsun 710
Hornet 4 Drive Hornet 4 Drive
Hornet Sportabout Hornet Sportabout
Valiant Valiant
mtcars$type
[1] "Mazda RX4" "Mazda RX4 Wag" "Datsun 710"
[4] "Hornet 4 Drive" "Hornet Sportabout" "Valiant"
[7] "Duster 360" "Merc 240D" "Merc 230"
[10] "Merc 280" "Merc 280C" "Merc 450SE"
[13] "Merc 450SL" "Merc 450SLC" "Cadillac Fleetwood"
[16] "Lincoln Continental" "Chrysler Imperial" "Fiat 128"
[19] "Honda Civic" "Toyota Corolla" "Toyota Corona"
[22] "Dodge Challenger" "AMC Javelin" "Camaro Z28"
[25] "Pontiac Firebird" "Fiat X1-9" "Porsche 914-2"
[28] "Lotus Europa" "Ford Pantera L" "Ferrari Dino"
[31] "Maserati Bora" "Volvo 142E"
let’s say we want to filter rows where we have type Ferrari then it can be done as follows −
> dplyr::filter(mtcars, grepl('Ferrari', type))
mpg cyl disp hp drat wt qsec vs am gear carb type
1 19.7 6 145 175 3.62 2.77 15.5 0 1 5 6 Ferrari Dino
Now if we want to filter rows where we have type Merc or Datsun then it can be done as
follows −
> dplyr::filter(mtcars, grepl('Merc|Datsun', type))
mpg cyl disp hp drat wt qsec vs am gear carb type
1 22.8 4 108.0 93 3.85 2.32 18.61 1 1 4 1 Datsun 710
2 24.4 4 146.7 62 3.69 3.19 20.00 1 0 4 2 Merc 240D
3 22.8 4 140.8 95 3.92 3.15 22.90 1 0 4 2 Merc 230
4 19.2 6 167.6 123 3.92 3.44 18.30 1 0 4 4 Merc 280
5 17.8 6 167.6 123 3.92 3.44 18.90 1 0 4 4 Merc 280C
6 16.4 8 275.8 180 3.07 4.07 17.40 0 0 3 3 Merc 450SE
7 17.3 8 275.8 180 3.07 3.73 17.60 0 0 3 3 Merc 450SL
8 15.2 8 275.8 180 3.07 3.78 18.00 0 0 3 3 Merc 450SLC
Suppose if we want to filter rows where we don’t have type Mazda or Merc or Toyota
then it can be done as follows −
> dplyr::filter(mtcars, !grepl('Mazda|Merc|Toyota', type))
mpg cyl disp hp drat wt qsec vs am gear carb type
1 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1 Datsun 710
2 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1 Hornet 4 Drive
3 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2 Hornet Sportabout
4 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1 Valiant
5 14.3 8 360.0 245 3.21 3.570 15.84 0 0 3 4 Duster 360
6 10.4 8 472.0 205 2.93 5.250 17.98 0 0 3 4 Cadillac Fleetwood
7 10.4 8 460.0 215 3.00 5.424 17.82 0 0 3 4 Lincoln Continental
8 14.7 8 440.0 230 3.23 5.345 17.42 0 0 3 4 Chrysler Imperial
9 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1 Fiat 128
10 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2 Honda Civic
11 15.5 8 318.0 150 2.76 3.520 16.87 0 0 3 2 Dodge Challenger
12 15.2 8 304.0 150 3.15 3.435 17.30 0 0 3 2 AMC Javelin
13 13.3 8 350.0 245 3.73 3.840 15.41 0 0 3 4 Camaro Z28
14 19.2 8 400.0 175 3.08 3.845 17.05 0 0 3 2 Pontiac Firebird
15 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1 Fiat X1-9
16 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2 Porsche 914-2
17 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2 Lotus Europa
18 15.8 8 351.0 264 4.22 3.170 14.50 0 1 5 4 Ford Pantera L
19 19.7 6 145.0 175 3.62 2.770 15.50 0 1 5 6 Ferrari Dino
20 15.0 8 301.0 335 3.54 3.570 14.60 0 1 5 8 Maserati Bora
21 21.4 4 121.0 109 4.11 2.780 18.60 1 1 4 2 Volvo 142E | [
{
"code": null,
"e": 1130,
"s": 1062,
"text": "We can do this by using filter and grepl function of dplyr package."
},
{
"code": null,
"e": 1160,
"s": 1130,
"text": "Consider the mtcars data set."
},
{
"code": null,
"e": 2253,
"s": 1160,
"text": "> data(mtcars)\n> head(mtcars)\nmpg cyl disp hp drat wt qsec vs am gear carb\nMazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4\nMazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4\nDatsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1\nHornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1\nHornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2\nValiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1\n type\nMazda RX4 Mazda RX4\nMazda RX4 Wag Mazda RX4 Wag\nDatsun 710 Datsun 710\nHornet 4 Drive Hornet 4 Drive\nHornet Sportabout Hornet Sportabout\nValiant Valiant\nmtcars$type\n[1] \"Mazda RX4\" \"Mazda RX4 Wag\" \"Datsun 710\"\n[4] \"Hornet 4 Drive\" \"Hornet Sportabout\" \"Valiant\"\n[7] \"Duster 360\" \"Merc 240D\" \"Merc 230\"\n[10] \"Merc 280\" \"Merc 280C\" \"Merc 450SE\"\n[13] \"Merc 450SL\" \"Merc 450SLC\" \"Cadillac Fleetwood\"\n[16] \"Lincoln Continental\" \"Chrysler Imperial\" \"Fiat 128\"\n[19] \"Honda Civic\" \"Toyota Corolla\" \"Toyota Corona\"\n[22] \"Dodge Challenger\" \"AMC Javelin\" \"Camaro Z28\"\n[25] \"Pontiac Firebird\" \"Fiat X1-9\" \"Porsche 914-2\"\n[28] \"Lotus Europa\" \"Ford Pantera L\" \"Ferrari Dino\"\n[31] \"Maserati Bora\" \"Volvo 142E\""
},
{
"code": null,
"e": 2346,
"s": 2253,
"text": "let’s say we want to filter rows where we have type Ferrari then it can be done as follows −"
},
{
"code": null,
"e": 2497,
"s": 2346,
"text": "> dplyr::filter(mtcars, grepl('Ferrari', type))\nmpg cyl disp hp drat wt qsec vs am gear carb type\n1 19.7 6 145 175 3.62 2.77 15.5 0 1 5 6 Ferrari Dino"
},
{
"code": null,
"e": 2594,
"s": 2497,
"text": "Now if we want to filter rows where we have type Merc or Datsun then it can be done as\nfollows −"
},
{
"code": null,
"e": 3120,
"s": 2594,
"text": "> dplyr::filter(mtcars, grepl('Merc|Datsun', type))\nmpg cyl disp hp drat wt qsec vs am gear carb type\n1 22.8 4 108.0 93 3.85 2.32 18.61 1 1 4 1 Datsun 710\n2 24.4 4 146.7 62 3.69 3.19 20.00 1 0 4 2 Merc 240D\n3 22.8 4 140.8 95 3.92 3.15 22.90 1 0 4 2 Merc 230\n4 19.2 6 167.6 123 3.92 3.44 18.30 1 0 4 4 Merc 280\n5 17.8 6 167.6 123 3.92 3.44 18.90 1 0 4 4 Merc 280C\n6 16.4 8 275.8 180 3.07 4.07 17.40 0 0 3 3 Merc 450SE\n7 17.3 8 275.8 180 3.07 3.73 17.60 0 0 3 3 Merc 450SL\n8 15.2 8 275.8 180 3.07 3.78 18.00 0 0 3 3 Merc 450SLC"
},
{
"code": null,
"e": 3236,
"s": 3120,
"text": "Suppose if we want to filter rows where we don’t have type Mazda or Merc or Toyota\nthen it can be done as follows −"
},
{
"code": null,
"e": 4560,
"s": 3236,
"text": "> dplyr::filter(mtcars, !grepl('Mazda|Merc|Toyota', type))\nmpg cyl disp hp drat wt qsec vs am gear carb type\n1 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1 Datsun 710\n2 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1 Hornet 4 Drive\n3 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2 Hornet Sportabout\n4 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1 Valiant\n5 14.3 8 360.0 245 3.21 3.570 15.84 0 0 3 4 Duster 360\n6 10.4 8 472.0 205 2.93 5.250 17.98 0 0 3 4 Cadillac Fleetwood\n7 10.4 8 460.0 215 3.00 5.424 17.82 0 0 3 4 Lincoln Continental\n8 14.7 8 440.0 230 3.23 5.345 17.42 0 0 3 4 Chrysler Imperial\n9 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1 Fiat 128\n10 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2 Honda Civic\n11 15.5 8 318.0 150 2.76 3.520 16.87 0 0 3 2 Dodge Challenger\n12 15.2 8 304.0 150 3.15 3.435 17.30 0 0 3 2 AMC Javelin\n13 13.3 8 350.0 245 3.73 3.840 15.41 0 0 3 4 Camaro Z28\n14 19.2 8 400.0 175 3.08 3.845 17.05 0 0 3 2 Pontiac Firebird\n15 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1 Fiat X1-9\n16 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2 Porsche 914-2\n17 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2 Lotus Europa\n18 15.8 8 351.0 264 4.22 3.170 14.50 0 1 5 4 Ford Pantera L\n19 19.7 6 145.0 175 3.62 2.770 15.50 0 1 5 6 Ferrari Dino\n20 15.0 8 301.0 335 3.54 3.570 14.60 0 1 5 8 Maserati Bora\n21 21.4 4 121.0 109 4.11 2.780 18.60 1 1 4 2 Volvo 142E"
}
]
|
What are the allowed characters in Python function names? | Python Identifiers
Identifier is the name given to entities like class, functions, variables etc. in Python. It helps in knowing one entity from another.
Rules for writing identifiers
Identifiers can be a combination of lowercase letters (a to z) or uppercase letters (A to Z) or digits (0 to 9) or an underscore (_). Names like myClass, var_3 and print_to_screen, all are valid examples.
An identifier cannot start with a digit. 2variable is invalid, but variable2 is perfectly correct.
Keywords cannot be used as identifiers. The word ‘global’ is a keyword in python. So we get an invalid syntax error here
global = "syntex"
print global
File "identifiers1.py", line 3
global = "syntex"
^
SyntaxError: invalid syntax
Explanation:
The above code when run shows error because keyword global is used
as a variable/identifier for assigning a string value.
We cannot use special symbols like !, @, #, $, % etc. in our identifier.
$local = 5
print $local
File "identifiers2.py", line 1
$local = 5
^
SyntaxError: invalid syntax
Explanation:
The above code when run shows error because special character $ is used in the variable/identifier for assigning a integer value. | [
{
"code": null,
"e": 1081,
"s": 1062,
"text": "Python Identifiers"
},
{
"code": null,
"e": 1216,
"s": 1081,
"text": "Identifier is the name given to entities like class, functions, variables etc. in Python. It helps in knowing one entity from another."
},
{
"code": null,
"e": 1246,
"s": 1216,
"text": "Rules for writing identifiers"
},
{
"code": null,
"e": 1451,
"s": 1246,
"text": "Identifiers can be a combination of lowercase letters (a to z) or uppercase letters (A to Z) or digits (0 to 9) or an underscore (_). Names like myClass, var_3 and print_to_screen, all are valid examples."
},
{
"code": null,
"e": 1550,
"s": 1451,
"text": "An identifier cannot start with a digit. 2variable is invalid, but variable2 is perfectly correct."
},
{
"code": null,
"e": 1671,
"s": 1550,
"text": "Keywords cannot be used as identifiers. The word ‘global’ is a keyword in python. So we get an invalid syntax error here"
},
{
"code": null,
"e": 1702,
"s": 1671,
"text": "global = \"syntex\"\nprint global"
},
{
"code": null,
"e": 1796,
"s": 1702,
"text": "File \"identifiers1.py\", line 3\n global = \"syntex\"\n ^\nSyntaxError: invalid syntax"
},
{
"code": null,
"e": 1809,
"s": 1796,
"text": "Explanation:"
},
{
"code": null,
"e": 1876,
"s": 1809,
"text": "The above code when run shows error because keyword global is used"
},
{
"code": null,
"e": 1931,
"s": 1876,
"text": "as a variable/identifier for assigning a string value."
},
{
"code": null,
"e": 2004,
"s": 1931,
"text": "We cannot use special symbols like !, @, #, $, % etc. in our identifier."
},
{
"code": null,
"e": 2028,
"s": 2004,
"text": "$local = 5\nprint $local"
},
{
"code": null,
"e": 2108,
"s": 2028,
"text": "File \"identifiers2.py\", line 1\n $local = 5\n ^\nSyntaxError: invalid syntax"
},
{
"code": null,
"e": 2121,
"s": 2108,
"text": "Explanation:"
},
{
"code": null,
"e": 2251,
"s": 2121,
"text": "The above code when run shows error because special character $ is used in the variable/identifier for assigning a integer value."
}
]
|
How to subtract elements of two arrays and store the result as a positive array in JavaScript? | Suppose, we have two arrays like these −
const arr1 = [1,2,3,4,5,6];
const arr2 = [9,8,7,5,8,3];
We are required to write a JavaScript function that takes in two such arrays and returns an array of absolute difference between the corresponding elements of the array.
Therefore, for these arrays, the output should look like −
const output = [8,6,4,1,3,3];
We will use a for loop and keep pushing the absolute difference iteratively into a new array and finally return the array.
Following is the code −
const arr1 = [1,2,3,4,5,6];
const arr2 = [9,8,7,5,8,3];
const absDifference = (arr1, arr2) => {
const res = [];
for(let i = 0; i < arr1.length; i++){
const el = Math.abs((arr1[i] || 0) - (arr2[i] || 0));
res[i] = el;
};
return res;
};
console.log(absDifference(arr1, arr2));
This will produce the following output in console −
[ 8, 6, 4, 1, 3, 3 ] | [
{
"code": null,
"e": 1103,
"s": 1062,
"text": "Suppose, we have two arrays like these −"
},
{
"code": null,
"e": 1159,
"s": 1103,
"text": "const arr1 = [1,2,3,4,5,6];\nconst arr2 = [9,8,7,5,8,3];"
},
{
"code": null,
"e": 1329,
"s": 1159,
"text": "We are required to write a JavaScript function that takes in two such arrays and returns an array of absolute difference between the corresponding elements of the array."
},
{
"code": null,
"e": 1388,
"s": 1329,
"text": "Therefore, for these arrays, the output should look like −"
},
{
"code": null,
"e": 1418,
"s": 1388,
"text": "const output = [8,6,4,1,3,3];"
},
{
"code": null,
"e": 1541,
"s": 1418,
"text": "We will use a for loop and keep pushing the absolute difference iteratively into a new array and finally return the array."
},
{
"code": null,
"e": 1565,
"s": 1541,
"text": "Following is the code −"
},
{
"code": null,
"e": 1864,
"s": 1565,
"text": "const arr1 = [1,2,3,4,5,6];\nconst arr2 = [9,8,7,5,8,3];\nconst absDifference = (arr1, arr2) => {\n const res = [];\n for(let i = 0; i < arr1.length; i++){\n const el = Math.abs((arr1[i] || 0) - (arr2[i] || 0));\n res[i] = el;\n };\n return res;\n};\nconsole.log(absDifference(arr1, arr2));"
},
{
"code": null,
"e": 1916,
"s": 1864,
"text": "This will produce the following output in console −"
},
{
"code": null,
"e": 1937,
"s": 1916,
"text": "[ 8, 6, 4, 1, 3, 3 ]"
}
]
|
How to get typed text from a textbox by using Selenium Webdriver? | We can get the typed text from a textbox with Selenium webdriver. Firstly, we have to enter text in the text box (after being identified with any locators) with the help of the sendKeys method.
Then apply the method getAttribute to obtain the text entered in that field and pass the parameter value to that method. Let us make an attempt to obtain the value entered in the Google search box −
WebElement m = driver.findElement(By.name("q"));
String st = m.getAttribute("value");
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
public class GetTextTyped{
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
//implicit wait
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//URL launch
driver.get("https://www.google.com/");
// identify element
WebElement t =driver.findElement(By.name("q"));
t.sendKeys("Tutorialspoint");
// obtain value with getAttribute
System.out.println("Value is: " + t.getAttribute("value"));
driver.quit();
}
} | [
{
"code": null,
"e": 1256,
"s": 1062,
"text": "We can get the typed text from a textbox with Selenium webdriver. Firstly, we have to enter text in the text box (after being identified with any locators) with the help of the sendKeys method."
},
{
"code": null,
"e": 1455,
"s": 1256,
"text": "Then apply the method getAttribute to obtain the text entered in that field and pass the parameter value to that method. Let us make an attempt to obtain the value entered in the Google search box −"
},
{
"code": null,
"e": 1541,
"s": 1455,
"text": "WebElement m = driver.findElement(By.name(\"q\"));\nString st = m.getAttribute(\"value\");"
},
{
"code": null,
"e": 2366,
"s": 1541,
"text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.firefox.FirefoxDriver;\nimport java.util.concurrent.TimeUnit;\npublic class GetTextTyped{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.gecko.driver\",\n\"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\geckodriver.exe\");\n WebDriver driver = new FirefoxDriver();\n //implicit wait\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n //URL launch\n driver.get(\"https://www.google.com/\");\n // identify element\n WebElement t =driver.findElement(By.name(\"q\"));\n t.sendKeys(\"Tutorialspoint\");\n // obtain value with getAttribute\n System.out.println(\"Value is: \" + t.getAttribute(\"value\"));\n driver.quit();\n }\n}"
}
]
|
String Formatting in Python using % - GeeksforGeeks | 19 Nov, 2020
In Python a string of required formatting can be achieved by different methods.Some of them are ;1) Using %2) Using {}3) Using Template Strings
In this article the formatting using % is discussed.
The formatting using % is similar to that of ‘printf’ in C programming language.%d – integer%f – float%s – string%x – hexadecimal%o – octal
The below example describes the use of formatting using % in Python
# Python program to demonstrate the use of formatting using % # Initialize variable as a string variable = '15'string = "Variable as string = %s" %(variable) print (string ) # Printing as raw data # Thanks to Himanshu Pant for this print ("Variable as raw data = %r" %(variable)) # Convert the variable to integer # And perform check other formatting options variable = int(variable) # Without this the below statement # will give error. string = "Variable as integer = %d" %(variable) print (string) print ("Variable as float = %f" %(variable)) # printing as any string or char after a mark # here i use mayank as a string print ("Variable as printing with special char = %cmayank" %(variable)) print ("Variable as hexadecimal = %x" %(variable))print ("Variable as octal = %o" %(variable))
Output :
Variable as string = 15
Variable as raw data = '15'
Variable as integer = 15
Variable as float = 15.000000
Variable as printing with special char = mayank
Variable as hexadecimal = f
Variable as octal = 17
This article is contributed by Nikhil Kumar Singh (nickzuck_007)
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
Selecting rows in pandas DataFrame based on conditions
sum() function in Python
*args and **kwargs in Python | [
{
"code": null,
"e": 24232,
"s": 24204,
"text": "\n19 Nov, 2020"
},
{
"code": null,
"e": 24376,
"s": 24232,
"text": "In Python a string of required formatting can be achieved by different methods.Some of them are ;1) Using %2) Using {}3) Using Template Strings"
},
{
"code": null,
"e": 24429,
"s": 24376,
"text": "In this article the formatting using % is discussed."
},
{
"code": null,
"e": 24569,
"s": 24429,
"text": "The formatting using % is similar to that of ‘printf’ in C programming language.%d – integer%f – float%s – string%x – hexadecimal%o – octal"
},
{
"code": null,
"e": 24637,
"s": 24569,
"text": "The below example describes the use of formatting using % in Python"
},
{
"code": "# Python program to demonstrate the use of formatting using % # Initialize variable as a string variable = '15'string = \"Variable as string = %s\" %(variable) print (string ) # Printing as raw data # Thanks to Himanshu Pant for this print (\"Variable as raw data = %r\" %(variable)) # Convert the variable to integer # And perform check other formatting options variable = int(variable) # Without this the below statement # will give error. string = \"Variable as integer = %d\" %(variable) print (string) print (\"Variable as float = %f\" %(variable)) # printing as any string or char after a mark # here i use mayank as a string print (\"Variable as printing with special char = %cmayank\" %(variable)) print (\"Variable as hexadecimal = %x\" %(variable))print (\"Variable as octal = %o\" %(variable)) ",
"e": 25463,
"s": 24637,
"text": null
},
{
"code": null,
"e": 25472,
"s": 25463,
"text": "Output :"
},
{
"code": null,
"e": 25679,
"s": 25472,
"text": "Variable as string = 15\nVariable as raw data = '15'\nVariable as integer = 15\nVariable as float = 15.000000\nVariable as printing with special char = mayank\nVariable as hexadecimal = f\nVariable as octal = 17\n"
},
{
"code": null,
"e": 25744,
"s": 25679,
"text": "This article is contributed by Nikhil Kumar Singh (nickzuck_007)"
},
{
"code": null,
"e": 25868,
"s": 25744,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 25875,
"s": 25868,
"text": "Python"
},
{
"code": null,
"e": 25973,
"s": 25875,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25982,
"s": 25973,
"text": "Comments"
},
{
"code": null,
"e": 25995,
"s": 25982,
"text": "Old Comments"
},
{
"code": null,
"e": 26030,
"s": 25995,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26052,
"s": 26030,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26084,
"s": 26052,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26126,
"s": 26084,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26152,
"s": 26126,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26189,
"s": 26152,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 26233,
"s": 26189,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 26288,
"s": 26233,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 26313,
"s": 26288,
"text": "sum() function in Python"
}
]
|
How to Serve Different Model Versions using TensorFlow Serving | by Renu Khandelwal | Towards Data Science | This article explains how to manage multiple models and multiple versions of the same model in TensorFlow Serving using configuration files along with a brief understanding of batching.
Deploying a TensorFlow Model to Production made Easy
You have TensorFlow deep learning models with different architectures or have trained your models with different hyperparameters and would like to test them locally or in production. The easiest way is to serve the models using a Model Server Config file.
A Model Server Configuration file is a protocol buffer file(protobuf), which is a language-neutral, platform-neutral extensible yet simple and faster way to serialize the structure data.
How do I create a Model Config File?
Below is a sample Model Config File that will serve all the versions of the “MNIST” models available on disk.
model_config_list { config { name: 'mnist' base_path: '/models/mnist/' model_platform: 'tensorflow' model_version_policy: {all: {}} }}
Each ModelConfig specifies one model to be served with the following parameters.
name - A servable model name
base_path - Specify the path to look for versions of the servable.
model_platform - Platform in which the model was developed.
model_version_policy - Version policy for the model indicates which version of the model to load and serve the client. By default, the latest version of the model will be served and can be overridden by changing the model_version_policy field.
How to load the Model Config File?
Read how to load the TensorFlow Serving Docker container on Windows 10 here
docker run -p 8501:8501 --mount type=bind,source=C:\TF_serv\TF_model,target=/models/mnist -e MODEL_NAME=mnist -t tensorflow/serving
List all the running Docker containers
docker container list
or
docker ps
Copy the models.config file from the source to the target of the Docker image
docker cp \TF_serv\TF_model\models.config ba978f5a9475:/models/mnist
When copying the file to docker container, provide the container Id, as shown above.
Stop the Docker container using the Docker container name or container Id
docker stop ba978f5a9475
Finally, loading the Model Config file using the option
--model_config_file_poll_wait_seconds flag instructs the server to check for a new config file at the path specified using --model_config_file every 60 seconds.
docker run -p 8501:8501 --mount type=bind,source=C:\TF_serv\TF_model,target=/models/mnist -e MODEL_NAME=mnist -t tensorflow/serving --model_config_file_poll_wait_seconds=60 --model_config_file=/models/mnist/models.config
How to make an inference using the model served using models.config file using a specific version of the model?
Using REST API to make the inference request
json_response = requests.post('http://localhost:8501/v1/models/mnist/versions/5:predict', data=data, headers=headers)
Since the models.config file specified above will load all versions on the disk; I have loaded version 5.
A generic way to call a specific version of the model to make an inference is shown below.
/v1/models/<model name>/versions/<version number>
How do I override and specify a specific version of the model to be loaded and served?
You will need to use the specified tag with the version number within the model_version_policy
model_config_list { config { name: 'mnist' base_path: '/models/mnist/' model_platform: 'tensorflow' model_version_policy{ specific{ versions:2 } } }}
with the above change models.config file, the client can now call the model’s predict method only for version 2.
Can I server multiple versions of the same model simultaneously?
You can also serve multiple versions of the same model simultaneously. In the example below, we are serving the MNIST model with versions 2 and 3 simultaneously.
model_config_list { config { name: 'mnist' base_path: '/models/mnist/' model_platform: 'tensorflow' model_version_policy{ specific{ versions:2 versions:3 } } }}
This is helpful when you have a newer version of the model and would like to divert a few users to a newer version and keep most clients on the stable older version of the model. This allows you to accomplish the A/B testing.
Can I server multiple models like a custom model and a transfer learned model?
To server multiple models, update the models.config file as shown below
model_config_list { config{ name: 'mnist' base_path: '/models/mnist/' model_platform: 'tensorflow' model_version_policy{ specific{ versions:2 versions:3 } } } config{ name: 'Inception_1' base_path: '/models/inception_1/' model_platform: 'tensorflow' }}
Will TensorFlow Serving allow for batching multiple requests?
TensorFlow Serving allows two different forms of batching.
Batch individual model inference requests, where TensorFlow serving waits for a predetermined time and then perform inferences on all requests that arrived in that time period
A single client can send batched requests to TensorFlow Serving.
Batching requires all requests to use the same version of the model.
Batching allows for higher resource utilization and higher throughput.
To enable batching, specify --enable_batching flag as true and also set the config file containing batching parameters using --batching_parameters_file flag.
docker run -p 8501:8501 --mount type=bind,source=C:\TF_serv\TF_model,target=/models/mnist -e MODEL_NAME=mnist -t tensorflow/serving --model_config_file_poll_wait_seconds=60 --model_config_file=/models/mnist/models.config --enable_batching=true --batching_parameters_file=/models/mnist/batch.config
The batch config file is a .protobuf file
max_batch_size { value: 128 }batch_timeout_micros { value: 0 }max_enqueued_batches { value: 1000000 }num_batch_threads { value: 8 }
max_batch_size: allows you to specify the maximum size of any batch. If you specify a batch larger than the max_batch_size, then you will get an error. This parameter governs the throughput/latency tradeoff and ensures the resource constraints are not exceeded.
batch_timeout_micros: This is the maximum amount of time for the server to retry the batched request. The parameter value is specified in microseconds.
num_batch_threads: defines the degree of parallelism by specifying the maximum number of batches to be processed concurrently.
max_enqueued_batches: It helps limit batch queue by turning away requests that would take a long time to be served and avoid building a large backlog of requests.
When I ran the below code with and without batching, batching gave me results almost 2 to 3 times faster.
import time#Build the batched data for making iferences for 100 imagesdata = json.dumps({"signature_name": "serving_default", "instances": test_images[:100].tolist()})st=time.perf_counter()headers = {"content-type": "application/json"}json_response = requests.post('http://localhost:8501/v1/models/mnist/labels/2:predict', data=data, headers=headers)predictions = json.loads(json_response.text)['predictions']end_t= time.perf_counter()print(end_t-st)
TensorFlow Serving has made the production deployment easier by providing easy ways to serve different models or different versions of the same model using Model Server configuration.
Batching allows you to batch multiple requests for the same client or different clients, thus optimizing the hardware accelerator resources and providing better throughput. | [
{
"code": null,
"e": 358,
"s": 172,
"text": "This article explains how to manage multiple models and multiple versions of the same model in TensorFlow Serving using configuration files along with a brief understanding of batching."
},
{
"code": null,
"e": 411,
"s": 358,
"text": "Deploying a TensorFlow Model to Production made Easy"
},
{
"code": null,
"e": 667,
"s": 411,
"text": "You have TensorFlow deep learning models with different architectures or have trained your models with different hyperparameters and would like to test them locally or in production. The easiest way is to serve the models using a Model Server Config file."
},
{
"code": null,
"e": 854,
"s": 667,
"text": "A Model Server Configuration file is a protocol buffer file(protobuf), which is a language-neutral, platform-neutral extensible yet simple and faster way to serialize the structure data."
},
{
"code": null,
"e": 891,
"s": 854,
"text": "How do I create a Model Config File?"
},
{
"code": null,
"e": 1001,
"s": 891,
"text": "Below is a sample Model Config File that will serve all the versions of the “MNIST” models available on disk."
},
{
"code": null,
"e": 1155,
"s": 1001,
"text": "model_config_list { config { name: 'mnist' base_path: '/models/mnist/' model_platform: 'tensorflow' model_version_policy: {all: {}} }}"
},
{
"code": null,
"e": 1236,
"s": 1155,
"text": "Each ModelConfig specifies one model to be served with the following parameters."
},
{
"code": null,
"e": 1265,
"s": 1236,
"text": "name - A servable model name"
},
{
"code": null,
"e": 1332,
"s": 1265,
"text": "base_path - Specify the path to look for versions of the servable."
},
{
"code": null,
"e": 1392,
"s": 1332,
"text": "model_platform - Platform in which the model was developed."
},
{
"code": null,
"e": 1636,
"s": 1392,
"text": "model_version_policy - Version policy for the model indicates which version of the model to load and serve the client. By default, the latest version of the model will be served and can be overridden by changing the model_version_policy field."
},
{
"code": null,
"e": 1671,
"s": 1636,
"text": "How to load the Model Config File?"
},
{
"code": null,
"e": 1747,
"s": 1671,
"text": "Read how to load the TensorFlow Serving Docker container on Windows 10 here"
},
{
"code": null,
"e": 1879,
"s": 1747,
"text": "docker run -p 8501:8501 --mount type=bind,source=C:\\TF_serv\\TF_model,target=/models/mnist -e MODEL_NAME=mnist -t tensorflow/serving"
},
{
"code": null,
"e": 1918,
"s": 1879,
"text": "List all the running Docker containers"
},
{
"code": null,
"e": 1940,
"s": 1918,
"text": "docker container list"
},
{
"code": null,
"e": 1943,
"s": 1940,
"text": "or"
},
{
"code": null,
"e": 1953,
"s": 1943,
"text": "docker ps"
},
{
"code": null,
"e": 2031,
"s": 1953,
"text": "Copy the models.config file from the source to the target of the Docker image"
},
{
"code": null,
"e": 2100,
"s": 2031,
"text": "docker cp \\TF_serv\\TF_model\\models.config ba978f5a9475:/models/mnist"
},
{
"code": null,
"e": 2185,
"s": 2100,
"text": "When copying the file to docker container, provide the container Id, as shown above."
},
{
"code": null,
"e": 2259,
"s": 2185,
"text": "Stop the Docker container using the Docker container name or container Id"
},
{
"code": null,
"e": 2284,
"s": 2259,
"text": "docker stop ba978f5a9475"
},
{
"code": null,
"e": 2340,
"s": 2284,
"text": "Finally, loading the Model Config file using the option"
},
{
"code": null,
"e": 2501,
"s": 2340,
"text": "--model_config_file_poll_wait_seconds flag instructs the server to check for a new config file at the path specified using --model_config_file every 60 seconds."
},
{
"code": null,
"e": 2722,
"s": 2501,
"text": "docker run -p 8501:8501 --mount type=bind,source=C:\\TF_serv\\TF_model,target=/models/mnist -e MODEL_NAME=mnist -t tensorflow/serving --model_config_file_poll_wait_seconds=60 --model_config_file=/models/mnist/models.config"
},
{
"code": null,
"e": 2834,
"s": 2722,
"text": "How to make an inference using the model served using models.config file using a specific version of the model?"
},
{
"code": null,
"e": 2879,
"s": 2834,
"text": "Using REST API to make the inference request"
},
{
"code": null,
"e": 2997,
"s": 2879,
"text": "json_response = requests.post('http://localhost:8501/v1/models/mnist/versions/5:predict', data=data, headers=headers)"
},
{
"code": null,
"e": 3103,
"s": 2997,
"text": "Since the models.config file specified above will load all versions on the disk; I have loaded version 5."
},
{
"code": null,
"e": 3194,
"s": 3103,
"text": "A generic way to call a specific version of the model to make an inference is shown below."
},
{
"code": null,
"e": 3244,
"s": 3194,
"text": "/v1/models/<model name>/versions/<version number>"
},
{
"code": null,
"e": 3331,
"s": 3244,
"text": "How do I override and specify a specific version of the model to be loaded and served?"
},
{
"code": null,
"e": 3426,
"s": 3331,
"text": "You will need to use the specified tag with the version number within the model_version_policy"
},
{
"code": null,
"e": 3692,
"s": 3426,
"text": "model_config_list { config { name: 'mnist' base_path: '/models/mnist/' model_platform: 'tensorflow' model_version_policy{ specific{ versions:2 } } }}"
},
{
"code": null,
"e": 3805,
"s": 3692,
"text": "with the above change models.config file, the client can now call the model’s predict method only for version 2."
},
{
"code": null,
"e": 3870,
"s": 3805,
"text": "Can I server multiple versions of the same model simultaneously?"
},
{
"code": null,
"e": 4032,
"s": 3870,
"text": "You can also serve multiple versions of the same model simultaneously. In the example below, we are serving the MNIST model with versions 2 and 3 simultaneously."
},
{
"code": null,
"e": 4333,
"s": 4032,
"text": "model_config_list { config { name: 'mnist' base_path: '/models/mnist/' model_platform: 'tensorflow' model_version_policy{ specific{ versions:2 versions:3 } } }}"
},
{
"code": null,
"e": 4559,
"s": 4333,
"text": "This is helpful when you have a newer version of the model and would like to divert a few users to a newer version and keep most clients on the stable older version of the model. This allows you to accomplish the A/B testing."
},
{
"code": null,
"e": 4638,
"s": 4559,
"text": "Can I server multiple models like a custom model and a transfer learned model?"
},
{
"code": null,
"e": 4710,
"s": 4638,
"text": "To server multiple models, update the models.config file as shown below"
},
{
"code": null,
"e": 5125,
"s": 4710,
"text": "model_config_list { config{ name: 'mnist' base_path: '/models/mnist/' model_platform: 'tensorflow' model_version_policy{ specific{ versions:2 versions:3 } } } config{ name: 'Inception_1' base_path: '/models/inception_1/' model_platform: 'tensorflow' }}"
},
{
"code": null,
"e": 5187,
"s": 5125,
"text": "Will TensorFlow Serving allow for batching multiple requests?"
},
{
"code": null,
"e": 5246,
"s": 5187,
"text": "TensorFlow Serving allows two different forms of batching."
},
{
"code": null,
"e": 5422,
"s": 5246,
"text": "Batch individual model inference requests, where TensorFlow serving waits for a predetermined time and then perform inferences on all requests that arrived in that time period"
},
{
"code": null,
"e": 5487,
"s": 5422,
"text": "A single client can send batched requests to TensorFlow Serving."
},
{
"code": null,
"e": 5556,
"s": 5487,
"text": "Batching requires all requests to use the same version of the model."
},
{
"code": null,
"e": 5627,
"s": 5556,
"text": "Batching allows for higher resource utilization and higher throughput."
},
{
"code": null,
"e": 5785,
"s": 5627,
"text": "To enable batching, specify --enable_batching flag as true and also set the config file containing batching parameters using --batching_parameters_file flag."
},
{
"code": null,
"e": 6084,
"s": 5785,
"text": "docker run -p 8501:8501 --mount type=bind,source=C:\\TF_serv\\TF_model,target=/models/mnist -e MODEL_NAME=mnist -t tensorflow/serving --model_config_file_poll_wait_seconds=60 --model_config_file=/models/mnist/models.config --enable_batching=true --batching_parameters_file=/models/mnist/batch.config"
},
{
"code": null,
"e": 6126,
"s": 6084,
"text": "The batch config file is a .protobuf file"
},
{
"code": null,
"e": 6258,
"s": 6126,
"text": "max_batch_size { value: 128 }batch_timeout_micros { value: 0 }max_enqueued_batches { value: 1000000 }num_batch_threads { value: 8 }"
},
{
"code": null,
"e": 6520,
"s": 6258,
"text": "max_batch_size: allows you to specify the maximum size of any batch. If you specify a batch larger than the max_batch_size, then you will get an error. This parameter governs the throughput/latency tradeoff and ensures the resource constraints are not exceeded."
},
{
"code": null,
"e": 6672,
"s": 6520,
"text": "batch_timeout_micros: This is the maximum amount of time for the server to retry the batched request. The parameter value is specified in microseconds."
},
{
"code": null,
"e": 6799,
"s": 6672,
"text": "num_batch_threads: defines the degree of parallelism by specifying the maximum number of batches to be processed concurrently."
},
{
"code": null,
"e": 6962,
"s": 6799,
"text": "max_enqueued_batches: It helps limit batch queue by turning away requests that would take a long time to be served and avoid building a large backlog of requests."
},
{
"code": null,
"e": 7068,
"s": 6962,
"text": "When I ran the below code with and without batching, batching gave me results almost 2 to 3 times faster."
},
{
"code": null,
"e": 7519,
"s": 7068,
"text": "import time#Build the batched data for making iferences for 100 imagesdata = json.dumps({\"signature_name\": \"serving_default\", \"instances\": test_images[:100].tolist()})st=time.perf_counter()headers = {\"content-type\": \"application/json\"}json_response = requests.post('http://localhost:8501/v1/models/mnist/labels/2:predict', data=data, headers=headers)predictions = json.loads(json_response.text)['predictions']end_t= time.perf_counter()print(end_t-st)"
},
{
"code": null,
"e": 7703,
"s": 7519,
"text": "TensorFlow Serving has made the production deployment easier by providing easy ways to serve different models or different versions of the same model using Model Server configuration."
}
]
|
Check if the String has only unicode digits or space in Java | In order to check if a String has only unicode digits or space in Java, we use the isDigit() method and the charAt() method with decision making statements.
The isDigit(int codePoint) method determines whether the specific character (Unicode codePoint) is a digit. It returns a boolean value, either true or false.
Declaration - The java.lang.Character.isDigit() method is declared as follows −
public static boolean isDigit(int codePoint)
The charAt() method returns a character value at a given index. It belongs to the String class in Java. The index must be between 0 to length()-1.
Declaration − The java.lang.String.charAt() method is declared as follows −
public char charAt(int index)
Let us see a program to check whether a String has only unicode digits or space in Java.
Live Demo
public class Example {
boolean check(String s) {
if (s == null) // checks if the String is null {
return false;
}
int len = s.length();
for (int i = 0; i < len; i++) {
// checks whether the character is not a digit and not a space
if ((Character.isDigit(s.charAt(i)) == false) && (s.charAt(i) != ' ')) {
return false; // if it is not any of them then it returns false
}
}
return true;
}
public static void main(String [] args) {
Example e = new Example();
String s = "0090"; // has only digits so it will return true
String s1 = "y o y"; // has spaces but also has letters so it will return false
System.out.println("String "+s+" has only unicode digits or spaces: "+e.check(s));
System.out.println("String "+s1+" has only unicode digits or spaces: "+e.check(s1));
}
}
String 0090 has only unicode digits or spaces: true
String y o y has only unicode digits or spaces: false | [
{
"code": null,
"e": 1219,
"s": 1062,
"text": "In order to check if a String has only unicode digits or space in Java, we use the isDigit() method and the charAt() method with decision making statements."
},
{
"code": null,
"e": 1377,
"s": 1219,
"text": "The isDigit(int codePoint) method determines whether the specific character (Unicode codePoint) is a digit. It returns a boolean value, either true or false."
},
{
"code": null,
"e": 1457,
"s": 1377,
"text": "Declaration - The java.lang.Character.isDigit() method is declared as follows −"
},
{
"code": null,
"e": 1502,
"s": 1457,
"text": "public static boolean isDigit(int codePoint)"
},
{
"code": null,
"e": 1649,
"s": 1502,
"text": "The charAt() method returns a character value at a given index. It belongs to the String class in Java. The index must be between 0 to length()-1."
},
{
"code": null,
"e": 1725,
"s": 1649,
"text": "Declaration − The java.lang.String.charAt() method is declared as follows −"
},
{
"code": null,
"e": 1755,
"s": 1725,
"text": "public char charAt(int index)"
},
{
"code": null,
"e": 1844,
"s": 1755,
"text": "Let us see a program to check whether a String has only unicode digits or space in Java."
},
{
"code": null,
"e": 1855,
"s": 1844,
"text": " Live Demo"
},
{
"code": null,
"e": 2746,
"s": 1855,
"text": "public class Example {\n boolean check(String s) {\n if (s == null) // checks if the String is null {\n return false;\n }\n int len = s.length();\n for (int i = 0; i < len; i++) {\n // checks whether the character is not a digit and not a space\n if ((Character.isDigit(s.charAt(i)) == false) && (s.charAt(i) != ' ')) {\n return false; // if it is not any of them then it returns false\n }\n }\n return true;\n }\n public static void main(String [] args) {\n Example e = new Example();\n String s = \"0090\"; // has only digits so it will return true\n String s1 = \"y o y\"; // has spaces but also has letters so it will return false\n System.out.println(\"String \"+s+\" has only unicode digits or spaces: \"+e.check(s));\n System.out.println(\"String \"+s1+\" has only unicode digits or spaces: \"+e.check(s1));\n }\n}"
},
{
"code": null,
"e": 2852,
"s": 2746,
"text": "String 0090 has only unicode digits or spaces: true\nString y o y has only unicode digits or spaces: false"
}
]
|
Data Engineering with Python, Django, and PostgreSQL | by Sammy Lee | Towards Data Science | Today’s post will deal with what may be one of the hardest aspects of data science which doesn’t involve analysis, but simply trying to make the backend of data science work. By backend I mean the database systems most data scientists will be working with on the job.
I will go over the following:
Build an absolute barebones Django app with a Relational Database Management System (RDBMS)
Illustrate the use of a PostgresSQL database attached to the Django app
How to move data in and out between different formats and platforms
While following this article doesn’t require any knowledge of Django, I think it’s important to appreciate the fact that a lot of data collection occurs through web apps.
For data scientists who are unfamiliar with Django, think of it as a framework for building web applications while adhering to the philosophy of “inversion of control”. This means Django takes care of the skeleton of the web app, and you’re responsible for fleshing out the actual content on top of the skeleton.
For readers who don’t like Django you can skip to the section titled: “The Payoff: Django’s Object Relational Mapper” towards the end of this post.
The app that I’m interested in creating is going to be called “DoubleBagger”, an investment blog where people self-publish their buy/sell opinions on public companies like Apple (ticker: AAPL) or Microsoft (ticker: MSFT).
And instead of firing up a Jupyter Notebook like my previous articles this time we’ll mainly be working with the command line + a text editor like Sublime Text.
And because this is aimed at data scientists, we’ll be using a conda environment:
# I like to do things on my desktop# From the terminal:$ cd desktop && mkdir doublebagger && cd doublebagger$ conda create -n doublebagger$ conda activate doublebagger# You should now have the (doublebagger) conda environment activated
And now we install our two main packages: Django and psycopg2 for connecting to a PostgreSQL database. Django already ships with SQLite which may actually be suitable for many organizations and for hobbyists, but we’re going to use Postgres instead. Furthermore, we’ll be using an older version of Django (current version is Django 2.1).
$ (doublebagger) conda install Django==1.9.6 psycopg2
After verifying you have these packages along with their depencies, create a source directory where we put our entire source code having to do with “Doublebagger.”
$ (doublebagger) mkdir src && cd src
We start every Django project in pretty much the same way with the same command:
# Inside of src:# don't forget the space and period at the end$ (doublebagger) django-admin startproject doublebagger_blog .
The django-admin startproject command is what creates the skeleton or framework for our project and now if you check out what it’s inside of the src folder you should see:
doublebagger_blog: contains the project configurations our project including the settings.py file.manage.py: utility functions
doublebagger_blog: contains the project configurations our project including the settings.py file.
manage.py: utility functions
Now we can open up our DoubleBagger project inside of Sublime Text or any other editor of your choice. You should see the exact same directory structure:
Assuming you have a postgres database already installed on your machine, we actually need to create a postgres database for our django app:
# from the command line:$ psql -d postgrespostgres=# CREATE DATABASE doublebagger;# That's it!# quit by:postgres=# \q
*If you don’t have postgreSQL you can follow these instructions.
Then inside of settings.py (using Sublime Text), we change the default configuration to account for the database we just created. Change this:
# settings.pyDATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }}
To this:
# Your 'User' is probably different depending on how you set up # postgres. In many cases, it's just 'postgres'.# Also depends if you set up a password with you postgres.DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'doublebagger', 'USER': 'WhoeverOwnsTheDatabase', 'PASSWORD': '', 'HOST': '127.0.0.1', 'PORT': '5432', }}
*Make sure to save your changes within the text-editor
Now if you go back to the command line, we can connect the app with the postgres database like so:
# Still inside of your src where manage.py lives:$ (doublebagger) python manage.py migrate
If everything went okay, you should see something like this:
Now from the same command line:
$ (doublebagger) python manage.py runserver
And point your browser to:
127.0.0.1:8000
You should see something like this:
This is essentially the homepage of your hypothetical web app displayed from Django’s local development sever which is meant to emulate a real web server. You can quit the development server with <control-C>.
This is pretty much it for the app — not even bare bones, not even hello world.
Because Django Models provides its users an object relational mapper (ORM) which allows us to manipulate model objects using python while connected to a postgresSQL database. It’s just one more layer of sophistication and awareness of the absolute zoo that makes up the pythonic data science ecosystem.
At this point we need to think about the organization of our data.
Our web app will primarily have two main components or Model Classes:
Post: Blog post about whether or not to invest in a particular company
Company: Information about the companies the blog posts mention
Post will contain information about:
title of the post
slug: a unique identifier for the blog post based on title)
text: the actual blog post text
pub_date: when the post was published
Company will contain information about:
name of the company
slug: a unique identifier for the company
description: what the company does
PE Ratio: An indication of company’s valuation relative to market price
Before we translate this to Django Models code, we need to create a Django app first.
# We're going to call our app 'post'# Inside of src from terminal:$ (doublebagger) python manage.py startapp post
You should now see the post app show up from your text editor:
After that we have to append our ‘post’ app under INSTALLED_APPS in settings.py:
# settings.pyINSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'post', ]# Don't forget to save changes
Now we can code up the organization for our data by going to post/models.py:
# post/models.pyfrom __future__ import unicode_literalsfrom django.db import models# Create your models here.class Post(models.Model): title = models.CharField(max_length=100) slug = models.SlugField() text = modelsle.TextField() pub_date = models.DateField()class Company(models.Model): name = models.CharField(max_length=100) slug = models.SlugField() description = models.TextField() pe_ratio = models.DecimalField(max_digits=7, decimal_places=2)
One of the most important aspects of the Models that we need to consider at this point is how these two things are related to each other. If we look at what we did above, from the point of SQL, Post is a TABLE and Company is its own TABLE, with the fields underneath like title, slug, and pub_date representing columns of the two tables.
With SQL we need to consider if the relationship between our two models is a:
One-to-Many or Many-to-One
Many-to-Many
If you consider it, what we have here is a Many-to-One relationship between Post and Company:
“One blog post can only be an investment thesis about one company, but one company can have many blog posts written about it.”
As a result our Post model will have a Foreign Key to Company.
The beauty of Django is that it takes care of all the hard work for us that would normally go with creating database schemas from scratch — no need to explicitly create primary keys, no need for indexes or junction tables for many-to-many relationships.
We can add our Foreign Key like so:
# post/models.pyclass Post(models.Model): title = models.CharField(max_length=100) slug = models.SlugField() text = modelsle.TextField() pub_date = models.DateField() company = models.ForeignKey('Company') # Here
Adding some extra parameters and string methods that allow our Model objects to be referenced by string names, here is our final updated post/models.py:
# post/models.pyfrom __future__ import unicode_literalsfrom django.db import models# Create your models here.class Post(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(max_length=50, unique_for_month='pub_date') text = models.TextField() pub_date = models.DateField('date_published', auto_now_add=True) company = models.ForeignKey('Company')def __str__(self): return "{} on {}".format( self.title, self.pub_date.strftime('%Y-%m-%m'))class Meta: verbose_name = 'investment thesis' ordering = ['-pub_date', 'title'] get_latest_by = 'pub_date'class Company(models.Model): name = models.CharField(max_length=100, db_index=True) slug = models.SlugField(max_length=50, unique=True) description = models.TextField() pe_ratio = models.DecimalField(max_digits=7, decimal_places=2)def __str__(self): return self.nameclass Meta: ordering = ['name']# Don't forget to save your changes
Now comes the magical part where Django creates a postgreSQL database for us.
Back on the command line:
$ (doublebagger) python manage.py makemigrations# Then $ (doublebagger) python manage.py migrate# That's it!
You should see something like this:
Now we can interact with our PostgreSQL database as data scientists by using nothing but Python!
From the command line:
$ (doublebagger) python manage.py shell
You should see something that reminds you of the Python interpreter, except this one allows you to play with Django’s database:
>>> from datetime import date>>> from post.models import Post, Company
Let’s create a Company object:
>>> Company.objects.create(name='Apple', slug='Apple-incorporated-nasdaq', description='One of the greatest companies in the world created by the amazing Steve Jobs.', pe_ratio=14.43)
You should see something like this after:
<Company: Apple>
No need to:
INSERT INTO company(name, slug, description, pe_ratio)VALUES('Apple', 'Apple-incorporated-nasdaq', description='...', pe_ration=14.43);
Some more companies:
>>> Company.objects.create(name='Amazon', slug='amzn-nasdaq', description='AWS baby!', pe_ratio=81.48)>>> Company.objects.create(name='Microsoft', slug='msft-nasdaq', description='I love GitHub!', pe_ratio=26.02)>>> Company.objects.create(name='MongoDB', slug='mdb-nasdaq', description='JSON in the cloud', pe_ratio=100)>>> Company.objects.all()# Output:[<Company: Amazon>, <Company: Apple>, <Company: Microsoft>, <Company: MongoDB>]
We can also do some cool queries:
>>> Company.objects.get(slug__contains='mdb')# Output:<Company: MongoDB>
Who likes tuples:
>>> Company.objects.values_list()# Output:[(3, u'Amazon', u'amzn-nasdaq', u'AWS baby!', Decimal('81.48')), (1, u'Apple', u'Apple-incorporated-nasdaq', u'One of the greatest companies in the world created by the amazing Steve Jobs, not so currently under Tim Cook.', Decimal('14.43')), (2, u'Microsoft', u'msft-nasdaq', u'I love GitHub!', Decimal('26.02')), (4, u'MongoDB', u'mdb-nasdaq', u'JSON in the cloud', Decimal('100.00'))]
We can also create a Post object:
>>> Post.objects.create(title='I heart Apple', slug='i-heart-apple', text='I heart Apple', company_id=1)>>> Post.objects.create(title='Buy more Microsoft', slug='buy-more-microsoft', text="Nadella leads the way", company_id=2)>>> Post.objects.create(title='Buy more Amazon', slug='buy-more-amazon', text="Jeff Bezos acquires Mars from Elon Musk", company_id=3)>>> Post.objects.create(title='Time to sell MongoDB', slug='time-to-sell-mongdb', text="MongoDB seems a little overvalued", company_id=4)
We can also verify that these objects actually exist in our postgreSQL database:
$ psql -d postgrespostgres=# \c doublebaggerdoublebagger=# \dtdoublebagger=# SELECT * FROM post_company;
You should see something like this:
And an SQL join:
doublebagger=# SELECT * FROM post_companydoublebagger=# JOIN post_post ONdoublebagger=# post_company.id = post_post.company_id;
Using sqlalchemy we can directly get access to postgreSQL objects straight from pandas:
If you fire up a Jupyter Notebook:
import pandas as pdfrom sqlalchemy import create_engineengine = create_engine('postgresql://sammylee@localhost:5432/doublebagger')posts = pd.read_sql('select * from post_post', engine)companies = pd.read_sql('select * from post_company', engine)posts_companies = pd.merge(companies, posts, left_on='id', right_on='company_id')posts_companies
And now we can use the full might and magic of pandas to do whatever we want as data scientists.
While knowledge of a web development framework isn’t necessary for data scientists, I think it’s really cool to take a step back and have a look at the Amazonian Forest that is data science by going from Django to postgreSQL to pandas.
Django has a “batteries included” philosophy, and provides an administration interface that basically serves as a GUI to your postgreSQL database. All we have to do is add some lines to post/admin.py
# post/admin.pyfrom django.contrib import adminfrom django.db import models# Register your models here.from .models import Post, Companyclass MyCompanyAdmin(admin.ModelAdmin): model = Company list_display = ('name', 'slug', 'description', 'pe_ratio',)admin.site.register(Company, MyCompanyAdmin)
And create a superuser on the command line:
$ (doublebagger) python manage.py createsuperuser# Then create your credentials# start up your local development server and head to your local host# and append "/admin" to it
Code for DoubleBagger lives here. | [
{
"code": null,
"e": 440,
"s": 172,
"text": "Today’s post will deal with what may be one of the hardest aspects of data science which doesn’t involve analysis, but simply trying to make the backend of data science work. By backend I mean the database systems most data scientists will be working with on the job."
},
{
"code": null,
"e": 470,
"s": 440,
"text": "I will go over the following:"
},
{
"code": null,
"e": 562,
"s": 470,
"text": "Build an absolute barebones Django app with a Relational Database Management System (RDBMS)"
},
{
"code": null,
"e": 634,
"s": 562,
"text": "Illustrate the use of a PostgresSQL database attached to the Django app"
},
{
"code": null,
"e": 702,
"s": 634,
"text": "How to move data in and out between different formats and platforms"
},
{
"code": null,
"e": 873,
"s": 702,
"text": "While following this article doesn’t require any knowledge of Django, I think it’s important to appreciate the fact that a lot of data collection occurs through web apps."
},
{
"code": null,
"e": 1186,
"s": 873,
"text": "For data scientists who are unfamiliar with Django, think of it as a framework for building web applications while adhering to the philosophy of “inversion of control”. This means Django takes care of the skeleton of the web app, and you’re responsible for fleshing out the actual content on top of the skeleton."
},
{
"code": null,
"e": 1334,
"s": 1186,
"text": "For readers who don’t like Django you can skip to the section titled: “The Payoff: Django’s Object Relational Mapper” towards the end of this post."
},
{
"code": null,
"e": 1556,
"s": 1334,
"text": "The app that I’m interested in creating is going to be called “DoubleBagger”, an investment blog where people self-publish their buy/sell opinions on public companies like Apple (ticker: AAPL) or Microsoft (ticker: MSFT)."
},
{
"code": null,
"e": 1717,
"s": 1556,
"text": "And instead of firing up a Jupyter Notebook like my previous articles this time we’ll mainly be working with the command line + a text editor like Sublime Text."
},
{
"code": null,
"e": 1799,
"s": 1717,
"text": "And because this is aimed at data scientists, we’ll be using a conda environment:"
},
{
"code": null,
"e": 2035,
"s": 1799,
"text": "# I like to do things on my desktop# From the terminal:$ cd desktop && mkdir doublebagger && cd doublebagger$ conda create -n doublebagger$ conda activate doublebagger# You should now have the (doublebagger) conda environment activated"
},
{
"code": null,
"e": 2373,
"s": 2035,
"text": "And now we install our two main packages: Django and psycopg2 for connecting to a PostgreSQL database. Django already ships with SQLite which may actually be suitable for many organizations and for hobbyists, but we’re going to use Postgres instead. Furthermore, we’ll be using an older version of Django (current version is Django 2.1)."
},
{
"code": null,
"e": 2427,
"s": 2373,
"text": "$ (doublebagger) conda install Django==1.9.6 psycopg2"
},
{
"code": null,
"e": 2591,
"s": 2427,
"text": "After verifying you have these packages along with their depencies, create a source directory where we put our entire source code having to do with “Doublebagger.”"
},
{
"code": null,
"e": 2628,
"s": 2591,
"text": "$ (doublebagger) mkdir src && cd src"
},
{
"code": null,
"e": 2709,
"s": 2628,
"text": "We start every Django project in pretty much the same way with the same command:"
},
{
"code": null,
"e": 2835,
"s": 2709,
"text": "# Inside of src:# don't forget the space and period at the end$ (doublebagger) django-admin startproject doublebagger_blog . "
},
{
"code": null,
"e": 3007,
"s": 2835,
"text": "The django-admin startproject command is what creates the skeleton or framework for our project and now if you check out what it’s inside of the src folder you should see:"
},
{
"code": null,
"e": 3134,
"s": 3007,
"text": "doublebagger_blog: contains the project configurations our project including the settings.py file.manage.py: utility functions"
},
{
"code": null,
"e": 3233,
"s": 3134,
"text": "doublebagger_blog: contains the project configurations our project including the settings.py file."
},
{
"code": null,
"e": 3262,
"s": 3233,
"text": "manage.py: utility functions"
},
{
"code": null,
"e": 3416,
"s": 3262,
"text": "Now we can open up our DoubleBagger project inside of Sublime Text or any other editor of your choice. You should see the exact same directory structure:"
},
{
"code": null,
"e": 3556,
"s": 3416,
"text": "Assuming you have a postgres database already installed on your machine, we actually need to create a postgres database for our django app:"
},
{
"code": null,
"e": 3674,
"s": 3556,
"text": "# from the command line:$ psql -d postgrespostgres=# CREATE DATABASE doublebagger;# That's it!# quit by:postgres=# \\q"
},
{
"code": null,
"e": 3739,
"s": 3674,
"text": "*If you don’t have postgreSQL you can follow these instructions."
},
{
"code": null,
"e": 3882,
"s": 3739,
"text": "Then inside of settings.py (using Sublime Text), we change the default configuration to account for the database we just created. Change this:"
},
{
"code": null,
"e": 4031,
"s": 3882,
"text": "# settings.pyDATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }}"
},
{
"code": null,
"e": 4040,
"s": 4031,
"text": "To this:"
},
{
"code": null,
"e": 4452,
"s": 4040,
"text": "# Your 'User' is probably different depending on how you set up # postgres. In many cases, it's just 'postgres'.# Also depends if you set up a password with you postgres.DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'doublebagger', 'USER': 'WhoeverOwnsTheDatabase', 'PASSWORD': '', 'HOST': '127.0.0.1', 'PORT': '5432', }}"
},
{
"code": null,
"e": 4507,
"s": 4452,
"text": "*Make sure to save your changes within the text-editor"
},
{
"code": null,
"e": 4606,
"s": 4507,
"text": "Now if you go back to the command line, we can connect the app with the postgres database like so:"
},
{
"code": null,
"e": 4697,
"s": 4606,
"text": "# Still inside of your src where manage.py lives:$ (doublebagger) python manage.py migrate"
},
{
"code": null,
"e": 4758,
"s": 4697,
"text": "If everything went okay, you should see something like this:"
},
{
"code": null,
"e": 4790,
"s": 4758,
"text": "Now from the same command line:"
},
{
"code": null,
"e": 4834,
"s": 4790,
"text": "$ (doublebagger) python manage.py runserver"
},
{
"code": null,
"e": 4861,
"s": 4834,
"text": "And point your browser to:"
},
{
"code": null,
"e": 4876,
"s": 4861,
"text": "127.0.0.1:8000"
},
{
"code": null,
"e": 4912,
"s": 4876,
"text": "You should see something like this:"
},
{
"code": null,
"e": 5121,
"s": 4912,
"text": "This is essentially the homepage of your hypothetical web app displayed from Django’s local development sever which is meant to emulate a real web server. You can quit the development server with <control-C>."
},
{
"code": null,
"e": 5201,
"s": 5121,
"text": "This is pretty much it for the app — not even bare bones, not even hello world."
},
{
"code": null,
"e": 5504,
"s": 5201,
"text": "Because Django Models provides its users an object relational mapper (ORM) which allows us to manipulate model objects using python while connected to a postgresSQL database. It’s just one more layer of sophistication and awareness of the absolute zoo that makes up the pythonic data science ecosystem."
},
{
"code": null,
"e": 5571,
"s": 5504,
"text": "At this point we need to think about the organization of our data."
},
{
"code": null,
"e": 5641,
"s": 5571,
"text": "Our web app will primarily have two main components or Model Classes:"
},
{
"code": null,
"e": 5712,
"s": 5641,
"text": "Post: Blog post about whether or not to invest in a particular company"
},
{
"code": null,
"e": 5776,
"s": 5712,
"text": "Company: Information about the companies the blog posts mention"
},
{
"code": null,
"e": 5813,
"s": 5776,
"text": "Post will contain information about:"
},
{
"code": null,
"e": 5831,
"s": 5813,
"text": "title of the post"
},
{
"code": null,
"e": 5891,
"s": 5831,
"text": "slug: a unique identifier for the blog post based on title)"
},
{
"code": null,
"e": 5923,
"s": 5891,
"text": "text: the actual blog post text"
},
{
"code": null,
"e": 5961,
"s": 5923,
"text": "pub_date: when the post was published"
},
{
"code": null,
"e": 6001,
"s": 5961,
"text": "Company will contain information about:"
},
{
"code": null,
"e": 6021,
"s": 6001,
"text": "name of the company"
},
{
"code": null,
"e": 6063,
"s": 6021,
"text": "slug: a unique identifier for the company"
},
{
"code": null,
"e": 6098,
"s": 6063,
"text": "description: what the company does"
},
{
"code": null,
"e": 6170,
"s": 6098,
"text": "PE Ratio: An indication of company’s valuation relative to market price"
},
{
"code": null,
"e": 6256,
"s": 6170,
"text": "Before we translate this to Django Models code, we need to create a Django app first."
},
{
"code": null,
"e": 6370,
"s": 6256,
"text": "# We're going to call our app 'post'# Inside of src from terminal:$ (doublebagger) python manage.py startapp post"
},
{
"code": null,
"e": 6433,
"s": 6370,
"text": "You should now see the post app show up from your text editor:"
},
{
"code": null,
"e": 6514,
"s": 6433,
"text": "After that we have to append our ‘post’ app under INSTALLED_APPS in settings.py:"
},
{
"code": null,
"e": 6769,
"s": 6514,
"text": "# settings.pyINSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'post', ]# Don't forget to save changes"
},
{
"code": null,
"e": 6846,
"s": 6769,
"text": "Now we can code up the organization for our data by going to post/models.py:"
},
{
"code": null,
"e": 7298,
"s": 6846,
"text": "# post/models.pyfrom __future__ import unicode_literalsfrom django.db import models# Create your models here.class Post(models.Model): title = models.CharField(max_length=100) slug = models.SlugField() text = modelsle.TextField() pub_date = models.DateField()class Company(models.Model): name = models.CharField(max_length=100) slug = models.SlugField() description = models.TextField() pe_ratio = models.DecimalField(max_digits=7, decimal_places=2)"
},
{
"code": null,
"e": 7636,
"s": 7298,
"text": "One of the most important aspects of the Models that we need to consider at this point is how these two things are related to each other. If we look at what we did above, from the point of SQL, Post is a TABLE and Company is its own TABLE, with the fields underneath like title, slug, and pub_date representing columns of the two tables."
},
{
"code": null,
"e": 7714,
"s": 7636,
"text": "With SQL we need to consider if the relationship between our two models is a:"
},
{
"code": null,
"e": 7741,
"s": 7714,
"text": "One-to-Many or Many-to-One"
},
{
"code": null,
"e": 7754,
"s": 7741,
"text": "Many-to-Many"
},
{
"code": null,
"e": 7848,
"s": 7754,
"text": "If you consider it, what we have here is a Many-to-One relationship between Post and Company:"
},
{
"code": null,
"e": 7975,
"s": 7848,
"text": "“One blog post can only be an investment thesis about one company, but one company can have many blog posts written about it.”"
},
{
"code": null,
"e": 8038,
"s": 7975,
"text": "As a result our Post model will have a Foreign Key to Company."
},
{
"code": null,
"e": 8292,
"s": 8038,
"text": "The beauty of Django is that it takes care of all the hard work for us that would normally go with creating database schemas from scratch — no need to explicitly create primary keys, no need for indexes or junction tables for many-to-many relationships."
},
{
"code": null,
"e": 8328,
"s": 8292,
"text": "We can add our Foreign Key like so:"
},
{
"code": null,
"e": 8543,
"s": 8328,
"text": "# post/models.pyclass Post(models.Model): title = models.CharField(max_length=100) slug = models.SlugField() text = modelsle.TextField() pub_date = models.DateField() company = models.ForeignKey('Company') # Here"
},
{
"code": null,
"e": 8696,
"s": 8543,
"text": "Adding some extra parameters and string methods that allow our Model objects to be referenced by string names, here is our final updated post/models.py:"
},
{
"code": null,
"e": 9613,
"s": 8696,
"text": "# post/models.pyfrom __future__ import unicode_literalsfrom django.db import models# Create your models here.class Post(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(max_length=50, unique_for_month='pub_date') text = models.TextField() pub_date = models.DateField('date_published', auto_now_add=True) company = models.ForeignKey('Company')def __str__(self): return \"{} on {}\".format( self.title, self.pub_date.strftime('%Y-%m-%m'))class Meta: verbose_name = 'investment thesis' ordering = ['-pub_date', 'title'] get_latest_by = 'pub_date'class Company(models.Model): name = models.CharField(max_length=100, db_index=True) slug = models.SlugField(max_length=50, unique=True) description = models.TextField() pe_ratio = models.DecimalField(max_digits=7, decimal_places=2)def __str__(self): return self.nameclass Meta: ordering = ['name']# Don't forget to save your changes"
},
{
"code": null,
"e": 9691,
"s": 9613,
"text": "Now comes the magical part where Django creates a postgreSQL database for us."
},
{
"code": null,
"e": 9717,
"s": 9691,
"text": "Back on the command line:"
},
{
"code": null,
"e": 9826,
"s": 9717,
"text": "$ (doublebagger) python manage.py makemigrations# Then $ (doublebagger) python manage.py migrate# That's it!"
},
{
"code": null,
"e": 9862,
"s": 9826,
"text": "You should see something like this:"
},
{
"code": null,
"e": 9959,
"s": 9862,
"text": "Now we can interact with our PostgreSQL database as data scientists by using nothing but Python!"
},
{
"code": null,
"e": 9982,
"s": 9959,
"text": "From the command line:"
},
{
"code": null,
"e": 10022,
"s": 9982,
"text": "$ (doublebagger) python manage.py shell"
},
{
"code": null,
"e": 10150,
"s": 10022,
"text": "You should see something that reminds you of the Python interpreter, except this one allows you to play with Django’s database:"
},
{
"code": null,
"e": 10221,
"s": 10150,
"text": ">>> from datetime import date>>> from post.models import Post, Company"
},
{
"code": null,
"e": 10252,
"s": 10221,
"text": "Let’s create a Company object:"
},
{
"code": null,
"e": 10436,
"s": 10252,
"text": ">>> Company.objects.create(name='Apple', slug='Apple-incorporated-nasdaq', description='One of the greatest companies in the world created by the amazing Steve Jobs.', pe_ratio=14.43)"
},
{
"code": null,
"e": 10478,
"s": 10436,
"text": "You should see something like this after:"
},
{
"code": null,
"e": 10495,
"s": 10478,
"text": "<Company: Apple>"
},
{
"code": null,
"e": 10507,
"s": 10495,
"text": "No need to:"
},
{
"code": null,
"e": 10643,
"s": 10507,
"text": "INSERT INTO company(name, slug, description, pe_ratio)VALUES('Apple', 'Apple-incorporated-nasdaq', description='...', pe_ration=14.43);"
},
{
"code": null,
"e": 10664,
"s": 10643,
"text": "Some more companies:"
},
{
"code": null,
"e": 11098,
"s": 10664,
"text": ">>> Company.objects.create(name='Amazon', slug='amzn-nasdaq', description='AWS baby!', pe_ratio=81.48)>>> Company.objects.create(name='Microsoft', slug='msft-nasdaq', description='I love GitHub!', pe_ratio=26.02)>>> Company.objects.create(name='MongoDB', slug='mdb-nasdaq', description='JSON in the cloud', pe_ratio=100)>>> Company.objects.all()# Output:[<Company: Amazon>, <Company: Apple>, <Company: Microsoft>, <Company: MongoDB>]"
},
{
"code": null,
"e": 11132,
"s": 11098,
"text": "We can also do some cool queries:"
},
{
"code": null,
"e": 11205,
"s": 11132,
"text": ">>> Company.objects.get(slug__contains='mdb')# Output:<Company: MongoDB>"
},
{
"code": null,
"e": 11223,
"s": 11205,
"text": "Who likes tuples:"
},
{
"code": null,
"e": 11653,
"s": 11223,
"text": ">>> Company.objects.values_list()# Output:[(3, u'Amazon', u'amzn-nasdaq', u'AWS baby!', Decimal('81.48')), (1, u'Apple', u'Apple-incorporated-nasdaq', u'One of the greatest companies in the world created by the amazing Steve Jobs, not so currently under Tim Cook.', Decimal('14.43')), (2, u'Microsoft', u'msft-nasdaq', u'I love GitHub!', Decimal('26.02')), (4, u'MongoDB', u'mdb-nasdaq', u'JSON in the cloud', Decimal('100.00'))]"
},
{
"code": null,
"e": 11687,
"s": 11653,
"text": "We can also create a Post object:"
},
{
"code": null,
"e": 12185,
"s": 11687,
"text": ">>> Post.objects.create(title='I heart Apple', slug='i-heart-apple', text='I heart Apple', company_id=1)>>> Post.objects.create(title='Buy more Microsoft', slug='buy-more-microsoft', text=\"Nadella leads the way\", company_id=2)>>> Post.objects.create(title='Buy more Amazon', slug='buy-more-amazon', text=\"Jeff Bezos acquires Mars from Elon Musk\", company_id=3)>>> Post.objects.create(title='Time to sell MongoDB', slug='time-to-sell-mongdb', text=\"MongoDB seems a little overvalued\", company_id=4)"
},
{
"code": null,
"e": 12266,
"s": 12185,
"text": "We can also verify that these objects actually exist in our postgreSQL database:"
},
{
"code": null,
"e": 12371,
"s": 12266,
"text": "$ psql -d postgrespostgres=# \\c doublebaggerdoublebagger=# \\dtdoublebagger=# SELECT * FROM post_company;"
},
{
"code": null,
"e": 12407,
"s": 12371,
"text": "You should see something like this:"
},
{
"code": null,
"e": 12424,
"s": 12407,
"text": "And an SQL join:"
},
{
"code": null,
"e": 12552,
"s": 12424,
"text": "doublebagger=# SELECT * FROM post_companydoublebagger=# JOIN post_post ONdoublebagger=# post_company.id = post_post.company_id;"
},
{
"code": null,
"e": 12640,
"s": 12552,
"text": "Using sqlalchemy we can directly get access to postgreSQL objects straight from pandas:"
},
{
"code": null,
"e": 12675,
"s": 12640,
"text": "If you fire up a Jupyter Notebook:"
},
{
"code": null,
"e": 13017,
"s": 12675,
"text": "import pandas as pdfrom sqlalchemy import create_engineengine = create_engine('postgresql://sammylee@localhost:5432/doublebagger')posts = pd.read_sql('select * from post_post', engine)companies = pd.read_sql('select * from post_company', engine)posts_companies = pd.merge(companies, posts, left_on='id', right_on='company_id')posts_companies"
},
{
"code": null,
"e": 13114,
"s": 13017,
"text": "And now we can use the full might and magic of pandas to do whatever we want as data scientists."
},
{
"code": null,
"e": 13350,
"s": 13114,
"text": "While knowledge of a web development framework isn’t necessary for data scientists, I think it’s really cool to take a step back and have a look at the Amazonian Forest that is data science by going from Django to postgreSQL to pandas."
},
{
"code": null,
"e": 13550,
"s": 13350,
"text": "Django has a “batteries included” philosophy, and provides an administration interface that basically serves as a GUI to your postgreSQL database. All we have to do is add some lines to post/admin.py"
},
{
"code": null,
"e": 13846,
"s": 13550,
"text": "# post/admin.pyfrom django.contrib import adminfrom django.db import models# Register your models here.from .models import Post, Companyclass MyCompanyAdmin(admin.ModelAdmin): model = Company list_display = ('name', 'slug', 'description', 'pe_ratio',)admin.site.register(Company, MyCompanyAdmin)"
},
{
"code": null,
"e": 13890,
"s": 13846,
"text": "And create a superuser on the command line:"
},
{
"code": null,
"e": 14065,
"s": 13890,
"text": "$ (doublebagger) python manage.py createsuperuser# Then create your credentials# start up your local development server and head to your local host# and append \"/admin\" to it"
}
]
|
Model Sub-Classing and Custom Training Loop from Scratch in TensorFlow 2 | by Mohammed Innat | Towards Data Science | In this article, we will try to understand the Model Sub-Classing API and Custom Training Loop from Scratch in TensorFlow 2. It may not be a beginner or advanced introduction but aim to get rough intuition of what they are all about. The post is divided into three parts:
Comparable Modelling Strategies in TensorFlow 2Build an Inception Network with Model Sub-Classing APIEnd-to-End Training with Custom Training Loop from Scratch
Comparable Modelling Strategies in TensorFlow 2
Build an Inception Network with Model Sub-Classing API
End-to-End Training with Custom Training Loop from Scratch
So, at first, we will see how many ways to define models using TensorFlow 2 and how they differ from each other. Next, we will see how feasible it is to build a complex neural architecture using the model subclassing API which is introduced in TF 2. And then we will implement a custom training loop and train these subclassing models end-to-end from scratch. We will also use Tensorboard in our custom training loop to track the model performance for each batch. We will also see how to save and load the model after training. In the end, we will measure the model performance via the confusion matrix and classification report, etc.
In TF.Keras there are basically three-way we can define a neural network, namely
Sequential API
Functional API
Model Subclassing API
Among them, Sequential API is the easiest way to implement but comes with certain limitations. For example, with this API, we can’t create a model that shares feature information to another layer except to its subsequent layer. In addition, multiple input and output are not possible to implement either. In this point, Functional API does solve these issues greatly. A model like Inception or ResNet is feasible to implement in Functional API. But often deep learning researcher wants to have more control over every nuance of the network and on the training pipelines and that’s exactly what Model Subclassing API serves. Model Sub-Classing is a fully customizable way to implement the feed-forward mechanism for our custom-designed deep neural network in an object-oriented fashion.
Let’s create a very basic neural network using these three APIs. It will be the same neural architecture and will see what are the implementation differences. This of course will not demonstrate the full potential, especially for Functional and Model Sub-Classing API. The architecture will be as follows:
Input - > Conv - > MaxPool - > BN - > Conv -> BN - > Droput - > GAP -> Dense
Simple enough. As mentioned, let’s create the neural nets with Sequential, Functional, and Model Sub-Classing respectively.
In Model Sub-Classing there are two most important functions __init__ and call. Basically, we will define all the tf.keras layers or custom implemented layers inside the __init__ method and call those layers based on our network design inside the call method which is used to perform a forward propagation. It’s quite the same as the forward method that is used to build the model in PyTorch anyway.
Let’s run these models on the MNIST data set. We will load from tf.keras.datasets. However, the input image is 28 by 28 and in grayscale shape. We will repeat the axis three times so that we can feasibly experiment with the pretrained weight later on if necessary.
Output
Sequential API469/469 [==============================] - 2s 3ms/step - loss: 7.5747 - categorical_accuracy: 0.2516Functional API469/469 [==============================] - 2s 3ms/step - loss: 8.1335 - categorical_accuracy: 0.2368Model Sub-Classing API469/469 [==============================] - 2s 3ms/step - loss: 5.2695 - categorical_accuracy: 0.1731
The core data structures in TF.Keras are layers and model classes. A layer encapsulates both state (weight) and the transformation from inputs to outputs, i.e. the call method that is used to define the forward pass. However, these layers are also recursively composable. It means if we assign a tf.keras.layers.Layer instances as an attribute of another tf.keras.layers.Layer, the outer layer will start tracking the weights matrix of the inner layer. So, each layer will track the weights of its sublayers, both trainable and non-trainable. Such functionality is required when we need to build such a layer of a higher level of abstraction.
In this part, we will be building a small Inception model by subclassing the layers and model classes. Please see the diagram below. It’s a small Inception network, src. If we give a close look we’ll see that it mainly consists of three special modules, namely:
Conv ModuleInception ModuleDownsample Module
Conv Module
Inception Module
Downsample Module
From the diagram we can see, it consists of one convolutional network, one batch normalization, and one relu activation. Also, it produces C times feature maps with K x K filters and S x S strides. Now, it would be very inefficient if we simply go with the sequential modeling approach because we will be re-using this module many times in the complete network. So, defining a functional block would be efficient and simple enough. But this time, we will prefer layer subclassing which is more pythonic and more efficient. To do that, we will create a class object that will inherit the tf.keras.layers.Layer classes.
Now, We can also initiate the object of this class and see the following properties.
cm = ConvModule(96, (3,3), (1,1))y = cm(tf.ones(shape=(2,32,32,3))) # first call to the `cm` will create weightsprint("weights:", len(cm.weights))print("trainable weights:", len(cm.trainable_weights))# outputweights: 6trainable weights: 4
Next comes the Inception module. According to the above graph, it consists of two convolutional modules and then merges together. Now as we know to merge, here we need to ensure that the output feature maps dimension ( height and width ) needs to be the same.
Here you may notice that we are now hard-coded exact kernel size and strides number for both convolutional layers according to the network (diagram). And also in ConvModule, we have already set padding to the ‘same’, so that the dimension of the feature maps will be the same for both (self.conv1 and self.conv2); which is required in order to concatenate them to the end.
Again, in this module, two variable performs as the placeholder, kernel_size1x1, and kernel_size3x3. This is for the purpose of course. Because we will need different numbers of feature maps to the different stages of the entire model. If we look into the diagram of the model, we will see that InceptionModule takes a different number of filters at different stages in the model.
Lastly the downsampling module. The main intuition for downsampling is that we hope to get more relevant feature information that highly represents the inputs to the model. As it tends to remove the unwanted feature so that model can focus on the most relevant. There are many ways we can reduce the dimension of the feature maps (or inputs). For example: using strides 2 or using the conventional pooling operation. There are many types of pooling operation, namely: MaxPooling, AveragePooling, GlobalAveragePooling.
From the diagram, we can see that the downsampling module contains one convolutional layer and one max-pooling layer which later merges together. Now, if we look closely at the diagram (top-right), we will see that the convolutional layer takes a 3 x 3 size filter with strides 2 x 2. And the pooling layer (here MaxPooling) takes pooling size 3 x 3 with strides 2 x 2. Fair enough, however, we also ensure that the dimension coming from each of them should be the same in order to merge at the end. Now, if we remember when we design the ConvModule we purposely set the value of the padding argument to `same`. But in this case, we need to set it to `valid`.
In general, we use the Layer class to define the inner computation blocks and will use the Model class to define the outer model, practically the object that we will train. In our case, in an Inception model, we define three computational blocks: Conv Module, Inception Module, and Downsample Module. These are created by subclassing the Layer class. And so next, we will use the Model class to encompass these computational blocks in order to create the entire Inception network. Typically the Model class has the same API as Layer but with some extra functionality.
Same as the Layer class, we will initialize the computational block inside the init method of the Model class as follows:
The amount of filter number for each computational block is set according to the design of the model (also visualized down below in the diagram). After initialing all the blocks, we will connect them according to the design (diagram). Here is the full Inception network using Model subclass:
As you may notice, apart from the __init__ and call method additionally we define a custom method build_graph. We’re using this as a helper function to plot the model summary information conveniently. Please, check out this discussion for more details. Anyway, let’s check out the model’s summary.
raw_input = (32, 32, 3)# init model objectcm = MiniInception()# The first call to the `cm` will create the weightsy = cm(tf.ones(shape=(0,*raw_input))) # print summarycm.build_graph(raw_input).summary()# ---------------------------------------------------------------------Layer (type) Output Shape Param # =================================================================input_6 (InputLayer) [(None, 32, 32, 3)] 0 _________________________________________________________________conv_module_329 (ConvModule) (None, 32, 32, 96) 3072 _________________________________________________________________inception_module_136 (Incept (None, 32, 32, 64) 31040 _________________________________________________________________inception_module_137 (Incept (None, 32, 32, 80) 30096 _________________________________________________________________downsample_module_34 (Downsa (None, 15, 15, 160) 58000 _________________________________________________________________inception_module_138 (Incept (None, 15, 15, 160) 87840 _________________________________________________________________inception_module_139 (Incept (None, 15, 15, 160) 108320 _________________________________________________________________inception_module_140 (Incept (None, 15, 15, 160) 128800 _________________________________________________________________inception_module_141 (Incept (None, 15, 15, 144) 146640 _________________________________________________________________downsample_module_35 (Downsa (None, 7, 7, 240) 124896 _________________________________________________________________inception_module_142 (Incept (None, 7, 7, 336) 389520 _________________________________________________________________inception_module_143 (Incept (None, 7, 7, 336) 544656 _________________________________________________________________average_pooling2d_17 (Averag (None, 1, 1, 336) 0 _________________________________________________________________flatten_13 (Flatten) (None, 336) 0 _________________________________________________________________dense_17 (Dense) (None, 10) 3370 =================================================================Total params: 1,656,250Trainable params: 1,652,826Non-trainable params: 3,424
Now, it is complete to build the entire Inception model via model subclassing. However, compared to the functional API, instead of defining each module in a separate function, using the subclassing API, it looks more natural.
Now we have built a complex network, it’s time to make it busy to learn something. We can now easily train the model simply just by using the compile and fit. But here we will look at a custom training loop from scratch. This functionality is newly introduced in TensorFlow 2. Please note, this functionality is a little bit complex comparatively and more fit for the deep learning researcher.
For the demonstration purpose, we will be using the CIFAR-10 data set. Let’s prepare it first.
Here we will convert the class vector (y_train, y_test) to the binary class matrix. And also we will separate the elements of the input tensor for better and more efficient input pipelines.
Let’s quickly check the data shape after label conversion and input slicing:
for i, (x, y) in enumerate(train_dataset): print(x.shape, y.shape) if i == 2: breakfor i, (x, y) in enumerate(val_dataset): print(x.shape, y.shape) if i == 2: break# output (64, 32, 32, 3) (64, 10)(64, 32, 32, 3) (64, 10)(64, 32, 32, 3) (64, 10)(64, 32, 32, 3) (64, 10)(64, 32, 32, 3) (64, 10)(64, 32, 32, 3) (64, 10)
so far so good. We have an input shape of 32 x 32 x 3 and a total of 10 classes to classify. However, it’s not ideal to make a test set as a validation set but for demonstration purposes, we are not considering the train_test_split approach. Now, let’s see what the custom training pipelines consist of in Tensorflow 2.
In TF.Keras, we have convenient training and evaluating loops, fit, and evaluate. But we also can have leveraged the low-level control over the training and evaluation process. In that case, we need to write our own training and evaluation loops from scratch. Here are the recipes:
We open a for loop that will iterate over the number of epochs.For each epoch, we open another for loop that will iterate over the datasets, in batches (x, y).For each batch, we open GradientTape() scope.Inside this scope, we call the model, the forward pass, and compute the loss.Outside this scope, we retrieve the gradients of the weights of the model with regard to the loss.Next, we use the optimizer to update the weights of the model based on the gradients.
We open a for loop that will iterate over the number of epochs.
For each epoch, we open another for loop that will iterate over the datasets, in batches (x, y).
For each batch, we open GradientTape() scope.
Inside this scope, we call the model, the forward pass, and compute the loss.
Outside this scope, we retrieve the gradients of the weights of the model with regard to the loss.
Next, we use the optimizer to update the weights of the model based on the gradients.
TensorFlow provides the tf.GradientTape() API for automatic differentiation, that is, computing the gradient of computation with respect to some inputs. Below is a short demonstration of its operation process. Here we have some input (x) and trainable param (w, b). Inside the tf.GradientTape() scope, output (y, which basically would be the model output), and loss are measured. And outside the scope, we retrieve the gradients of the weight parameter with respect to the loss.
Now, let’s implement the custom training recipes accordingly.
Great. However, we are still not talking about how we gonna add metrics to monitor this custom training loop. Obviously, we can use built-in metrics or even custom metrics in the training loop also. To add metrics in the training loop is fairly simple, here is the flow:
Call metric.update_state() after each batchCall metric.result() when we need to display the current value of the metricCall metric.reset_states() when we need to clear the state of the metric, typically we do this at the very end of an epoch.
Call metric.update_state() after each batch
Call metric.result() when we need to display the current value of the metric
Call metric.reset_states() when we need to clear the state of the metric, typically we do this at the very end of an epoch.
Here is another thing to consider. The default runtime in TensorFlow 2.0 is eager execution. The above training loops are executing eagerly. But if we want graph compilation we can compile any function into a static graph with @tf.function decorator. This also speeds up the training step much faster. Here is the setup for the training and evaluation function with @tf.function decorator.
Here we’re seeing the usage of metrics.update_state(). These functions return to the training loop where we will set up displaying the log message, metric.result(), and also reset the metrics, metric.reset_states().
Here is the last thing we like to set up, the TensorBoard. There are some great functionalities in it to utilize such as: displaying per batches samples + confusion matrix, hyper-parameter tuning, embedding projector, model graph, etc. For now, we will only focus on logging the training metrics on it. Simple enough but we will integrate it in the custom training loop. So, we can’t use tf.keras.callbacks.TensorBoard but need to use the TensorFlow Summary API. The tf.summary module provides API for writing summary data on TensorBoard. We want to write the logging state after each batch operation to get more details. Otherwise, we may prefer at the end of each epoch. Let’s create a directory where the message of the event will be saved. In the working directory, create the log/train and log/test. Below is the full training pipelines. We recommend reading the code thoroughly at first in order to get the overall training flow.
Voila! We run the code in our local system, having RTX 2070. By enabling the mixed-precision we’re able to increase the batch size up to 256. Here is the log output:
ETA: 0.78 - epoch: 1 loss: 0.7587890625 acc: 0.5794399976730347 val loss: 3.173828125 val acc: 0.10159999877214432ETA: 0.29 - epoch: 2 loss: 0.63232421875 acc: 0.7421200275421143 val loss: 1.0126953125 val acc: 0.5756999850273132ETA: 0.32 - epoch: 3 loss: 0.453369140625 acc: 0.8073400259017944 val loss: 0.7734375 val acc: 0.7243000268936157ETA: 0.33 - epoch: 4 loss: 0.474365234375 acc: 0.8501200079917908 val loss: 0.64111328125 val acc: 0.7628999948501587....ETA: 0.35 - epoch: 17 loss: 0.0443115234375 acc: 0.9857199788093567 val loss: 1.8603515625 val acc: 0.7465000152587891ETA: 0.68 - epoch: 18 loss: 0.01328277587890625 acc: 0.9839400053024292 val loss: 0.65380859375 val acc: 0.7875999808311462ETA: 0.53 - epoch: 19 loss: 0.035552978515625 acc: 0.9851599931716919 val loss: 1.0849609375 val acc: 0.7432000041007996ETA: 0.4 - epoch: 20 loss: 0.04217529296875 acc: 0.9877399802207947 val loss: 3.078125 val acc: 0.7224000096321106
Overfitting! But that’s ok for now. For that, we just need some care to consider such as Image Augmentation, Learning Rate Schedule, etc. In the working directory, run the following command to live tensorboard. In the below command, logs are the folder name that we created manually to save the event logs.
tensorboard --logdir logs
There are various ways to save TensorFlow models depending on the API we’re using. Model saving and re-loading in model subclassing are not the same as in Sequential or Functional API. It needs some special attention. Currently, there are two formats to store the model: SaveModel and HDF5. From the official doc:
The key difference between HDF5 and SavedModel is that HDF5 uses object configs to save the model architecture, while SavedModel saves the execution graph. Thus, SavedModels are able to save custom objects like subclassed models and custom layers without requiring the orginal code.
So, it looks like SavedModels are able to save our custom subclassed models. But what if we want HDF5 format for our custom subclassed models? According to the doc. we can do that either but we need some extra stuff. We must define the get_config method in our object. And also need to pass the object to the custom_object argument when loading the model. This argument must be a dictionary mapping: tf.keras.models.load_model(path, custom_objects={‘CustomLayer’: CustomLayer}). However, it seems like we can’t use HDF5 for now as we don’t use the get_config method in our customed object. However, it’s actually a good practice to define this function in the custom object. This will allow us to easily update the computation later if needed.
But for now, let’s now save the model and reload it again with SavedModel format.
model.save('net', save_format='tf')
After that, it will create a new folder named net in the working directory. It will contain assets, saved_model.pb, and variables. The model architecture and training configuration, including the optimizer, losses, and metrics are stored in saved_model.pb. The weights are saved in the variables directory.
When saving the model and its layers, the SavedModel format stores the class name, call function, losses, and weights (and the config, if implemented). The call function defines the computation graph of the model/layer. In the absence of the model/layer config, the call function is used to create a model that exists like the original model which can be trained, evaluated, and used for inference. Later to re-load the saved model, we will do:
new_model = tf.keras.models.load_model("net", compile=False)
Set compile=False is optional, I do this to avoid warning logs. Also as we are doing custom loop training, we don’t need any compilation.
So far, we have talked about saving the entire model (computation graph and parameters). But what, if we want to save the trained weight only and reload the weight when need it. Yeap, we can do that too. Simply just,
model.save_weights('net.h5')
It will save the weight of our model. Now, when it comes to re-load it again, here is one thing to keep in mind. We need to call the build method before we try to load the weight. It mainly initializes the layers in a subclassed model, so that the computation graph can build. For example, if we try as follows:
new_model = MiniInception()new_model.load_weights('net.h5')--------------------------------------ValueError: Unable to load weights saved in HDF5 format into a subclassed Model which has not created its variables yet. Call the Model first, then load the weights.
To solve that we can do as follows:
new_model = MiniInception()new_model.build((None, *x_train.shape[1:])) # or .build((x_train.shape))new_model.load_weights('net.h5')
It will load successfully. Here is an awesome article regarding saving and serializing models in TF.Keras by François Chollet, must-read.
Though not necessary, let’s end up with measuring the model performance. CIFAR-10 class label maps are as follows: 0:airplane, 1:automobile, 2:bird, 3:cat, 4:deer, 5:dog, 6:frog, 7:horse, 8:ship, 9:truck. Let’s find the classification report first.
Next, multi-class ROC AUC score:
Confusion Matrix:
Prediction / Inference on new sample:
This ends here. Thank you so much for reading the article, hope you guys enjoy it. The article is a bit long, so here is a quick summary; we first compare TF.Keras modeling APIs. Next, we use the Model Sub-Classing API to build a small Inception network step by step. Then we look at the training process of newly introduced custom loop training in TensorFlow 2 with GradientTape. We’ve also trained the subclassed Inception model end to end. And lastly, we discuss custom model saving and reloading followed by measuring the performance of these trained models.
There are many new kinds of stuff introduced in TensorFlow 2. And TensorFlow developers are actively working to improve it in every release. Recently (5 days ago) they’ve released TensorFlow 2.4 with lots of modifications. For example, these works use TensorFlow 2.3.1, differ from it, in 2.4 the tf.keras.mixed_precision is no longer experimental and now it allows the use of 16-bit floating-point formats during training, improving performance by up to 3x on GPUs and 60% on TPUs which are really cool.
Jokes aside, Medium developers should add the code syntax highlighter by default; copy-paste — copy-paste from gist is annoying (IMO). However, in case you want to play with the colorful code, here. | [
{
"code": null,
"e": 443,
"s": 171,
"text": "In this article, we will try to understand the Model Sub-Classing API and Custom Training Loop from Scratch in TensorFlow 2. It may not be a beginner or advanced introduction but aim to get rough intuition of what they are all about. The post is divided into three parts:"
},
{
"code": null,
"e": 603,
"s": 443,
"text": "Comparable Modelling Strategies in TensorFlow 2Build an Inception Network with Model Sub-Classing APIEnd-to-End Training with Custom Training Loop from Scratch"
},
{
"code": null,
"e": 651,
"s": 603,
"text": "Comparable Modelling Strategies in TensorFlow 2"
},
{
"code": null,
"e": 706,
"s": 651,
"text": "Build an Inception Network with Model Sub-Classing API"
},
{
"code": null,
"e": 765,
"s": 706,
"text": "End-to-End Training with Custom Training Loop from Scratch"
},
{
"code": null,
"e": 1400,
"s": 765,
"text": "So, at first, we will see how many ways to define models using TensorFlow 2 and how they differ from each other. Next, we will see how feasible it is to build a complex neural architecture using the model subclassing API which is introduced in TF 2. And then we will implement a custom training loop and train these subclassing models end-to-end from scratch. We will also use Tensorboard in our custom training loop to track the model performance for each batch. We will also see how to save and load the model after training. In the end, we will measure the model performance via the confusion matrix and classification report, etc."
},
{
"code": null,
"e": 1481,
"s": 1400,
"text": "In TF.Keras there are basically three-way we can define a neural network, namely"
},
{
"code": null,
"e": 1496,
"s": 1481,
"text": "Sequential API"
},
{
"code": null,
"e": 1511,
"s": 1496,
"text": "Functional API"
},
{
"code": null,
"e": 1533,
"s": 1511,
"text": "Model Subclassing API"
},
{
"code": null,
"e": 2319,
"s": 1533,
"text": "Among them, Sequential API is the easiest way to implement but comes with certain limitations. For example, with this API, we can’t create a model that shares feature information to another layer except to its subsequent layer. In addition, multiple input and output are not possible to implement either. In this point, Functional API does solve these issues greatly. A model like Inception or ResNet is feasible to implement in Functional API. But often deep learning researcher wants to have more control over every nuance of the network and on the training pipelines and that’s exactly what Model Subclassing API serves. Model Sub-Classing is a fully customizable way to implement the feed-forward mechanism for our custom-designed deep neural network in an object-oriented fashion."
},
{
"code": null,
"e": 2625,
"s": 2319,
"text": "Let’s create a very basic neural network using these three APIs. It will be the same neural architecture and will see what are the implementation differences. This of course will not demonstrate the full potential, especially for Functional and Model Sub-Classing API. The architecture will be as follows:"
},
{
"code": null,
"e": 2702,
"s": 2625,
"text": "Input - > Conv - > MaxPool - > BN - > Conv -> BN - > Droput - > GAP -> Dense"
},
{
"code": null,
"e": 2826,
"s": 2702,
"text": "Simple enough. As mentioned, let’s create the neural nets with Sequential, Functional, and Model Sub-Classing respectively."
},
{
"code": null,
"e": 3226,
"s": 2826,
"text": "In Model Sub-Classing there are two most important functions __init__ and call. Basically, we will define all the tf.keras layers or custom implemented layers inside the __init__ method and call those layers based on our network design inside the call method which is used to perform a forward propagation. It’s quite the same as the forward method that is used to build the model in PyTorch anyway."
},
{
"code": null,
"e": 3491,
"s": 3226,
"text": "Let’s run these models on the MNIST data set. We will load from tf.keras.datasets. However, the input image is 28 by 28 and in grayscale shape. We will repeat the axis three times so that we can feasibly experiment with the pretrained weight later on if necessary."
},
{
"code": null,
"e": 3498,
"s": 3491,
"text": "Output"
},
{
"code": null,
"e": 3849,
"s": 3498,
"text": "Sequential API469/469 [==============================] - 2s 3ms/step - loss: 7.5747 - categorical_accuracy: 0.2516Functional API469/469 [==============================] - 2s 3ms/step - loss: 8.1335 - categorical_accuracy: 0.2368Model Sub-Classing API469/469 [==============================] - 2s 3ms/step - loss: 5.2695 - categorical_accuracy: 0.1731"
},
{
"code": null,
"e": 4492,
"s": 3849,
"text": "The core data structures in TF.Keras are layers and model classes. A layer encapsulates both state (weight) and the transformation from inputs to outputs, i.e. the call method that is used to define the forward pass. However, these layers are also recursively composable. It means if we assign a tf.keras.layers.Layer instances as an attribute of another tf.keras.layers.Layer, the outer layer will start tracking the weights matrix of the inner layer. So, each layer will track the weights of its sublayers, both trainable and non-trainable. Such functionality is required when we need to build such a layer of a higher level of abstraction."
},
{
"code": null,
"e": 4754,
"s": 4492,
"text": "In this part, we will be building a small Inception model by subclassing the layers and model classes. Please see the diagram below. It’s a small Inception network, src. If we give a close look we’ll see that it mainly consists of three special modules, namely:"
},
{
"code": null,
"e": 4799,
"s": 4754,
"text": "Conv ModuleInception ModuleDownsample Module"
},
{
"code": null,
"e": 4811,
"s": 4799,
"text": "Conv Module"
},
{
"code": null,
"e": 4828,
"s": 4811,
"text": "Inception Module"
},
{
"code": null,
"e": 4846,
"s": 4828,
"text": "Downsample Module"
},
{
"code": null,
"e": 5464,
"s": 4846,
"text": "From the diagram we can see, it consists of one convolutional network, one batch normalization, and one relu activation. Also, it produces C times feature maps with K x K filters and S x S strides. Now, it would be very inefficient if we simply go with the sequential modeling approach because we will be re-using this module many times in the complete network. So, defining a functional block would be efficient and simple enough. But this time, we will prefer layer subclassing which is more pythonic and more efficient. To do that, we will create a class object that will inherit the tf.keras.layers.Layer classes."
},
{
"code": null,
"e": 5549,
"s": 5464,
"text": "Now, We can also initiate the object of this class and see the following properties."
},
{
"code": null,
"e": 5788,
"s": 5549,
"text": "cm = ConvModule(96, (3,3), (1,1))y = cm(tf.ones(shape=(2,32,32,3))) # first call to the `cm` will create weightsprint(\"weights:\", len(cm.weights))print(\"trainable weights:\", len(cm.trainable_weights))# outputweights: 6trainable weights: 4"
},
{
"code": null,
"e": 6048,
"s": 5788,
"text": "Next comes the Inception module. According to the above graph, it consists of two convolutional modules and then merges together. Now as we know to merge, here we need to ensure that the output feature maps dimension ( height and width ) needs to be the same."
},
{
"code": null,
"e": 6421,
"s": 6048,
"text": "Here you may notice that we are now hard-coded exact kernel size and strides number for both convolutional layers according to the network (diagram). And also in ConvModule, we have already set padding to the ‘same’, so that the dimension of the feature maps will be the same for both (self.conv1 and self.conv2); which is required in order to concatenate them to the end."
},
{
"code": null,
"e": 6802,
"s": 6421,
"text": "Again, in this module, two variable performs as the placeholder, kernel_size1x1, and kernel_size3x3. This is for the purpose of course. Because we will need different numbers of feature maps to the different stages of the entire model. If we look into the diagram of the model, we will see that InceptionModule takes a different number of filters at different stages in the model."
},
{
"code": null,
"e": 7320,
"s": 6802,
"text": "Lastly the downsampling module. The main intuition for downsampling is that we hope to get more relevant feature information that highly represents the inputs to the model. As it tends to remove the unwanted feature so that model can focus on the most relevant. There are many ways we can reduce the dimension of the feature maps (or inputs). For example: using strides 2 or using the conventional pooling operation. There are many types of pooling operation, namely: MaxPooling, AveragePooling, GlobalAveragePooling."
},
{
"code": null,
"e": 7980,
"s": 7320,
"text": "From the diagram, we can see that the downsampling module contains one convolutional layer and one max-pooling layer which later merges together. Now, if we look closely at the diagram (top-right), we will see that the convolutional layer takes a 3 x 3 size filter with strides 2 x 2. And the pooling layer (here MaxPooling) takes pooling size 3 x 3 with strides 2 x 2. Fair enough, however, we also ensure that the dimension coming from each of them should be the same in order to merge at the end. Now, if we remember when we design the ConvModule we purposely set the value of the padding argument to `same`. But in this case, we need to set it to `valid`."
},
{
"code": null,
"e": 8548,
"s": 7980,
"text": "In general, we use the Layer class to define the inner computation blocks and will use the Model class to define the outer model, practically the object that we will train. In our case, in an Inception model, we define three computational blocks: Conv Module, Inception Module, and Downsample Module. These are created by subclassing the Layer class. And so next, we will use the Model class to encompass these computational blocks in order to create the entire Inception network. Typically the Model class has the same API as Layer but with some extra functionality."
},
{
"code": null,
"e": 8670,
"s": 8548,
"text": "Same as the Layer class, we will initialize the computational block inside the init method of the Model class as follows:"
},
{
"code": null,
"e": 8962,
"s": 8670,
"text": "The amount of filter number for each computational block is set according to the design of the model (also visualized down below in the diagram). After initialing all the blocks, we will connect them according to the design (diagram). Here is the full Inception network using Model subclass:"
},
{
"code": null,
"e": 9260,
"s": 8962,
"text": "As you may notice, apart from the __init__ and call method additionally we define a custom method build_graph. We’re using this as a helper function to plot the model summary information conveniently. Please, check out this discussion for more details. Anyway, let’s check out the model’s summary."
},
{
"code": null,
"e": 11691,
"s": 9260,
"text": "raw_input = (32, 32, 3)# init model objectcm = MiniInception()# The first call to the `cm` will create the weightsy = cm(tf.ones(shape=(0,*raw_input))) # print summarycm.build_graph(raw_input).summary()# ---------------------------------------------------------------------Layer (type) Output Shape Param # =================================================================input_6 (InputLayer) [(None, 32, 32, 3)] 0 _________________________________________________________________conv_module_329 (ConvModule) (None, 32, 32, 96) 3072 _________________________________________________________________inception_module_136 (Incept (None, 32, 32, 64) 31040 _________________________________________________________________inception_module_137 (Incept (None, 32, 32, 80) 30096 _________________________________________________________________downsample_module_34 (Downsa (None, 15, 15, 160) 58000 _________________________________________________________________inception_module_138 (Incept (None, 15, 15, 160) 87840 _________________________________________________________________inception_module_139 (Incept (None, 15, 15, 160) 108320 _________________________________________________________________inception_module_140 (Incept (None, 15, 15, 160) 128800 _________________________________________________________________inception_module_141 (Incept (None, 15, 15, 144) 146640 _________________________________________________________________downsample_module_35 (Downsa (None, 7, 7, 240) 124896 _________________________________________________________________inception_module_142 (Incept (None, 7, 7, 336) 389520 _________________________________________________________________inception_module_143 (Incept (None, 7, 7, 336) 544656 _________________________________________________________________average_pooling2d_17 (Averag (None, 1, 1, 336) 0 _________________________________________________________________flatten_13 (Flatten) (None, 336) 0 _________________________________________________________________dense_17 (Dense) (None, 10) 3370 =================================================================Total params: 1,656,250Trainable params: 1,652,826Non-trainable params: 3,424"
},
{
"code": null,
"e": 11917,
"s": 11691,
"text": "Now, it is complete to build the entire Inception model via model subclassing. However, compared to the functional API, instead of defining each module in a separate function, using the subclassing API, it looks more natural."
},
{
"code": null,
"e": 12311,
"s": 11917,
"text": "Now we have built a complex network, it’s time to make it busy to learn something. We can now easily train the model simply just by using the compile and fit. But here we will look at a custom training loop from scratch. This functionality is newly introduced in TensorFlow 2. Please note, this functionality is a little bit complex comparatively and more fit for the deep learning researcher."
},
{
"code": null,
"e": 12406,
"s": 12311,
"text": "For the demonstration purpose, we will be using the CIFAR-10 data set. Let’s prepare it first."
},
{
"code": null,
"e": 12596,
"s": 12406,
"text": "Here we will convert the class vector (y_train, y_test) to the binary class matrix. And also we will separate the elements of the input tensor for better and more efficient input pipelines."
},
{
"code": null,
"e": 12673,
"s": 12596,
"text": "Let’s quickly check the data shape after label conversion and input slicing:"
},
{
"code": null,
"e": 13024,
"s": 12673,
"text": "for i, (x, y) in enumerate(train_dataset): print(x.shape, y.shape) if i == 2: breakfor i, (x, y) in enumerate(val_dataset): print(x.shape, y.shape) if i == 2: break# output (64, 32, 32, 3) (64, 10)(64, 32, 32, 3) (64, 10)(64, 32, 32, 3) (64, 10)(64, 32, 32, 3) (64, 10)(64, 32, 32, 3) (64, 10)(64, 32, 32, 3) (64, 10)"
},
{
"code": null,
"e": 13344,
"s": 13024,
"text": "so far so good. We have an input shape of 32 x 32 x 3 and a total of 10 classes to classify. However, it’s not ideal to make a test set as a validation set but for demonstration purposes, we are not considering the train_test_split approach. Now, let’s see what the custom training pipelines consist of in Tensorflow 2."
},
{
"code": null,
"e": 13626,
"s": 13344,
"text": "In TF.Keras, we have convenient training and evaluating loops, fit, and evaluate. But we also can have leveraged the low-level control over the training and evaluation process. In that case, we need to write our own training and evaluation loops from scratch. Here are the recipes:"
},
{
"code": null,
"e": 14091,
"s": 13626,
"text": "We open a for loop that will iterate over the number of epochs.For each epoch, we open another for loop that will iterate over the datasets, in batches (x, y).For each batch, we open GradientTape() scope.Inside this scope, we call the model, the forward pass, and compute the loss.Outside this scope, we retrieve the gradients of the weights of the model with regard to the loss.Next, we use the optimizer to update the weights of the model based on the gradients."
},
{
"code": null,
"e": 14155,
"s": 14091,
"text": "We open a for loop that will iterate over the number of epochs."
},
{
"code": null,
"e": 14252,
"s": 14155,
"text": "For each epoch, we open another for loop that will iterate over the datasets, in batches (x, y)."
},
{
"code": null,
"e": 14298,
"s": 14252,
"text": "For each batch, we open GradientTape() scope."
},
{
"code": null,
"e": 14376,
"s": 14298,
"text": "Inside this scope, we call the model, the forward pass, and compute the loss."
},
{
"code": null,
"e": 14475,
"s": 14376,
"text": "Outside this scope, we retrieve the gradients of the weights of the model with regard to the loss."
},
{
"code": null,
"e": 14561,
"s": 14475,
"text": "Next, we use the optimizer to update the weights of the model based on the gradients."
},
{
"code": null,
"e": 15040,
"s": 14561,
"text": "TensorFlow provides the tf.GradientTape() API for automatic differentiation, that is, computing the gradient of computation with respect to some inputs. Below is a short demonstration of its operation process. Here we have some input (x) and trainable param (w, b). Inside the tf.GradientTape() scope, output (y, which basically would be the model output), and loss are measured. And outside the scope, we retrieve the gradients of the weight parameter with respect to the loss."
},
{
"code": null,
"e": 15102,
"s": 15040,
"text": "Now, let’s implement the custom training recipes accordingly."
},
{
"code": null,
"e": 15373,
"s": 15102,
"text": "Great. However, we are still not talking about how we gonna add metrics to monitor this custom training loop. Obviously, we can use built-in metrics or even custom metrics in the training loop also. To add metrics in the training loop is fairly simple, here is the flow:"
},
{
"code": null,
"e": 15616,
"s": 15373,
"text": "Call metric.update_state() after each batchCall metric.result() when we need to display the current value of the metricCall metric.reset_states() when we need to clear the state of the metric, typically we do this at the very end of an epoch."
},
{
"code": null,
"e": 15660,
"s": 15616,
"text": "Call metric.update_state() after each batch"
},
{
"code": null,
"e": 15737,
"s": 15660,
"text": "Call metric.result() when we need to display the current value of the metric"
},
{
"code": null,
"e": 15861,
"s": 15737,
"text": "Call metric.reset_states() when we need to clear the state of the metric, typically we do this at the very end of an epoch."
},
{
"code": null,
"e": 16251,
"s": 15861,
"text": "Here is another thing to consider. The default runtime in TensorFlow 2.0 is eager execution. The above training loops are executing eagerly. But if we want graph compilation we can compile any function into a static graph with @tf.function decorator. This also speeds up the training step much faster. Here is the setup for the training and evaluation function with @tf.function decorator."
},
{
"code": null,
"e": 16467,
"s": 16251,
"text": "Here we’re seeing the usage of metrics.update_state(). These functions return to the training loop where we will set up displaying the log message, metric.result(), and also reset the metrics, metric.reset_states()."
},
{
"code": null,
"e": 17403,
"s": 16467,
"text": "Here is the last thing we like to set up, the TensorBoard. There are some great functionalities in it to utilize such as: displaying per batches samples + confusion matrix, hyper-parameter tuning, embedding projector, model graph, etc. For now, we will only focus on logging the training metrics on it. Simple enough but we will integrate it in the custom training loop. So, we can’t use tf.keras.callbacks.TensorBoard but need to use the TensorFlow Summary API. The tf.summary module provides API for writing summary data on TensorBoard. We want to write the logging state after each batch operation to get more details. Otherwise, we may prefer at the end of each epoch. Let’s create a directory where the message of the event will be saved. In the working directory, create the log/train and log/test. Below is the full training pipelines. We recommend reading the code thoroughly at first in order to get the overall training flow."
},
{
"code": null,
"e": 17569,
"s": 17403,
"text": "Voila! We run the code in our local system, having RTX 2070. By enabling the mixed-precision we’re able to increase the batch size up to 256. Here is the log output:"
},
{
"code": null,
"e": 18516,
"s": 17569,
"text": "ETA: 0.78 - epoch: 1 loss: 0.7587890625 acc: 0.5794399976730347 val loss: 3.173828125 val acc: 0.10159999877214432ETA: 0.29 - epoch: 2 loss: 0.63232421875 acc: 0.7421200275421143 val loss: 1.0126953125 val acc: 0.5756999850273132ETA: 0.32 - epoch: 3 loss: 0.453369140625 acc: 0.8073400259017944 val loss: 0.7734375 val acc: 0.7243000268936157ETA: 0.33 - epoch: 4 loss: 0.474365234375 acc: 0.8501200079917908 val loss: 0.64111328125 val acc: 0.7628999948501587....ETA: 0.35 - epoch: 17 loss: 0.0443115234375 acc: 0.9857199788093567 val loss: 1.8603515625 val acc: 0.7465000152587891ETA: 0.68 - epoch: 18 loss: 0.01328277587890625 acc: 0.9839400053024292 val loss: 0.65380859375 val acc: 0.7875999808311462ETA: 0.53 - epoch: 19 loss: 0.035552978515625 acc: 0.9851599931716919 val loss: 1.0849609375 val acc: 0.7432000041007996ETA: 0.4 - epoch: 20 loss: 0.04217529296875 acc: 0.9877399802207947 val loss: 3.078125 val acc: 0.7224000096321106"
},
{
"code": null,
"e": 18823,
"s": 18516,
"text": "Overfitting! But that’s ok for now. For that, we just need some care to consider such as Image Augmentation, Learning Rate Schedule, etc. In the working directory, run the following command to live tensorboard. In the below command, logs are the folder name that we created manually to save the event logs."
},
{
"code": null,
"e": 18849,
"s": 18823,
"text": "tensorboard --logdir logs"
},
{
"code": null,
"e": 19163,
"s": 18849,
"text": "There are various ways to save TensorFlow models depending on the API we’re using. Model saving and re-loading in model subclassing are not the same as in Sequential or Functional API. It needs some special attention. Currently, there are two formats to store the model: SaveModel and HDF5. From the official doc:"
},
{
"code": null,
"e": 19446,
"s": 19163,
"text": "The key difference between HDF5 and SavedModel is that HDF5 uses object configs to save the model architecture, while SavedModel saves the execution graph. Thus, SavedModels are able to save custom objects like subclassed models and custom layers without requiring the orginal code."
},
{
"code": null,
"e": 20190,
"s": 19446,
"text": "So, it looks like SavedModels are able to save our custom subclassed models. But what if we want HDF5 format for our custom subclassed models? According to the doc. we can do that either but we need some extra stuff. We must define the get_config method in our object. And also need to pass the object to the custom_object argument when loading the model. This argument must be a dictionary mapping: tf.keras.models.load_model(path, custom_objects={‘CustomLayer’: CustomLayer}). However, it seems like we can’t use HDF5 for now as we don’t use the get_config method in our customed object. However, it’s actually a good practice to define this function in the custom object. This will allow us to easily update the computation later if needed."
},
{
"code": null,
"e": 20272,
"s": 20190,
"text": "But for now, let’s now save the model and reload it again with SavedModel format."
},
{
"code": null,
"e": 20308,
"s": 20272,
"text": "model.save('net', save_format='tf')"
},
{
"code": null,
"e": 20615,
"s": 20308,
"text": "After that, it will create a new folder named net in the working directory. It will contain assets, saved_model.pb, and variables. The model architecture and training configuration, including the optimizer, losses, and metrics are stored in saved_model.pb. The weights are saved in the variables directory."
},
{
"code": null,
"e": 21060,
"s": 20615,
"text": "When saving the model and its layers, the SavedModel format stores the class name, call function, losses, and weights (and the config, if implemented). The call function defines the computation graph of the model/layer. In the absence of the model/layer config, the call function is used to create a model that exists like the original model which can be trained, evaluated, and used for inference. Later to re-load the saved model, we will do:"
},
{
"code": null,
"e": 21121,
"s": 21060,
"text": "new_model = tf.keras.models.load_model(\"net\", compile=False)"
},
{
"code": null,
"e": 21259,
"s": 21121,
"text": "Set compile=False is optional, I do this to avoid warning logs. Also as we are doing custom loop training, we don’t need any compilation."
},
{
"code": null,
"e": 21476,
"s": 21259,
"text": "So far, we have talked about saving the entire model (computation graph and parameters). But what, if we want to save the trained weight only and reload the weight when need it. Yeap, we can do that too. Simply just,"
},
{
"code": null,
"e": 21505,
"s": 21476,
"text": "model.save_weights('net.h5')"
},
{
"code": null,
"e": 21817,
"s": 21505,
"text": "It will save the weight of our model. Now, when it comes to re-load it again, here is one thing to keep in mind. We need to call the build method before we try to load the weight. It mainly initializes the layers in a subclassed model, so that the computation graph can build. For example, if we try as follows:"
},
{
"code": null,
"e": 22080,
"s": 21817,
"text": "new_model = MiniInception()new_model.load_weights('net.h5')--------------------------------------ValueError: Unable to load weights saved in HDF5 format into a subclassed Model which has not created its variables yet. Call the Model first, then load the weights."
},
{
"code": null,
"e": 22116,
"s": 22080,
"text": "To solve that we can do as follows:"
},
{
"code": null,
"e": 22248,
"s": 22116,
"text": "new_model = MiniInception()new_model.build((None, *x_train.shape[1:])) # or .build((x_train.shape))new_model.load_weights('net.h5')"
},
{
"code": null,
"e": 22387,
"s": 22248,
"text": "It will load successfully. Here is an awesome article regarding saving and serializing models in TF.Keras by François Chollet, must-read."
},
{
"code": null,
"e": 22636,
"s": 22387,
"text": "Though not necessary, let’s end up with measuring the model performance. CIFAR-10 class label maps are as follows: 0:airplane, 1:automobile, 2:bird, 3:cat, 4:deer, 5:dog, 6:frog, 7:horse, 8:ship, 9:truck. Let’s find the classification report first."
},
{
"code": null,
"e": 22669,
"s": 22636,
"text": "Next, multi-class ROC AUC score:"
},
{
"code": null,
"e": 22687,
"s": 22669,
"text": "Confusion Matrix:"
},
{
"code": null,
"e": 22725,
"s": 22687,
"text": "Prediction / Inference on new sample:"
},
{
"code": null,
"e": 23288,
"s": 22725,
"text": "This ends here. Thank you so much for reading the article, hope you guys enjoy it. The article is a bit long, so here is a quick summary; we first compare TF.Keras modeling APIs. Next, we use the Model Sub-Classing API to build a small Inception network step by step. Then we look at the training process of newly introduced custom loop training in TensorFlow 2 with GradientTape. We’ve also trained the subclassed Inception model end to end. And lastly, we discuss custom model saving and reloading followed by measuring the performance of these trained models."
},
{
"code": null,
"e": 23793,
"s": 23288,
"text": "There are many new kinds of stuff introduced in TensorFlow 2. And TensorFlow developers are actively working to improve it in every release. Recently (5 days ago) they’ve released TensorFlow 2.4 with lots of modifications. For example, these works use TensorFlow 2.3.1, differ from it, in 2.4 the tf.keras.mixed_precision is no longer experimental and now it allows the use of 16-bit floating-point formats during training, improving performance by up to 3x on GPUs and 60% on TPUs which are really cool."
}
]
|
Modify the string such that every character gets replaced with the next character in the keyboard | 14 May, 2021
Given a string str consisting of lowercase English alphabets. The task is to change each character of the string with the next letter (in a circular fashion) key in the keyboard. For example, ‘a’ gets replaced with ‘s’, ‘b’ gets replaced with ‘n’, ....., ‘l’ gets replaced with ‘z’, ....., ‘m’ gets replaced with ‘q’.Examples:
Input: str = “geeks” Output: hrrldInput: str = “plmabc” Output: azqsnv
Approach: For every lowercase character of the English alphabet, insert the character next to it in the keyboard in an unordered_map. Now traverse the given string character by character, and update every character with the map created earlier.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; const string CHARS = "qwertyuiopasdfghjklzxcvbnm";const int MAX = 26; // Function to return the modified stringstring getString(string str, int n){ // Map to store the next character // on the keyboard for every // possible lowercase character unordered_map<char, char> uMap; for (int i = 0; i < MAX; i++) { uMap[CHARS[i]] = CHARS[(i + 1) % MAX]; } // Update the string for (int i = 0; i < n; i++) { str[i] = uMap[str[i]]; } return str;} // Driver codeint main(){ string str = "geeks"; int n = str.length(); cout << getString(str, n); return 0;}
// Java implementation of the approachimport java.util.*; class GFG{ static String CHARS = "qwertyuiopasdfghjklzxcvbnm";static int MAX = 26; // Function to return the modified Stringstatic String getString(char[] str, int n){ // Map to store the next character // on the keyboard for every // possible lowercase character Map<Character, Character> uMap = new HashMap<>(); for (int i = 0; i < MAX; i++) { uMap. put(CHARS.charAt(i), CHARS.charAt((i + 1) % MAX)); } // Update the String for (int i = 0; i < n; i++) { str[i] = uMap.get(str[i]); } return String.valueOf(str);} // Driver codepublic static void main(String []args){ String str = "geeks"; int n = str.length(); System.out.println(getString(str.toCharArray(), n));}} // This code is contributed by Rajput-Ji
# Python3 implementation of the approach CHARS = "qwertyuiopasdfghjklzxcvbnm";MAX = 26; # Function to return the modified stringdef getString(string, n) : string = list(string); # Map to store the next character # on the keyboard for every # possible lowercase character uMap = {}; for i in range(MAX) : uMap[CHARS[i]] = CHARS[(i + 1) % MAX]; # Update the string for i in range(n) : string[i] = uMap[string[i]]; return "".join(string); # Driver codeif __name__ == "__main__" : string = "geeks"; n = len(string); print(getString(string, n)); # This code is contributed by AnkitRai01
// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ static String CHARS = "qwertyuiopasdfghjklzxcvbnm";static int MAX = 26; // Function to return the modified Stringstatic String getString(char[] str, int n){ // Map to store the next character // on the keyboard for every // possible lowercase character Dictionary<char, char> uMap = new Dictionary<char, char>(); for (int i = 0; i < MAX; i++) { if(!uMap.ContainsKey(CHARS[i])) uMap.Add(CHARS[i], CHARS[(i + 1) % MAX]); else uMap[CHARS[i]] = CHARS[(i + 1) % MAX]; } // Update the String for (int i = 0; i < n; i++) { str[i] = uMap[str[i]]; } return String.Join("", str);} // Driver codepublic static void Main(String []args){ String str = "geeks"; int n = str.Length; Console.WriteLine(getString(str.ToCharArray(), n));}} // This code is contributed by PrinciRaj1992
<script> // JavaScript implementation of the approach var CHARS = "qwertyuiopasdfghjklzxcvbnm"; var MAX = 26; // Function to return the modified string function getString(string, n) { var string = string.split(""); // Map to store the next character // on the keyboard for every // possible lowercase character uMap = []; for (let i = 0; i < MAX; i++) { uMap[CHARS[i]] = CHARS[(i + 1) % MAX]; } // Update the string for (let i = 0; i < n; i++) { string[i] = uMap[string[i]]; } return string.join(""); } // Driver code var string = "geeks"; var n = string.length; document.write(getString(string, n)); </script>
hrrld
ankthon
Rajput-Ji
princiraj1992
rdtank
Arrays
Articles
Hash
Strings
Arrays
Hash
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Find the smallest positive integer value that cannot be represented as sum of any subset of a given array
Find a triplet that sum to a given value
Product of Array except itself
Median of two sorted arrays of same size
Smallest subarray with sum greater than a given value
Tree Traversals (Inorder, Preorder and Postorder)
SQL | Join (Inner, Left, Right and Full Joins)
find command in Linux with examples
Analysis of Algorithms | Set 1 (Asymptotic Analysis)
Time Complexity and Space Complexity | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 May, 2021"
},
{
"code": null,
"e": 357,
"s": 28,
"text": "Given a string str consisting of lowercase English alphabets. The task is to change each character of the string with the next letter (in a circular fashion) key in the keyboard. For example, ‘a’ gets replaced with ‘s’, ‘b’ gets replaced with ‘n’, ....., ‘l’ gets replaced with ‘z’, ....., ‘m’ gets replaced with ‘q’.Examples: "
},
{
"code": null,
"e": 430,
"s": 357,
"text": "Input: str = “geeks” Output: hrrldInput: str = “plmabc” Output: azqsnv "
},
{
"code": null,
"e": 729,
"s": 432,
"text": "Approach: For every lowercase character of the English alphabet, insert the character next to it in the keyboard in an unordered_map. Now traverse the given string character by character, and update every character with the map created earlier.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 733,
"s": 729,
"text": "C++"
},
{
"code": null,
"e": 738,
"s": 733,
"text": "Java"
},
{
"code": null,
"e": 746,
"s": 738,
"text": "Python3"
},
{
"code": null,
"e": 749,
"s": 746,
"text": "C#"
},
{
"code": null,
"e": 760,
"s": 749,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; const string CHARS = \"qwertyuiopasdfghjklzxcvbnm\";const int MAX = 26; // Function to return the modified stringstring getString(string str, int n){ // Map to store the next character // on the keyboard for every // possible lowercase character unordered_map<char, char> uMap; for (int i = 0; i < MAX; i++) { uMap[CHARS[i]] = CHARS[(i + 1) % MAX]; } // Update the string for (int i = 0; i < n; i++) { str[i] = uMap[str[i]]; } return str;} // Driver codeint main(){ string str = \"geeks\"; int n = str.length(); cout << getString(str, n); return 0;}",
"e": 1449,
"s": 760,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*; class GFG{ static String CHARS = \"qwertyuiopasdfghjklzxcvbnm\";static int MAX = 26; // Function to return the modified Stringstatic String getString(char[] str, int n){ // Map to store the next character // on the keyboard for every // possible lowercase character Map<Character, Character> uMap = new HashMap<>(); for (int i = 0; i < MAX; i++) { uMap. put(CHARS.charAt(i), CHARS.charAt((i + 1) % MAX)); } // Update the String for (int i = 0; i < n; i++) { str[i] = uMap.get(str[i]); } return String.valueOf(str);} // Driver codepublic static void main(String []args){ String str = \"geeks\"; int n = str.length(); System.out.println(getString(str.toCharArray(), n));}} // This code is contributed by Rajput-Ji",
"e": 2294,
"s": 1449,
"text": null
},
{
"code": "# Python3 implementation of the approach CHARS = \"qwertyuiopasdfghjklzxcvbnm\";MAX = 26; # Function to return the modified stringdef getString(string, n) : string = list(string); # Map to store the next character # on the keyboard for every # possible lowercase character uMap = {}; for i in range(MAX) : uMap[CHARS[i]] = CHARS[(i + 1) % MAX]; # Update the string for i in range(n) : string[i] = uMap[string[i]]; return \"\".join(string); # Driver codeif __name__ == \"__main__\" : string = \"geeks\"; n = len(string); print(getString(string, n)); # This code is contributed by AnkitRai01",
"e": 2957,
"s": 2294,
"text": null
},
{
"code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ static String CHARS = \"qwertyuiopasdfghjklzxcvbnm\";static int MAX = 26; // Function to return the modified Stringstatic String getString(char[] str, int n){ // Map to store the next character // on the keyboard for every // possible lowercase character Dictionary<char, char> uMap = new Dictionary<char, char>(); for (int i = 0; i < MAX; i++) { if(!uMap.ContainsKey(CHARS[i])) uMap.Add(CHARS[i], CHARS[(i + 1) % MAX]); else uMap[CHARS[i]] = CHARS[(i + 1) % MAX]; } // Update the String for (int i = 0; i < n; i++) { str[i] = uMap[str[i]]; } return String.Join(\"\", str);} // Driver codepublic static void Main(String []args){ String str = \"geeks\"; int n = str.Length; Console.WriteLine(getString(str.ToCharArray(), n));}} // This code is contributed by PrinciRaj1992",
"e": 3967,
"s": 2957,
"text": null
},
{
"code": "<script> // JavaScript implementation of the approach var CHARS = \"qwertyuiopasdfghjklzxcvbnm\"; var MAX = 26; // Function to return the modified string function getString(string, n) { var string = string.split(\"\"); // Map to store the next character // on the keyboard for every // possible lowercase character uMap = []; for (let i = 0; i < MAX; i++) { uMap[CHARS[i]] = CHARS[(i + 1) % MAX]; } // Update the string for (let i = 0; i < n; i++) { string[i] = uMap[string[i]]; } return string.join(\"\"); } // Driver code var string = \"geeks\"; var n = string.length; document.write(getString(string, n)); </script>",
"e": 4730,
"s": 3967,
"text": null
},
{
"code": null,
"e": 4736,
"s": 4730,
"text": "hrrld"
},
{
"code": null,
"e": 4746,
"s": 4738,
"text": "ankthon"
},
{
"code": null,
"e": 4756,
"s": 4746,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 4770,
"s": 4756,
"text": "princiraj1992"
},
{
"code": null,
"e": 4777,
"s": 4770,
"text": "rdtank"
},
{
"code": null,
"e": 4784,
"s": 4777,
"text": "Arrays"
},
{
"code": null,
"e": 4793,
"s": 4784,
"text": "Articles"
},
{
"code": null,
"e": 4798,
"s": 4793,
"text": "Hash"
},
{
"code": null,
"e": 4806,
"s": 4798,
"text": "Strings"
},
{
"code": null,
"e": 4813,
"s": 4806,
"text": "Arrays"
},
{
"code": null,
"e": 4818,
"s": 4813,
"text": "Hash"
},
{
"code": null,
"e": 4826,
"s": 4818,
"text": "Strings"
},
{
"code": null,
"e": 4924,
"s": 4826,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5030,
"s": 4924,
"text": "Find the smallest positive integer value that cannot be represented as sum of any subset of a given array"
},
{
"code": null,
"e": 5071,
"s": 5030,
"text": "Find a triplet that sum to a given value"
},
{
"code": null,
"e": 5102,
"s": 5071,
"text": "Product of Array except itself"
},
{
"code": null,
"e": 5143,
"s": 5102,
"text": "Median of two sorted arrays of same size"
},
{
"code": null,
"e": 5197,
"s": 5143,
"text": "Smallest subarray with sum greater than a given value"
},
{
"code": null,
"e": 5247,
"s": 5197,
"text": "Tree Traversals (Inorder, Preorder and Postorder)"
},
{
"code": null,
"e": 5294,
"s": 5247,
"text": "SQL | Join (Inner, Left, Right and Full Joins)"
},
{
"code": null,
"e": 5330,
"s": 5294,
"text": "find command in Linux with examples"
},
{
"code": null,
"e": 5383,
"s": 5330,
"text": "Analysis of Algorithms | Set 1 (Asymptotic Analysis)"
}
]
|
Kivy – Material design Icon button | 24 Feb, 2021
Kivy is a platform-independent GUI tool in Python. It can run on Android, IOS, Linux and Windows, etc. This is the only GUI library from python which can independently run on an android device even we can use it on Raspberry pi also. It is an open-source Python library for rapid development of applications that make use of innovative user interfaces, such as multi-touch apps. Its graphic engine is built over OpenGL ES 2 and has fast graphics pipeline.
In this article, we will develop a GUI window using kivy framework of python, and we will add material design icon buttons of different sizes on this window.
Approach:
Import required modules.
Create an App class.
Add Buttons.
Return layout.
Run an instance of the class.
Implementation:
Python3
# importing mdapp from kivymd frameworkfrom kivymd.app import MDApp # importing builder from kivyfrom kivy.lang import Builder # this is the main class which# will render the whole applicationclass uiApp(MDApp): # method which will render our application def build(self): return Builder.load_string(""" MDBoxLayout: spacing:300 MDIconButton: # name of mdicon icon:"language-python" pos_hint: {"center_x": .5, "center_y": .5} user_font_size: "64sp" # bgcolor of iconbutton md_bg_color:[1,1,0,1] MDIconButton: # custom image as mdicon icon:"gfg.png" pos_hint: {"center_x": .5, "center_y": .5} user_font_size: "16sp" MDIconButton: icon:"language-python" pos_hint: {"center_x": .5, "center_y": .5} """) # running the applicationuiApp().run()
Output:
Python-kivy
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 ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Create a directory in Python | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n24 Feb, 2021"
},
{
"code": null,
"e": 512,
"s": 54,
"text": "Kivy is a platform-independent GUI tool in Python. It can run on Android, IOS, Linux and Windows, etc. This is the only GUI library from python which can independently run on an android device even we can use it on Raspberry pi also. It is an open-source Python library for rapid development of applications that make use of innovative user interfaces, such as multi-touch apps. Its graphic engine is built over OpenGL ES 2 and has fast graphics pipeline. "
},
{
"code": null,
"e": 670,
"s": 512,
"text": "In this article, we will develop a GUI window using kivy framework of python, and we will add material design icon buttons of different sizes on this window."
},
{
"code": null,
"e": 680,
"s": 670,
"text": "Approach:"
},
{
"code": null,
"e": 705,
"s": 680,
"text": "Import required modules."
},
{
"code": null,
"e": 726,
"s": 705,
"text": "Create an App class."
},
{
"code": null,
"e": 739,
"s": 726,
"text": "Add Buttons."
},
{
"code": null,
"e": 754,
"s": 739,
"text": "Return layout."
},
{
"code": null,
"e": 784,
"s": 754,
"text": "Run an instance of the class."
},
{
"code": null,
"e": 818,
"s": 784,
"text": "Implementation: "
},
{
"code": null,
"e": 826,
"s": 818,
"text": "Python3"
},
{
"code": "# importing mdapp from kivymd frameworkfrom kivymd.app import MDApp # importing builder from kivyfrom kivy.lang import Builder # this is the main class which# will render the whole applicationclass uiApp(MDApp): # method which will render our application def build(self): return Builder.load_string(\"\"\" MDBoxLayout: spacing:300 MDIconButton: # name of mdicon icon:\"language-python\" pos_hint: {\"center_x\": .5, \"center_y\": .5} user_font_size: \"64sp\" # bgcolor of iconbutton md_bg_color:[1,1,0,1] MDIconButton: # custom image as mdicon icon:\"gfg.png\" pos_hint: {\"center_x\": .5, \"center_y\": .5} user_font_size: \"16sp\" MDIconButton: icon:\"language-python\" pos_hint: {\"center_x\": .5, \"center_y\": .5} \"\"\") # running the applicationuiApp().run()",
"e": 1854,
"s": 826,
"text": null
},
{
"code": null,
"e": 1862,
"s": 1854,
"text": "Output:"
},
{
"code": null,
"e": 1874,
"s": 1862,
"text": "Python-kivy"
},
{
"code": null,
"e": 1898,
"s": 1874,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 1905,
"s": 1898,
"text": "Python"
},
{
"code": null,
"e": 1924,
"s": 1905,
"text": "Technical Scripter"
},
{
"code": null,
"e": 2022,
"s": 1924,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2054,
"s": 2022,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2081,
"s": 2054,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2102,
"s": 2081,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2125,
"s": 2102,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2181,
"s": 2125,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2212,
"s": 2181,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2254,
"s": 2212,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2296,
"s": 2254,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2335,
"s": 2296,
"text": "Python | Get unique values from a list"
}
]
|
Lodash _.clamp() Method | 09 Sep, 2020
The _.clamp() method is used to clamp number within the inclusive range within the lower and upper bounds.
Syntax:
_.clamp(number, lower, upper)
Parameters: This method accepts three parameters as mentioned above and described below:
number: This parameter holds the number to clamp.
lower: This parameter holds the lower bound.
upper: This parameter holds the upper bound.
Return Value: This method returns the clamped number.
Example 1:
Javascript
// Requiring the lodash library const _ = require("lodash"); // Use of _.clamp method console.log(_.clamp(2, 3, 5)); console.log(_.clamp(2, -2, -5));
Output:
3
-2
Example 2:
Javascript
// Requiring the lodash library const _ = require("lodash"); // Use of _.clamp method console.log(_.clamp(15, -13, 13)); console.log(_.clamp(-15, -13, 13));
Output:
13
-13
JavaScript-Lodash
JavaScript
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": "\n09 Sep, 2020"
},
{
"code": null,
"e": 135,
"s": 28,
"text": "The _.clamp() method is used to clamp number within the inclusive range within the lower and upper bounds."
},
{
"code": null,
"e": 143,
"s": 135,
"text": "Syntax:"
},
{
"code": null,
"e": 174,
"s": 143,
"text": "_.clamp(number, lower, upper)\n"
},
{
"code": null,
"e": 263,
"s": 174,
"text": "Parameters: This method accepts three parameters as mentioned above and described below:"
},
{
"code": null,
"e": 313,
"s": 263,
"text": "number: This parameter holds the number to clamp."
},
{
"code": null,
"e": 358,
"s": 313,
"text": "lower: This parameter holds the lower bound."
},
{
"code": null,
"e": 403,
"s": 358,
"text": "upper: This parameter holds the upper bound."
},
{
"code": null,
"e": 457,
"s": 403,
"text": "Return Value: This method returns the clamped number."
},
{
"code": null,
"e": 468,
"s": 457,
"text": "Example 1:"
},
{
"code": null,
"e": 479,
"s": 468,
"text": "Javascript"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); // Use of _.clamp method console.log(_.clamp(2, 3, 5)); console.log(_.clamp(2, -2, -5)); ",
"e": 634,
"s": 479,
"text": null
},
{
"code": null,
"e": 642,
"s": 634,
"text": "Output:"
},
{
"code": null,
"e": 648,
"s": 642,
"text": "3\n-2\n"
},
{
"code": null,
"e": 661,
"s": 648,
"text": "Example 2: "
},
{
"code": null,
"e": 672,
"s": 661,
"text": "Javascript"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); // Use of _.clamp method console.log(_.clamp(15, -13, 13)); console.log(_.clamp(-15, -13, 13)); ",
"e": 834,
"s": 672,
"text": null
},
{
"code": null,
"e": 842,
"s": 834,
"text": "Output:"
},
{
"code": null,
"e": 850,
"s": 842,
"text": "13\n-13\n"
},
{
"code": null,
"e": 868,
"s": 850,
"text": "JavaScript-Lodash"
},
{
"code": null,
"e": 879,
"s": 868,
"text": "JavaScript"
},
{
"code": null,
"e": 896,
"s": 879,
"text": "Web Technologies"
}
]
|
Print characters having odd frequencies in order of occurrence | 12 May, 2021
Given a string str containing only lowercase characters. The task is to print the characters having an odd frequency in the order of their occurrence.Note: Repeated elements with odd frequency are printed as many times they occur in order of their occurrences.Examples:
Input: str = “geeksforgeeks” Output: for
‘f’, ‘o’ and ‘r’ are the only characters with odd frequencies.Input: str = “elephant” Output: lphant
Approach: Create a frequency array to store the frequency of each of the characters of the given string str. Traverse the string str again and check whether the frequency of that character is odd. If yes, then print the character.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;#define SIZE 26 // Function to print the odd frequency characters// in the order of their occurrencevoid printChar(string str, int n){ // To store the frequency of each of // the character of the string int freq[SIZE]; // Initialize all elements of freq[] to 0 memset(freq, 0, sizeof(freq)); // Update the frequency of each character for (int i = 0; i < n; i++) freq[str[i] - 'a']++; // Traverse str character by character for (int i = 0; i < n; i++) { // If frequency of current character is odd if (freq[str[i] - 'a'] % 2 == 1) { cout << str[i]; } }} // Driver codeint main(){ string str = "geeksforgeeks"; int n = str.length(); printChar(str, n); return 0;}
// Java implementation of the approachclass GFG { // Function to print the odd frequency characters // in the order of their occurrence public static void printChar(String str, int n) { // To store the frequency of each of // the character of the string int[] freq = new int[26]; // Update the frequency of each character for (int i = 0; i < n; i++) freq[str.charAt(i) - 'a']++; // Traverse str character by character for (int i = 0; i < n; i++) { // If frequency of current character is odd if (freq[str.charAt(i) - 'a'] % 2 == 1) { System.out.print(str.charAt(i)); } } } // Driver code public static void main(String[] args) { String str = "geeksforgeeks"; int n = str.length(); printChar(str, n); }} // This code is contributed by Naman_Garg.
# Python3 implementation of the approachimport sysimport math # Function to print the odd frequency characters# in the order of their occurrencedef printChar(str_, n): # To store the frequency of each of # the character of the string and # Initialize all elements of freq[] to 0 freq = [0] * 26 # Update the frequency of each character for i in range(n): freq[ord(str_[i]) - ord('a')] += 1 # Traverse str character by character for i in range(n): # If frequency of current character is odd if (freq[ord(str_[i]) - ord('a')]) % 2 == 1: print("{}".format(str_[i]), end = "") # Driver codeif __name__=='__main__': str_ = "geeksforgeeks" n = len(str_) printChar(str_, n) # This code is contributed by Vikash Kumar 37
// C# implementation of the approachusing System; class GFG { // Function to print the odd frequency characters // in the order of their occurrence public static void printChar(String str, int n) { // To store the frequency of each of // the character of the string int[] freq = new int[26]; // Update the frequency of each character for (int i = 0; i < n; i++) freq[str[i] - 'a']++; // Traverse str character by character for (int i = 0; i < n; i++) { // If frequency of current character is odd if (freq[str[i] - 'a'] % 2 == 1) { Console.Write(str[i]); } } } // Driver code public static void Main(String[] args) { String str = "geeksforgeeks"; int n = str.Length; printChar(str, n); }} // This code has been contributed by 29AjayKumar
<script>// javascript implementation of the approach let SIZE = 26; // Function to print the odd frequency characters// in the order of their occurrencefunction printChar(str, n){ // To store the frequency of each of // the character of the string let freq = []; // Initialize all elements of freq[] to 0 for(let i = 0; i < SIZE; i++){ freq.push(0); } // Update the frequency of each character for (let i = 0; i < n; i++) freq[str.charCodeAt(i) - 97]++; // Traverse str character by character for (let i = 0; i < n; i++) { // If frequency of current character is odd if (freq[str.charCodeAt(i) - 97] % 2 == 1) { document.write(str[i]); } }} let str = "geeksforgeeks";let n = str.length;printChar(str, n); // This code is contributed by rohitsingh07052.</script>
Output:
for
Time Complexity: O(n) Auxiliary Space: O(1)
Approach:
We will scan the string and count the occurrence of all characters using built in Counter() function after that we traverse the counter list and check if the occurrences are odd or not if there is any even frequency character then we immediately print No.
Note: This method is applicable for all type of characters
Below is the implementation of the above approach:
Python3
# importing Counter functionfrom collections import Counter # function to check if all# elements occur odd timesdef checkString(s): # Counting the frequency of all # character using Counter function frequency = Counter(s) # Traversing frequency for i in frequency: # Checking if any element # has even count if (frequency[i] % 2 == 0): return False return True # Driver codes = "gggfffaaa"if(checkString(s)): print("Yes")else: print("No") # This code is contributed by vikkycirus
Output:
Yes
Vikash Kumar 37
Naman_Garg
29AjayKumar
vikkycirus
rohitsingh07052
frequency-counting
Arrays
Hash
Strings
Arrays
Hash
Strings
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
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
What is Hashing | A Complete Tutorial
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Count pairs with given sum | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 May, 2021"
},
{
"code": null,
"e": 299,
"s": 28,
"text": "Given a string str containing only lowercase characters. The task is to print the characters having an odd frequency in the order of their occurrence.Note: Repeated elements with odd frequency are printed as many times they occur in order of their occurrences.Examples: "
},
{
"code": null,
"e": 342,
"s": 299,
"text": "Input: str = “geeksforgeeks” Output: for "
},
{
"code": null,
"e": 444,
"s": 342,
"text": "‘f’, ‘o’ and ‘r’ are the only characters with odd frequencies.Input: str = “elephant” Output: lphant "
},
{
"code": null,
"e": 726,
"s": 444,
"text": "Approach: Create a frequency array to store the frequency of each of the characters of the given string str. Traverse the string str again and check whether the frequency of that character is odd. If yes, then print the character.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 730,
"s": 726,
"text": "C++"
},
{
"code": null,
"e": 735,
"s": 730,
"text": "Java"
},
{
"code": null,
"e": 743,
"s": 735,
"text": "Python3"
},
{
"code": null,
"e": 746,
"s": 743,
"text": "C#"
},
{
"code": null,
"e": 757,
"s": 746,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define SIZE 26 // Function to print the odd frequency characters// in the order of their occurrencevoid printChar(string str, int n){ // To store the frequency of each of // the character of the string int freq[SIZE]; // Initialize all elements of freq[] to 0 memset(freq, 0, sizeof(freq)); // Update the frequency of each character for (int i = 0; i < n; i++) freq[str[i] - 'a']++; // Traverse str character by character for (int i = 0; i < n; i++) { // If frequency of current character is odd if (freq[str[i] - 'a'] % 2 == 1) { cout << str[i]; } }} // Driver codeint main(){ string str = \"geeksforgeeks\"; int n = str.length(); printChar(str, n); return 0;}",
"e": 1586,
"s": 757,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG { // Function to print the odd frequency characters // in the order of their occurrence public static void printChar(String str, int n) { // To store the frequency of each of // the character of the string int[] freq = new int[26]; // Update the frequency of each character for (int i = 0; i < n; i++) freq[str.charAt(i) - 'a']++; // Traverse str character by character for (int i = 0; i < n; i++) { // If frequency of current character is odd if (freq[str.charAt(i) - 'a'] % 2 == 1) { System.out.print(str.charAt(i)); } } } // Driver code public static void main(String[] args) { String str = \"geeksforgeeks\"; int n = str.length(); printChar(str, n); }} // This code is contributed by Naman_Garg.",
"e": 2500,
"s": 1586,
"text": null
},
{
"code": "# Python3 implementation of the approachimport sysimport math # Function to print the odd frequency characters# in the order of their occurrencedef printChar(str_, n): # To store the frequency of each of # the character of the string and # Initialize all elements of freq[] to 0 freq = [0] * 26 # Update the frequency of each character for i in range(n): freq[ord(str_[i]) - ord('a')] += 1 # Traverse str character by character for i in range(n): # If frequency of current character is odd if (freq[ord(str_[i]) - ord('a')]) % 2 == 1: print(\"{}\".format(str_[i]), end = \"\") # Driver codeif __name__=='__main__': str_ = \"geeksforgeeks\" n = len(str_) printChar(str_, n) # This code is contributed by Vikash Kumar 37",
"e": 3302,
"s": 2500,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG { // Function to print the odd frequency characters // in the order of their occurrence public static void printChar(String str, int n) { // To store the frequency of each of // the character of the string int[] freq = new int[26]; // Update the frequency of each character for (int i = 0; i < n; i++) freq[str[i] - 'a']++; // Traverse str character by character for (int i = 0; i < n; i++) { // If frequency of current character is odd if (freq[str[i] - 'a'] % 2 == 1) { Console.Write(str[i]); } } } // Driver code public static void Main(String[] args) { String str = \"geeksforgeeks\"; int n = str.Length; printChar(str, n); }} // This code has been contributed by 29AjayKumar",
"e": 4208,
"s": 3302,
"text": null
},
{
"code": "<script>// javascript implementation of the approach let SIZE = 26; // Function to print the odd frequency characters// in the order of their occurrencefunction printChar(str, n){ // To store the frequency of each of // the character of the string let freq = []; // Initialize all elements of freq[] to 0 for(let i = 0; i < SIZE; i++){ freq.push(0); } // Update the frequency of each character for (let i = 0; i < n; i++) freq[str.charCodeAt(i) - 97]++; // Traverse str character by character for (let i = 0; i < n; i++) { // If frequency of current character is odd if (freq[str.charCodeAt(i) - 97] % 2 == 1) { document.write(str[i]); } }} let str = \"geeksforgeeks\";let n = str.length;printChar(str, n); // This code is contributed by rohitsingh07052.</script>",
"e": 5053,
"s": 4208,
"text": null
},
{
"code": null,
"e": 5062,
"s": 5053,
"text": "Output: "
},
{
"code": null,
"e": 5066,
"s": 5062,
"text": "for"
},
{
"code": null,
"e": 5111,
"s": 5066,
"text": "Time Complexity: O(n) Auxiliary Space: O(1) "
},
{
"code": null,
"e": 5121,
"s": 5111,
"text": "Approach:"
},
{
"code": null,
"e": 5380,
"s": 5121,
"text": "We will scan the string and count the occurrence of all characters using built in Counter() function after that we traverse the counter list and check if the occurrences are odd or not if there is any even frequency character then we immediately print No."
},
{
"code": null,
"e": 5439,
"s": 5380,
"text": "Note: This method is applicable for all type of characters"
},
{
"code": null,
"e": 5490,
"s": 5439,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 5498,
"s": 5490,
"text": "Python3"
},
{
"code": "# importing Counter functionfrom collections import Counter # function to check if all# elements occur odd timesdef checkString(s): # Counting the frequency of all # character using Counter function frequency = Counter(s) # Traversing frequency for i in frequency: # Checking if any element # has even count if (frequency[i] % 2 == 0): return False return True # Driver codes = \"gggfffaaa\"if(checkString(s)): print(\"Yes\")else: print(\"No\") # This code is contributed by vikkycirus",
"e": 6054,
"s": 5498,
"text": null
},
{
"code": null,
"e": 6062,
"s": 6054,
"text": "Output:"
},
{
"code": null,
"e": 6066,
"s": 6062,
"text": "Yes"
},
{
"code": null,
"e": 6082,
"s": 6066,
"text": "Vikash Kumar 37"
},
{
"code": null,
"e": 6093,
"s": 6082,
"text": "Naman_Garg"
},
{
"code": null,
"e": 6105,
"s": 6093,
"text": "29AjayKumar"
},
{
"code": null,
"e": 6116,
"s": 6105,
"text": "vikkycirus"
},
{
"code": null,
"e": 6132,
"s": 6116,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 6151,
"s": 6132,
"text": "frequency-counting"
},
{
"code": null,
"e": 6158,
"s": 6151,
"text": "Arrays"
},
{
"code": null,
"e": 6163,
"s": 6158,
"text": "Hash"
},
{
"code": null,
"e": 6171,
"s": 6163,
"text": "Strings"
},
{
"code": null,
"e": 6178,
"s": 6171,
"text": "Arrays"
},
{
"code": null,
"e": 6183,
"s": 6178,
"text": "Hash"
},
{
"code": null,
"e": 6191,
"s": 6183,
"text": "Strings"
},
{
"code": null,
"e": 6289,
"s": 6191,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6357,
"s": 6289,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 6401,
"s": 6357,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 6433,
"s": 6401,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 6481,
"s": 6433,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 6495,
"s": 6481,
"text": "Linear Search"
},
{
"code": null,
"e": 6580,
"s": 6495,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 6618,
"s": 6580,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 6654,
"s": 6618,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 6685,
"s": 6654,
"text": "Hashing | Set 1 (Introduction)"
}
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.