title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Everything you need to know about Min-Max normalization: A Python tutorial | by Serafeim Loukas | Towards Data Science
This is my second post about the normalization techniques that are often used prior to machine learning (ML) model fitting. In my first post, I covered the Standardization technique using scikit-learn’s StandardScaler function. If you are not familiar with the standardization technique, you can learn the essentials in only 3 min by clicking here. In the present post, I will explain the second most famous normalization method i.e. Min-Max Scaling using scikit-learn (function name: MinMaxScaler ). Another way to normalize the input features/variables (apart from the standardization that scales the features so that they have μ=0and σ=1) is the Min-Max scaler. By doing so, all features will be transformed into the range [0,1] meaning that the minimum and maximum value of a feature/variable is going to be 0 and 1, respectively. The main idea behind normalization/standardization is always the same. Variables that are measured at different scales do not contribute equally to the model fitting & model learned function and might end up creating a bias. Thus, to deal with this potential problem feature-wise normalization such as MinMax Scaling is usually used prior to model fitting. This can be very useful for some ML models like the Multi-layer Perceptrons (MLP), where the back-propagation can be more stable and even faster when input features are min-max scaled (or in general scaled) compared to using the original unscaled data. Note: Tree-based models are usually not dependent on scaling, but non-tree models models such as SVM, LDA etc. are often hugely dependent on it. Here we will use the famous iris dataset that is available through scikit-learn. Reminder: scikit-learn functions expect as input a numpy array X with dimension [samples, features/variables] . from sklearn.datasets import load_irisfrom sklearn.preprocessing import MinMaxScalerimport numpy as np# use the iris datasetX, y = load_iris(return_X_y=True)print(X.shape)# (150, 4) # 150 samples (rows) with 4 features/variables (columns)# build the scaler modelscaler = MinMaxScaler()# fit using the train setscaler.fit(X)# transform the test testX_scaled = scaler.transform(X)# Verify minimum value of all featuresX_scaled.min(axis=0)# array([0., 0., 0., 0.])# Verify maximum value of all featuresX_scaled.max(axis=0)# array([1., 1., 1., 1.])# Manually normalise without using scikit-learnX_manual_scaled = (X — X.min(axis=0)) / (X.max(axis=0) — X.min(axis=0))# Verify manually VS scikit-learn estimationprint(np.allclose(X_scaled, X_manual_scaled))#True import matplotlib.pyplot as pltfig, axes = plt.subplots(1,2)axes[0].scatter(X[:,0], X[:,1], c=y)axes[0].set_title("Original data")axes[1].scatter(X_scaled[:,0], X_scaled[:,1], c=y)axes[1].set_title("MinMax scaled data")plt.show() It is obvious that the values of the features are within the range [0,1] following the Min-Max scaling (right plot). One important thing to keep in mind when using the MinMax Scaling is that it is highly influenced by the maximum and minimum values in our data so if our data contains outliers it is going to be biased. MinMaxScaler rescales the data set such that all feature values are in the range [0, 1]. This is done feature-wise in an independent way. The MinMaxScaler scaling might compress all inliers in a narrow range. Manual way (not recommended): Visually inspect the data and remove outliers using outlier removal statistical methods. Recommended way: Use the RobustScaler that will just scale the features but in this case using statistics that are robust to outliers. This scaler removes the median and scales the data according to the quantile range (defaults to IQR: Interquartile Range). The IQR is the range between the 1st quartile (25th quantile) and the 3rd quartile (75th quantile). That’s all for today! Hope you liked this first post! Next story coming next week. Stay tuned & safe. - My mailing list in just 5 seconds: https://seralouk.medium.com/subscribe - Become a member and support me:https://seralouk.medium.com/membership towardsdatascience.com towardsdatascience.com towardsdatascience.com towardsdatascience.com If you liked and found this article useful, follow me and applaud my story to support me! See all scikit-learn normalization methods side-by-side here: https://scikit-learn.org/stable/auto_examples/preprocessing/plot_all_scaling.html [1] https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MinMaxScaler.html [2] https://scikit-learn.org/stable/auto_examples/preprocessing/plot_all_scaling.html [3] https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.RobustScaler.html LinkedIn: https://www.linkedin.com/in/serafeim-loukas/ ResearchGate: https://www.researchgate.net/profile/Serafeim_Loukas EPFL profile: https://people.epfl.ch/serafeim.loukas Stack Overflow: https://stackoverflow.com/users/5025009/seralouk
[ { "code": null, "e": 521, "s": 172, "text": "This is my second post about the normalization techniques that are often used prior to machine learning (ML) model fitting. In my first post, I covered the Standardization technique using scikit-learn’s StandardScaler function. If you are not familiar with the standardization technique, you can learn the essentials in only 3 min by clicking here." }, { "code": null, "e": 673, "s": 521, "text": "In the present post, I will explain the second most famous normalization method i.e. Min-Max Scaling using scikit-learn (function name: MinMaxScaler )." }, { "code": null, "e": 1007, "s": 673, "text": "Another way to normalize the input features/variables (apart from the standardization that scales the features so that they have μ=0and σ=1) is the Min-Max scaler. By doing so, all features will be transformed into the range [0,1] meaning that the minimum and maximum value of a feature/variable is going to be 0 and 1, respectively." }, { "code": null, "e": 1364, "s": 1007, "text": "The main idea behind normalization/standardization is always the same. Variables that are measured at different scales do not contribute equally to the model fitting & model learned function and might end up creating a bias. Thus, to deal with this potential problem feature-wise normalization such as MinMax Scaling is usually used prior to model fitting." }, { "code": null, "e": 1617, "s": 1364, "text": "This can be very useful for some ML models like the Multi-layer Perceptrons (MLP), where the back-propagation can be more stable and even faster when input features are min-max scaled (or in general scaled) compared to using the original unscaled data." }, { "code": null, "e": 1762, "s": 1617, "text": "Note: Tree-based models are usually not dependent on scaling, but non-tree models models such as SVM, LDA etc. are often hugely dependent on it." }, { "code": null, "e": 1843, "s": 1762, "text": "Here we will use the famous iris dataset that is available through scikit-learn." }, { "code": null, "e": 1955, "s": 1843, "text": "Reminder: scikit-learn functions expect as input a numpy array X with dimension [samples, features/variables] ." }, { "code": null, "e": 2712, "s": 1955, "text": "from sklearn.datasets import load_irisfrom sklearn.preprocessing import MinMaxScalerimport numpy as np# use the iris datasetX, y = load_iris(return_X_y=True)print(X.shape)# (150, 4) # 150 samples (rows) with 4 features/variables (columns)# build the scaler modelscaler = MinMaxScaler()# fit using the train setscaler.fit(X)# transform the test testX_scaled = scaler.transform(X)# Verify minimum value of all featuresX_scaled.min(axis=0)# array([0., 0., 0., 0.])# Verify maximum value of all featuresX_scaled.max(axis=0)# array([1., 1., 1., 1.])# Manually normalise without using scikit-learnX_manual_scaled = (X — X.min(axis=0)) / (X.max(axis=0) — X.min(axis=0))# Verify manually VS scikit-learn estimationprint(np.allclose(X_scaled, X_manual_scaled))#True" }, { "code": null, "e": 2942, "s": 2712, "text": "import matplotlib.pyplot as pltfig, axes = plt.subplots(1,2)axes[0].scatter(X[:,0], X[:,1], c=y)axes[0].set_title(\"Original data\")axes[1].scatter(X_scaled[:,0], X_scaled[:,1], c=y)axes[1].set_title(\"MinMax scaled data\")plt.show()" }, { "code": null, "e": 3059, "s": 2942, "text": "It is obvious that the values of the features are within the range [0,1] following the Min-Max scaling (right plot)." }, { "code": null, "e": 3262, "s": 3059, "text": "One important thing to keep in mind when using the MinMax Scaling is that it is highly influenced by the maximum and minimum values in our data so if our data contains outliers it is going to be biased." }, { "code": null, "e": 3400, "s": 3262, "text": "MinMaxScaler rescales the data set such that all feature values are in the range [0, 1]. This is done feature-wise in an independent way." }, { "code": null, "e": 3471, "s": 3400, "text": "The MinMaxScaler scaling might compress all inliers in a narrow range." }, { "code": null, "e": 3590, "s": 3471, "text": "Manual way (not recommended): Visually inspect the data and remove outliers using outlier removal statistical methods." }, { "code": null, "e": 3948, "s": 3590, "text": "Recommended way: Use the RobustScaler that will just scale the features but in this case using statistics that are robust to outliers. This scaler removes the median and scales the data according to the quantile range (defaults to IQR: Interquartile Range). The IQR is the range between the 1st quartile (25th quantile) and the 3rd quartile (75th quantile)." }, { "code": null, "e": 4050, "s": 3948, "text": "That’s all for today! Hope you liked this first post! Next story coming next week. Stay tuned & safe." }, { "code": null, "e": 4125, "s": 4050, "text": "- My mailing list in just 5 seconds: https://seralouk.medium.com/subscribe" }, { "code": null, "e": 4197, "s": 4125, "text": "- Become a member and support me:https://seralouk.medium.com/membership" }, { "code": null, "e": 4220, "s": 4197, "text": "towardsdatascience.com" }, { "code": null, "e": 4243, "s": 4220, "text": "towardsdatascience.com" }, { "code": null, "e": 4266, "s": 4243, "text": "towardsdatascience.com" }, { "code": null, "e": 4289, "s": 4266, "text": "towardsdatascience.com" }, { "code": null, "e": 4379, "s": 4289, "text": "If you liked and found this article useful, follow me and applaud my story to support me!" }, { "code": null, "e": 4523, "s": 4379, "text": "See all scikit-learn normalization methods side-by-side here: https://scikit-learn.org/stable/auto_examples/preprocessing/plot_all_scaling.html" }, { "code": null, "e": 4617, "s": 4523, "text": "[1] https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MinMaxScaler.html" }, { "code": null, "e": 4703, "s": 4617, "text": "[2] https://scikit-learn.org/stable/auto_examples/preprocessing/plot_all_scaling.html" }, { "code": null, "e": 4797, "s": 4703, "text": "[3] https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.RobustScaler.html" }, { "code": null, "e": 4852, "s": 4797, "text": "LinkedIn: https://www.linkedin.com/in/serafeim-loukas/" }, { "code": null, "e": 4919, "s": 4852, "text": "ResearchGate: https://www.researchgate.net/profile/Serafeim_Loukas" }, { "code": null, "e": 4972, "s": 4919, "text": "EPFL profile: https://people.epfl.ch/serafeim.loukas" } ]
To understand LSTM architecture, code a forward pass with just NumPy | by Greg Condit | Towards Data Science
If you’re like me, you learn best by starting simple and building from the ground up. No matter how often I read colah’s famous LSTM post, or Karpathy’s post on RNNs (great resources!), the LSTM network architecture seemed overly complicated and the gates were hazy. Eventually, I wrote an LSTM forward pass with just NumPy. I highly recommend doing this exercise, because you can examine the hidden and cell states, inputs and outputs, and clearly see how they were created. In this walkthrough, we will: Represent each of the LSTM gates with its own distinct Python functionChain them together logically to create a NumPy Network with a single LSTM cell Represent each of the LSTM gates with its own distinct Python function Chain them together logically to create a NumPy Network with a single LSTM cell Here’s the point: these functions can be edited to include print statements, which allows examination of the shapes of your data, the hidden state (short term memory), and the cell state (long term memory) at various stages throughout the LSTM cell. This will help you understand why the gates exist. Secondly, to confirm we’ve done it right, we will: Set up a small Neural Network with a single LSTM cell using PyTorchInitialize both networks with the same, random weightsMake 1 forward pass with both networks, and check that the output is the same Set up a small Neural Network with a single LSTM cell using PyTorch Initialize both networks with the same, random weights Make 1 forward pass with both networks, and check that the output is the same Let’s go! Below is the LSTM Reference Card. It contains the Python functions, as well as an important diagram. On this diagram can be found every individual operation and variable (inputs, weights, states) from the LSTM gate functions. They are color-coded to match the gate they belong to. The code for the functions can be copied below the card. I highly recommend saving this reference card, and using this to analyze and understand LSTM architecture. (A printable pdf version is available for download here.) Here’s the copy-able code from the above reference card — one function for each gate: Typically, an LSTM feeds a final, fully-connected linear layer. Let’s do that as well: Create a PyTorch LSTM with the same parameters. PyTorch will automatically assign the weights with random values — we’ll extract those and use them to initialize our NumPy network as well. OrderedDict([ ('lstm.weight_ih_l0', tensor([[ 0.3813, -0.4317], [ 0.4705, 0.3694], [ 0.4851, -0.4427], [-0.3875, 0.2747], [-0.5389, 0.5706], [ 0.1229, 0.0746], [-0.4937, 0.1840], [ 0.2483, 0.0916], [ 0.5553, 0.1734], [-0.5120, 0.4851], [ 0.1960, -0.2754], [-0.5303, 0.3291]])), ('lstm.weight_hh_l0', tensor([[ 0.5487, -0.4730, 0.0316], [ 0.2071, -0.2726, -0.1263], [-0.3855, -0.2730, -0.5264], [-0.0134, 0.3423, 0.2808], [ 0.5424, -0.5071, -0.0710], [ 0.5621, 0.0945, -0.1628], [-0.5200, 0.2687, 0.4383], [ 0.4630, 0.4833, 0.1130], [ 0.4115, -0.1453, 0.4689], [-0.0494, -0.1191, -0.2870], [ 0.3074, 0.2336, 0.3672], [-0.3690, -0.3070, 0.5464]])), ('lstm.bias_ih_l0', tensor([-0.3205, -0.3293, -0.1545, -0.1866, -0.3926, 0.4666, 0.0644, 0.2632, 0.4282, -0.3741, 0.4407, -0.2892])), ('lstm.bias_hh_l0', tensor([-0.0919, 0.4369, 0.5323, 0.5068, 0.3320, 0.5366, -0.2080, -0.0367, -0.1975, -0.0424, -0.0702, 0.3085])), ('fc.weight', tensor([[ 0.3968, -0.4158, -0.3188]])), ('fc.bias', tensor([-0.1776])) ]) Don’t get overwhelmed! The PyTorch documentation explains all we need to break this down: The weights for each gate in are in this order: ignore, forget, learn, output keys with ‘ih’ in the name are the weights/biases for the input, or Wx_ and Bx_ keys with ‘hh’ in the name are the weights/biases for the hidden state, or Wh_ and Bh_ Given the parameters we chose, we can therefore extract the weights for the NumPy LSTM to use in this way: Now, we have two networks — one in PyTorch, one in NumPy — with access to the same starting weights. We’ll put some time series data through each to ensure they are identical. To do a forward pass with our network, we’ll pass the data into the LSTM gates in sequence, and print the output after each event: Good News! Putting the same data through the PyTorch model shows that we return identical output: We can additionally verify that after the data has gone through the LSTM cells, the two models have the same hidden and cell states: I hope this helps build an intuition for how LSTM networks make predictions! You can copy the whole code at once from this gist. The LSTM Reference Card can be downloaded from this page, including printable versions. Thanks to Mike Ricos for collaborating on the creation of this great resource.
[ { "code": null, "e": 439, "s": 172, "text": "If you’re like me, you learn best by starting simple and building from the ground up. No matter how often I read colah’s famous LSTM post, or Karpathy’s post on RNNs (great resources!), the LSTM network architecture seemed overly complicated and the gates were hazy." }, { "code": null, "e": 648, "s": 439, "text": "Eventually, I wrote an LSTM forward pass with just NumPy. I highly recommend doing this exercise, because you can examine the hidden and cell states, inputs and outputs, and clearly see how they were created." }, { "code": null, "e": 678, "s": 648, "text": "In this walkthrough, we will:" }, { "code": null, "e": 828, "s": 678, "text": "Represent each of the LSTM gates with its own distinct Python functionChain them together logically to create a NumPy Network with a single LSTM cell" }, { "code": null, "e": 899, "s": 828, "text": "Represent each of the LSTM gates with its own distinct Python function" }, { "code": null, "e": 979, "s": 899, "text": "Chain them together logically to create a NumPy Network with a single LSTM cell" }, { "code": null, "e": 1280, "s": 979, "text": "Here’s the point: these functions can be edited to include print statements, which allows examination of the shapes of your data, the hidden state (short term memory), and the cell state (long term memory) at various stages throughout the LSTM cell. This will help you understand why the gates exist." }, { "code": null, "e": 1331, "s": 1280, "text": "Secondly, to confirm we’ve done it right, we will:" }, { "code": null, "e": 1530, "s": 1331, "text": "Set up a small Neural Network with a single LSTM cell using PyTorchInitialize both networks with the same, random weightsMake 1 forward pass with both networks, and check that the output is the same" }, { "code": null, "e": 1598, "s": 1530, "text": "Set up a small Neural Network with a single LSTM cell using PyTorch" }, { "code": null, "e": 1653, "s": 1598, "text": "Initialize both networks with the same, random weights" }, { "code": null, "e": 1731, "s": 1653, "text": "Make 1 forward pass with both networks, and check that the output is the same" }, { "code": null, "e": 1741, "s": 1731, "text": "Let’s go!" }, { "code": null, "e": 2022, "s": 1741, "text": "Below is the LSTM Reference Card. It contains the Python functions, as well as an important diagram. On this diagram can be found every individual operation and variable (inputs, weights, states) from the LSTM gate functions. They are color-coded to match the gate they belong to." }, { "code": null, "e": 2244, "s": 2022, "text": "The code for the functions can be copied below the card. I highly recommend saving this reference card, and using this to analyze and understand LSTM architecture. (A printable pdf version is available for download here.)" }, { "code": null, "e": 2330, "s": 2244, "text": "Here’s the copy-able code from the above reference card — one function for each gate:" }, { "code": null, "e": 2417, "s": 2330, "text": "Typically, an LSTM feeds a final, fully-connected linear layer. Let’s do that as well:" }, { "code": null, "e": 2606, "s": 2417, "text": "Create a PyTorch LSTM with the same parameters. PyTorch will automatically assign the weights with random values — we’ll extract those and use them to initialize our NumPy network as well." }, { "code": null, "e": 4477, "s": 2606, "text": "OrderedDict([\n ('lstm.weight_ih_l0', tensor([[ 0.3813, -0.4317],\n [ 0.4705, 0.3694],\n [ 0.4851, -0.4427],\n [-0.3875, 0.2747],\n [-0.5389, 0.5706],\n [ 0.1229, 0.0746],\n [-0.4937, 0.1840],\n [ 0.2483, 0.0916],\n [ 0.5553, 0.1734],\n [-0.5120, 0.4851],\n [ 0.1960, -0.2754],\n [-0.5303, 0.3291]])),\n ('lstm.weight_hh_l0', tensor([[ 0.5487, -0.4730, 0.0316],\n [ 0.2071, -0.2726, -0.1263],\n [-0.3855, -0.2730, -0.5264],\n [-0.0134, 0.3423, 0.2808],\n [ 0.5424, -0.5071, -0.0710],\n [ 0.5621, 0.0945, -0.1628],\n [-0.5200, 0.2687, 0.4383],\n [ 0.4630, 0.4833, 0.1130],\n [ 0.4115, -0.1453, 0.4689],\n [-0.0494, -0.1191, -0.2870],\n [ 0.3074, 0.2336, 0.3672],\n [-0.3690, -0.3070, 0.5464]])),\n ('lstm.bias_ih_l0', tensor([-0.3205, -0.3293, -0.1545, -0.1866,\n -0.3926, 0.4666, 0.0644, 0.2632,\n 0.4282, -0.3741, 0.4407, -0.2892])),\n ('lstm.bias_hh_l0', tensor([-0.0919, 0.4369, 0.5323, 0.5068,\n 0.3320, 0.5366, -0.2080, -0.0367,\n -0.1975, -0.0424, -0.0702, 0.3085])),\n ('fc.weight', tensor([[ 0.3968, -0.4158, -0.3188]])),\n ('fc.bias', tensor([-0.1776]))\n])\n" }, { "code": null, "e": 4567, "s": 4477, "text": "Don’t get overwhelmed! The PyTorch documentation explains all we need to break this down:" }, { "code": null, "e": 4645, "s": 4567, "text": "The weights for each gate in are in this order: ignore, forget, learn, output" }, { "code": null, "e": 4725, "s": 4645, "text": "keys with ‘ih’ in the name are the weights/biases for the input, or Wx_ and Bx_" }, { "code": null, "e": 4812, "s": 4725, "text": "keys with ‘hh’ in the name are the weights/biases for the hidden state, or Wh_ and Bh_" }, { "code": null, "e": 4919, "s": 4812, "text": "Given the parameters we chose, we can therefore extract the weights for the NumPy LSTM to use in this way:" }, { "code": null, "e": 5226, "s": 4919, "text": "Now, we have two networks — one in PyTorch, one in NumPy — with access to the same starting weights. We’ll put some time series data through each to ensure they are identical. To do a forward pass with our network, we’ll pass the data into the LSTM gates in sequence, and print the output after each event:" }, { "code": null, "e": 5324, "s": 5226, "text": "Good News! Putting the same data through the PyTorch model shows that we return identical output:" }, { "code": null, "e": 5457, "s": 5324, "text": "We can additionally verify that after the data has gone through the LSTM cells, the two models have the same hidden and cell states:" }, { "code": null, "e": 5586, "s": 5457, "text": "I hope this helps build an intuition for how LSTM networks make predictions! You can copy the whole code at once from this gist." } ]
How to convert a JavaScript array to C# array?
Let us say our JavaScript array is − <script> var myArr = new Array(5); myArr[0] = "Welcome"; myArr[1] = "to"; myArr[2] = "the"; myArr[3] = "Web"; myArr[4] = "World"; </script> Now, convert the array into a string using comma as a separator − document.getElementById('demo1').value = myArr.join(','); Now, take this to C# − string[] str = demo.Split(",".ToCharArray()); The above converts the JavaScript array to C#.
[ { "code": null, "e": 1099, "s": 1062, "text": "Let us say our JavaScript array is −" }, { "code": null, "e": 1257, "s": 1099, "text": "<script>\n var myArr = new Array(5);\n myArr[0] = \"Welcome\";\n myArr[1] = \"to\";\n myArr[2] = \"the\";\n myArr[3] = \"Web\";\n myArr[4] = \"World\";\n</script>" }, { "code": null, "e": 1323, "s": 1257, "text": "Now, convert the array into a string using comma as a separator −" }, { "code": null, "e": 1381, "s": 1323, "text": "document.getElementById('demo1').value = myArr.join(',');" }, { "code": null, "e": 1404, "s": 1381, "text": "Now, take this to C# −" }, { "code": null, "e": 1450, "s": 1404, "text": "string[] str = demo.Split(\",\".ToCharArray());" }, { "code": null, "e": 1497, "s": 1450, "text": "The above converts the JavaScript array to C#." } ]
Explainable Artificial Intelligence (XAI). But, for Whom? | by Carlos Mougan | Towards Data Science
Attempting to explain predictions or build interpretable machine learning models is a hot topic that is quickly expanding. When applying Machine Learning in the decision process in many areas such as medicine, nuclear energy, terrorism, healthcare, or finance, one cannot blindly trust the predictions and leave the algorithm “in the wild,” as that might have disastrous consequences. Predictive performance of models is evaluated through a wide portfolio of metrics such as accuracy, recall, F1, AUC, RMSE, MAPE... but high predictive performance might not be the only requirement. There is a huge trend in the field of Explainable AI and Interpretable ML to build trust in the predictions of the model. Many papers, blogs, and software tools present explainability and interpretability in a very defined way, but... Accountability for whom? Explainability for whom? I guess that we can all agree on the fact that we don't all need the same type of explanation for how a model behaves. Artificial Intelligence experts such as Andrew NG, Geoffrey Hinton, Ian Goodfellow... won't need the same explanations of why a model is doing what and for which reason, compared to the average data scientist. Moreover, the layperson user probably needs a completely different explanation since they probably have no knowledge of the AI field (nor do they probably wants to). So, explanations in Artificial Intelligence have different audiences. Andrew NG and a randomly selected user of the Netflix recommendation system have different needs of understanding “why was this TV series recommended?” A random user might find it sufficient to get suggested a certain action movie because they have been watching action movies every night for the last two weeks, but then Andrew NG (replace name with any other famous AI person) might require a different type of explanation. Machine Learning explanations are done for a specific audience. Current xAI trends seem to be building explanations that are made for Data Scientists that have a good knowledge of Machine Learning... But should xAI focus on explaining AI to the Data Scientist or to average users? One typical error in software development is that developers end up developing software for themselves and it turns out to be poorly designed for their target audience [3]. Explainable AI might risk a similar fate as poor software development. Explanations of AI might be developed for data scientists and machine learning researchers themselves and not for the everyday user. One technique that has proved useful is the usage of Local Surrogate models. Probably the most famous is Local Interpretable Model-agnostic Explanations (LIME). The idea is quite simple: the goal is to understand why the machine learning model made an individual prediction; this is called individual explanations. LIME tests what happens to the predictions when you give variations of your data into the machine learning model [5]. In the figure below we can see a local approximation to a certain instance of the well-known wine quality dataset. No matter what the original model is (model agnostic), we can make a local approximation to see which features contribute and for how much. With this local approximation, we have a linear model that works well just for this data instance. We have perturbed the input data space, defined a local approximation, and fitted a model there. To whom can we explain this? Someone can say that this explanation is intuitive for them since it’s built as a linear model estimator with few features. The contribution of each feature is linear. One could even argue that this kind of explanation will be good for a person that has a bit of knowledge in the field, but no previous experience in ML. Also, this can be useful to a Data Scientist that has no time and is going fast through the same interpretations samples for some reason, so a Data Scientist with no time. But, what are we really doing? Are we using a black-box explainer to predict a black-box algorithm? Only a fraction of the Data Scientists are able to actually understand how a Random Forest or Gradient Boosted Decision Tree behaves, but the fraction of Data Scientists who actually know what LIME does exactly when built out of a Random Forest is even smaller. What is being represented in the LIME local explanation graph? How stable is this explanation? What about its contestability? Even though the rise of the interest in explainable AI is evolving really fast, some questions remain. For whom are we building the explanations? Are we targeting researchers/data scientists? Or are we targeting the general audience? This blog is a scientific divulgation from the following published paper(link) at the ECMLPKDD workshop on Bias. Please, cite as: @misc{mougan2021desiderataECB, title={Desiderata for Explainable AI in statistical production systems of the European Central Bank}, author={Carlos Mougan Navarro and Georgios Kanellos and Thomas Gottron}, year={2021}, eprint={2107.08045}, archivePrefix={arXiv}, primaryClass={cs.CY}} 1- Desiderata for Explainable AI in statistical production systems of the European Central Bank 2- May Edition: Questions on Explainable AI 3- Explainable AI: Beware of Inmates Running the Asylum Or: How I Learnt to Stop Worrying and Love the Social and Behavioural Sciences 4- Stop explaining black box machine learning models for high stakes decisions and use interpretable models instead 5- “Why Should I Trust You?”: Explaining the Predictions of Any Classifier 6- Explanation in Artificial Intelligence: Insights from the Social Sciences 7- Interpretable Machine Learning: A Guide for Making Black Box Models Explainable. Many thanks to Laura State and Xuan Zhao for the input and discussions. European Commission, NoBIAS — H2020-MSCA-ITN-2019 project GA No860630.
[ { "code": null, "e": 556, "s": 171, "text": "Attempting to explain predictions or build interpretable machine learning models is a hot topic that is quickly expanding. When applying Machine Learning in the decision process in many areas such as medicine, nuclear energy, terrorism, healthcare, or finance, one cannot blindly trust the predictions and leave the algorithm “in the wild,” as that might have disastrous consequences." }, { "code": null, "e": 754, "s": 556, "text": "Predictive performance of models is evaluated through a wide portfolio of metrics such as accuracy, recall, F1, AUC, RMSE, MAPE... but high predictive performance might not be the only requirement." }, { "code": null, "e": 989, "s": 754, "text": "There is a huge trend in the field of Explainable AI and Interpretable ML to build trust in the predictions of the model. Many papers, blogs, and software tools present explainability and interpretability in a very defined way, but..." }, { "code": null, "e": 1039, "s": 989, "text": "Accountability for whom? Explainability for whom?" }, { "code": null, "e": 1534, "s": 1039, "text": "I guess that we can all agree on the fact that we don't all need the same type of explanation for how a model behaves. Artificial Intelligence experts such as Andrew NG, Geoffrey Hinton, Ian Goodfellow... won't need the same explanations of why a model is doing what and for which reason, compared to the average data scientist. Moreover, the layperson user probably needs a completely different explanation since they probably have no knowledge of the AI field (nor do they probably wants to)." }, { "code": null, "e": 1604, "s": 1534, "text": "So, explanations in Artificial Intelligence have different audiences." }, { "code": null, "e": 2030, "s": 1604, "text": "Andrew NG and a randomly selected user of the Netflix recommendation system have different needs of understanding “why was this TV series recommended?” A random user might find it sufficient to get suggested a certain action movie because they have been watching action movies every night for the last two weeks, but then Andrew NG (replace name with any other famous AI person) might require a different type of explanation." }, { "code": null, "e": 2311, "s": 2030, "text": "Machine Learning explanations are done for a specific audience. Current xAI trends seem to be building explanations that are made for Data Scientists that have a good knowledge of Machine Learning... But should xAI focus on explaining AI to the Data Scientist or to average users?" }, { "code": null, "e": 2484, "s": 2311, "text": "One typical error in software development is that developers end up developing software for themselves and it turns out to be poorly designed for their target audience [3]." }, { "code": null, "e": 2688, "s": 2484, "text": "Explainable AI might risk a similar fate as poor software development. Explanations of AI might be developed for data scientists and machine learning researchers themselves and not for the everyday user." }, { "code": null, "e": 3121, "s": 2688, "text": "One technique that has proved useful is the usage of Local Surrogate models. Probably the most famous is Local Interpretable Model-agnostic Explanations (LIME). The idea is quite simple: the goal is to understand why the machine learning model made an individual prediction; this is called individual explanations. LIME tests what happens to the predictions when you give variations of your data into the machine learning model [5]." }, { "code": null, "e": 3376, "s": 3121, "text": "In the figure below we can see a local approximation to a certain instance of the well-known wine quality dataset. No matter what the original model is (model agnostic), we can make a local approximation to see which features contribute and for how much." }, { "code": null, "e": 3572, "s": 3376, "text": "With this local approximation, we have a linear model that works well just for this data instance. We have perturbed the input data space, defined a local approximation, and fitted a model there." }, { "code": null, "e": 3601, "s": 3572, "text": "To whom can we explain this?" }, { "code": null, "e": 4094, "s": 3601, "text": "Someone can say that this explanation is intuitive for them since it’s built as a linear model estimator with few features. The contribution of each feature is linear. One could even argue that this kind of explanation will be good for a person that has a bit of knowledge in the field, but no previous experience in ML. Also, this can be useful to a Data Scientist that has no time and is going fast through the same interpretations samples for some reason, so a Data Scientist with no time." }, { "code": null, "e": 4582, "s": 4094, "text": "But, what are we really doing? Are we using a black-box explainer to predict a black-box algorithm? Only a fraction of the Data Scientists are able to actually understand how a Random Forest or Gradient Boosted Decision Tree behaves, but the fraction of Data Scientists who actually know what LIME does exactly when built out of a Random Forest is even smaller. What is being represented in the LIME local explanation graph? How stable is this explanation? What about its contestability?" }, { "code": null, "e": 4816, "s": 4582, "text": "Even though the rise of the interest in explainable AI is evolving really fast, some questions remain. For whom are we building the explanations? Are we targeting researchers/data scientists? Or are we targeting the general audience?" }, { "code": null, "e": 4946, "s": 4816, "text": "This blog is a scientific divulgation from the following published paper(link) at the ECMLPKDD workshop on Bias. Please, cite as:" }, { "code": null, "e": 5232, "s": 4946, "text": "@misc{mougan2021desiderataECB, title={Desiderata for Explainable AI in statistical production systems of the European Central Bank}, author={Carlos Mougan Navarro and Georgios Kanellos and Thomas Gottron}, year={2021}, eprint={2107.08045}, archivePrefix={arXiv}, primaryClass={cs.CY}}" }, { "code": null, "e": 5328, "s": 5232, "text": "1- Desiderata for Explainable AI in statistical production systems of the European Central Bank" }, { "code": null, "e": 5372, "s": 5328, "text": "2- May Edition: Questions on Explainable AI" }, { "code": null, "e": 5507, "s": 5372, "text": "3- Explainable AI: Beware of Inmates Running the Asylum Or: How I Learnt to Stop Worrying and Love the Social and Behavioural Sciences" }, { "code": null, "e": 5623, "s": 5507, "text": "4- Stop explaining black box machine learning models for high stakes decisions and use interpretable models instead" }, { "code": null, "e": 5698, "s": 5623, "text": "5- “Why Should I Trust You?”: Explaining the Predictions of Any Classifier" }, { "code": null, "e": 5775, "s": 5698, "text": "6- Explanation in Artificial Intelligence: Insights from the Social Sciences" }, { "code": null, "e": 5859, "s": 5775, "text": "7- Interpretable Machine Learning: A Guide for Making Black Box Models Explainable." }, { "code": null, "e": 5931, "s": 5859, "text": "Many thanks to Laura State and Xuan Zhao for the input and discussions." } ]
AngularJS | Directive - GeeksforGeeks
28 Jun, 2019 AngularJS is an open-source MVC framework which is very similar to the JavaScript framework.Directives are markers on DOM element which tell Angular JS to attach a specified behavior to that DOM element or even transform the DOM element with its children. Simple AngularJS allows extending HTML with new attributes called Directives. AngularJS has a set of built-in directives which offers functionality to the applications. It also defines its own directives.A directive can be defined using some functions which are: Element name, Attribute, Class, Comment. Why Use It ? It gives support to create custom directives for a different type of elements. A directive is activated when the same element or matching element is there in front. It is used to give more power of HTML by helping them with the new syntax. Directive classes, like component classes, can implement life-cycle hooks to influence their configuration and behavior. Directive Components: The AngularJS directives extends the attribute with prefix ng-. Some directive components are discussed below: ng-app: It is an auto bootstrap AngularJS application which says that all the AngularJS should have a root element.Example:<html> <head> <title>AngularJS ng-app Directive</title> <script src= "https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script> </head> <body style="text-align:center"> <h2 style = "color:green">ng-app directive</h2> <div ng-app="" ng-init="name='GeeksforGeeks'"> <p>{{ name }} is the portal for geeks.</p> </div> </body> </html> Output: Example: <html> <head> <title>AngularJS ng-app Directive</title> <script src= "https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script> </head> <body style="text-align:center"> <h2 style = "color:green">ng-app directive</h2> <div ng-app="" ng-init="name='GeeksforGeeks'"> <p>{{ name }} is the portal for geeks.</p> </div> </body> </html> Output: ng-controller: The ng-controller Directive in AngularJS is used to add controller to the application. It can be used to add methods, functions, and variables that can be called on some event like a click, etc to perform a certain action.Example:<!DOCTYPE html> <html> <head> <title>ng-controller Directive</title> <script src= "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"> </script> </head> <body ng-app="app" style="text-align:center"> <h1 style="color:green">GeeksforGeeks</h1> <h2>ng-controller Directive</h2><br> <div ng-controller="geek"> Name: <input class="form-control" type="text" ng-model="name"> <br><br> You entered: <b><span>{{name}}</span></b> </div> <script> var app = angular.module('app', []); app.controller('geek', function ($scope) { $scope.name = "geeksforgeeks"; }); </script> </body> </html> Output: Example: <!DOCTYPE html> <html> <head> <title>ng-controller Directive</title> <script src= "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"> </script> </head> <body ng-app="app" style="text-align:center"> <h1 style="color:green">GeeksforGeeks</h1> <h2>ng-controller Directive</h2><br> <div ng-controller="geek"> Name: <input class="form-control" type="text" ng-model="name"> <br><br> You entered: <b><span>{{name}}</span></b> </div> <script> var app = angular.module('app', []); app.controller('geek', function ($scope) { $scope.name = "geeksforgeeks"; }); </script> </body> </html> Output: ng-bind: It is used to bind/replace the text content of a particular element with the value that is entered in the given expression. The value of specified HTML content updates whenever the value of the expression changes in the ng-bind directive.Example:<!DOCTYPE html> <html> <head> <title>ng-checked Directive</title> <script src= "https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script> </head> <body ng-app="gfg" style="text-align:center"> <h1 style="color:green">GeeksforGeeks</h1> <h2>ng-bind Directive</h2> <div ng-controller="app"> num1: <input type="number" ng-model="num1" ng-change="product()" /> <br><br> num2: <input type="number" ng-model="num2" ng-change="product()" /> <br><br> <b>Product:</b> <span ng-bind="result"></span> </div> <script> var app = angular.module("gfg", []); app.controller('app', ['$scope', function ($app) { $app.num1 = 1; $app.num2 = 1; $app.product = function () { $app.result = ($app.num1 * $app.num2); } }]); </script> </body> </html> Output: Example: <!DOCTYPE html> <html> <head> <title>ng-checked Directive</title> <script src= "https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script> </head> <body ng-app="gfg" style="text-align:center"> <h1 style="color:green">GeeksforGeeks</h1> <h2>ng-bind Directive</h2> <div ng-controller="app"> num1: <input type="number" ng-model="num1" ng-change="product()" /> <br><br> num2: <input type="number" ng-model="num2" ng-change="product()" /> <br><br> <b>Product:</b> <span ng-bind="result"></span> </div> <script> var app = angular.module("gfg", []); app.controller('app', ['$scope', function ($app) { $app.num1 = 1; $app.num2 = 1; $app.product = function () { $app.result = ($app.num1 * $app.num2); } }]); </script> </body> </html> Output: Benefits of AngularJS Directive: Directives are helpful in creating repeat and independent code. They modularize the code by clubbing requirement-specific behavioral functions in one place. It does not create objects in the central controller and manipulate them using multiple JavaScript methods. Such type of modular code will have multiple directives that can handle their own functionalities and data, and work should be isolation from other directives. As an added benefit, the HTML page and Angular scripts become less messy and more organized. AngularJS-Basics Picked AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Auth Guards in Angular 9/10/11 How to bundle an Angular app for production? What is AOT and JIT Compiler in Angular ? Angular PrimeNG Dropdown Component How to set focus on input field automatically on page load in AngularJS ? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24138, "s": 24110, "text": "\n28 Jun, 2019" }, { "code": null, "e": 24698, "s": 24138, "text": "AngularJS is an open-source MVC framework which is very similar to the JavaScript framework.Directives are markers on DOM element which tell Angular JS to attach a specified behavior to that DOM element or even transform the DOM element with its children. Simple AngularJS allows extending HTML with new attributes called Directives. AngularJS has a set of built-in directives which offers functionality to the applications. It also defines its own directives.A directive can be defined using some functions which are: Element name, Attribute, Class, Comment." }, { "code": null, "e": 24711, "s": 24698, "text": "Why Use It ?" }, { "code": null, "e": 24790, "s": 24711, "text": "It gives support to create custom directives for a different type of elements." }, { "code": null, "e": 24876, "s": 24790, "text": "A directive is activated when the same element or matching element is there in front." }, { "code": null, "e": 24951, "s": 24876, "text": "It is used to give more power of HTML by helping them with the new syntax." }, { "code": null, "e": 25072, "s": 24951, "text": "Directive classes, like component classes, can implement life-cycle hooks to influence their configuration and behavior." }, { "code": null, "e": 25205, "s": 25072, "text": "Directive Components: The AngularJS directives extends the attribute with prefix ng-. Some directive components are discussed below:" }, { "code": null, "e": 25745, "s": 25205, "text": "ng-app: It is an auto bootstrap AngularJS application which says that all the AngularJS should have a root element.Example:<html> <head> <title>AngularJS ng-app Directive</title> <script src= \"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script> </head> <body style=\"text-align:center\"> <h2 style = \"color:green\">ng-app directive</h2> <div ng-app=\"\" ng-init=\"name='GeeksforGeeks'\"> <p>{{ name }} is the portal for geeks.</p> </div> </body> </html> Output:" }, { "code": null, "e": 25754, "s": 25745, "text": "Example:" }, { "code": "<html> <head> <title>AngularJS ng-app Directive</title> <script src= \"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script> </head> <body style=\"text-align:center\"> <h2 style = \"color:green\">ng-app directive</h2> <div ng-app=\"\" ng-init=\"name='GeeksforGeeks'\"> <p>{{ name }} is the portal for geeks.</p> </div> </body> </html> ", "e": 26164, "s": 25754, "text": null }, { "code": null, "e": 26172, "s": 26164, "text": "Output:" }, { "code": null, "e": 27168, "s": 26172, "text": "ng-controller: The ng-controller Directive in AngularJS is used to add controller to the application. It can be used to add methods, functions, and variables that can be called on some event like a click, etc to perform a certain action.Example:<!DOCTYPE html> <html> <head> <title>ng-controller Directive</title> <script src= \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js\"> </script> </head> <body ng-app=\"app\" style=\"text-align:center\"> <h1 style=\"color:green\">GeeksforGeeks</h1> <h2>ng-controller Directive</h2><br> <div ng-controller=\"geek\"> Name: <input class=\"form-control\" type=\"text\" ng-model=\"name\"> <br><br> You entered: <b><span>{{name}}</span></b> </div> <script> var app = angular.module('app', []); app.controller('geek', function ($scope) { $scope.name = \"geeksforgeeks\"; }); </script> </body> </html> Output:" }, { "code": null, "e": 27177, "s": 27168, "text": "Example:" }, { "code": "<!DOCTYPE html> <html> <head> <title>ng-controller Directive</title> <script src= \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js\"> </script> </head> <body ng-app=\"app\" style=\"text-align:center\"> <h1 style=\"color:green\">GeeksforGeeks</h1> <h2>ng-controller Directive</h2><br> <div ng-controller=\"geek\"> Name: <input class=\"form-control\" type=\"text\" ng-model=\"name\"> <br><br> You entered: <b><span>{{name}}</span></b> </div> <script> var app = angular.module('app', []); app.controller('geek', function ($scope) { $scope.name = \"geeksforgeeks\"; }); </script> </body> </html> ", "e": 27921, "s": 27177, "text": null }, { "code": null, "e": 27929, "s": 27921, "text": "Output:" }, { "code": null, "e": 29191, "s": 27929, "text": "ng-bind: It is used to bind/replace the text content of a particular element with the value that is entered in the given expression. The value of specified HTML content updates whenever the value of the expression changes in the ng-bind directive.Example:<!DOCTYPE html> <html> <head> <title>ng-checked Directive</title> <script src= \"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script> </head> <body ng-app=\"gfg\" style=\"text-align:center\"> <h1 style=\"color:green\">GeeksforGeeks</h1> <h2>ng-bind Directive</h2> <div ng-controller=\"app\"> num1: <input type=\"number\" ng-model=\"num1\" ng-change=\"product()\" /> <br><br> num2: <input type=\"number\" ng-model=\"num2\" ng-change=\"product()\" /> <br><br> <b>Product:</b> <span ng-bind=\"result\"></span> </div> <script> var app = angular.module(\"gfg\", []); app.controller('app', ['$scope', function ($app) { $app.num1 = 1; $app.num2 = 1; $app.product = function () { $app.result = ($app.num1 * $app.num2); } }]); </script> </body> </html> Output:" }, { "code": null, "e": 29200, "s": 29191, "text": "Example:" }, { "code": "<!DOCTYPE html> <html> <head> <title>ng-checked Directive</title> <script src= \"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script> </head> <body ng-app=\"gfg\" style=\"text-align:center\"> <h1 style=\"color:green\">GeeksforGeeks</h1> <h2>ng-bind Directive</h2> <div ng-controller=\"app\"> num1: <input type=\"number\" ng-model=\"num1\" ng-change=\"product()\" /> <br><br> num2: <input type=\"number\" ng-model=\"num2\" ng-change=\"product()\" /> <br><br> <b>Product:</b> <span ng-bind=\"result\"></span> </div> <script> var app = angular.module(\"gfg\", []); app.controller('app', ['$scope', function ($app) { $app.num1 = 1; $app.num2 = 1; $app.product = function () { $app.result = ($app.num1 * $app.num2); } }]); </script> </body> </html> ", "e": 30200, "s": 29200, "text": null }, { "code": null, "e": 30208, "s": 30200, "text": "Output:" }, { "code": null, "e": 30241, "s": 30208, "text": "Benefits of AngularJS Directive:" }, { "code": null, "e": 30305, "s": 30241, "text": "Directives are helpful in creating repeat and independent code." }, { "code": null, "e": 30506, "s": 30305, "text": "They modularize the code by clubbing requirement-specific behavioral functions in one place. It does not create objects in the central controller and manipulate them using multiple JavaScript methods." }, { "code": null, "e": 30666, "s": 30506, "text": "Such type of modular code will have multiple directives that can handle their own functionalities and data, and work should be isolation from other directives." }, { "code": null, "e": 30759, "s": 30666, "text": "As an added benefit, the HTML page and Angular scripts become less messy and more organized." }, { "code": null, "e": 30776, "s": 30759, "text": "AngularJS-Basics" }, { "code": null, "e": 30783, "s": 30776, "text": "Picked" }, { "code": null, "e": 30793, "s": 30783, "text": "AngularJS" }, { "code": null, "e": 30810, "s": 30793, "text": "Web Technologies" }, { "code": null, "e": 30908, "s": 30810, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30917, "s": 30908, "text": "Comments" }, { "code": null, "e": 30930, "s": 30917, "text": "Old Comments" }, { "code": null, "e": 30961, "s": 30930, "text": "Auth Guards in Angular 9/10/11" }, { "code": null, "e": 31006, "s": 30961, "text": "How to bundle an Angular app for production?" }, { "code": null, "e": 31048, "s": 31006, "text": "What is AOT and JIT Compiler in Angular ?" }, { "code": null, "e": 31083, "s": 31048, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 31157, "s": 31083, "text": "How to set focus on input field automatically on page load in AngularJS ?" }, { "code": null, "e": 31213, "s": 31157, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 31246, "s": 31213, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 31308, "s": 31246, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 31351, "s": 31308, "text": "How to fetch data from an API in ReactJS ?" } ]
Python range function example - onlinetutorialspoint
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws The range() is a built-in function in Python that returns the sequence of numbers between the specified range. This function is preferred over a list when we want a series of integers that needs to be generated at runtime. The signature for the range() function is as shown below. However, there are two variants in the range function. range(stop) range(start, stop, step) There are two different ways in which this function can be used. The first one shows when we are only passing one parameter stop. The second one shows when we use starting, ending, and step. However, step is an optional parameter. However, it returns a sequence of numbers between the given range. Example 1: In this example, let us demonstrate the working of the range function with a single parameter. #Using range r=range(10) # Printing the range print (r) #Printing range of values as tuple print(tuple(r)) Output range(0, 10) (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) Example 2: In this case, we will generate a sequence of numbers with specific start and end values and step. Here, we are printing it as a list. #Using range r=range(111,120,2) #Printing range and values as a list print (r) print(list(r)) Output range(111, 120,2) [111, 113, 115, 117, 119] Example 3: For this example, we will take a string and the end value will be the length of the string. #Initializing s="python" #Using range r=range(0,len(s)) #Printing print (r) print(list(r)) Output range(0, 6) [0, 1, 2, 3, 4, 5] The range() function returns the sequence of numbers between the given range of numbers. Python Built-in Functions Happy Learning 🙂 Python any function example Python Callable function Example Python compile function example Python exec function example How to use fromkeys for a Dictionary in Python What are Python default function parameters ? What are different Python Data Types How to get elements from Dict in Python Python – How to filter a list in python ? What is Python NumPy Library How to perform Intersection Operation on a Set in Python How to perform Union operation on a Set in Python How to set default values to a Dictionary in Python How to use update method in a Set in Python How to find Symmetric Difference of two Sets in Python Python any function example Python Callable function Example Python compile function example Python exec function example How to use fromkeys for a Dictionary in Python What are Python default function parameters ? What are different Python Data Types How to get elements from Dict in Python Python – How to filter a list in python ? What is Python NumPy Library How to perform Intersection Operation on a Set in Python How to perform Union operation on a Set in Python How to set default values to a Dictionary in Python How to use update method in a Set in Python How to find Symmetric Difference of two Sets in Python Δ Python – Introduction Python – Features Python – Install on Windows Python – Modes of Program Python – Number System Python – Identifiers Python – Operators Python – Ternary Operator Python – Command Line Arguments Python – Keywords Python – Data Types Python – Upgrade Python PIP Python – Virtual Environment Pyhton – Type Casting Python – String to Int Python – Conditional Statements Python – if statement Python – *args and **kwargs Python – Date Formatting Python – Read input from keyboard Python – raw_input Python – List In Depth Python – List Comprehension Python – Set in Depth Python – Dictionary in Depth Python – Tuple in Depth Python – Stack Datastructure Python – Classes and Objects Python – Constructors Python – Object Introspection Python – Inheritance Python – Decorators Python – Serialization with Pickle Python – Exceptions Handling Python – User defined Exceptions Python – Multiprocessing Python – Default function parameters Python – Lambdas Functions Python – NumPy Library Python – MySQL Connector Python – MySQL Create Database Python – MySQL Read Data Python – MySQL Insert Data Python – MySQL Update Records Python – MySQL Delete Records Python – String Case Conversion Howto – Find biggest of 2 numbers Howto – Remove duplicates from List Howto – Convert any Number to Binary Howto – Merge two Lists Howto – Merge two dicts Howto – Get Characters Count in a File Howto – Get Words Count in a File Howto – Remove Spaces from String Howto – Read Env variables Howto – Read a text File Howto – Read a JSON File Howto – Read Config.ini files Howto – Iterate Dictionary Howto – Convert List Of Objects to CSV Howto – Merge two dict in Python Howto – create Zip File Howto – Get OS info Howto – Get size of Directory Howto – Check whether a file exists Howto – Remove key from dictionary Howto – Sort Objects Howto – Create or Delete Directories Howto – Read CSV File Howto – Create Python Iterable class Howto – Access for loop index Howto – Clear all elements from List Howto – Remove empty lists from a List Howto – Remove special characters from String Howto – Sort dictionary by key Howto – Filter a list
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 621, "s": 398, "text": "The range() is a built-in function in Python that returns the sequence of numbers between the specified range. This function is preferred over a list when we want a series of integers that needs to be generated at runtime." }, { "code": null, "e": 734, "s": 621, "text": "The signature for the range() function is as shown below. However, there are two variants in the range function." }, { "code": null, "e": 772, "s": 734, "text": "range(stop)\nrange(start, stop, step)\n" }, { "code": null, "e": 1003, "s": 772, "text": "There are two different ways in which this function can be used. The first one shows when we are only passing one parameter stop. The second one shows when we use starting, ending, and step. However, step is an optional parameter." }, { "code": null, "e": 1070, "s": 1003, "text": "However, it returns a sequence of numbers between the given range." }, { "code": null, "e": 1176, "s": 1070, "text": "Example 1: In this example, let us demonstrate the working of the range function with a single parameter." }, { "code": null, "e": 1284, "s": 1176, "text": "#Using range\nr=range(10)\n# Printing the range\nprint (r)\n#Printing range of values as tuple\nprint(tuple(r))\n" }, { "code": null, "e": 1291, "s": 1284, "text": "Output" }, { "code": null, "e": 1336, "s": 1291, "text": "range(0, 10)\n(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)\n" }, { "code": null, "e": 1481, "s": 1336, "text": "Example 2: In this case, we will generate a sequence of numbers with specific start and end values and step. Here, we are printing it as a list." }, { "code": null, "e": 1576, "s": 1481, "text": "#Using range\nr=range(111,120,2)\n#Printing range and values as a list\nprint (r)\nprint(list(r))\n" }, { "code": null, "e": 1583, "s": 1576, "text": "Output" }, { "code": null, "e": 1628, "s": 1583, "text": "range(111, 120,2)\n[111, 113, 115, 117, 119]\n" }, { "code": null, "e": 1731, "s": 1628, "text": "Example 3: For this example, we will take a string and the end value will be the length of the string." }, { "code": null, "e": 1823, "s": 1731, "text": "#Initializing\ns=\"python\"\n#Using range\nr=range(0,len(s))\n#Printing\nprint (r)\nprint(list(r))\n" }, { "code": null, "e": 1830, "s": 1823, "text": "Output" }, { "code": null, "e": 1862, "s": 1830, "text": "range(0, 6)\n[0, 1, 2, 3, 4, 5]\n" }, { "code": null, "e": 1951, "s": 1862, "text": "The range() function returns the sequence of numbers between the given range of numbers." }, { "code": null, "e": 1977, "s": 1951, "text": "Python Built-in Functions" }, { "code": null, "e": 1994, "s": 1977, "text": "Happy Learning 🙂" }, { "code": null, "e": 2617, "s": 1994, "text": "\nPython any function example\nPython Callable function Example\nPython compile function example\nPython exec function example\nHow to use fromkeys for a Dictionary in Python\nWhat are Python default function parameters ?\nWhat are different Python Data Types\nHow to get elements from Dict in Python\nPython – How to filter a list in python ?\nWhat is Python NumPy Library\nHow to perform Intersection Operation on a Set in Python\nHow to perform Union operation on a Set in Python\nHow to set default values to a Dictionary in Python\nHow to use update method in a Set in Python\nHow to find Symmetric Difference of two Sets in Python\n" }, { "code": null, "e": 2645, "s": 2617, "text": "Python any function example" }, { "code": null, "e": 2678, "s": 2645, "text": "Python Callable function Example" }, { "code": null, "e": 2710, "s": 2678, "text": "Python compile function example" }, { "code": null, "e": 2739, "s": 2710, "text": "Python exec function example" }, { "code": null, "e": 2786, "s": 2739, "text": "How to use fromkeys for a Dictionary in Python" }, { "code": null, "e": 2832, "s": 2786, "text": "What are Python default function parameters ?" }, { "code": null, "e": 2869, "s": 2832, "text": "What are different Python Data Types" }, { "code": null, "e": 2909, "s": 2869, "text": "How to get elements from Dict in Python" }, { "code": null, "e": 2951, "s": 2909, "text": "Python – How to filter a list in python ?" }, { "code": null, "e": 2980, "s": 2951, "text": "What is Python NumPy Library" }, { "code": null, "e": 3037, "s": 2980, "text": "How to perform Intersection Operation on a Set in Python" }, { "code": null, "e": 3087, "s": 3037, "text": "How to perform Union operation on a Set in Python" }, { "code": null, "e": 3139, "s": 3087, "text": "How to set default values to a Dictionary in Python" }, { "code": null, "e": 3183, "s": 3139, "text": "How to use update method in a Set in Python" }, { "code": null, "e": 3238, "s": 3183, "text": "How to find Symmetric Difference of two Sets in Python" }, { "code": null, "e": 3244, "s": 3242, "text": "Δ" }, { "code": null, "e": 3267, "s": 3244, "text": " Python – Introduction" }, { "code": null, "e": 3286, "s": 3267, "text": " Python – Features" }, { "code": null, "e": 3315, "s": 3286, "text": " Python – Install on Windows" }, { "code": null, "e": 3342, "s": 3315, "text": " Python – Modes of Program" }, { "code": null, "e": 3366, "s": 3342, "text": " Python – Number System" }, { "code": null, "e": 3388, "s": 3366, "text": " Python – Identifiers" }, { "code": null, "e": 3408, "s": 3388, "text": " Python – Operators" }, { "code": null, "e": 3435, "s": 3408, "text": " Python – Ternary Operator" }, { "code": null, "e": 3468, "s": 3435, "text": " Python – Command Line Arguments" }, { "code": null, "e": 3487, "s": 3468, "text": " Python – Keywords" }, { "code": null, "e": 3508, "s": 3487, "text": " Python – Data Types" }, { "code": null, "e": 3537, "s": 3508, "text": " Python – Upgrade Python PIP" }, { "code": null, "e": 3567, "s": 3537, "text": " Python – Virtual Environment" }, { "code": null, "e": 3590, "s": 3567, "text": " Pyhton – Type Casting" }, { "code": null, "e": 3614, "s": 3590, "text": " Python – String to Int" }, { "code": null, "e": 3647, "s": 3614, "text": " Python – Conditional Statements" }, { "code": null, "e": 3670, "s": 3647, "text": " Python – if statement" }, { "code": null, "e": 3699, "s": 3670, "text": " Python – *args and **kwargs" }, { "code": null, "e": 3725, "s": 3699, "text": " Python – Date Formatting" }, { "code": null, "e": 3760, "s": 3725, "text": " Python – Read input from keyboard" }, { "code": null, "e": 3780, "s": 3760, "text": " Python – raw_input" }, { "code": null, "e": 3804, "s": 3780, "text": " Python – List In Depth" }, { "code": null, "e": 3833, "s": 3804, "text": " Python – List Comprehension" }, { "code": null, "e": 3856, "s": 3833, "text": " Python – Set in Depth" }, { "code": null, "e": 3886, "s": 3856, "text": " Python – Dictionary in Depth" }, { "code": null, "e": 3911, "s": 3886, "text": " Python – Tuple in Depth" }, { "code": null, "e": 3941, "s": 3911, "text": " Python – Stack Datastructure" }, { "code": null, "e": 3971, "s": 3941, "text": " Python – Classes and Objects" }, { "code": null, "e": 3994, "s": 3971, "text": " Python – Constructors" }, { "code": null, "e": 4025, "s": 3994, "text": " Python – Object Introspection" }, { "code": null, "e": 4047, "s": 4025, "text": " Python – Inheritance" }, { "code": null, "e": 4068, "s": 4047, "text": " Python – Decorators" }, { "code": null, "e": 4104, "s": 4068, "text": " Python – Serialization with Pickle" }, { "code": null, "e": 4134, "s": 4104, "text": " Python – Exceptions Handling" }, { "code": null, "e": 4168, "s": 4134, "text": " Python – User defined Exceptions" }, { "code": null, "e": 4194, "s": 4168, "text": " Python – Multiprocessing" }, { "code": null, "e": 4232, "s": 4194, "text": " Python – Default function parameters" }, { "code": null, "e": 4260, "s": 4232, "text": " Python – Lambdas Functions" }, { "code": null, "e": 4284, "s": 4260, "text": " Python – NumPy Library" }, { "code": null, "e": 4310, "s": 4284, "text": " Python – MySQL Connector" }, { "code": null, "e": 4342, "s": 4310, "text": " Python – MySQL Create Database" }, { "code": null, "e": 4368, "s": 4342, "text": " Python – MySQL Read Data" }, { "code": null, "e": 4396, "s": 4368, "text": " Python – MySQL Insert Data" }, { "code": null, "e": 4427, "s": 4396, "text": " Python – MySQL Update Records" }, { "code": null, "e": 4458, "s": 4427, "text": " Python – MySQL Delete Records" }, { "code": null, "e": 4491, "s": 4458, "text": " Python – String Case Conversion" }, { "code": null, "e": 4526, "s": 4491, "text": " Howto – Find biggest of 2 numbers" }, { "code": null, "e": 4563, "s": 4526, "text": " Howto – Remove duplicates from List" }, { "code": null, "e": 4601, "s": 4563, "text": " Howto – Convert any Number to Binary" }, { "code": null, "e": 4627, "s": 4601, "text": " Howto – Merge two Lists" }, { "code": null, "e": 4652, "s": 4627, "text": " Howto – Merge two dicts" }, { "code": null, "e": 4692, "s": 4652, "text": " Howto – Get Characters Count in a File" }, { "code": null, "e": 4727, "s": 4692, "text": " Howto – Get Words Count in a File" }, { "code": null, "e": 4762, "s": 4727, "text": " Howto – Remove Spaces from String" }, { "code": null, "e": 4791, "s": 4762, "text": " Howto – Read Env variables" }, { "code": null, "e": 4817, "s": 4791, "text": " Howto – Read a text File" }, { "code": null, "e": 4843, "s": 4817, "text": " Howto – Read a JSON File" }, { "code": null, "e": 4875, "s": 4843, "text": " Howto – Read Config.ini files" }, { "code": null, "e": 4903, "s": 4875, "text": " Howto – Iterate Dictionary" }, { "code": null, "e": 4943, "s": 4903, "text": " Howto – Convert List Of Objects to CSV" }, { "code": null, "e": 4977, "s": 4943, "text": " Howto – Merge two dict in Python" }, { "code": null, "e": 5002, "s": 4977, "text": " Howto – create Zip File" }, { "code": null, "e": 5023, "s": 5002, "text": " Howto – Get OS info" }, { "code": null, "e": 5054, "s": 5023, "text": " Howto – Get size of Directory" }, { "code": null, "e": 5091, "s": 5054, "text": " Howto – Check whether a file exists" }, { "code": null, "e": 5128, "s": 5091, "text": " Howto – Remove key from dictionary" }, { "code": null, "e": 5150, "s": 5128, "text": " Howto – Sort Objects" }, { "code": null, "e": 5188, "s": 5150, "text": " Howto – Create or Delete Directories" }, { "code": null, "e": 5211, "s": 5188, "text": " Howto – Read CSV File" }, { "code": null, "e": 5249, "s": 5211, "text": " Howto – Create Python Iterable class" }, { "code": null, "e": 5280, "s": 5249, "text": " Howto – Access for loop index" }, { "code": null, "e": 5318, "s": 5280, "text": " Howto – Clear all elements from List" }, { "code": null, "e": 5358, "s": 5318, "text": " Howto – Remove empty lists from a List" }, { "code": null, "e": 5405, "s": 5358, "text": " Howto – Remove special characters from String" }, { "code": null, "e": 5437, "s": 5405, "text": " Howto – Sort dictionary by key" } ]
Can we declare the variables of a Java interface private and protected?
Interface in Java is similar to class but, it contains only abstract methods and fields which are final and static. If the fields of the interface are private, you cannot access them in the implementing class. If you try to declare the fields of an interface private, a compile time error is generated saying “modifier private not allowed here”. In the following Java example, we are trying to declare the field and method of an interface private. public interface MyInterface{ private static final int num = 10; private abstract void demo(); } On compiling, the above program generates the following error MyInterface.java:2: error: modifier private not allowed here private static final int num = 10; ^ MyInterface.java:3: error: modifier private not allowed here private abstract void demo(); ^ 2 errors In general, the protected fields can be accessed in the same class or, the class inheriting it. But, we do not inherit an interface we will implement it. Therefore, cannot declare the fields of an interface protected. If you try to do so, a compile time error is generated saying “modifier protected not allowed here”. In the following Java example, we are trying to declare the field and method of an interface protected. public interface MyInterface{ protected static final int num = 10; protected abstract void demo(); } MyInterface.java:2: error: modifier protected not allowed here protected static final int num = 10; ^ MyInterface.java:3: error: modifier protected not allowed here protected abstract void demo();
[ { "code": null, "e": 1178, "s": 1062, "text": "Interface in Java is similar to class but, it contains only abstract methods and fields which are final and static." }, { "code": null, "e": 1272, "s": 1178, "text": "If the fields of the interface are private, you cannot access them in the implementing class." }, { "code": null, "e": 1408, "s": 1272, "text": "If you try to declare the fields of an interface private, a compile time error is generated saying “modifier private not allowed here”." }, { "code": null, "e": 1510, "s": 1408, "text": "In the following Java example, we are trying to declare the field and method of an interface private." }, { "code": null, "e": 1613, "s": 1510, "text": "public interface MyInterface{\n private static final int num = 10;\n private abstract void demo();\n}" }, { "code": null, "e": 1675, "s": 1613, "text": "On compiling, the above program generates the following error" }, { "code": null, "e": 1907, "s": 1675, "text": "MyInterface.java:2: error: modifier private not allowed here\n private static final int num = 10;\n ^\nMyInterface.java:3: error: modifier private not allowed here\n private abstract void demo();\n^\n2 errors" }, { "code": null, "e": 2061, "s": 1907, "text": "In general, the protected fields can be accessed in the same class or, the class inheriting it. But, we do not inherit an interface we will implement it." }, { "code": null, "e": 2226, "s": 2061, "text": "Therefore, cannot declare the fields of an interface protected. If you try to do so, a compile time error is generated saying “modifier protected not allowed here”." }, { "code": null, "e": 2330, "s": 2226, "text": "In the following Java example, we are trying to declare the field and method of an interface protected." }, { "code": null, "e": 2437, "s": 2330, "text": "public interface MyInterface{\n protected static final int num = 10;\n protected abstract void demo();\n}" }, { "code": null, "e": 2640, "s": 2437, "text": "MyInterface.java:2: error: modifier protected not allowed here\n protected static final int num = 10;\n^\nMyInterface.java:3: error: modifier protected not allowed here\n protected abstract void demo();" } ]
How to add accelerators to a menu item?
A menu is a list of options or commands presented to the user, typically menus contains items that perform some action. The contents of a menu are known as menu items and a menu bar holds multiple menus. In JavaFX a menu is represented by the javafx.scene.control.Menu class, a menu item is represented by the javafx.scene.control.MenuItem class, And, the javafx.scene.control.MenuBar class represents a menu bar. Accelerators are short cuts to menu Items. The MenuItem class contains a property named accelerator (of type KeyCombination), which associates a combination to the action of the current MenuItem. You can set value to this property using the setAccelerator() method. Therefore, to set accelerator to a particular MenuItem, invoke the setAccelerator() method on it as shown below − MenuItem item = new MenuItem("Exit", imgView3); item.setAccelerator(KeyCombination.keyCombination("Ctrl+X")); import javafx.application.Application; import javafx.event.ActionEvent; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.Menu; import javafx.scene.control.MenuBar; import javafx.scene.control.MenuItem; import javafx.scene.image.ImageView; import javafx.scene.input.KeyCombination; import javafx.scene.paint.Color; import javafx.stage.Stage; public class MenuItemAccelerators extends Application { @Override public void start(Stage stage) { //Creating image view files ImageView imgView1 = new ImageView("UIControls/open.png"); imgView1.setFitWidth(20); imgView1.setFitHeight(20); ImageView imgView2 = new ImageView("UIControls/Save.png"); imgView2.setFitWidth(20); imgView2.setFitHeight(20); ImageView imgView3 = new ImageView("UIControls/Exit.png"); imgView3.setFitWidth(20); imgView3.setFitHeight(20); //Creating menu Menu fileMenu = new Menu("File"); //Creating menu Items MenuItem item1 = new MenuItem("Open File", imgView1); MenuItem item2 = new MenuItem("Save file", imgView2); MenuItem item3 = new MenuItem("Exit", imgView3); //Setting accelerators to the menu items item1.setAccelerator(KeyCombination.keyCombination("Ctrl+F")); item2.setAccelerator(KeyCombination.keyCombination("Ctrl+S")); item3.setAccelerator(KeyCombination.keyCombination("Ctrl+X")); //Adding all the menu items to the menu fileMenu.getItems().addAll(item1, item2, item3); //Creating a menu bar and adding menu to it. MenuBar menuBar = new MenuBar(fileMenu); menuBar.setTranslateX(200); menuBar.setTranslateY(20); //Setting the stage Group root = new Group(menuBar); Scene scene = new Scene(root, 595, 200, Color.BEIGE); stage.setTitle("Menu Example"); stage.setScene(scene); stage.show(); } public static void main(String args[]){ launch(args); } }
[ { "code": null, "e": 1266, "s": 1062, "text": "A menu is a list of options or commands presented to the user, typically menus contains items that perform some action. The contents of a menu are known as menu items and a menu bar holds multiple menus." }, { "code": null, "e": 1476, "s": 1266, "text": "In JavaFX a menu is represented by the javafx.scene.control.Menu class, a menu item is represented by the javafx.scene.control.MenuItem class, And, the javafx.scene.control.MenuBar class represents a menu bar." }, { "code": null, "e": 1672, "s": 1476, "text": "Accelerators are short cuts to menu Items. The MenuItem class contains a property named accelerator (of type KeyCombination), which associates a combination to the action of the current MenuItem." }, { "code": null, "e": 1856, "s": 1672, "text": "You can set value to this property using the setAccelerator() method. Therefore, to set accelerator to a particular MenuItem, invoke the setAccelerator() method on it as shown below −" }, { "code": null, "e": 1966, "s": 1856, "text": "MenuItem item = new MenuItem(\"Exit\", imgView3);\nitem.setAccelerator(KeyCombination.keyCombination(\"Ctrl+X\"));" }, { "code": null, "e": 3941, "s": 1966, "text": "import javafx.application.Application;\nimport javafx.event.ActionEvent;\nimport javafx.scene.Group;\nimport javafx.scene.Scene;\nimport javafx.scene.control.Menu;\nimport javafx.scene.control.MenuBar;\nimport javafx.scene.control.MenuItem;\nimport javafx.scene.image.ImageView;\nimport javafx.scene.input.KeyCombination;\nimport javafx.scene.paint.Color;\nimport javafx.stage.Stage;\npublic class MenuItemAccelerators extends Application {\n @Override\n public void start(Stage stage) {\n //Creating image view files\n ImageView imgView1 = new ImageView(\"UIControls/open.png\");\n imgView1.setFitWidth(20);\n imgView1.setFitHeight(20);\n ImageView imgView2 = new ImageView(\"UIControls/Save.png\");\n imgView2.setFitWidth(20);\n imgView2.setFitHeight(20);\n ImageView imgView3 = new ImageView(\"UIControls/Exit.png\");\n imgView3.setFitWidth(20);\n imgView3.setFitHeight(20);\n //Creating menu\n Menu fileMenu = new Menu(\"File\");\n //Creating menu Items\n MenuItem item1 = new MenuItem(\"Open File\", imgView1);\n MenuItem item2 = new MenuItem(\"Save file\", imgView2);\n MenuItem item3 = new MenuItem(\"Exit\", imgView3);\n //Setting accelerators to the menu items\n item1.setAccelerator(KeyCombination.keyCombination(\"Ctrl+F\"));\n item2.setAccelerator(KeyCombination.keyCombination(\"Ctrl+S\"));\n item3.setAccelerator(KeyCombination.keyCombination(\"Ctrl+X\"));\n //Adding all the menu items to the menu\n fileMenu.getItems().addAll(item1, item2, item3);\n //Creating a menu bar and adding menu to it.\n MenuBar menuBar = new MenuBar(fileMenu);\n menuBar.setTranslateX(200);\n menuBar.setTranslateY(20);\n //Setting the stage\n Group root = new Group(menuBar);\n Scene scene = new Scene(root, 595, 200, Color.BEIGE);\n stage.setTitle(\"Menu Example\");\n stage.setScene(scene);\n stage.show();\n }\n public static void main(String args[]){\n launch(args);\n }\n}" } ]
Sentiment Analysis using Classification | by Songhao Wu | Towards Data Science
Sentiment analysis is a commonly used text analysis technique to determine whether the text is positive, negative, or neutral. It can be used to understand the satisfaction of the audience and a great feature for forecasting. If you have a well-labeled dataset(with a ground truth sentiment score), you can consider using text classification to calculate the sentiment score. Usage of classification can automatically capture patterns from historical data that are specific to the industry or topic. You do not need to search for a positive or negative word list specific to the topic.It is more convenient to include different bag-of-words calculations as the feature for sentiment classification because you can directly define that in the existing package. Those negation phrases like ‘not good’ and ‘do not like’ can be captured but it is hard to capture all those phrases by yourself.There are many existing classification algorithms for you to choose from. The potential for a best-fitted model is high. Usage of classification can automatically capture patterns from historical data that are specific to the industry or topic. You do not need to search for a positive or negative word list specific to the topic. It is more convenient to include different bag-of-words calculations as the feature for sentiment classification because you can directly define that in the existing package. Those negation phrases like ‘not good’ and ‘do not like’ can be captured but it is hard to capture all those phrases by yourself. There are many existing classification algorithms for you to choose from. The potential for a best-fitted model is high. The only downside: You need to have labeled data! The data we are using is Yelp labeled dataset from Kaggle. The first column is the review text and the second column is the ground truth of sentiment score(1 being negative sentiment and 2 being positive sentiment) Firstly let us split the dataset into training and testing sets (you can decide on test_size based on the amount of data you have). If you have a sufficiently large dataset you can choose to lower the proportion of the testing set. from sklearn.model_selection import train_test_splitY=sample_new['rating']X=sample_new['review']X_train,X_test,Y_train,Y_test=train_test_split(X,Y,test_size=0.2) Here we are using two sklearn packages: CountVectorizer: It converts the text into a token count matrix. The token can be single words or 2-gram or 3-gram phrases. It also allows you to specify n_gram range, stop-word removal, etc in the parameter. CountVectorizer: It converts the text into a token count matrix. The token can be single words or 2-gram or 3-gram phrases. It also allows you to specify n_gram range, stop-word removal, etc in the parameter. 2. TfidfTransformer: Here we need to understand TF-IDF first. TF-IDF full name is ‘term frequency-inverse document frequency. Term frequency means how frequently the word or phrase occurs in the whole text. However, if a term occurs too frequently then it conveys less useful information and TF-IDF calculation uses log function to scale down terms that occur too frequently. You can also choose to just use term frequency instead. TF-IDF(term, documents) = term_frequency(term, document) * log(Total count of documents/(document frequency+ 1)) For example, a data science article usually has the word ‘data’. However, it usually does not tell you whether the article’s opinion(just a general word). TF-IDF transformer basically transforms the word count matrix into a frequency matrix. from sklearn.feature_extraction.text import CountVectorizervectorize = CountVectorizer(ngram_range=(1,2))X_train_counts=vectorize.fit_transform(X_train)from sklearn.feature_extraction.text import TfidfTransformertfidf_transformer = TfidfTransformer()X_train_tfidf = tfidf_transformer.fit_transform(X_train_counts)X_train_tfidf.shape#(24000, 44563) Here, I specify tokens to be single words or 2-gram words in the ngram_range parameter(you can change the (1,2) to n_gram you want) and finally output the frequency matrix as the feature for classification. Finally, modeling part There is no restriction on what to use, you can take a sample of the whole dataset and see which model suit best for the sample in terms of accuracy or other evaluation metrics. You can refer here to how you can evaluate your classification model. from sklearn.linear_model import LogisticRegressionlr=LogisticRegression().fit(X_train_tfidf, Y_train)X_test_count=vectorize.transform(X_test)X_test_tfidf=tfidf_transformer.transform(X_test_count)predicted=lr.predict(X_test_tfidf)#evaluate accuracynp.mean(predicted == Y_test)#0.89883 Logistic regression gives almost 90% of accuracy rate from sklearn import svmfrom sklearn.pipeline import Pipelinetext_svm = Pipeline([ ('vectorize', CountVectorizer()), ('tfidf', TfidfTransformer()), ('svm', svm.SVC()), ])text_svm.fit(X_train,Y_train)predicted=text_svm.predict(X_test)np.mean(predicted==Y_test)#0.9 Here I used sklearn package pipeline to combine all processes together. Support Vector Machine gives exactly 90% accuracy. from sklearn.neural_network import MLPClassifiertext_nn = Pipeline([ ('vectorize', CountVectorizer()), ('tfidf', TfidfTransformer()), ('nn', MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(5, 2), random_state=1)), ])text_nn.fit(X_train,Y_train)predicted=text_nn.predict(X_test)np.mean(predicted==Y_test)#0.88167 Deep learning MLP classifier can reach around 88% Parameter tuning for CountVectorizer: parameters like n_gram_range, maximum/minimum document frequency to retrieve the ideal frequency score for classification. This would require a good level of understanding of the dataset and also some trial and error to reach the ideal outputParameter tuning for classification model: you can use search methods like grid_search or random search to find the best set of parameters in terms of accuracy or other metrics. This would cause the whole process to run much longer.Classification model evaluation: Evaluate performance on multiple metrics like recall, precision rather than simply accuracy Parameter tuning for CountVectorizer: parameters like n_gram_range, maximum/minimum document frequency to retrieve the ideal frequency score for classification. This would require a good level of understanding of the dataset and also some trial and error to reach the ideal output Parameter tuning for classification model: you can use search methods like grid_search or random search to find the best set of parameters in terms of accuracy or other metrics. This would cause the whole process to run much longer. Classification model evaluation: Evaluate performance on multiple metrics like recall, precision rather than simply accuracy The quantity of data is important for classification performance. If you do not have a sufficiently large dataset, do not make the model too complicated because there is a risk of overfitting. In addition, an initial understanding of the data is important, you should take out some sample text to understand more about the pattern of the data before doing all those work. Lastly, if you do not have labeled data and want to see how you can calculate sentiment score by counting positive/negative words you can refer to my other article below.
[ { "code": null, "e": 548, "s": 172, "text": "Sentiment analysis is a commonly used text analysis technique to determine whether the text is positive, negative, or neutral. It can be used to understand the satisfaction of the audience and a great feature for forecasting. If you have a well-labeled dataset(with a ground truth sentiment score), you can consider using text classification to calculate the sentiment score." }, { "code": null, "e": 1182, "s": 548, "text": "Usage of classification can automatically capture patterns from historical data that are specific to the industry or topic. You do not need to search for a positive or negative word list specific to the topic.It is more convenient to include different bag-of-words calculations as the feature for sentiment classification because you can directly define that in the existing package. Those negation phrases like ‘not good’ and ‘do not like’ can be captured but it is hard to capture all those phrases by yourself.There are many existing classification algorithms for you to choose from. The potential for a best-fitted model is high." }, { "code": null, "e": 1392, "s": 1182, "text": "Usage of classification can automatically capture patterns from historical data that are specific to the industry or topic. You do not need to search for a positive or negative word list specific to the topic." }, { "code": null, "e": 1697, "s": 1392, "text": "It is more convenient to include different bag-of-words calculations as the feature for sentiment classification because you can directly define that in the existing package. Those negation phrases like ‘not good’ and ‘do not like’ can be captured but it is hard to capture all those phrases by yourself." }, { "code": null, "e": 1818, "s": 1697, "text": "There are many existing classification algorithms for you to choose from. The potential for a best-fitted model is high." }, { "code": null, "e": 1868, "s": 1818, "text": "The only downside: You need to have labeled data!" }, { "code": null, "e": 2083, "s": 1868, "text": "The data we are using is Yelp labeled dataset from Kaggle. The first column is the review text and the second column is the ground truth of sentiment score(1 being negative sentiment and 2 being positive sentiment)" }, { "code": null, "e": 2315, "s": 2083, "text": "Firstly let us split the dataset into training and testing sets (you can decide on test_size based on the amount of data you have). If you have a sufficiently large dataset you can choose to lower the proportion of the testing set." }, { "code": null, "e": 2477, "s": 2315, "text": "from sklearn.model_selection import train_test_splitY=sample_new['rating']X=sample_new['review']X_train,X_test,Y_train,Y_test=train_test_split(X,Y,test_size=0.2)" }, { "code": null, "e": 2517, "s": 2477, "text": "Here we are using two sklearn packages:" }, { "code": null, "e": 2726, "s": 2517, "text": "CountVectorizer: It converts the text into a token count matrix. The token can be single words or 2-gram or 3-gram phrases. It also allows you to specify n_gram range, stop-word removal, etc in the parameter." }, { "code": null, "e": 2935, "s": 2726, "text": "CountVectorizer: It converts the text into a token count matrix. The token can be single words or 2-gram or 3-gram phrases. It also allows you to specify n_gram range, stop-word removal, etc in the parameter." }, { "code": null, "e": 3367, "s": 2935, "text": "2. TfidfTransformer: Here we need to understand TF-IDF first. TF-IDF full name is ‘term frequency-inverse document frequency. Term frequency means how frequently the word or phrase occurs in the whole text. However, if a term occurs too frequently then it conveys less useful information and TF-IDF calculation uses log function to scale down terms that occur too frequently. You can also choose to just use term frequency instead." }, { "code": null, "e": 3480, "s": 3367, "text": "TF-IDF(term, documents) = term_frequency(term, document) * log(Total count of documents/(document frequency+ 1))" }, { "code": null, "e": 3722, "s": 3480, "text": "For example, a data science article usually has the word ‘data’. However, it usually does not tell you whether the article’s opinion(just a general word). TF-IDF transformer basically transforms the word count matrix into a frequency matrix." }, { "code": null, "e": 4070, "s": 3722, "text": "from sklearn.feature_extraction.text import CountVectorizervectorize = CountVectorizer(ngram_range=(1,2))X_train_counts=vectorize.fit_transform(X_train)from sklearn.feature_extraction.text import TfidfTransformertfidf_transformer = TfidfTransformer()X_train_tfidf = tfidf_transformer.fit_transform(X_train_counts)X_train_tfidf.shape#(24000, 44563)" }, { "code": null, "e": 4277, "s": 4070, "text": "Here, I specify tokens to be single words or 2-gram words in the ngram_range parameter(you can change the (1,2) to n_gram you want) and finally output the frequency matrix as the feature for classification." }, { "code": null, "e": 4300, "s": 4277, "text": "Finally, modeling part" }, { "code": null, "e": 4548, "s": 4300, "text": "There is no restriction on what to use, you can take a sample of the whole dataset and see which model suit best for the sample in terms of accuracy or other evaluation metrics. You can refer here to how you can evaluate your classification model." }, { "code": null, "e": 4833, "s": 4548, "text": "from sklearn.linear_model import LogisticRegressionlr=LogisticRegression().fit(X_train_tfidf, Y_train)X_test_count=vectorize.transform(X_test)X_test_tfidf=tfidf_transformer.transform(X_test_count)predicted=lr.predict(X_test_tfidf)#evaluate accuracynp.mean(predicted == Y_test)#0.89883" }, { "code": null, "e": 4887, "s": 4833, "text": "Logistic regression gives almost 90% of accuracy rate" }, { "code": null, "e": 5162, "s": 4887, "text": "from sklearn import svmfrom sklearn.pipeline import Pipelinetext_svm = Pipeline([ ('vectorize', CountVectorizer()), ('tfidf', TfidfTransformer()), ('svm', svm.SVC()), ])text_svm.fit(X_train,Y_train)predicted=text_svm.predict(X_test)np.mean(predicted==Y_test)#0.9" }, { "code": null, "e": 5285, "s": 5162, "text": "Here I used sklearn package pipeline to combine all processes together. Support Vector Machine gives exactly 90% accuracy." }, { "code": null, "e": 5643, "s": 5285, "text": "from sklearn.neural_network import MLPClassifiertext_nn = Pipeline([ ('vectorize', CountVectorizer()), ('tfidf', TfidfTransformer()), ('nn', MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(5, 2), random_state=1)), ])text_nn.fit(X_train,Y_train)predicted=text_nn.predict(X_test)np.mean(predicted==Y_test)#0.88167" }, { "code": null, "e": 5693, "s": 5643, "text": "Deep learning MLP classifier can reach around 88%" }, { "code": null, "e": 6330, "s": 5693, "text": "Parameter tuning for CountVectorizer: parameters like n_gram_range, maximum/minimum document frequency to retrieve the ideal frequency score for classification. This would require a good level of understanding of the dataset and also some trial and error to reach the ideal outputParameter tuning for classification model: you can use search methods like grid_search or random search to find the best set of parameters in terms of accuracy or other metrics. This would cause the whole process to run much longer.Classification model evaluation: Evaluate performance on multiple metrics like recall, precision rather than simply accuracy" }, { "code": null, "e": 6611, "s": 6330, "text": "Parameter tuning for CountVectorizer: parameters like n_gram_range, maximum/minimum document frequency to retrieve the ideal frequency score for classification. This would require a good level of understanding of the dataset and also some trial and error to reach the ideal output" }, { "code": null, "e": 6844, "s": 6611, "text": "Parameter tuning for classification model: you can use search methods like grid_search or random search to find the best set of parameters in terms of accuracy or other metrics. This would cause the whole process to run much longer." }, { "code": null, "e": 6969, "s": 6844, "text": "Classification model evaluation: Evaluate performance on multiple metrics like recall, precision rather than simply accuracy" }, { "code": null, "e": 7341, "s": 6969, "text": "The quantity of data is important for classification performance. If you do not have a sufficiently large dataset, do not make the model too complicated because there is a risk of overfitting. In addition, an initial understanding of the data is important, you should take out some sample text to understand more about the pattern of the data before doing all those work." } ]
Recursive sum of digits of a number formed by repeated appends in C++
Given two integers ‘number’ and ‘repeat’ as input. The goal is to calculate the sum of digits of the input number repeated ‘repeat’ number of times until the sum becomes a single digit. Do this till the obtained number with sum of digits becomes a single digit number. If the input number is 123 and repeat=2 than the sum of digits of 123123 will be 1+2+3+1+2+3=12 which is not a single digit number. Now the sum of digits of 12 is 1+2=3. Output will be 3 Input − number=32 repeat=3 Output − Recursive sum of digits of a number formed by repeated appends is: 6 Explanation − Sum of digits of 323232 is 3+2+3+2+3+2=15 and sum of digits of 15 is 1+5=6. 6 is a single digit number so output will be 6. Input − number=81 repeat=4 Output − Recursive sum of digits of a number formed by repeated appends is: 9 Explanation − Sum of digits of 81818181 is 1+8+1+8+1+8+1+8=36 and sum of digits of 36 is 3+6=9. 9 is a single digit number so output will be 9. Declare two integer type variables as number and repeat. Pass the data to the function as Recursive_Sum(number, repeat). Declare two integer type variables as number and repeat. Pass the data to the function as Recursive_Sum(number, repeat). Inside the function as Recursive_Sum(int number, int repeat)Declare an integer variable as total and set it with a repeat * sum(number);Return call to the function as sum(total). Inside the function as Recursive_Sum(int number, int repeat) Declare an integer variable as total and set it with a repeat * sum(number); Declare an integer variable as total and set it with a repeat * sum(number); Return call to the function as sum(total). Return call to the function as sum(total). Inside the function as sum(int number)Check IF number is 0 then return 0.Check IF number % 9 is 0 then return 9.ELSE, return number % 9 Inside the function as sum(int number) Check IF number is 0 then return 0. Check IF number is 0 then return 0. Check IF number % 9 is 0 then return 9. Check IF number % 9 is 0 then return 9. ELSE, return number % 9 ELSE, return number % 9 Print the result. Print the result. #include <bits/stdc++.h> using namespace std; int sum(int number){ if(number == 0){ return 0; } if(number % 9 == 0){ return 9; } else{ return number % 9; } } int Recursive_Sum(int number, int repeat){ int total = repeat * sum(number); return sum(total); } int main(){ int number = 12; int repeat = 4; cout<<"Recursive sum of digits of a number formed by repeated appends is: "<<Recursive_Sum(number, repeat); return 0; } If we run the above code it will generate the following Output Recursive sum of digits of a number formed by repeated appends is: 3
[ { "code": null, "e": 1518, "s": 1062, "text": "Given two integers ‘number’ and ‘repeat’ as input. The goal is to calculate the sum of digits of the input number repeated ‘repeat’ number of times until the sum becomes a single digit. Do this till the obtained number with sum of digits becomes a single digit number. If the input number is 123 and repeat=2 than the sum of digits of 123123 will be\n1+2+3+1+2+3=12 which is not a single digit number. Now the sum of digits of 12 is 1+2=3. Output will be 3" }, { "code": null, "e": 1545, "s": 1518, "text": "Input − number=32 repeat=3" }, { "code": null, "e": 1623, "s": 1545, "text": "Output − Recursive sum of digits of a number formed by repeated appends is: 6" }, { "code": null, "e": 1761, "s": 1623, "text": "Explanation − Sum of digits of 323232 is 3+2+3+2+3+2=15 and sum of digits of 15 is 1+5=6. 6 is a single digit number so output will be 6." }, { "code": null, "e": 1788, "s": 1761, "text": "Input − number=81 repeat=4" }, { "code": null, "e": 1866, "s": 1788, "text": "Output − Recursive sum of digits of a number formed by repeated appends is: 9" }, { "code": null, "e": 2010, "s": 1866, "text": "Explanation − Sum of digits of 81818181 is 1+8+1+8+1+8+1+8=36 and sum of digits of 36 is 3+6=9. 9 is a single digit number so output will be 9." }, { "code": null, "e": 2131, "s": 2010, "text": "Declare two integer type variables as number and repeat. Pass the data to the function as Recursive_Sum(number, repeat)." }, { "code": null, "e": 2252, "s": 2131, "text": "Declare two integer type variables as number and repeat. Pass the data to the function as Recursive_Sum(number, repeat)." }, { "code": null, "e": 2431, "s": 2252, "text": "Inside the function as Recursive_Sum(int number, int repeat)Declare an integer variable as total and set it with a repeat * sum(number);Return call to the function as sum(total)." }, { "code": null, "e": 2492, "s": 2431, "text": "Inside the function as Recursive_Sum(int number, int repeat)" }, { "code": null, "e": 2569, "s": 2492, "text": "Declare an integer variable as total and set it with a repeat * sum(number);" }, { "code": null, "e": 2646, "s": 2569, "text": "Declare an integer variable as total and set it with a repeat * sum(number);" }, { "code": null, "e": 2689, "s": 2646, "text": "Return call to the function as sum(total)." }, { "code": null, "e": 2732, "s": 2689, "text": "Return call to the function as sum(total)." }, { "code": null, "e": 2868, "s": 2732, "text": "Inside the function as sum(int number)Check IF number is 0 then return 0.Check IF number % 9 is 0 then return 9.ELSE, return number % 9" }, { "code": null, "e": 2907, "s": 2868, "text": "Inside the function as sum(int number)" }, { "code": null, "e": 2943, "s": 2907, "text": "Check IF number is 0 then return 0." }, { "code": null, "e": 2979, "s": 2943, "text": "Check IF number is 0 then return 0." }, { "code": null, "e": 3019, "s": 2979, "text": "Check IF number % 9 is 0 then return 9." }, { "code": null, "e": 3059, "s": 3019, "text": "Check IF number % 9 is 0 then return 9." }, { "code": null, "e": 3083, "s": 3059, "text": "ELSE, return number % 9" }, { "code": null, "e": 3107, "s": 3083, "text": "ELSE, return number % 9" }, { "code": null, "e": 3125, "s": 3107, "text": "Print the result." }, { "code": null, "e": 3143, "s": 3125, "text": "Print the result." }, { "code": null, "e": 3618, "s": 3143, "text": "#include <bits/stdc++.h>\nusing namespace std;\nint sum(int number){\n if(number == 0){\n return 0;\n }\n if(number % 9 == 0){\n return 9;\n }\n else{\n return number % 9;\n }\n}\nint Recursive_Sum(int number, int repeat){\n int total = repeat * sum(number);\n return sum(total);\n}\nint main(){\n int number = 12;\n int repeat = 4;\n cout<<\"Recursive sum of digits of a number formed by repeated appends is: \"<<Recursive_Sum(number, repeat);\n return 0;\n}" }, { "code": null, "e": 3681, "s": 3618, "text": "If we run the above code it will generate the following Output" }, { "code": null, "e": 3750, "s": 3681, "text": "Recursive sum of digits of a number formed by repeated appends is: 3" } ]
lexicographical_compare in C++ - GeeksforGeeks
17 Aug, 2018 C++ STL offer many utilities to solve basic common life problems. Comparing values are always necessary, but sometimes we need to compare the strings also. Therefore, this article aims at explaining about “lexicographical_compare()” that allows to compare strings. This function is defined in “algorithm” header. It has two implementations. Syntax 1 : lexicographical_compare(iter1 beg1, iter1 end1, iter2 beg2, iter2 end2) Template: template bool lexicographical_compare(iter1 beg1, iter1 end1, iter2 beg2, iter2 end2) Parameters : beg1 : Input iterator to initial position of first sequence. end1 : Input iterator to final position of first sequence. beg2 : Input iterator to initial position of second sequence. end2 : Input iterator to final position of second sequence. Return value : Returns a boolean true, if range1 is strictly lexicographically smaller than range2 else returns a false. // C++ code to demonstrate the working of // lexicographical_compare() #include<iostream>#include<algorithm> // for lexicographical_compare()using namespace std; int main(){ // initializing char arrays char one[] = "geeksforgeeks"; char two[] = "gfg"; // using lexicographical_compare for checking // is "one" is less than "two" if( lexicographical_compare(one, one+13, two, two+3)) { cout << "geeksforgeeks is lexicographically less than gfg"; } else { cout << "geeksforgeeks is not lexicographically less than gfg"; } } Output: geeksforgeeks is lexicographically less than gfg Syntax 2 : lexicographical_compare(iter1 beg1, iter1 end1, iter2 beg2, iter2 end2, Compare comp) Template: template bool lexicographical_compare(iter1 beg1, iter1 end1, iter2 beg2, iter2 end2) Parameters : beg1 : Input iterator to initial position of first sequence. end1 : Input iterator to final position of first sequence. beg2 : Input iterator to initial position of second sequence. end2 : Input iterator to final position of second sequence. comp : The comparator function that returns a boolean true/false of the each elements compared. This function accepts two arguments. This can be function pointer or function object and cannot change values. Return value : Returns a boolean true, if range1 is strictly lexicographically smaller than range2 else returns a false. // C++ code to demonstrate the working of // lexicographical_compare() #include<iostream>#include<algorithm> // for lexicographical_compare()using namespace std; // helper function to convert all into lower case:bool comp (char s1, char s2){ return tolower(s1)<tolower(s2);} int main(){ // initializing char arrays char one[] = "geeksforgeeks"; char two[] = "Gfg"; // using lexicographical_compare for checking // is "one" is less than "two" // returns false as "g" has larger ASCII value than "G" if( lexicographical_compare(one, one+13, two, two+3)) { cout << "geeksforgeeks is lexicographically less than Gfg\n"; } else { cout << "geeksforgeeks is not lexicographically less than Gfg\n"; } // using lexicographical_compare for checking // is "one" is less than "two" // returns true this time as all converted into lowercase if( lexicographical_compare(one, one+13, two, two+3, comp)) { cout << "geeksforgeeks is lexicographically less "; cout << "than Gfg( case-insensitive )"; } else { cout << "geeksforgeeks is not lexicographically less "; cout<< "than Gfg( case-insensitive )"; } } Output: geeksforgeeks is not lexicographically less than Gfg geeksforgeeks is lexicographically less than Gfg( case-insensitive ) Possible application : Comparing strings can be generally used in dictionary, where we need to place words in lexicographical order. Example of this can be to find the word which occurs 1st in dictionary among given set of words. // C++ code to demonstrate the application of // lexicographical_compare() #include<bits/stdc++.h>using namespace std; int main(){ // initializing char arrays char list[][100]={ {'a','b','a','c','u','s'}, {'a','p','p','l','e'}, {'c','a','r'}, {'a','b','b','a'} }; char min[100] = "zzzzzz"; // using lexicographical_compare for checking // the smallest for (int i=0; i<4; i++) { if( lexicographical_compare(list[i], list[i] + strlen(list[i]), min, min+strlen(min))) { strcpy(min,list[i]); } } // prints "abacus" cout << "The smallest string is : "; for(int i = 0; min[i]!='\0'; i++) { cout<<min[i]; } } Output: The smallest string is : abacus This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. cpp-algorithm-library lexicographic-ordering STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Iterators in C++ STL Operator Overloading in C++ Friend class and function in C++ Polymorphism in C++ Sorting a vector in C++ Convert string to char array in C++ Inline Functions in C++ List in C++ Standard Template Library (STL) std::string class in C++ new and delete operators in C++ for dynamic memory
[ { "code": null, "e": 24044, "s": 24016, "text": "\n17 Aug, 2018" }, { "code": null, "e": 24385, "s": 24044, "text": "C++ STL offer many utilities to solve basic common life problems. Comparing values are always necessary, but sometimes we need to compare the strings also. Therefore, this article aims at explaining about “lexicographical_compare()” that allows to compare strings. This function is defined in “algorithm” header. It has two implementations." }, { "code": null, "e": 24468, "s": 24385, "text": "Syntax 1 : lexicographical_compare(iter1 beg1, iter1 end1, iter2 beg2, iter2 end2)" }, { "code": null, "e": 24953, "s": 24468, "text": "Template:\ntemplate \n bool lexicographical_compare(iter1 beg1, iter1 end1, iter2 beg2, iter2 end2)\nParameters : \nbeg1 : Input iterator to initial position of first sequence.\nend1 : Input iterator to final position of first sequence.\n\nbeg2 : Input iterator to initial position of second sequence.\nend2 : Input iterator to final position of second sequence.\n\nReturn value : \nReturns a boolean true, if range1 is strictly lexicographically \nsmaller than range2 else returns a false.\n" }, { "code": "// C++ code to demonstrate the working of // lexicographical_compare() #include<iostream>#include<algorithm> // for lexicographical_compare()using namespace std; int main(){ // initializing char arrays char one[] = \"geeksforgeeks\"; char two[] = \"gfg\"; // using lexicographical_compare for checking // is \"one\" is less than \"two\" if( lexicographical_compare(one, one+13, two, two+3)) { cout << \"geeksforgeeks is lexicographically less than gfg\"; } else { cout << \"geeksforgeeks is not lexicographically less than gfg\"; } }", "e": 25556, "s": 24953, "text": null }, { "code": null, "e": 25564, "s": 25556, "text": "Output:" }, { "code": null, "e": 25614, "s": 25564, "text": "geeksforgeeks is lexicographically less than gfg\n" }, { "code": null, "e": 25711, "s": 25614, "text": "Syntax 2 : lexicographical_compare(iter1 beg1, iter1 end1, iter2 beg2, iter2 end2, Compare comp)" }, { "code": null, "e": 26406, "s": 25711, "text": "Template:\ntemplate \n bool lexicographical_compare(iter1 beg1, iter1 end1, iter2 beg2, iter2 end2)\nParameters : \nbeg1 : Input iterator to initial position of first sequence.\nend1 : Input iterator to final position of first sequence.\n\nbeg2 : Input iterator to initial position of second sequence.\nend2 : Input iterator to final position of second sequence.\n\ncomp : The comparator function that returns a boolean\ntrue/false of the each elements compared. This function \naccepts two arguments. This can be function pointer or \nfunction object and cannot change values.\n\nReturn value : \nReturns a boolean true, if range1 is strictly lexicographically smaller \nthan range2 else returns a false.\n" }, { "code": "// C++ code to demonstrate the working of // lexicographical_compare() #include<iostream>#include<algorithm> // for lexicographical_compare()using namespace std; // helper function to convert all into lower case:bool comp (char s1, char s2){ return tolower(s1)<tolower(s2);} int main(){ // initializing char arrays char one[] = \"geeksforgeeks\"; char two[] = \"Gfg\"; // using lexicographical_compare for checking // is \"one\" is less than \"two\" // returns false as \"g\" has larger ASCII value than \"G\" if( lexicographical_compare(one, one+13, two, two+3)) { cout << \"geeksforgeeks is lexicographically less than Gfg\\n\"; } else { cout << \"geeksforgeeks is not lexicographically less than Gfg\\n\"; } // using lexicographical_compare for checking // is \"one\" is less than \"two\" // returns true this time as all converted into lowercase if( lexicographical_compare(one, one+13, two, two+3, comp)) { cout << \"geeksforgeeks is lexicographically less \"; cout << \"than Gfg( case-insensitive )\"; } else { cout << \"geeksforgeeks is not lexicographically less \"; cout<< \"than Gfg( case-insensitive )\"; } }", "e": 27667, "s": 26406, "text": null }, { "code": null, "e": 27675, "s": 27667, "text": "Output:" }, { "code": null, "e": 27798, "s": 27675, "text": "geeksforgeeks is not lexicographically less than Gfg\ngeeksforgeeks is lexicographically less than Gfg( case-insensitive )\n" }, { "code": null, "e": 28028, "s": 27798, "text": "Possible application : Comparing strings can be generally used in dictionary, where we need to place words in lexicographical order. Example of this can be to find the word which occurs 1st in dictionary among given set of words." }, { "code": "// C++ code to demonstrate the application of // lexicographical_compare() #include<bits/stdc++.h>using namespace std; int main(){ // initializing char arrays char list[][100]={ {'a','b','a','c','u','s'}, {'a','p','p','l','e'}, {'c','a','r'}, {'a','b','b','a'} }; char min[100] = \"zzzzzz\"; // using lexicographical_compare for checking // the smallest for (int i=0; i<4; i++) { if( lexicographical_compare(list[i], list[i] + strlen(list[i]), min, min+strlen(min))) { strcpy(min,list[i]); } } // prints \"abacus\" cout << \"The smallest string is : \"; for(int i = 0; min[i]!='\\0'; i++) { cout<<min[i]; } }", "e": 28768, "s": 28028, "text": null }, { "code": null, "e": 28776, "s": 28768, "text": "Output:" }, { "code": null, "e": 28809, "s": 28776, "text": "The smallest string is : abacus\n" }, { "code": null, "e": 29110, "s": 28809, "text": "This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 29235, "s": 29110, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 29257, "s": 29235, "text": "cpp-algorithm-library" }, { "code": null, "e": 29280, "s": 29257, "text": "lexicographic-ordering" }, { "code": null, "e": 29284, "s": 29280, "text": "STL" }, { "code": null, "e": 29288, "s": 29284, "text": "C++" }, { "code": null, "e": 29292, "s": 29288, "text": "STL" }, { "code": null, "e": 29296, "s": 29292, "text": "CPP" }, { "code": null, "e": 29394, "s": 29296, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29403, "s": 29394, "text": "Comments" }, { "code": null, "e": 29416, "s": 29403, "text": "Old Comments" }, { "code": null, "e": 29437, "s": 29416, "text": "Iterators in C++ STL" }, { "code": null, "e": 29465, "s": 29437, "text": "Operator Overloading in C++" }, { "code": null, "e": 29498, "s": 29465, "text": "Friend class and function in C++" }, { "code": null, "e": 29518, "s": 29498, "text": "Polymorphism in C++" }, { "code": null, "e": 29542, "s": 29518, "text": "Sorting a vector in C++" }, { "code": null, "e": 29578, "s": 29542, "text": "Convert string to char array in C++" }, { "code": null, "e": 29602, "s": 29578, "text": "Inline Functions in C++" }, { "code": null, "e": 29646, "s": 29602, "text": "List in C++ Standard Template Library (STL)" }, { "code": null, "e": 29671, "s": 29646, "text": "std::string class in C++" } ]
How to create a responsive form with CSS?
Following is the code to create a responsive form with CSS − Live Demo <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1" /> <style> body { font-family: Arial; font-size: 17px; padding: 8px; } * { box-sizing: border-box; } .Fields { display: flex; flex-wrap: wrap; padding: 20px; justify-content: space-around; } .Fields div { margin-right: 10px; } label { margin: 15px; } .formContainer { margin: 10px; background-color: #efffc9; padding: 5px 20px 15px 20px; border: 1px solid rgb(191, 246, 250); border-radius: 3px; } input[type="text"] { display: inline-block; width: 100%; margin-bottom: 20px; padding: 12px; border: 1px solid #ccc; border-radius: 3px; } label { margin-left: 20px; display: block; } .icon-formContainer { margin-bottom: 20px; padding: 7px 0; font-size: 24px; } .checkout { background-color: #4caf50; color: white; padding: 12px; margin: 10px 0; border: none; width: 100%; border-radius: 3px; cursor: pointer; font-size: 17px; } .checkout:hover { background-color: #45a049; } a { color: black; } span.price { float: right; color: grey; } @media (max-width: 657px) { .Fields { flex-direction: column-reverse; } } </style> </head> <body> <h1 style="text-align: center;">Responsive Form Example</h1> <div class="Fields"> <div> <div class="formContainer"> <form> <div class="Fields"> <div> <h3>Register</h3> <label for="fname">Full Name</label> <input type="text" id="fname" name="firstname" /> <label for="email"> Email</label> <input type="text" id="email" name="email" /> <label for="adr"> Address</label> <input type="text" id="adr" name="address" /> </div> <div> <h3>Account Details</h3> <label for="uname">Username</label> <input type="text" id="uname" name="cardname" /> <label for="pass">Password</label> <input type="text" id="pass" name="cardnumber" /> <div class="Fields"> <div> <label for="accountAge">Account Age</label> <input type="text" id="accountAge" name="accountAge" /> </div> <div> <label for="cvv">Security Question</label> <input type="text" id="cvv" name="cvv" /> </div> </div> </div> </div> </form> </div> </div> </div> </body> </html> The above code will produce the following output on larger screens − On smaller screen size the content will resize as follows −
[ { "code": null, "e": 1123, "s": 1062, "text": "Following is the code to create a responsive form with CSS −" }, { "code": null, "e": 1134, "s": 1123, "text": " Live Demo" }, { "code": null, "e": 3316, "s": 1134, "text": "<!DOCTYPE html>\n<html>\n<head>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n<style>\nbody {\n font-family: Arial;\n font-size: 17px;\n padding: 8px;\n}\n* {\n box-sizing: border-box;\n}\n.Fields {\n display: flex;\n flex-wrap: wrap;\n padding: 20px;\n justify-content: space-around;\n}\n.Fields div {\n margin-right: 10px;\n}\nlabel {\n margin: 15px;\n}\n.formContainer {\n margin: 10px;\n background-color: #efffc9;\n padding: 5px 20px 15px 20px;\n border: 1px solid rgb(191, 246, 250);\n border-radius: 3px;\n}\ninput[type=\"text\"] {\n display: inline-block;\n width: 100%;\n margin-bottom: 20px;\n padding: 12px;\n border: 1px solid #ccc;\n border-radius: 3px;\n}\nlabel {\n margin-left: 20px;\n display: block;\n}\n.icon-formContainer {\n margin-bottom: 20px;\n padding: 7px 0;\n font-size: 24px;\n}\n.checkout {\n background-color: #4caf50;\n color: white;\n padding: 12px;\n margin: 10px 0;\n border: none;\n width: 100%;\n border-radius: 3px;\n cursor: pointer;\n font-size: 17px;\n}\n.checkout:hover {\n background-color: #45a049;\n}\na {\n color: black;\n}\nspan.price {\n float: right;\n color: grey;\n}\n@media (max-width: 657px) {\n .Fields {\n flex-direction: column-reverse;\n }\n}\n</style>\n</head>\n<body>\n<h1 style=\"text-align: center;\">Responsive Form Example</h1>\n<div class=\"Fields\">\n<div>\n<div class=\"formContainer\">\n<form>\n<div class=\"Fields\">\n<div>\n<h3>Register</h3>\n<label for=\"fname\">Full Name</label>\n<input type=\"text\" id=\"fname\" name=\"firstname\" />\n<label for=\"email\"> Email</label>\n<input type=\"text\" id=\"email\" name=\"email\" />\n<label for=\"adr\"> Address</label>\n<input type=\"text\" id=\"adr\" name=\"address\" />\n</div>\n<div>\n<h3>Account Details</h3>\n<label for=\"uname\">Username</label>\n<input type=\"text\" id=\"uname\" name=\"cardname\" />\n<label for=\"pass\">Password</label>\n<input type=\"text\" id=\"pass\" name=\"cardnumber\" />\n<div class=\"Fields\">\n<div>\n<label for=\"accountAge\">Account Age</label>\n<input type=\"text\" id=\"accountAge\" name=\"accountAge\" />\n</div>\n<div>\n<label for=\"cvv\">Security Question</label>\n<input type=\"text\" id=\"cvv\" name=\"cvv\" />\n</div>\n</div>\n</div>\n</div>\n</form>\n</div>\n</div>\n</div>\n</body>\n</html>" }, { "code": null, "e": 3385, "s": 3316, "text": "The above code will produce the following output on larger screens −" }, { "code": null, "e": 3445, "s": 3385, "text": "On smaller screen size the content will resize as follows −" } ]
A Beginner’s Guide to Data Analysis in Python | by Natassha Selvaraj | Towards Data Science
A data analyst uses programming tools to mine large amounts of complex data, and find relevant information from this data. In short, an analyst is someone who derives meaning from messy data. A data analyst needs to have skills in the following areas, in order to be useful in the workplace: Domain Expertise — In order to mine data and come up with insights that are relevant to their workplace, an analyst needs to have domain expertise. Programming Skills —As a data analyst, you will need to know the right libraries to use in order to clean data, mine, and gain insights from it. Statistics — An analyst might need to use some statistical tools to derive meaning from data. Visualization Skills — A data analyst needs to have great data visualization skills, in order to summarize and present data to a third party. Storytelling — Finally, an analyst needs to communicate their findings to a stakeholder or client. This means that they will need to create a data story, and have the ability to narrate it. In this article, I am going to walk you through the end-to-end data analysis process with Python. We will start with downloading and cleaning the dataset, and then move on to the analysis and visualization. Finally, we will tell a story around our data findings. I will be using a dataset from Kaggle called Pima Indian Diabetes Database, which you can download to perform the analysis. For this entire analysis, I will be using a Jupyter Notebook. You can use any Python IDE you like. You will need to install libraries along the way, and I will provide links that will walk you through the installation process. After downloading the dataset, you will need to read the .csv file as a data frame in Python. You can do this using the Pandas library. If you do not have it installed, you can do so with a simple “pip install pandas” in your terminal. If you face any difficulty with the installation or simply want to learn more about the Pandas library, you can check out their documentation here. To read the data frame into Python, you will need to import Pandas first. Then, you can read the file and create a data frame with the following lines of code: import pandas as pddf = pd.read_csv('diabetes.csv') To check the head of the data frame, run: df.head() From the screenshot above, you can see 9 different variables related to a patient’s health. As an analyst, you will need to have a basic understanding of these variables: Pregnancies: The number of pregnancies the patient had Glucose: The patient’s glucose level Blood Pressure Skin Thickness: The thickness of the patient’s skin in mm Insulin: Insulin level of the patient BMI: Body Mass Index of patient DiabetesPedigreeFunction: History of diabetes mellitus in relatives Age Outcome: Whether or not a patient has diabetes As an analyst, you will need to know the difference between these variable types — Numeric and Categorical. Numeric variables are variables that are a measure, and have some kind of numeric meaning. All the variables in this dataset except for “outcome” are numeric. Categorical variables are also called nominal variables, and have two or more categories that can be classified. The variable “outcome” is categorical — 0 represents the absence of diabetes, and 1 represents the presence of diabetes. Before continuing with the analysis, I would like to make a quick note: Analysts are humans, and we often come with preconceived notions of what we expect to see in the data. For example, you would expect an older person to be more likely to have diabetes. You would want to see this correlation in the data, which might not always be the case. Keep an open mind during the analysis process, and do not let your bias effect the decision making. This is a very useful tool that can be used by analysts. It generates an analysis report on the data frame, and helps you better understand the correlation between variables. To generate a Pandas Profiling report, run the following lines of code: import pandas_profiling as pppp.ProfileReport(df) This report will give you some overall statistical information on the dataset, which looks like this: By just glancing at the dataset statistics, we can see that there are no missing or duplicate cells in our data frame. The information provided above usually requires us to run a few lines of codes to find, but is generated a lot more easily with Pandas Profiling. Pandas Profiling also provides more information on each variable. I will show you an example: This is information generated for the variable called “Pregnancies.” As an analyst, this report saves a lot of time, as we don’t have to go through each individual variable and run too many lines of code. From here, we can see that: The variable “Pregnancies” has 17 distinct values. The minimum number of pregnancies a person has is 0, and the maximum is 17. The number of zero values in this column is pretty low (only 14.5%). This means that above 80% of the patients in the dataset are pregnant. In the report, there is information like this provided for each variable. This helps us a lot in our understanding of the dataset and all the columns in it. The plot above is a correlation matrix. It helps us gain a better understanding of the correlation between the variables in the dataset. There is a slight positive correlation between the variables “Age” and “Skin Thickness”, which can be looked into further in the visualization section of the analysis. Since there are no missing or duplicate rows in the data frame as seen above, we don’t need to do any additional data cleaning. Now that we have a basic understanding of each variable, we can try to find the relationship between them. The simplest and fastest way to do this is by generating visualizations. In this tutorial, we will be using three libraries to get the job done — Matplotlib, Seaborn, and Plotly. If you are a complete beginner to Python, I suggest starting out and getting familiar with Matplotlib and Seaborn. Here is the documentation for Matplotlib, and here is the one for Seaborn. I strongly suggest spending some time reading the documentation, and doing tutorials using these two libraries in order to improve on your visualization skills. Plotly is a library that allows you to create interactive charts, and requires slightly more familiarity with Python to master. You can find the installation guide and requirements here. If you follow along to this tutorial exactly, you will be able to make beautiful charts with these three libraries. You can then use my code as a template for any future analysis or visualization tasks in the future. First, run the following lines of code to import Matplotlib, Seaborn, Numpy, and Plotly after installation: # Visualization Importsimport matplotlib.pyplot as pltimport seaborn as snscolor = sns.color_palette()get_ipython().run_line_magic('matplotlib', 'inline')import plotly.offline as pypy.init_notebook_mode(connected=True)import plotly.graph_objs as goimport plotly.tools as tlsimport plotly.express as pximport numpy as np Next, run the following lines of code to create a pie chart visualizing the outcome variable: dist = df['Outcome'].value_counts()colors = ['mediumturquoise', 'darkorange']trace = go.Pie(values=(np.array(dist)),labels=dist.index)layout = go.Layout(title='Diabetes Outcome')data = [trace]fig = go.Figure(trace,layout)fig.update_traces(marker=dict(colors=colors, line=dict(color='#000000', width=2)))fig.show() This is done with the Plotly library, and you will get an interactive chart that looks like this: You can play around with the chart and choose to change the colors, labels, and legend. From the chart above, however, we can see that most patients in the dataset are not diabetic. Less than half of them have an outcome of 1 (have diabetes). Similar to the correlation matrix generated in Pandas Profiling, we can create one using Plotly: def df_to_plotly(df): return {'z': df.values.tolist(), 'x': df.columns.tolist(), 'y': df.index.tolist() }import plotly.graph_objects as godfNew = df.corr()fig = go.Figure(data=go.Heatmap(df_to_plotly(dfNew)))fig.show() The codes above will generate a correlation matrix that is similar to the one above: Again, similar to the matrix generated above, a positive correlation can be observed between the variables: Age and Pregnancies Glucose and Outcome SkinThickness and Insulin To further understand the correlations between variables, we will create some plots: fig = px.scatter(df, x='Glucose', y='Insulin')fig.update_traces(marker_color="turquoise",marker_line_color='rgb(8,48,107)', marker_line_width=1.5)fig.update_layout(title_text='Glucose and Insulin')fig.show() Running the codes above should give you a plot that looks like this: There is a positive correlation between the variables glucose and insulin. This makes sense, because a person with higher glucose levels would be expected to take more insulin. Now, we will visualize the variables outcome and age. We will create a boxplot to do so, using the code below: fig = px.box(df, x='Outcome', y='Age')fig.update_traces(marker_color="midnightblue",marker_line_color='rgb(8,48,107)', marker_line_width=1.5)fig.update_layout(title_text='Age and Outcome')fig.show() The resulting plot will look somewhat like this: From the plot above, you can see that older people are more likely to have diabetes. The median age for adults with diabetes is around 35, while it is much lower for people without diabetes. However, there are a lot of outliers. There are a few elderly people without diabetes (one even over 80 years old), that can be observed in the boxplot. Finally, we will visualize the variables “BMI” and “Outcome”, to see if there is any correlation between the two variables. To do this, we will use the Seaborn library: plot = sns.boxplot(x='Outcome',y="BMI",data=df) The boxplot created here is similar to the one created above using Plotly. However, Plotly is better at creating visualizations that are interactive, and the charts look prettier compared to the ones made in Seaborn. From the box plot above, we can see that higher BMI correlates with a positive outcome. People with diabetes tend to have higher BMI’s than people without diabetes. You can make more visualizations like the ones above, by simply changing the variable names and running the same lines of code. I will leave that as an exercise for you to do, to get a better grasp on your visualization skills with Python. Finally, we can tell a story around the data we have analyzed and visualized. Our findings can be broken down as follows: People with diabetes are highly likely to be older than people who don’t. They are also more likely to have higher BMI’s, or suffer from obesity. They are also more likely to have higher glucose levels in their blood. People with higher glucose levels also tend to take more insulin, and this positive correlation indicates that patients with diabetes could also have higher insulin levels (this correlation can be checked by creating a scatter plot). That’s all for this article! I hope you found this tutorial helpful, and can use it as a future reference for projects you need to create. Good luck in your data science journey, and happy learning! Learn everything you can, anytime you can, from anyone you can; there will always come a time you will be grateful you did — Sarah Caldwell.
[ { "code": null, "e": 295, "s": 172, "text": "A data analyst uses programming tools to mine large amounts of complex data, and find relevant information from this data." }, { "code": null, "e": 464, "s": 295, "text": "In short, an analyst is someone who derives meaning from messy data. A data analyst needs to have skills in the following areas, in order to be useful in the workplace:" }, { "code": null, "e": 612, "s": 464, "text": "Domain Expertise — In order to mine data and come up with insights that are relevant to their workplace, an analyst needs to have domain expertise." }, { "code": null, "e": 757, "s": 612, "text": "Programming Skills —As a data analyst, you will need to know the right libraries to use in order to clean data, mine, and gain insights from it." }, { "code": null, "e": 851, "s": 757, "text": "Statistics — An analyst might need to use some statistical tools to derive meaning from data." }, { "code": null, "e": 993, "s": 851, "text": "Visualization Skills — A data analyst needs to have great data visualization skills, in order to summarize and present data to a third party." }, { "code": null, "e": 1183, "s": 993, "text": "Storytelling — Finally, an analyst needs to communicate their findings to a stakeholder or client. This means that they will need to create a data story, and have the ability to narrate it." }, { "code": null, "e": 1281, "s": 1183, "text": "In this article, I am going to walk you through the end-to-end data analysis process with Python." }, { "code": null, "e": 1446, "s": 1281, "text": "We will start with downloading and cleaning the dataset, and then move on to the analysis and visualization. Finally, we will tell a story around our data findings." }, { "code": null, "e": 1570, "s": 1446, "text": "I will be using a dataset from Kaggle called Pima Indian Diabetes Database, which you can download to perform the analysis." }, { "code": null, "e": 1669, "s": 1570, "text": "For this entire analysis, I will be using a Jupyter Notebook. You can use any Python IDE you like." }, { "code": null, "e": 1797, "s": 1669, "text": "You will need to install libraries along the way, and I will provide links that will walk you through the installation process." }, { "code": null, "e": 1933, "s": 1797, "text": "After downloading the dataset, you will need to read the .csv file as a data frame in Python. You can do this using the Pandas library." }, { "code": null, "e": 2181, "s": 1933, "text": "If you do not have it installed, you can do so with a simple “pip install pandas” in your terminal. If you face any difficulty with the installation or simply want to learn more about the Pandas library, you can check out their documentation here." }, { "code": null, "e": 2341, "s": 2181, "text": "To read the data frame into Python, you will need to import Pandas first. Then, you can read the file and create a data frame with the following lines of code:" }, { "code": null, "e": 2393, "s": 2341, "text": "import pandas as pddf = pd.read_csv('diabetes.csv')" }, { "code": null, "e": 2435, "s": 2393, "text": "To check the head of the data frame, run:" }, { "code": null, "e": 2445, "s": 2435, "text": "df.head()" }, { "code": null, "e": 2537, "s": 2445, "text": "From the screenshot above, you can see 9 different variables related to a patient’s health." }, { "code": null, "e": 2616, "s": 2537, "text": "As an analyst, you will need to have a basic understanding of these variables:" }, { "code": null, "e": 2671, "s": 2616, "text": "Pregnancies: The number of pregnancies the patient had" }, { "code": null, "e": 2708, "s": 2671, "text": "Glucose: The patient’s glucose level" }, { "code": null, "e": 2723, "s": 2708, "text": "Blood Pressure" }, { "code": null, "e": 2781, "s": 2723, "text": "Skin Thickness: The thickness of the patient’s skin in mm" }, { "code": null, "e": 2819, "s": 2781, "text": "Insulin: Insulin level of the patient" }, { "code": null, "e": 2851, "s": 2819, "text": "BMI: Body Mass Index of patient" }, { "code": null, "e": 2919, "s": 2851, "text": "DiabetesPedigreeFunction: History of diabetes mellitus in relatives" }, { "code": null, "e": 2923, "s": 2919, "text": "Age" }, { "code": null, "e": 2970, "s": 2923, "text": "Outcome: Whether or not a patient has diabetes" }, { "code": null, "e": 3078, "s": 2970, "text": "As an analyst, you will need to know the difference between these variable types — Numeric and Categorical." }, { "code": null, "e": 3237, "s": 3078, "text": "Numeric variables are variables that are a measure, and have some kind of numeric meaning. All the variables in this dataset except for “outcome” are numeric." }, { "code": null, "e": 3350, "s": 3237, "text": "Categorical variables are also called nominal variables, and have two or more categories that can be classified." }, { "code": null, "e": 3471, "s": 3350, "text": "The variable “outcome” is categorical — 0 represents the absence of diabetes, and 1 represents the presence of diabetes." }, { "code": null, "e": 3543, "s": 3471, "text": "Before continuing with the analysis, I would like to make a quick note:" }, { "code": null, "e": 3646, "s": 3543, "text": "Analysts are humans, and we often come with preconceived notions of what we expect to see in the data." }, { "code": null, "e": 3816, "s": 3646, "text": "For example, you would expect an older person to be more likely to have diabetes. You would want to see this correlation in the data, which might not always be the case." }, { "code": null, "e": 3916, "s": 3816, "text": "Keep an open mind during the analysis process, and do not let your bias effect the decision making." }, { "code": null, "e": 4091, "s": 3916, "text": "This is a very useful tool that can be used by analysts. It generates an analysis report on the data frame, and helps you better understand the correlation between variables." }, { "code": null, "e": 4163, "s": 4091, "text": "To generate a Pandas Profiling report, run the following lines of code:" }, { "code": null, "e": 4213, "s": 4163, "text": "import pandas_profiling as pppp.ProfileReport(df)" }, { "code": null, "e": 4315, "s": 4213, "text": "This report will give you some overall statistical information on the dataset, which looks like this:" }, { "code": null, "e": 4434, "s": 4315, "text": "By just glancing at the dataset statistics, we can see that there are no missing or duplicate cells in our data frame." }, { "code": null, "e": 4580, "s": 4434, "text": "The information provided above usually requires us to run a few lines of codes to find, but is generated a lot more easily with Pandas Profiling." }, { "code": null, "e": 4674, "s": 4580, "text": "Pandas Profiling also provides more information on each variable. I will show you an example:" }, { "code": null, "e": 4743, "s": 4674, "text": "This is information generated for the variable called “Pregnancies.”" }, { "code": null, "e": 4879, "s": 4743, "text": "As an analyst, this report saves a lot of time, as we don’t have to go through each individual variable and run too many lines of code." }, { "code": null, "e": 4907, "s": 4879, "text": "From here, we can see that:" }, { "code": null, "e": 4958, "s": 4907, "text": "The variable “Pregnancies” has 17 distinct values." }, { "code": null, "e": 5034, "s": 4958, "text": "The minimum number of pregnancies a person has is 0, and the maximum is 17." }, { "code": null, "e": 5174, "s": 5034, "text": "The number of zero values in this column is pretty low (only 14.5%). This means that above 80% of the patients in the dataset are pregnant." }, { "code": null, "e": 5331, "s": 5174, "text": "In the report, there is information like this provided for each variable. This helps us a lot in our understanding of the dataset and all the columns in it." }, { "code": null, "e": 5468, "s": 5331, "text": "The plot above is a correlation matrix. It helps us gain a better understanding of the correlation between the variables in the dataset." }, { "code": null, "e": 5636, "s": 5468, "text": "There is a slight positive correlation between the variables “Age” and “Skin Thickness”, which can be looked into further in the visualization section of the analysis." }, { "code": null, "e": 5764, "s": 5636, "text": "Since there are no missing or duplicate rows in the data frame as seen above, we don’t need to do any additional data cleaning." }, { "code": null, "e": 5871, "s": 5764, "text": "Now that we have a basic understanding of each variable, we can try to find the relationship between them." }, { "code": null, "e": 5944, "s": 5871, "text": "The simplest and fastest way to do this is by generating visualizations." }, { "code": null, "e": 6050, "s": 5944, "text": "In this tutorial, we will be using three libraries to get the job done — Matplotlib, Seaborn, and Plotly." }, { "code": null, "e": 6165, "s": 6050, "text": "If you are a complete beginner to Python, I suggest starting out and getting familiar with Matplotlib and Seaborn." }, { "code": null, "e": 6401, "s": 6165, "text": "Here is the documentation for Matplotlib, and here is the one for Seaborn. I strongly suggest spending some time reading the documentation, and doing tutorials using these two libraries in order to improve on your visualization skills." }, { "code": null, "e": 6588, "s": 6401, "text": "Plotly is a library that allows you to create interactive charts, and requires slightly more familiarity with Python to master. You can find the installation guide and requirements here." }, { "code": null, "e": 6805, "s": 6588, "text": "If you follow along to this tutorial exactly, you will be able to make beautiful charts with these three libraries. You can then use my code as a template for any future analysis or visualization tasks in the future." }, { "code": null, "e": 6913, "s": 6805, "text": "First, run the following lines of code to import Matplotlib, Seaborn, Numpy, and Plotly after installation:" }, { "code": null, "e": 7233, "s": 6913, "text": "# Visualization Importsimport matplotlib.pyplot as pltimport seaborn as snscolor = sns.color_palette()get_ipython().run_line_magic('matplotlib', 'inline')import plotly.offline as pypy.init_notebook_mode(connected=True)import plotly.graph_objs as goimport plotly.tools as tlsimport plotly.express as pximport numpy as np" }, { "code": null, "e": 7327, "s": 7233, "text": "Next, run the following lines of code to create a pie chart visualizing the outcome variable:" }, { "code": null, "e": 7641, "s": 7327, "text": "dist = df['Outcome'].value_counts()colors = ['mediumturquoise', 'darkorange']trace = go.Pie(values=(np.array(dist)),labels=dist.index)layout = go.Layout(title='Diabetes Outcome')data = [trace]fig = go.Figure(trace,layout)fig.update_traces(marker=dict(colors=colors, line=dict(color='#000000', width=2)))fig.show()" }, { "code": null, "e": 7739, "s": 7641, "text": "This is done with the Plotly library, and you will get an interactive chart that looks like this:" }, { "code": null, "e": 7827, "s": 7739, "text": "You can play around with the chart and choose to change the colors, labels, and legend." }, { "code": null, "e": 7982, "s": 7827, "text": "From the chart above, however, we can see that most patients in the dataset are not diabetic. Less than half of them have an outcome of 1 (have diabetes)." }, { "code": null, "e": 8079, "s": 7982, "text": "Similar to the correlation matrix generated in Pandas Profiling, we can create one using Plotly:" }, { "code": null, "e": 8323, "s": 8079, "text": "def df_to_plotly(df): return {'z': df.values.tolist(), 'x': df.columns.tolist(), 'y': df.index.tolist() }import plotly.graph_objects as godfNew = df.corr()fig = go.Figure(data=go.Heatmap(df_to_plotly(dfNew)))fig.show()" }, { "code": null, "e": 8408, "s": 8323, "text": "The codes above will generate a correlation matrix that is similar to the one above:" }, { "code": null, "e": 8516, "s": 8408, "text": "Again, similar to the matrix generated above, a positive correlation can be observed between the variables:" }, { "code": null, "e": 8536, "s": 8516, "text": "Age and Pregnancies" }, { "code": null, "e": 8556, "s": 8536, "text": "Glucose and Outcome" }, { "code": null, "e": 8582, "s": 8556, "text": "SkinThickness and Insulin" }, { "code": null, "e": 8667, "s": 8582, "text": "To further understand the correlations between variables, we will create some plots:" }, { "code": null, "e": 8892, "s": 8667, "text": "fig = px.scatter(df, x='Glucose', y='Insulin')fig.update_traces(marker_color=\"turquoise\",marker_line_color='rgb(8,48,107)', marker_line_width=1.5)fig.update_layout(title_text='Glucose and Insulin')fig.show()" }, { "code": null, "e": 8961, "s": 8892, "text": "Running the codes above should give you a plot that looks like this:" }, { "code": null, "e": 9138, "s": 8961, "text": "There is a positive correlation between the variables glucose and insulin. This makes sense, because a person with higher glucose levels would be expected to take more insulin." }, { "code": null, "e": 9249, "s": 9138, "text": "Now, we will visualize the variables outcome and age. We will create a boxplot to do so, using the code below:" }, { "code": null, "e": 9465, "s": 9249, "text": "fig = px.box(df, x='Outcome', y='Age')fig.update_traces(marker_color=\"midnightblue\",marker_line_color='rgb(8,48,107)', marker_line_width=1.5)fig.update_layout(title_text='Age and Outcome')fig.show()" }, { "code": null, "e": 9514, "s": 9465, "text": "The resulting plot will look somewhat like this:" }, { "code": null, "e": 9705, "s": 9514, "text": "From the plot above, you can see that older people are more likely to have diabetes. The median age for adults with diabetes is around 35, while it is much lower for people without diabetes." }, { "code": null, "e": 9743, "s": 9705, "text": "However, there are a lot of outliers." }, { "code": null, "e": 9858, "s": 9743, "text": "There are a few elderly people without diabetes (one even over 80 years old), that can be observed in the boxplot." }, { "code": null, "e": 9982, "s": 9858, "text": "Finally, we will visualize the variables “BMI” and “Outcome”, to see if there is any correlation between the two variables." }, { "code": null, "e": 10027, "s": 9982, "text": "To do this, we will use the Seaborn library:" }, { "code": null, "e": 10075, "s": 10027, "text": "plot = sns.boxplot(x='Outcome',y=\"BMI\",data=df)" }, { "code": null, "e": 10292, "s": 10075, "text": "The boxplot created here is similar to the one created above using Plotly. However, Plotly is better at creating visualizations that are interactive, and the charts look prettier compared to the ones made in Seaborn." }, { "code": null, "e": 10457, "s": 10292, "text": "From the box plot above, we can see that higher BMI correlates with a positive outcome. People with diabetes tend to have higher BMI’s than people without diabetes." }, { "code": null, "e": 10585, "s": 10457, "text": "You can make more visualizations like the ones above, by simply changing the variable names and running the same lines of code." }, { "code": null, "e": 10697, "s": 10585, "text": "I will leave that as an exercise for you to do, to get a better grasp on your visualization skills with Python." }, { "code": null, "e": 10819, "s": 10697, "text": "Finally, we can tell a story around the data we have analyzed and visualized. Our findings can be broken down as follows:" }, { "code": null, "e": 11271, "s": 10819, "text": "People with diabetes are highly likely to be older than people who don’t. They are also more likely to have higher BMI’s, or suffer from obesity. They are also more likely to have higher glucose levels in their blood. People with higher glucose levels also tend to take more insulin, and this positive correlation indicates that patients with diabetes could also have higher insulin levels (this correlation can be checked by creating a scatter plot)." }, { "code": null, "e": 11470, "s": 11271, "text": "That’s all for this article! I hope you found this tutorial helpful, and can use it as a future reference for projects you need to create. Good luck in your data science journey, and happy learning!" } ]
ASP.NET - Server Controls
Controls are small building blocks of the graphical user interface, which include text boxes, buttons, check boxes, list boxes, labels, and numerous other tools. Using these tools, the users can enter data, make selections and indicate their preferences. Controls are also used for structural jobs, like validation, data access, security, creating master pages, and data manipulation. ASP.NET uses five types of web controls, which are: HTML controls HTML Server controls ASP.NET Server controls ASP.NET Ajax Server controls User controls and custom controls ASP.NET server controls are the primary controls used in ASP.NET. These controls can be grouped into the following categories: Validation controls - These are used to validate user input and they work by running client-side script. Validation controls - These are used to validate user input and they work by running client-side script. Data source controls - These controls provides data binding to different data sources. Data source controls - These controls provides data binding to different data sources. Data view controls - These are various lists and tables, which can bind to data from data sources for displaying. Data view controls - These are various lists and tables, which can bind to data from data sources for displaying. Personalization controls - These are used for personalization of a page according to the user preferences, based on user information. Personalization controls - These are used for personalization of a page according to the user preferences, based on user information. Login and security controls - These controls provide user authentication. Login and security controls - These controls provide user authentication. Master pages - These controls provide consistent layout and interface throughout the application. Master pages - These controls provide consistent layout and interface throughout the application. Navigation controls - These controls help in navigation. For example, menus, tree view etc. Navigation controls - These controls help in navigation. For example, menus, tree view etc. Rich controls - These controls implement special features. For example, AdRotator, FileUpload, and Calendar control. Rich controls - These controls implement special features. For example, AdRotator, FileUpload, and Calendar control. The syntax for using server controls is: <asp:controlType ID ="ControlID" runat="server" Property1=value1 [Property2=value2] /> In addition, visual studio has the following features, to help produce in error-free coding: Dragging and dropping of controls in design view IntelliSense feature that displays and auto-completes the properties The properties window to set the property values directly ASP.NET server controls with a visual aspect are derived from the WebControl class and inherit all the properties, events, and methods of this class. The WebControl class itself and some other server controls that are not visually rendered are derived from the System.Web.UI.Control class. For example, PlaceHolder control or XML control. ASP.Net server controls inherit all properties, events, and methods of the WebControl and System.Web.UI.Control class. The following table shows the inherited properties, common to all server controls: The following table provides the methods of the server controls: Let us look at a particular server control - a tree view control. A Tree view control comes under navigation controls. Other Navigation controls are: Menu control and SiteMapPath control. Add a tree view control on the page. Select Edit Nodes... from the tasks. Edit each of the nodes using the Tree view node editor as shown: Once you have created the nodes, it looks like the following in design view: The AutoFormat... task allows you to format the tree view as shown: Add a label control and a text box control on the page and name them lblmessage and txtmessage respectively. Write a few lines of code to ensure that when a particular node is selected, the label control displays the node text and the text box displays all child nodes under it, if any. The code behind the file should look like this: using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; namespace eventdemo { public partial class treeviewdemo : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { txtmessage.Text = " "; } protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e) { txtmessage.Text = " "; lblmessage.Text = "Selected node changed to: " + TreeView1.SelectedNode.Text; TreeNodeCollection childnodes = TreeView1.SelectedNode.ChildNodes; if(childnodes != null) { txtmessage.Text = " "; foreach (TreeNode t in childnodes) { txtmessage.Text += t.Value; } } } } } Execute the page to see the effects. You will be able to expand and collapse the nodes. 51 Lectures 5.5 hours Anadi Sharma 44 Lectures 4.5 hours Kaushik Roy Chowdhury 42 Lectures 18 hours SHIVPRASAD KOIRALA 57 Lectures 3.5 hours University Code 40 Lectures 2.5 hours University Code 138 Lectures 9 hours Bhrugen Patel Print Add Notes Bookmark this page
[ { "code": null, "e": 2602, "s": 2347, "text": "Controls are small building blocks of the graphical user interface, which include text boxes, buttons, check boxes, list boxes, labels, and numerous other tools. Using these tools, the users can enter data, make selections and indicate their preferences." }, { "code": null, "e": 2732, "s": 2602, "text": "Controls are also used for structural jobs, like validation, data access, security, creating master pages, and data manipulation." }, { "code": null, "e": 2784, "s": 2732, "text": "ASP.NET uses five types of web controls, which are:" }, { "code": null, "e": 2798, "s": 2784, "text": "HTML controls" }, { "code": null, "e": 2819, "s": 2798, "text": "HTML Server controls" }, { "code": null, "e": 2843, "s": 2819, "text": "ASP.NET Server controls" }, { "code": null, "e": 2872, "s": 2843, "text": "ASP.NET Ajax Server controls" }, { "code": null, "e": 2906, "s": 2872, "text": "User controls and custom controls" }, { "code": null, "e": 3033, "s": 2906, "text": "ASP.NET server controls are the primary controls used in ASP.NET. These controls can be grouped into the following categories:" }, { "code": null, "e": 3138, "s": 3033, "text": "Validation controls - These are used to validate user input and they work by running client-side script." }, { "code": null, "e": 3243, "s": 3138, "text": "Validation controls - These are used to validate user input and they work by running client-side script." }, { "code": null, "e": 3331, "s": 3243, "text": "Data source controls - These controls provides data binding to different data sources." }, { "code": null, "e": 3419, "s": 3331, "text": "Data source controls - These controls provides data binding to different data sources." }, { "code": null, "e": 3533, "s": 3419, "text": "Data view controls - These are various lists and tables, which can bind to data from data sources for displaying." }, { "code": null, "e": 3647, "s": 3533, "text": "Data view controls - These are various lists and tables, which can bind to data from data sources for displaying." }, { "code": null, "e": 3781, "s": 3647, "text": "Personalization controls - These are used for personalization of a page according to the user preferences, based on user information." }, { "code": null, "e": 3915, "s": 3781, "text": "Personalization controls - These are used for personalization of a page according to the user preferences, based on user information." }, { "code": null, "e": 3989, "s": 3915, "text": "Login and security controls - These controls provide user authentication." }, { "code": null, "e": 4063, "s": 3989, "text": "Login and security controls - These controls provide user authentication." }, { "code": null, "e": 4161, "s": 4063, "text": "Master pages - These controls provide consistent layout and interface throughout the application." }, { "code": null, "e": 4259, "s": 4161, "text": "Master pages - These controls provide consistent layout and interface throughout the application." }, { "code": null, "e": 4351, "s": 4259, "text": "Navigation controls - These controls help in navigation. For example, menus, tree view etc." }, { "code": null, "e": 4443, "s": 4351, "text": "Navigation controls - These controls help in navigation. For example, menus, tree view etc." }, { "code": null, "e": 4560, "s": 4443, "text": "Rich controls - These controls implement special features. For example, AdRotator, FileUpload, and Calendar control." }, { "code": null, "e": 4677, "s": 4560, "text": "Rich controls - These controls implement special features. For example, AdRotator, FileUpload, and Calendar control." }, { "code": null, "e": 4718, "s": 4677, "text": "The syntax for using server controls is:" }, { "code": null, "e": 4807, "s": 4718, "text": "<asp:controlType ID =\"ControlID\" runat=\"server\" Property1=value1 [Property2=value2] />" }, { "code": null, "e": 4900, "s": 4807, "text": "In addition, visual studio has the following features, to help produce in error-free coding:" }, { "code": null, "e": 4949, "s": 4900, "text": "Dragging and dropping of controls in design view" }, { "code": null, "e": 5018, "s": 4949, "text": "IntelliSense feature that displays and auto-completes the properties" }, { "code": null, "e": 5076, "s": 5018, "text": "The properties window to set the property values directly" }, { "code": null, "e": 5226, "s": 5076, "text": "ASP.NET server controls with a visual aspect are derived from the WebControl class and inherit all the properties, events, and methods of this class." }, { "code": null, "e": 5415, "s": 5226, "text": "The WebControl class itself and some other server controls that are not visually rendered are derived from the System.Web.UI.Control class. For example, PlaceHolder control or XML control." }, { "code": null, "e": 5534, "s": 5415, "text": "ASP.Net server controls inherit all properties, events, and methods of the WebControl and System.Web.UI.Control class." }, { "code": null, "e": 5617, "s": 5534, "text": "The following table shows the inherited properties, common to all server controls:" }, { "code": null, "e": 5682, "s": 5617, "text": "The following table provides the methods of the server controls:" }, { "code": null, "e": 5870, "s": 5682, "text": "Let us look at a particular server control - a tree view control. A Tree view control comes under navigation controls. Other Navigation controls are: Menu control and SiteMapPath control." }, { "code": null, "e": 6009, "s": 5870, "text": "Add a tree view control on the page. Select Edit Nodes... from the tasks. Edit each of the nodes using the Tree view node editor as shown:" }, { "code": null, "e": 6086, "s": 6009, "text": "Once you have created the nodes, it looks like the following in design view:" }, { "code": null, "e": 6154, "s": 6086, "text": "The AutoFormat... task allows you to format the tree view as shown:" }, { "code": null, "e": 6263, "s": 6154, "text": "Add a label control and a text box control on the page and name them lblmessage and txtmessage respectively." }, { "code": null, "e": 6490, "s": 6263, "text": " Write a few lines of code to ensure that when a particular node is selected, the label control displays the node text and the text box displays all child nodes under it, if any. The code behind the file should look like this:" }, { "code": null, "e": 7502, "s": 6490, "text": "using System;\nusing System.Collections;\nusing System.Configuration;\nusing System.Data;\nusing System.Linq;\n\nusing System.Web;\nusing System.Web.Security;\nusing System.Web.UI;\nusing System.Web.UI.HtmlControls;\nusing System.Web.UI.WebControls;\nusing System.Web.UI.WebControls.WebParts;\n\nusing System.Xml.Linq;\n \nnamespace eventdemo {\n public partial class treeviewdemo : System.Web.UI.Page {\n \n protected void Page_Load(object sender, EventArgs e) { \n txtmessage.Text = \" \"; \n }\n \n protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e) {\n \n txtmessage.Text = \" \"; \n lblmessage.Text = \"Selected node changed to: \" + TreeView1.SelectedNode.Text;\n TreeNodeCollection childnodes = TreeView1.SelectedNode.ChildNodes;\n \n if(childnodes != null) {\n txtmessage.Text = \" \";\n \n foreach (TreeNode t in childnodes) {\n txtmessage.Text += t.Value;\n }\n }\n }\n }\n}" }, { "code": null, "e": 7591, "s": 7502, "text": "Execute the page to see the effects. You will be able to expand and collapse the nodes." }, { "code": null, "e": 7626, "s": 7591, "text": "\n 51 Lectures \n 5.5 hours \n" }, { "code": null, "e": 7640, "s": 7626, "text": " Anadi Sharma" }, { "code": null, "e": 7675, "s": 7640, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 7698, "s": 7675, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 7732, "s": 7698, "text": "\n 42 Lectures \n 18 hours \n" }, { "code": null, "e": 7752, "s": 7732, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 7787, "s": 7752, "text": "\n 57 Lectures \n 3.5 hours \n" }, { "code": null, "e": 7804, "s": 7787, "text": " University Code" }, { "code": null, "e": 7839, "s": 7804, "text": "\n 40 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7856, "s": 7839, "text": " University Code" }, { "code": null, "e": 7890, "s": 7856, "text": "\n 138 Lectures \n 9 hours \n" }, { "code": null, "e": 7905, "s": 7890, "text": " Bhrugen Patel" }, { "code": null, "e": 7912, "s": 7905, "text": " Print" }, { "code": null, "e": 7923, "s": 7912, "text": " Add Notes" } ]
What is the use of "from...import" Statement in Python?
The "from module import function" statement is used to import a specific function from a Python module. For example, if you want to import the sin function from the math library without importing any other function, you can do it as follows: >>> from math import sin >>> sin(0) 0.0 Note that you don't have to prefix sin with "math." as only sin has been imported and not math. Also you can alias imported functions. For example, >>> from math import cos as cosine >>> cosine(0) 1.0
[ { "code": null, "e": 1304, "s": 1062, "text": "The \"from module import function\" statement is used to import a specific function from a Python module. For example, if you want to import the sin function from the math library without importing any other function, you can do it as follows:" }, { "code": null, "e": 1344, "s": 1304, "text": ">>> from math import sin\n>>> sin(0)\n0.0" }, { "code": null, "e": 1492, "s": 1344, "text": "Note that you don't have to prefix sin with \"math.\" as only sin has been imported and not math. Also you can alias imported functions. For example," }, { "code": null, "e": 1545, "s": 1492, "text": ">>> from math import cos as cosine\n>>> cosine(0)\n1.0" } ]
How to create a hoverable dropdown menu with CSS?
Following is the code to create a hoverable dropdown menu with CSS − Live Demo <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1" /> <style> .menu-btn { background-color: #7e32d4; color: white; padding: 16px; font-size: 20px; font-weight: bolder; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; border: none; } .dropdown-menu { position: relative; display: inline-block; } .menu-content { display: none; position: absolute; background-color: #017575; min-width: 160px; z-index: 1; } .links { color: rgb(255, 255, 255); padding: 12px 16px; text-decoration: none; display: block; font-size: 18px; font-weight: bold; border-bottom: 1px solid black; } .links:hover { background-color: rgb(8, 107, 46); } .dropdown-menu:hover .menu-content { display: block; } .dropdown-menu:hover .menu-btn { background-color: #3e8e41; } </style> </head> <body> <h2>Hover over the below dropdown button to open dropdown menu</h2> <div class="dropdown-menu"> <button class="menu-btn">Open </button> <div class="menu-content"> <a class="links" href="#">Contact Us</a> <a class="links" href="#">Visit Us</a> <a class="links" href="#">About Us</a> </div> </div> </body> </html> The above code will produce the following output − On hovering over the open button the dropdown menu will open as shown below −
[ { "code": null, "e": 1131, "s": 1062, "text": "Following is the code to create a hoverable dropdown menu with CSS −" }, { "code": null, "e": 1142, "s": 1131, "text": " Live Demo" }, { "code": null, "e": 2349, "s": 1142, "text": "<!DOCTYPE html>\n<html>\n<head>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n<style>\n.menu-btn {\n background-color: #7e32d4;\n color: white;\n padding: 16px;\n font-size: 20px;\n font-weight: bolder;\n font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;\n border: none;\n}\n.dropdown-menu {\n position: relative;\n display: inline-block;\n}\n.menu-content {\n display: none;\n position: absolute;\n background-color: #017575;\n min-width: 160px;\n z-index: 1;\n}\n.links {\n color: rgb(255, 255, 255);\n padding: 12px 16px;\n text-decoration: none;\n display: block;\n font-size: 18px;\n font-weight: bold;\n border-bottom: 1px solid black;\n}\n.links:hover {\n background-color: rgb(8, 107, 46);\n}\n.dropdown-menu:hover .menu-content {\n display: block;\n}\n.dropdown-menu:hover .menu-btn {\n background-color: #3e8e41;\n}\n</style>\n</head>\n<body>\n<h2>Hover over the below dropdown button to open dropdown menu</h2>\n<div class=\"dropdown-menu\">\n<button class=\"menu-btn\">Open </button>\n<div class=\"menu-content\">\n<a class=\"links\" href=\"#\">Contact Us</a>\n<a class=\"links\" href=\"#\">Visit Us</a>\n<a class=\"links\" href=\"#\">About Us</a>\n</div>\n</div>\n</body>\n</html>" }, { "code": null, "e": 2400, "s": 2349, "text": "The above code will produce the following output −" }, { "code": null, "e": 2478, "s": 2400, "text": "On hovering over the open button the dropdown menu will open as shown below −" } ]
How to count the total number of radio buttons in a page in Selenium with python?
We can count the total number of radio buttons in a page in Selenium with the help of find_elements method. While working on any radio buttons, we will always find an attribute type in the html code and its value should be radio. This characteristic is only applicable to radio buttons on that particular page and to no other types of UI elements like edit box, link and so on. To retrieve all the elements with attribute type = 'radio', we will use find_elements_by_xpath() method. This method returns a list of web elements with the type of xpath specified in the method argument. In case there are no matching elements, an empty list will be returned. After the list of radio buttons are fetched, in order to count its total numbers, we need to get the size of that list. The size of the list can be obtained from the len() method of the list data structure. Finally this length is printed on the console. driver.find_elements_by_xpath("//input[@type='radio']") Code Implementation for counting radio buttons. from selenium import webdriver #browser exposes an executable file #Through Selenium test we will invoke the executable file which will then #invoke actual browser driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe") # to maximize the browser window driver.maximize_window() #get method to launch the URL driver.get("https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm") #to refresh the browser driver.refresh() # identifying the radio buttons with type attribute in a list chk =driver.find_elements_by_xpath("//input[@type='radio']") # len method is used to get the size of that list print(len(chk)) #to close the browser driver.close()
[ { "code": null, "e": 1292, "s": 1062, "text": "We can count the total number of radio buttons in a page in Selenium with the help of find_elements method. While working on any radio buttons, we will always find an attribute type in the html code and its value should be radio." }, { "code": null, "e": 1440, "s": 1292, "text": "This characteristic is only applicable to radio buttons on that particular page and to no other types of UI elements like edit box, link and so on." }, { "code": null, "e": 1717, "s": 1440, "text": "To retrieve all the elements with attribute type = 'radio', we will use find_elements_by_xpath() method. This method returns a list of web elements with the type of xpath specified in the method argument. In case there are no matching elements, an empty list will be returned." }, { "code": null, "e": 1924, "s": 1717, "text": "After the list of radio buttons are fetched, in order to count its total numbers, we need to get the size of that list. The size of the list can be obtained from the len() method of the list data structure." }, { "code": null, "e": 1971, "s": 1924, "text": "Finally this length is printed on the console." }, { "code": null, "e": 2027, "s": 1971, "text": "driver.find_elements_by_xpath(\"//input[@type='radio']\")" }, { "code": null, "e": 2075, "s": 2027, "text": "Code Implementation for counting radio buttons." }, { "code": null, "e": 2747, "s": 2075, "text": "from selenium import webdriver\n#browser exposes an executable file\n#Through Selenium test we will invoke the executable file which will then #invoke actual browser\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\")\n# to maximize the browser window\ndriver.maximize_window()\n#get method to launch the URL\ndriver.get(\"https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm\")\n#to refresh the browser\ndriver.refresh()\n# identifying the radio buttons with type attribute in a list\nchk =driver.find_elements_by_xpath(\"//input[@type='radio']\")\n# len method is used to get the size of that list\nprint(len(chk))\n#to close the browser\ndriver.close()" } ]
Rust - Variables
A variable is a named storage that programs can manipulate. Simply put, a variable helps programs to store values. Variables in Rust are associated with a specific data type. The data type determines the size and layout of the variable's memory, the range of values that can be stored within that memory and the set of operations that can be performed on the variable. In this section, we will learn about the different rules for naming a variable. The name of a variable can be composed of letters, digits, and the underscore character. The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because Rust is case-sensitive. Upper and lowercase letters are distinct because Rust is case-sensitive. The data type is optional while declaring a variable in Rust. The data type is inferred from the value assigned to the variable. The syntax for declaring a variable is given below. let variable_name = value; // no type specified let variable_name:dataType = value; //type specified fn main() { let fees = 25_000; let salary:f64 = 35_000.00; println!("fees is {} and salary is {}",fees,salary); } The output of the above code will be fees is 25000 and salary is 35000. By default, variables are immutable − read only in Rust. In other words, the variable's value cannot be changed once a value is bound to a variable name. Let us understand this with an example. fn main() { let fees = 25_000; println!("fees is {} ",fees); fees = 35_000; println!("fees changed is {}",fees); } The output will be as shown below − error[E0384]: re-assignment of immutable variable `fees` --> main.rs:6:3 | 3 | let fees = 25_000; | ---- first assignment to `fees` ... 6 | fees=35_000; | ^^^^^^^^^^^ re-assignment of immutable variable error: aborting due to previous error(s) The error message indicates the cause of the error – you cannot assign values twice to immutable variable fees. This is one of the many ways Rust allows programmers to write code and takes advantage of the safety and easy concurrency. Variables are immutable by default. Prefix the variable name with mut keyword to make it mutable. The value of a mutable variable can be changed. The syntax for declaring a mutable variable is as shown below − let mut variable_name = value; let mut variable_name:dataType = value; Let us understand this with an example fn main() { let mut fees:i32 = 25_000; println!("fees is {} ",fees); fees = 35_000; println!("fees changed is {}",fees); } The output of the snippet is given below − fees is 25000 fees changed is 35000 45 Lectures 4.5 hours Stone River ELearning 10 Lectures 33 mins Ken Burke Print Add Notes Bookmark this page
[ { "code": null, "e": 2456, "s": 2087, "text": "A variable is a named storage that programs can manipulate. Simply put, a variable helps programs to store values. Variables in Rust are associated with a specific data type. The data type determines the size and layout of the variable's memory, the range of values that can be stored within that memory and the set of operations that can be performed on the variable." }, { "code": null, "e": 2536, "s": 2456, "text": "In this section, we will learn about the different rules for naming a variable." }, { "code": null, "e": 2625, "s": 2536, "text": "The name of a variable can be composed of letters, digits, and the underscore character." }, { "code": null, "e": 2714, "s": 2625, "text": "The name of a variable can be composed of letters, digits, and the underscore character." }, { "code": null, "e": 2767, "s": 2714, "text": "It must begin with either a letter or an underscore." }, { "code": null, "e": 2820, "s": 2767, "text": "It must begin with either a letter or an underscore." }, { "code": null, "e": 2893, "s": 2820, "text": "Upper and lowercase letters are distinct because Rust is case-sensitive." }, { "code": null, "e": 2966, "s": 2893, "text": "Upper and lowercase letters are distinct because Rust is case-sensitive." }, { "code": null, "e": 3095, "s": 2966, "text": "The data type is optional while declaring a variable in Rust. The data type is inferred from the value assigned to the variable." }, { "code": null, "e": 3147, "s": 3095, "text": "The syntax for declaring a variable is given below." }, { "code": null, "e": 3262, "s": 3147, "text": "let variable_name = value; // no type specified\nlet variable_name:dataType = value; //type specified\n" }, { "code": null, "e": 3385, "s": 3262, "text": "fn main() {\n let fees = 25_000;\n let salary:f64 = 35_000.00;\n println!(\"fees is {} and salary is {}\",fees,salary);\n}" }, { "code": null, "e": 3457, "s": 3385, "text": "The output of the above code will be fees is 25000 and salary is 35000." }, { "code": null, "e": 3611, "s": 3457, "text": "By default, variables are immutable − read only in Rust. In other words, the variable's value cannot be changed once a value is bound to a variable name." }, { "code": null, "e": 3651, "s": 3611, "text": "Let us understand this with an example." }, { "code": null, "e": 3778, "s": 3651, "text": "fn main() {\n let fees = 25_000;\n println!(\"fees is {} \",fees);\n fees = 35_000;\n println!(\"fees changed is {}\",fees);\n}" }, { "code": null, "e": 3814, "s": 3778, "text": "The output will be as shown below −" }, { "code": null, "e": 4072, "s": 3814, "text": "error[E0384]: re-assignment of immutable variable `fees`\n --> main.rs:6:3\n |\n 3 | let fees = 25_000;\n | ---- first assignment to `fees`\n...\n 6 | fees=35_000;\n | ^^^^^^^^^^^ re-assignment of immutable variable\n\nerror: aborting due to previous error(s)\n" }, { "code": null, "e": 4307, "s": 4072, "text": "The error message indicates the cause of the error – you cannot assign values twice to immutable variable fees. This is one of the many ways Rust allows programmers to write code and takes advantage of the safety and easy concurrency." }, { "code": null, "e": 4453, "s": 4307, "text": "Variables are immutable by default. Prefix the variable name with mut keyword to make it mutable. The value of a mutable variable can be changed." }, { "code": null, "e": 4517, "s": 4453, "text": "The syntax for declaring a mutable variable is as shown below −" }, { "code": null, "e": 4763, "s": 4517, "text": "let mut variable_name = value;\nlet mut variable_name:dataType = value;\nLet us understand this with an example\n\nfn main() {\n let mut fees:i32 = 25_000;\n println!(\"fees is {} \",fees);\n fees = 35_000;\n println!(\"fees changed is {}\",fees);\n}" }, { "code": null, "e": 4806, "s": 4763, "text": "The output of the snippet is given below −" }, { "code": null, "e": 4843, "s": 4806, "text": "fees is 25000\nfees changed is 35000\n" }, { "code": null, "e": 4878, "s": 4843, "text": "\n 45 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4901, "s": 4878, "text": " Stone River ELearning" }, { "code": null, "e": 4933, "s": 4901, "text": "\n 10 Lectures \n 33 mins\n" }, { "code": null, "e": 4944, "s": 4933, "text": " Ken Burke" }, { "code": null, "e": 4951, "s": 4944, "text": " Print" }, { "code": null, "e": 4962, "s": 4951, "text": " Add Notes" } ]
OpenCV - Using Camera
In this chapter, we will learn how to use OpenCV to capture frames using the system camera. The VideoCapture class of the org.opencv.videoio package contains classes and methods to capture video using the camera. Let’s go step by step and learn how to capture frames − While writing Java code using OpenCV library, the first step you need to do is to load the native library of OpenCV using the loadLibrary(). Load the OpenCV native library as shown below. // Loading the core library System.loadLibrary(Core.NATIVE_LIBRARY_NAME); Instantiate the Mat class using any of the functions mentioned in this tutorial earlier. // Instantiating the VideoCapture class (camera:: 0) VideoCapture capture = new VideoCapture(0); You can read the frames from the camera using the read() method of the VideoCapture class. This method accepts an object of the class Mat to store the frame read. // Reading the next video frame from the camera Mat matrix = new Mat(); capture.read(matrix); The following program demonstrates how to capture a frame using camera and display it using JavaFX window. It also saves the captured frame. import java.awt.image.BufferedImage; import java.awt.image.DataBufferByte; import java.awt.image.WritableRaster; import java.io.FileNotFoundException; import java.io.IOException; import javafx.application.Application; import javafx.embed.swing.SwingFXUtils; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.image.ImageView; import javafx.scene.image.WritableImage; import javafx.stage.Stage; import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.imgcodecs.Imgcodecs; import org.opencv.videoio.VideoCapture; public class CameraSnapshotJavaFX extends Application { Mat matrix = null; @Override public void start(Stage stage) throws FileNotFoundException, IOException { // Capturing the snapshot from the camera CameraSnapshotJavaFX obj = new CameraSnapshotJavaFX(); WritableImage writableImage = obj.capureSnapShot(); // Saving the image obj.saveImage(); // Setting the image view ImageView imageView = new ImageView(writableImage); // setting the fit height and width of the image view imageView.setFitHeight(400); imageView.setFitWidth(600); // Setting the preserve ratio of the image view imageView.setPreserveRatio(true); // Creating a Group object Group root = new Group(imageView); // Creating a scene object Scene scene = new Scene(root, 600, 400); // Setting title to the Stage stage.setTitle("Capturing an image"); // Adding scene to the stage stage.setScene(scene); // Displaying the contents of the stage stage.show(); } public WritableImage capureSnapShot() { WritableImage WritableImage = null; // Loading the OpenCV core library System.loadLibrary( Core.NATIVE_LIBRARY_NAME ); // Instantiating the VideoCapture class (camera:: 0) VideoCapture capture = new VideoCapture(0); // Reading the next video frame from the camera Mat matrix = new Mat(); capture.read(matrix); // If camera is opened if( capture.isOpened()) { // If there is next video frame if (capture.read(matrix)) { // Creating BuffredImage from the matrix BufferedImage image = new BufferedImage(matrix.width(), matrix.height(), BufferedImage.TYPE_3BYTE_BGR); WritableRaster raster = image.getRaster(); DataBufferByte dataBuffer = (DataBufferByte) raster.getDataBuffer(); byte[] data = dataBuffer.getData(); matrix.get(0, 0, data); this.matrix = matrix; // Creating the Writable Image WritableImage = SwingFXUtils.toFXImage(image, null); } } return WritableImage; } public void saveImage() { // Saving the Image String file = "E:/OpenCV/chap22/sanpshot.jpg"; // Instantiating the imgcodecs class Imgcodecs imageCodecs = new Imgcodecs(); // Saving it again imageCodecs.imwrite(file, matrix); } public static void main(String args[]) { launch(args); } } On executing the program, you will get the following output. If you open the specified path, you can observe the same frame which is saved as a jpg file. 70 Lectures 9 hours Abhilash Nelson 41 Lectures 4 hours Abhilash Nelson 20 Lectures 2 hours Spotle Learn 12 Lectures 46 mins Srikanth Guskra 19 Lectures 2 hours Haithem Gasmi 67 Lectures 6.5 hours Gianluca Mottola Print Add Notes Bookmark this page
[ { "code": null, "e": 3273, "s": 3004, "text": "In this chapter, we will learn how to use OpenCV to capture frames using the system camera. The VideoCapture class of the org.opencv.videoio package contains classes and methods to capture video using the camera. Let’s go step by step and learn how to capture frames −" }, { "code": null, "e": 3461, "s": 3273, "text": "While writing Java code using OpenCV library, the first step you need to do is to load the native library of OpenCV using the loadLibrary(). Load the OpenCV native library as shown below." }, { "code": null, "e": 3537, "s": 3461, "text": "// Loading the core library \nSystem.loadLibrary(Core.NATIVE_LIBRARY_NAME);\n" }, { "code": null, "e": 3626, "s": 3537, "text": "Instantiate the Mat class using any of the functions mentioned in this tutorial earlier." }, { "code": null, "e": 3725, "s": 3626, "text": "// Instantiating the VideoCapture class (camera:: 0) \nVideoCapture capture = new VideoCapture(0);\n" }, { "code": null, "e": 3888, "s": 3725, "text": "You can read the frames from the camera using the read() method of the VideoCapture class. This method accepts an object of the class Mat to store the frame read." }, { "code": null, "e": 3985, "s": 3888, "text": "// Reading the next video frame from the camera \nMat matrix = new Mat(); \ncapture.read(matrix);\n" }, { "code": null, "e": 4126, "s": 3985, "text": "The following program demonstrates how to capture a frame using camera and display it using JavaFX window. It also saves the captured frame." }, { "code": null, "e": 7272, "s": 4126, "text": "import java.awt.image.BufferedImage;\nimport java.awt.image.DataBufferByte;\nimport java.awt.image.WritableRaster;\n\nimport java.io.FileNotFoundException;\nimport java.io.IOException;\n\nimport javafx.application.Application;\nimport javafx.embed.swing.SwingFXUtils;\nimport javafx.scene.Group;\nimport javafx.scene.Scene;\nimport javafx.scene.image.ImageView;\nimport javafx.scene.image.WritableImage;\nimport javafx.stage.Stage;\n\nimport org.opencv.core.Core;\nimport org.opencv.core.Mat;\nimport org.opencv.imgcodecs.Imgcodecs;\nimport org.opencv.videoio.VideoCapture;\n\npublic class CameraSnapshotJavaFX extends Application {\n Mat matrix = null;\n\n @Override\n public void start(Stage stage) throws FileNotFoundException, IOException {\n // Capturing the snapshot from the camera\n CameraSnapshotJavaFX obj = new CameraSnapshotJavaFX();\n WritableImage writableImage = obj.capureSnapShot();\n\n // Saving the image\n obj.saveImage();\n\n // Setting the image view\n ImageView imageView = new ImageView(writableImage);\n\n // setting the fit height and width of the image view\n imageView.setFitHeight(400);\n imageView.setFitWidth(600);\n\n // Setting the preserve ratio of the image view\n imageView.setPreserveRatio(true);\n\n // Creating a Group object\n Group root = new Group(imageView);\n\n // Creating a scene object\n Scene scene = new Scene(root, 600, 400);\n\n // Setting title to the Stage\n stage.setTitle(\"Capturing an image\");\n\n // Adding scene to the stage\n stage.setScene(scene);\n\n // Displaying the contents of the stage\n stage.show();\n }\n public WritableImage capureSnapShot() {\n WritableImage WritableImage = null;\n\n // Loading the OpenCV core library\n System.loadLibrary( Core.NATIVE_LIBRARY_NAME );\n\n // Instantiating the VideoCapture class (camera:: 0)\n VideoCapture capture = new VideoCapture(0);\n\n // Reading the next video frame from the camera\n Mat matrix = new Mat();\n capture.read(matrix);\n\n // If camera is opened\n if( capture.isOpened()) {\n // If there is next video frame\n if (capture.read(matrix)) {\n // Creating BuffredImage from the matrix\n BufferedImage image = new BufferedImage(matrix.width(), \n matrix.height(), BufferedImage.TYPE_3BYTE_BGR);\n \n WritableRaster raster = image.getRaster();\n DataBufferByte dataBuffer = (DataBufferByte) raster.getDataBuffer();\n byte[] data = dataBuffer.getData();\n matrix.get(0, 0, data);\n this.matrix = matrix;\n \n // Creating the Writable Image\n WritableImage = SwingFXUtils.toFXImage(image, null);\n }\n }\n return WritableImage;\n }\n public void saveImage() {\n // Saving the Image\n String file = \"E:/OpenCV/chap22/sanpshot.jpg\";\n\n // Instantiating the imgcodecs class\n Imgcodecs imageCodecs = new Imgcodecs();\n\n // Saving it again \n imageCodecs.imwrite(file, matrix);\n }\n public static void main(String args[]) {\n launch(args);\n }\n}" }, { "code": null, "e": 7333, "s": 7272, "text": "On executing the program, you will get the following output." }, { "code": null, "e": 7426, "s": 7333, "text": "If you open the specified path, you can observe the same frame which is saved as a jpg file." }, { "code": null, "e": 7459, "s": 7426, "text": "\n 70 Lectures \n 9 hours \n" }, { "code": null, "e": 7476, "s": 7459, "text": " Abhilash Nelson" }, { "code": null, "e": 7509, "s": 7476, "text": "\n 41 Lectures \n 4 hours \n" }, { "code": null, "e": 7526, "s": 7509, "text": " Abhilash Nelson" }, { "code": null, "e": 7559, "s": 7526, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 7573, "s": 7559, "text": " Spotle Learn" }, { "code": null, "e": 7605, "s": 7573, "text": "\n 12 Lectures \n 46 mins\n" }, { "code": null, "e": 7622, "s": 7605, "text": " Srikanth Guskra" }, { "code": null, "e": 7655, "s": 7622, "text": "\n 19 Lectures \n 2 hours \n" }, { "code": null, "e": 7670, "s": 7655, "text": " Haithem Gasmi" }, { "code": null, "e": 7705, "s": 7670, "text": "\n 67 Lectures \n 6.5 hours \n" }, { "code": null, "e": 7723, "s": 7705, "text": " Gianluca Mottola" }, { "code": null, "e": 7730, "s": 7723, "text": " Print" }, { "code": null, "e": 7741, "s": 7730, "text": " Add Notes" } ]
Practical Python: Try, Except, and Assert | by Soner Yıldırım | Towards Data Science
The dream of every software programmer is to write a program that runs smoothly. However, this is not usually the case at first. The execution of a code stops in case of an error. Unexpected situations or conditions might cause errors. Python considers these situations as exceptions and raises different kinds of errors depending on the type of exception. ValueError, TypeError, AttributeError, and SyntaxError are some examples for those exceptions. The good thing is that Python also provides ways to handle the exceptions. Consider the following code that asks the user to input a number and prints the square of the number. a = int(input("Please enter a number: "))print(f'{a} squared is {a*a}') It works fine as long as the input is a number. However, if the user inputs a string, python will raise a ValueError: We can implement a try-except block in our code to handle this exception better. For instance, we can return a simpler error message to the users or ask them for another input. try: a = int(input("Please enter a number: ")) print(f'{a} squared is {a*a}')except: print("Wrong input type! You must enter a number!") In the case above, the code informs the user about the error more clearly. If an exception is raised due to the code in the try block, the execution continues with the statements in the except block. So, it is up to the programmer how to handle the exception. The plain try-except block will catch any type of error. But, we can be more specific. For instance, we may be interested in only a particular type of error or want to handle different types of error differently. The type of error can be specified with the except statement. Consider the following code that asks user for a number from a list. Then, it returns a name from a dictionary based on the input. dict_a = {1:'Max', 2:'Ashley', 3:'John'}number = int(input(f'Pick a number from the list: {list(dict_a.keys())}')) If the user enters a number that is not in the given list, we will get a KeyError. If the input is not a number, we will get a ValueError. We can handle both cases using two except statements. try: dict_a = {1:'Max', 2:'Ashley', 3:'John'} number = int(input(f'Pick a number from the list: {list(dict_a.keys())}')) print(dict_a[number])except KeyError: print(f'{number} is not in the list')except ValueError: print('You must enter a number!') Python also allows raising your own exception. It is kind of customizing the default exceptions. The raise keyword along with the error type is used to create your own exception. try: a = int(input("Please enter a number: ")) print(f'{a} squared is {a*a}')except: raise ValueError("You must enter a number!") Here is the error message in case of a non-number input. ValueError: You must enter a number! Let’s do another example that shows how to use try-except block in a function. The avg_value function returns the average value of a list of numbers. a = [1, 2, 3]def avg_value(lst): avg = sum(lst) / len(lst) return avgprint(avg_value(a))2 If we pass an empty list to this function, it will give a ZeroDivisionError because the length of an empty list is zero. We can implement a try-except block in the function to handle this exception. def avg_value(lst): try: avg = sum(lst) / len(lst) return avg except: print('Warning: Empty list') return 0 In case of empty lists, the function will print a warning and return 0. a = []print(avg_value(a))Warning: Empty list0 The try and except blocks are used to handle exceptions. The assert is used to ensure the conditions are compatible with the requirements of a function. If the assert is false, the function does not continue. Thus, the assert can be an example of defensive programming. The programmer is making sure that everything is as expected. Let’s implement the assert in our avg_value function. We must ensure the list is not empty. def avg_value(lst): assert not len(lst) == 0, 'No values' avg = sum(lst) / len(lst) return avg If the length of list is zero, the function immediately terminates. Otherwise, it continues until the end. If the condition in the assert statement is false, an AssertionError will be raised: a = []print(avg_value(a))AssertionError: No values The assert is pretty useful to find bugs in the code. Thus, they can be used to support testing. We have covered how try, except, and assert can be implemented in the code. They all come in handy in many cases because it is very likely to encounter situations that do not meet the expectations. Try, except, and assert provides the programmer with more control and supervision over the code. They spot and handle exceptions very well. Thank you for reading. Please let me know if you have any feedback.
[ { "code": null, "e": 352, "s": 172, "text": "The dream of every software programmer is to write a program that runs smoothly. However, this is not usually the case at first. The execution of a code stops in case of an error." }, { "code": null, "e": 529, "s": 352, "text": "Unexpected situations or conditions might cause errors. Python considers these situations as exceptions and raises different kinds of errors depending on the type of exception." }, { "code": null, "e": 699, "s": 529, "text": "ValueError, TypeError, AttributeError, and SyntaxError are some examples for those exceptions. The good thing is that Python also provides ways to handle the exceptions." }, { "code": null, "e": 801, "s": 699, "text": "Consider the following code that asks the user to input a number and prints the square of the number." }, { "code": null, "e": 873, "s": 801, "text": "a = int(input(\"Please enter a number: \"))print(f'{a} squared is {a*a}')" }, { "code": null, "e": 991, "s": 873, "text": "It works fine as long as the input is a number. However, if the user inputs a string, python will raise a ValueError:" }, { "code": null, "e": 1168, "s": 991, "text": "We can implement a try-except block in our code to handle this exception better. For instance, we can return a simpler error message to the users or ask them for another input." }, { "code": null, "e": 1311, "s": 1168, "text": "try: a = int(input(\"Please enter a number: \")) print(f'{a} squared is {a*a}')except: print(\"Wrong input type! You must enter a number!\")" }, { "code": null, "e": 1386, "s": 1311, "text": "In the case above, the code informs the user about the error more clearly." }, { "code": null, "e": 1571, "s": 1386, "text": "If an exception is raised due to the code in the try block, the execution continues with the statements in the except block. So, it is up to the programmer how to handle the exception." }, { "code": null, "e": 1784, "s": 1571, "text": "The plain try-except block will catch any type of error. But, we can be more specific. For instance, we may be interested in only a particular type of error or want to handle different types of error differently." }, { "code": null, "e": 1977, "s": 1784, "text": "The type of error can be specified with the except statement. Consider the following code that asks user for a number from a list. Then, it returns a name from a dictionary based on the input." }, { "code": null, "e": 2092, "s": 1977, "text": "dict_a = {1:'Max', 2:'Ashley', 3:'John'}number = int(input(f'Pick a number from the list: {list(dict_a.keys())}'))" }, { "code": null, "e": 2285, "s": 2092, "text": "If the user enters a number that is not in the given list, we will get a KeyError. If the input is not a number, we will get a ValueError. We can handle both cases using two except statements." }, { "code": null, "e": 2547, "s": 2285, "text": "try: dict_a = {1:'Max', 2:'Ashley', 3:'John'} number = int(input(f'Pick a number from the list: {list(dict_a.keys())}')) print(dict_a[number])except KeyError: print(f'{number} is not in the list')except ValueError: print('You must enter a number!')" }, { "code": null, "e": 2726, "s": 2547, "text": "Python also allows raising your own exception. It is kind of customizing the default exceptions. The raise keyword along with the error type is used to create your own exception." }, { "code": null, "e": 2862, "s": 2726, "text": "try: a = int(input(\"Please enter a number: \")) print(f'{a} squared is {a*a}')except: raise ValueError(\"You must enter a number!\")" }, { "code": null, "e": 2919, "s": 2862, "text": "Here is the error message in case of a non-number input." }, { "code": null, "e": 2956, "s": 2919, "text": "ValueError: You must enter a number!" }, { "code": null, "e": 3035, "s": 2956, "text": "Let’s do another example that shows how to use try-except block in a function." }, { "code": null, "e": 3106, "s": 3035, "text": "The avg_value function returns the average value of a list of numbers." }, { "code": null, "e": 3200, "s": 3106, "text": "a = [1, 2, 3]def avg_value(lst): avg = sum(lst) / len(lst) return avgprint(avg_value(a))2" }, { "code": null, "e": 3321, "s": 3200, "text": "If we pass an empty list to this function, it will give a ZeroDivisionError because the length of an empty list is zero." }, { "code": null, "e": 3399, "s": 3321, "text": "We can implement a try-except block in the function to handle this exception." }, { "code": null, "e": 3531, "s": 3399, "text": "def avg_value(lst): try: avg = sum(lst) / len(lst) return avg except: print('Warning: Empty list') return 0" }, { "code": null, "e": 3603, "s": 3531, "text": "In case of empty lists, the function will print a warning and return 0." }, { "code": null, "e": 3649, "s": 3603, "text": "a = []print(avg_value(a))Warning: Empty list0" }, { "code": null, "e": 3802, "s": 3649, "text": "The try and except blocks are used to handle exceptions. The assert is used to ensure the conditions are compatible with the requirements of a function." }, { "code": null, "e": 3981, "s": 3802, "text": "If the assert is false, the function does not continue. Thus, the assert can be an example of defensive programming. The programmer is making sure that everything is as expected." }, { "code": null, "e": 4073, "s": 3981, "text": "Let’s implement the assert in our avg_value function. We must ensure the list is not empty." }, { "code": null, "e": 4174, "s": 4073, "text": "def avg_value(lst): assert not len(lst) == 0, 'No values' avg = sum(lst) / len(lst) return avg" }, { "code": null, "e": 4281, "s": 4174, "text": "If the length of list is zero, the function immediately terminates. Otherwise, it continues until the end." }, { "code": null, "e": 4366, "s": 4281, "text": "If the condition in the assert statement is false, an AssertionError will be raised:" }, { "code": null, "e": 4417, "s": 4366, "text": "a = []print(avg_value(a))AssertionError: No values" }, { "code": null, "e": 4514, "s": 4417, "text": "The assert is pretty useful to find bugs in the code. Thus, they can be used to support testing." }, { "code": null, "e": 4712, "s": 4514, "text": "We have covered how try, except, and assert can be implemented in the code. They all come in handy in many cases because it is very likely to encounter situations that do not meet the expectations." }, { "code": null, "e": 4852, "s": 4712, "text": "Try, except, and assert provides the programmer with more control and supervision over the code. They spot and handle exceptions very well." } ]
Explain the architecture of Java Swing in Java?
Java Swing is a set of APIs that provides a graphical user interface (GUI) for the java programs. The Java Swing was developed based on earlier APIs called Abstract Windows Toolkit (AWT). The Java Swing provides richer and more sophisticated GUI components than AWT. The GUI components are ranging from a simple level to complex tree and table. The Java Swing provides the pluggable look and feels to allow look and feel of Java programs independent from the underlying platform. The Java Swing is platform independent and follows the MVC (Model View and Controller) framework. Pluggable look and feel − The Java Swing supports several looks and feels and currently supports Windows, UNIX, Motif, and native Java metal look and feel and allows users to switch look and feel at runtime without restarting the application. By doing this, users can make their own choice to choose which look and feel is the best for them instantly. Lightweight components − All Java swing components are lightweight except for some top-level containers. A Lightweight means component renders or paints itself using drawing primitives of the Graphics object instead of relying on the host operating system (OS). As a result, the application presentation is rendered faster and consumed less memory than previous Java GUI applications like AWT. Simplified MVC − The Java Swing uses a simplified Model-View-Controller architecture (MVC) as the core design behind each of its components called the model-delegate. Based on this architecture, each Java Swing component contains a model and a UI delegate and wraps a view and a controller in MVC architecture. The UI delegate is responsible for painting screen and handling GUI events. Model is in charge of maintaining information or states of the component. import javax.swing.*; import java.awt.*; import java.awt.event.*; // model part class Model { private int x; public Model() { x = 0; } public Model(int x) { this.x = x; } public void setX(){ x++; } public int getX() { return x; } } // view part class View { private JFrame frame; private JLabel label; private JButton button; public View(String text) { frame = new JFrame("View"); frame.getContentPane().setLayout(new BorderLayout()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(200,200); frame.setVisible(true); label = new JLabel(text); frame.getContentPane().add(label, BorderLayout.CENTER); button = new JButton("Button"); frame.getContentPane().add(button, BorderLayout.SOUTH); } public JButton getButton() { return button; } public void setText(String text) { label.setText(text); } } // controller part class Controller { private Model model; private View view; private ActionListener actionListener; public Controller(Model model, View view) { this.model = model; this.view = view; } public void contol() { actionListener = new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { linkBtnAndLabel(); } }; view.getButton().addActionListener(actionListener); } private void linkBtnAndLabel() { model.setX(); view.setText(Integer.toString(model.getX())); } } // main class public class Main { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { try { // Look and Feel, Java Look and Feel UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception ex) { } Model model = new Model(0); View view = new View("-"); Controller controller = new Controller(model,view); controller.contol(); } }); } }
[ { "code": null, "e": 1542, "s": 1062, "text": "Java Swing is a set of APIs that provides a graphical user interface (GUI) for the java programs. The Java Swing was developed based on earlier APIs called Abstract Windows Toolkit (AWT). The Java Swing provides richer and more sophisticated GUI components than AWT. The GUI components are ranging from a simple level to complex tree and table. The Java Swing provides the pluggable look and feels to allow look and feel of Java programs independent from the underlying platform." }, { "code": null, "e": 1640, "s": 1542, "text": "The Java Swing is platform independent and follows the MVC (Model View and Controller) framework." }, { "code": null, "e": 1992, "s": 1640, "text": "Pluggable look and feel − The Java Swing supports several looks and feels and currently supports Windows, UNIX, Motif, and native Java metal look and feel and allows users to switch look and feel at runtime without restarting the application. By doing this, users can make their own choice to choose which look and feel is the best for them instantly." }, { "code": null, "e": 2386, "s": 1992, "text": "Lightweight components − All Java swing components are lightweight except for some top-level containers. A Lightweight means component renders or paints itself using drawing primitives of the Graphics object instead of relying on the host operating system (OS). As a result, the application presentation is rendered faster and consumed less memory than previous Java GUI applications like AWT." }, { "code": null, "e": 2847, "s": 2386, "text": "Simplified MVC − The Java Swing uses a simplified Model-View-Controller architecture (MVC) as the core design behind each of its components called the model-delegate. Based on this architecture, each Java Swing component contains a model and a UI delegate and wraps a view and a controller in MVC architecture. The UI delegate is responsible for painting screen and handling GUI events. Model is in charge of maintaining information or states of the component." }, { "code": null, "e": 4958, "s": 2847, "text": "import javax.swing.*;\nimport java.awt.*;\nimport java.awt.event.*;\n// model part\nclass Model {\n private int x;\n public Model() {\n x = 0;\n }\n public Model(int x) {\n this.x = x;\n }\n public void setX(){\n x++;\n }\n public int getX() {\n return x;\n }\n}\n// view part\nclass View {\n private JFrame frame;\n private JLabel label;\n private JButton button;\n public View(String text) {\n frame = new JFrame(\"View\");\n frame.getContentPane().setLayout(new BorderLayout());\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.setSize(200,200);\n frame.setVisible(true);\n label = new JLabel(text);\n frame.getContentPane().add(label, BorderLayout.CENTER);\n button = new JButton(\"Button\");\n frame.getContentPane().add(button, BorderLayout.SOUTH);\n }\n public JButton getButton() {\n return button;\n }\n public void setText(String text) {\n label.setText(text);\n }\n}\n// controller part\nclass Controller {\n private Model model;\n private View view;\n private ActionListener actionListener;\n public Controller(Model model, View view) {\n this.model = model;\n this.view = view;\n }\n public void contol() {\n actionListener = new ActionListener() {\n public void actionPerformed(ActionEvent actionEvent) {\n linkBtnAndLabel();\n }\n };\n view.getButton().addActionListener(actionListener);\n }\n private void linkBtnAndLabel() {\n model.setX();\n view.setText(Integer.toString(model.getX()));\n }\n}\n// main class\npublic class Main {\n public static void main(String[] args) {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n try {\n// Look and Feel, Java Look and Feel\n UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());\n } catch (Exception ex) { }\n Model model = new Model(0);\n View view = new View(\"-\");\n Controller controller = new Controller(model,view);\n controller.contol();\n }\n });\n }\n}" } ]
Tk - Text Widget
Tk text widget is a general purpose editable text widget with features for multiple options. The syntax for text widget is shown below − text textName options The options available for the text widget are listed below in table − -background color Used to set background color for widget. -borderwidth width Used to draw with border in 3D effects. -font fontDescriptor Used to set font for widget. -foreground color Used to set foreground color for widget. -relief condition Sets the 3D relief for this widget. The condition may be raised, sunken, flat, ridge, solid, or groove. -width number Sets the width for widget. -height number Used to set height for widget. A simple example for text widget is shown below − #!/usr/bin/wish grid [text .myText -background red -foreground white -relief ridge -borderwidth 8 -padx 10 -pady 10 -font {Helvetica -18 bold} -width 20 -height 5] .myText insert 1.0 "Hello\nWorld\n" .myText insert end "A new line\n" .myText tag configure para -spacing1 0.15i -spacing2 0.05i \ -lmargin1 0.25i -lmargin2 0.2i -rmargin 0.25i .myText tag configure hang -lmargin1 0.30i -lmargin2 0.25i .myText tag add para 1.0 2.end .myText tag add hang 3.0 3.end When we run the above program, we will get the following output − As you can see, text widgets works with the help of procedures like tag, insert, and delete. Most of the tag usages have been covered in the above example. Print Add Notes Bookmark this page
[ { "code": null, "e": 2338, "s": 2201, "text": "Tk text widget is a general purpose editable text widget with features for multiple options. The syntax for text widget is shown below −" }, { "code": null, "e": 2361, "s": 2338, "text": "text textName options\n" }, { "code": null, "e": 2431, "s": 2361, "text": "The options available for the text widget are listed below in table −" }, { "code": null, "e": 2449, "s": 2431, "text": "-background color" }, { "code": null, "e": 2490, "s": 2449, "text": "Used to set background color for widget." }, { "code": null, "e": 2509, "s": 2490, "text": "-borderwidth width" }, { "code": null, "e": 2549, "s": 2509, "text": "Used to draw with border in 3D effects." }, { "code": null, "e": 2570, "s": 2549, "text": "-font fontDescriptor" }, { "code": null, "e": 2599, "s": 2570, "text": "Used to set font for widget." }, { "code": null, "e": 2617, "s": 2599, "text": "-foreground color" }, { "code": null, "e": 2658, "s": 2617, "text": "Used to set foreground color for widget." }, { "code": null, "e": 2676, "s": 2658, "text": "-relief condition" }, { "code": null, "e": 2780, "s": 2676, "text": "Sets the 3D relief for this widget. The condition may be raised, sunken, flat, ridge, solid, or groove." }, { "code": null, "e": 2794, "s": 2780, "text": "-width number" }, { "code": null, "e": 2821, "s": 2794, "text": "Sets the width for widget." }, { "code": null, "e": 2836, "s": 2821, "text": "-height number" }, { "code": null, "e": 2867, "s": 2836, "text": "Used to set height for widget." }, { "code": null, "e": 2917, "s": 2867, "text": "A simple example for text widget is shown below −" }, { "code": null, "e": 3386, "s": 2917, "text": "#!/usr/bin/wish\n\ngrid [text .myText -background red -foreground white -relief ridge -borderwidth 8 -padx 10\n -pady 10 -font {Helvetica -18 bold} -width 20 -height 5]\n.myText insert 1.0 \"Hello\\nWorld\\n\"\n.myText insert end \"A new line\\n\"\n.myText tag configure para -spacing1 0.15i -spacing2 0.05i \\\n -lmargin1 0.25i -lmargin2 0.2i -rmargin 0.25i\n.myText tag configure hang -lmargin1 0.30i -lmargin2 0.25i\n.myText tag add para 1.0 2.end\n.myText tag add hang 3.0 3.end" }, { "code": null, "e": 3452, "s": 3386, "text": "When we run the above program, we will get the following output −" }, { "code": null, "e": 3608, "s": 3452, "text": "As you can see, text widgets works with the help of procedures like tag, insert, and delete. Most of the tag usages have been covered in the above example." }, { "code": null, "e": 3615, "s": 3608, "text": " Print" }, { "code": null, "e": 3626, "s": 3615, "text": " Add Notes" } ]
How to create a thread in android?
Before getting into an example, we should know what thread is. A thread is a lightweight sub-process, it going to do background operations without interrupt to ui. This example demonstrate about How to create a thread in android. 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"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:gravity="center_horizontal" android:layout_marginTop="100dp" tools:context=".MainActivity"> <EditText android:id="@+id/edit_query" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter string" /> <Button android:id="@+id/click" android:layout_marginTop="50dp" style="@style/Base.TextAppearance.AppCompat.Widget.Button.Borderless.Colored" android:layout_width="wrap_content" android:background="#c1c1c1" android:textColor="#FFF" android:layout_height="wrap_content" android:text="Button" /> <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> In the above code, we have taken edittext and textview. When user enter some text into edittext, it going to wait till 5000ms and update textview. Step 3 − Add the following code to src/MainActivity.java package com.example.myapplication; import android.os.Bundle; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends AppCompatActivity { EditText edit_query; TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); edit_query = findViewById(R.id.edit_query); textView = findViewById(R.id.text); findViewById(R.id.click).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { runthread(); } }); } private void runthread() { final String s1 = edit_query.getText().toString(); Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { textView.setText(s1); } }); } }, 5000); } } 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 − In the above result, Enter some text in edit text and click on the button, after 5000ms it will update textview. Click here to download the project code
[ { "code": null, "e": 1292, "s": 1062, "text": "Before getting into an example, we should know what thread is. A thread is a lightweight sub-process, it going to do background operations without interrupt to ui. This example demonstrate about How to create a thread in android." }, { "code": null, "e": 1421, "s": 1292, "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": 1486, "s": 1421, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2531, "s": 1486, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"vertical\"\n android:gravity=\"center_horizontal\"\n android:layout_marginTop=\"100dp\"\n tools:context=\".MainActivity\">\n <EditText\n android:id=\"@+id/edit_query\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:hint=\"Enter string\" />\n <Button\n android:id=\"@+id/click\"\n android:layout_marginTop=\"50dp\"\n style=\"@style/Base.TextAppearance.AppCompat.Widget.Button.Borderless.Colored\"\n android:layout_width=\"wrap_content\"\n android:background=\"#c1c1c1\"\n android:textColor=\"#FFF\"\n android:layout_height=\"wrap_content\"\n android:text=\"Button\" />\n <TextView\n android:id=\"@+id/text\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\" />\n</LinearLayout>" }, { "code": null, "e": 2678, "s": 2531, "text": "In the above code, we have taken edittext and textview. When user enter some text into edittext, it going to wait till 5000ms and update textview." }, { "code": null, "e": 2735, "s": 2678, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3930, "s": 2735, "text": "package com.example.myapplication;\n\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.EditText;\nimport android.widget.TextView;\n\npublic class MainActivity extends AppCompatActivity {\n EditText edit_query;\n TextView textView;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n edit_query = findViewById(R.id.edit_query);\n textView = findViewById(R.id.text);\n findViewById(R.id.click).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n runthread();\n }\n });\n }\n\n private void runthread() {\n final String s1 = edit_query.getText().toString();\n Handler handler = new Handler();\n handler.postDelayed(new Runnable() {\n @Override\n public void run() {\n runOnUiThread(new Runnable() {\n @Override\n public void run() {\n textView.setText(s1);\n }\n });\n }\n }, 5000);\n }\n}" }, { "code": null, "e": 4277, "s": 3930, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" }, { "code": null, "e": 4390, "s": 4277, "text": "In the above result, Enter some text in edit text and click on the button, after 5000ms it will update textview." }, { "code": null, "e": 4430, "s": 4390, "text": "Click here to download the project code" } ]
Regular Expression Vs Context Free Grammar - GeeksforGeeks
01 May, 2019 Regular Expressions are capable of describing the syntax of Tokens. Any syntactic construct that can be described by Regular Expression can also be described by the Context free grammar. Regular Expression: (a|b)(a|b|01) Context-free grammar: S --> aA|bA A --> aA|bA|0A|1A|e *e denotes epsilon. The Context-free grammar form NFA for the Regular Expression using the following construction rules: For each state there is a Non-Terminal symbol.If state A has a transition to state B on a symbol aIF state A goes to state B, input symbol is eIf A is accepting state.Make the start symbol of the NFA with the start symbol of the grammar. For each state there is a Non-Terminal symbol. If state A has a transition to state B on a symbol a IF state A goes to state B, input symbol is e If A is accepting state. Make the start symbol of the NFA with the start symbol of the grammar. Every Regular set can be described the Context-free grammar that’s why we are using Regular Expression. There are several reasons and they are: Compiler Design GATE CS Theory of Computation & Automata Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between Top down parsing and Bottom up parsing Loop Optimization in Compiler Design Backpatching in Compiler Design Directed Acyclic graph in Compiler Design (with examples) Issues in the design of a code generator Layers of OSI Model ACID Properties in DBMS Types of Operating Systems Normal Forms in DBMS
[ { "code": null, "e": 24446, "s": 24418, "text": "\n01 May, 2019" }, { "code": null, "e": 24633, "s": 24446, "text": "Regular Expressions are capable of describing the syntax of Tokens. Any syntactic construct that can be described by Regular Expression can also be described by the Context free grammar." }, { "code": null, "e": 24653, "s": 24633, "text": "Regular Expression:" }, { "code": null, "e": 24668, "s": 24653, "text": "(a|b)(a|b|01) " }, { "code": null, "e": 24690, "s": 24668, "text": "Context-free grammar:" }, { "code": null, "e": 24723, "s": 24690, "text": "S --> aA|bA\nA --> aA|bA|0A|1A|e " }, { "code": null, "e": 24743, "s": 24723, "text": "*e denotes epsilon." }, { "code": null, "e": 24844, "s": 24743, "text": "The Context-free grammar form NFA for the Regular Expression using the following construction rules:" }, { "code": null, "e": 25082, "s": 24844, "text": "For each state there is a Non-Terminal symbol.If state A has a transition to state B on a symbol aIF state A goes to state B, input symbol is eIf A is accepting state.Make the start symbol of the NFA with the start symbol of the grammar." }, { "code": null, "e": 25129, "s": 25082, "text": "For each state there is a Non-Terminal symbol." }, { "code": null, "e": 25182, "s": 25129, "text": "If state A has a transition to state B on a symbol a" }, { "code": null, "e": 25228, "s": 25182, "text": "IF state A goes to state B, input symbol is e" }, { "code": null, "e": 25253, "s": 25228, "text": "If A is accepting state." }, { "code": null, "e": 25324, "s": 25253, "text": "Make the start symbol of the NFA with the start symbol of the grammar." }, { "code": null, "e": 25468, "s": 25324, "text": "Every Regular set can be described the Context-free grammar that’s why we are using Regular Expression. There are several reasons and they are:" }, { "code": null, "e": 25484, "s": 25468, "text": "Compiler Design" }, { "code": null, "e": 25492, "s": 25484, "text": "GATE CS" }, { "code": null, "e": 25525, "s": 25492, "text": "Theory of Computation & Automata" }, { "code": null, "e": 25623, "s": 25525, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25632, "s": 25623, "text": "Comments" }, { "code": null, "e": 25645, "s": 25632, "text": "Old Comments" }, { "code": null, "e": 25703, "s": 25645, "text": "Difference between Top down parsing and Bottom up parsing" }, { "code": null, "e": 25740, "s": 25703, "text": "Loop Optimization in Compiler Design" }, { "code": null, "e": 25772, "s": 25740, "text": "Backpatching in Compiler Design" }, { "code": null, "e": 25830, "s": 25772, "text": "Directed Acyclic graph in Compiler Design (with examples)" }, { "code": null, "e": 25871, "s": 25830, "text": "Issues in the design of a code generator" }, { "code": null, "e": 25891, "s": 25871, "text": "Layers of OSI Model" }, { "code": null, "e": 25915, "s": 25891, "text": "ACID Properties in DBMS" }, { "code": null, "e": 25942, "s": 25915, "text": "Types of Operating Systems" } ]
Dynamic Allocation of Data Types and Variables in Python | by Bipin P. | Towards Data Science
Suppose you are given a list (list_main) with 10 elements. You have to divide it into 3 parts. The first part is allocated to list1, the second part to list2, and the third part to list3. This division or partition of the list is analogous to K-fold Cross-Validation. For the uninitiated, cross-validation is a resampling procedure to access the accuracy of a predictive model in practice. In K-fold cross-validation, the dataset is divided into training data (usually 80%) and test data (usually 20% and will remain unseen data). The training data is again divided into k-folds or partitions that inturn is considered training data and validation data. The model will be trained on training data and the validation of the model will be done using validation data. The following code divides the list into 3 partitions or sections and allocates the elements of each section to a list. list_main = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]folds = 3section = int(len(list_main)/folds)start_index = 0end_index = 0counter = 1for i in range(folds): if counter == 1: end_index += section list1 = list_main[start_index:end_index] counter += 1 elif counter == folds: list3 = list_main[end_index: ] counter += 1 elif counter < folds: start_index = end_index end_index += section list2 = list_main[start_index:end_index] counter += 1print(f'List1: {list1}')print(f'List2: {list2}')print(f'List3: {list3}')list1 = [1, 2, 3]list2 = [4, 5, 6]list3 = [7, 8, 9, 10] The output: List1: [1, 2, 3]List2: [4, 5, 6]List3: [7, 8, 9, 10] However, the code is not generic and more of a hardcoded type. For instance, if the number of divisions(folds) of the list_main increased to 4, then another list(list4) is required to store list elements. If it was increased to 6, then a total of 6 lists are required altogether. To accommodate the changes based on the number of partitions, the code needs to be changed. Specifically, new lists need to be assigned. However, that leads to more complexities and confusion. For instance, if folds=4, then the second partition and third partition have the same condition in the above code (counter < folds). It would have been better if we write a generic code that can allocate lists as the number of folds increases or decreases. The globals() function in Python made the seemingly impossible job possible. It returns the global symbol table as a dictionary. print(globals()){'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x02A8C2D0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'demo_ref_globals.py', '__cached__': None, 'x'_ {...}} The modified code: The output: Enter the no. of folds: 5List 0: [1, 2]List 1: [3, 4]List 2: [5, 6]List 3: [7, 8]List 4: [9, 10] You can do this dynamic allocation(frankly speaking, I don’t know the appropriate term for the allotment of data types)with other data types like variables, tuple, set, etc. You can find the codes here. We are all going through tough times. Uncertainty looms large over the future. However, every cloud has a silver lining. The pandemic has healed earth to a greater extent than any other mission by environmentalists. So I can’t help sharing this awesome meme that I received as forward from my friend in WhatsApp. I really want to thank the unknown creator of this meme for the creativity and the harsh reality that it was portraying about the world we live in. As the world is limping forward through an unprecedented time of an endemic that has attained gigantic proportions, we humans have no choice but to resort to social distancing(whenever we venture out for essentials)and stay at home. While you are in self-imposed quarantine, upgrade your skills, and learn something new. Hope you could learn something new. Happy Coding!!!
[ { "code": null, "e": 936, "s": 171, "text": "Suppose you are given a list (list_main) with 10 elements. You have to divide it into 3 parts. The first part is allocated to list1, the second part to list2, and the third part to list3. This division or partition of the list is analogous to K-fold Cross-Validation. For the uninitiated, cross-validation is a resampling procedure to access the accuracy of a predictive model in practice. In K-fold cross-validation, the dataset is divided into training data (usually 80%) and test data (usually 20% and will remain unseen data). The training data is again divided into k-folds or partitions that inturn is considered training data and validation data. The model will be trained on training data and the validation of the model will be done using validation data." }, { "code": null, "e": 1056, "s": 936, "text": "The following code divides the list into 3 partitions or sections and allocates the elements of each section to a list." }, { "code": null, "e": 1684, "s": 1056, "text": "list_main = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]folds = 3section = int(len(list_main)/folds)start_index = 0end_index = 0counter = 1for i in range(folds): if counter == 1: end_index += section list1 = list_main[start_index:end_index] counter += 1 elif counter == folds: list3 = list_main[end_index: ] counter += 1 elif counter < folds: start_index = end_index end_index += section list2 = list_main[start_index:end_index] counter += 1print(f'List1: {list1}')print(f'List2: {list2}')print(f'List3: {list3}')list1 = [1, 2, 3]list2 = [4, 5, 6]list3 = [7, 8, 9, 10]" }, { "code": null, "e": 1696, "s": 1684, "text": "The output:" }, { "code": null, "e": 1749, "s": 1696, "text": "List1: [1, 2, 3]List2: [4, 5, 6]List3: [7, 8, 9, 10]" }, { "code": null, "e": 2355, "s": 1749, "text": "However, the code is not generic and more of a hardcoded type. For instance, if the number of divisions(folds) of the list_main increased to 4, then another list(list4) is required to store list elements. If it was increased to 6, then a total of 6 lists are required altogether. To accommodate the changes based on the number of partitions, the code needs to be changed. Specifically, new lists need to be assigned. However, that leads to more complexities and confusion. For instance, if folds=4, then the second partition and third partition have the same condition in the above code (counter < folds)." }, { "code": null, "e": 2608, "s": 2355, "text": "It would have been better if we write a generic code that can allocate lists as the number of folds increases or decreases. The globals() function in Python made the seemingly impossible job possible. It returns the global symbol table as a dictionary." }, { "code": null, "e": 2925, "s": 2608, "text": "print(globals()){'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x02A8C2D0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'demo_ref_globals.py', '__cached__': None, 'x'_ {...}}" }, { "code": null, "e": 2944, "s": 2925, "text": "The modified code:" }, { "code": null, "e": 2956, "s": 2944, "text": "The output:" }, { "code": null, "e": 3053, "s": 2956, "text": "Enter the no. of folds: 5List 0: [1, 2]List 1: [3, 4]List 2: [5, 6]List 3: [7, 8]List 4: [9, 10]" }, { "code": null, "e": 3256, "s": 3053, "text": "You can do this dynamic allocation(frankly speaking, I don’t know the appropriate term for the allotment of data types)with other data types like variables, tuple, set, etc. You can find the codes here." }, { "code": null, "e": 3717, "s": 3256, "text": "We are all going through tough times. Uncertainty looms large over the future. However, every cloud has a silver lining. The pandemic has healed earth to a greater extent than any other mission by environmentalists. So I can’t help sharing this awesome meme that I received as forward from my friend in WhatsApp. I really want to thank the unknown creator of this meme for the creativity and the harsh reality that it was portraying about the world we live in." } ]
Data Science Code Refactoring Example | by John DeJesus | Towards Data Science
When learning to code for data science we don’t usually consider the idea of modifying our code to reap a particular benefit in terms of performance. We code to modify our data, produce a visualization, and to construct our ML models. But if your code is going to be used for a dashboard or app, we have to consider if our code is optimal. In this code example, we will make a small modification to an ecdf function for speed. If you are not sure what an ecdf is you can check out my blog post on it for more details. Here is a quick visual example for your convenience. The data we will be using to plot the above ecdf function is on avocado prices from 2015 to 2018. Code Refactoring is the modification of code to make improvements in its readability and performance. For the performance part, this implies you will have to adjust your code to either decrease memory usage or for shorter run time. First, let us get the imports and data loading done. # Load Librariesimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as snsimport time# Load the data from data.worldavocado = pd.read_csv('https://query.data.world/s/qou5hvocejsu4qt4qb2xlndg5ntzbm') Seaborn is here by preference. When I create plots in a jupyter notebook I use seaborn to also set the plot backgrounds using sns.set(). Now that our imports and data are set up let's check out our ecdf plotting function. # Create a function for computing and plotting the ECDF with default parametersdef plot_ecdf(data, title='ECDF Plot', xlabel='Data Values', ylabel='Percentage'): """ Function to plot ecdf taking a column of data as input. """ xaxis = np.sort(data) yaxis = np.arange(1, len(data)+1)/len(data) plt.plot(xaxis,yaxis,linestyle='none',marker='.') plt.title(title) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.margins(0.02) For the speed refactoring, we are going to focus on where the yaxis is defined. yaxis = np.arange(1, len(data)+1)/len(data) Notice that we call len() twice to construct the yaxis. This causes an unnecessary increase in run time. To remedy this, we will refactor our yaxis code into the following: length = len(data)yaxis = np.arange(1,length+1)/length In the above code: we assigned the variable length to hold the data length value.replaced the calls for the len() with the variable length we defined beforehand. we assigned the variable length to hold the data length value. replaced the calls for the len() with the variable length we defined beforehand. Now to look at our function with these changes: # ECDF plot function with modificationsdef plot_ecdf_vtwo(data, title='ECDF Plot', xlabel='Data Values', ylabel='Percentage'): """ Function to plot ecdf taking a column of data as input. """ xaxis = np.sort(data) length = len(data) yaxis = np.arange(1,length+1)/length plt.plot(xaxis,yaxis,linestyle='none',marker='.') plt.title(title) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.margins(0.02) Yes, we did use another line of code. It also does use a bit more memory than our last version of the function. But now our function will generate a plot faster than before. To determine the improvement we imported the time module for this exact purpose. Let’s take a look. # Generating Run Time of plot_ecdfstart1 = time.time()plot_ecdf(avocado['AveragePrice'])end1 = time.time()diff1 = end1-start1print(diff1)0.04869723320007324 So the first version clocks in at about 5 hundredths of a second. Now to see if our refactored version is really an improvement. # Generating Run Time of plot_ecdf_vtwostart2 = time.time()plot_ecdf_vtwo(avocado['AveragePrice'])end2 = time.time()diff2 = end2-start2print(diff2)0.019404888153076172 Great! We improved the run time of our plot function by about 2 hundredths of a second! Suppose this was a plot function that was going into a dashboard. A dashboard that you are making for your employer. What if this was instead a function for an ML model that is going into an app? These are a couple of cases when faster run time is important. Hundredths of seconds may not seem like much. But if you consider the amount of usage the function will get, that is a large amount of time you are saving for the users of the dashboard or app. It will make your product for them as quick as lightning. If you need more examples, check out this awesome blog post by Julian Sequeria of Pybites.Review your own code from old projects. Find some of your code where you use a function more than once. Then try to refactor the code so the function is only called once.If you would like to see me go through this same example verbally you can watch the short youtube video version of this post. Here is the notebook for this post and video also. If you need more examples, check out this awesome blog post by Julian Sequeria of Pybites. Review your own code from old projects. Find some of your code where you use a function more than once. Then try to refactor the code so the function is only called once. If you would like to see me go through this same example verbally you can watch the short youtube video version of this post. Here is the notebook for this post and video also. Tony Fischetti is a data scientist at the NY Public Library. He was the first mentor I had in the Data Science world. He was the one that made me more aware of code refactoring. Thanks for reading! Hope you enjoyed this example of code refactoring and you consider refactoring your code also. What code do you think you will be refactoring? If enjoy reading on Medium and would like to support me further, you can use my referral link to sign up for a Medium membership. Doing so would support me financially with a portion of your membership fee which would be greatly appreciated. Until next time,
[ { "code": null, "e": 599, "s": 172, "text": "When learning to code for data science we don’t usually consider the idea of modifying our code to reap a particular benefit in terms of performance. We code to modify our data, produce a visualization, and to construct our ML models. But if your code is going to be used for a dashboard or app, we have to consider if our code is optimal. In this code example, we will make a small modification to an ecdf function for speed." }, { "code": null, "e": 743, "s": 599, "text": "If you are not sure what an ecdf is you can check out my blog post on it for more details. Here is a quick visual example for your convenience." }, { "code": null, "e": 841, "s": 743, "text": "The data we will be using to plot the above ecdf function is on avocado prices from 2015 to 2018." }, { "code": null, "e": 1073, "s": 841, "text": "Code Refactoring is the modification of code to make improvements in its readability and performance. For the performance part, this implies you will have to adjust your code to either decrease memory usage or for shorter run time." }, { "code": null, "e": 1126, "s": 1073, "text": "First, let us get the imports and data loading done." }, { "code": null, "e": 1356, "s": 1126, "text": "# Load Librariesimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as snsimport time# Load the data from data.worldavocado = pd.read_csv('https://query.data.world/s/qou5hvocejsu4qt4qb2xlndg5ntzbm')" }, { "code": null, "e": 1493, "s": 1356, "text": "Seaborn is here by preference. When I create plots in a jupyter notebook I use seaborn to also set the plot backgrounds using sns.set()." }, { "code": null, "e": 1578, "s": 1493, "text": "Now that our imports and data are set up let's check out our ecdf plotting function." }, { "code": null, "e": 2028, "s": 1578, "text": "# Create a function for computing and plotting the ECDF with default parametersdef plot_ecdf(data, title='ECDF Plot', xlabel='Data Values', ylabel='Percentage'): \"\"\" Function to plot ecdf taking a column of data as input. \"\"\" xaxis = np.sort(data) yaxis = np.arange(1, len(data)+1)/len(data) plt.plot(xaxis,yaxis,linestyle='none',marker='.') plt.title(title) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.margins(0.02)" }, { "code": null, "e": 2108, "s": 2028, "text": "For the speed refactoring, we are going to focus on where the yaxis is defined." }, { "code": null, "e": 2152, "s": 2108, "text": "yaxis = np.arange(1, len(data)+1)/len(data)" }, { "code": null, "e": 2325, "s": 2152, "text": "Notice that we call len() twice to construct the yaxis. This causes an unnecessary increase in run time. To remedy this, we will refactor our yaxis code into the following:" }, { "code": null, "e": 2380, "s": 2325, "text": "length = len(data)yaxis = np.arange(1,length+1)/length" }, { "code": null, "e": 2399, "s": 2380, "text": "In the above code:" }, { "code": null, "e": 2542, "s": 2399, "text": "we assigned the variable length to hold the data length value.replaced the calls for the len() with the variable length we defined beforehand." }, { "code": null, "e": 2605, "s": 2542, "text": "we assigned the variable length to hold the data length value." }, { "code": null, "e": 2686, "s": 2605, "text": "replaced the calls for the len() with the variable length we defined beforehand." }, { "code": null, "e": 2734, "s": 2686, "text": "Now to look at our function with these changes:" }, { "code": null, "e": 3164, "s": 2734, "text": "# ECDF plot function with modificationsdef plot_ecdf_vtwo(data, title='ECDF Plot', xlabel='Data Values', ylabel='Percentage'): \"\"\" Function to plot ecdf taking a column of data as input. \"\"\" xaxis = np.sort(data) length = len(data) yaxis = np.arange(1,length+1)/length plt.plot(xaxis,yaxis,linestyle='none',marker='.') plt.title(title) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.margins(0.02)" }, { "code": null, "e": 3438, "s": 3164, "text": "Yes, we did use another line of code. It also does use a bit more memory than our last version of the function. But now our function will generate a plot faster than before. To determine the improvement we imported the time module for this exact purpose. Let’s take a look." }, { "code": null, "e": 3595, "s": 3438, "text": "# Generating Run Time of plot_ecdfstart1 = time.time()plot_ecdf(avocado['AveragePrice'])end1 = time.time()diff1 = end1-start1print(diff1)0.04869723320007324" }, { "code": null, "e": 3724, "s": 3595, "text": "So the first version clocks in at about 5 hundredths of a second. Now to see if our refactored version is really an improvement." }, { "code": null, "e": 3892, "s": 3724, "text": "# Generating Run Time of plot_ecdf_vtwostart2 = time.time()plot_ecdf_vtwo(avocado['AveragePrice'])end2 = time.time()diff2 = end2-start2print(diff2)0.019404888153076172" }, { "code": null, "e": 3980, "s": 3892, "text": "Great! We improved the run time of our plot function by about 2 hundredths of a second!" }, { "code": null, "e": 4097, "s": 3980, "text": "Suppose this was a plot function that was going into a dashboard. A dashboard that you are making for your employer." }, { "code": null, "e": 4176, "s": 4097, "text": "What if this was instead a function for an ML model that is going into an app?" }, { "code": null, "e": 4239, "s": 4176, "text": "These are a couple of cases when faster run time is important." }, { "code": null, "e": 4491, "s": 4239, "text": "Hundredths of seconds may not seem like much. But if you consider the amount of usage the function will get, that is a large amount of time you are saving for the users of the dashboard or app. It will make your product for them as quick as lightning." }, { "code": null, "e": 4928, "s": 4491, "text": "If you need more examples, check out this awesome blog post by Julian Sequeria of Pybites.Review your own code from old projects. Find some of your code where you use a function more than once. Then try to refactor the code so the function is only called once.If you would like to see me go through this same example verbally you can watch the short youtube video version of this post. Here is the notebook for this post and video also." }, { "code": null, "e": 5019, "s": 4928, "text": "If you need more examples, check out this awesome blog post by Julian Sequeria of Pybites." }, { "code": null, "e": 5190, "s": 5019, "text": "Review your own code from old projects. Find some of your code where you use a function more than once. Then try to refactor the code so the function is only called once." }, { "code": null, "e": 5367, "s": 5190, "text": "If you would like to see me go through this same example verbally you can watch the short youtube video version of this post. Here is the notebook for this post and video also." }, { "code": null, "e": 5545, "s": 5367, "text": "Tony Fischetti is a data scientist at the NY Public Library. He was the first mentor I had in the Data Science world. He was the one that made me more aware of code refactoring." }, { "code": null, "e": 5708, "s": 5545, "text": "Thanks for reading! Hope you enjoyed this example of code refactoring and you consider refactoring your code also. What code do you think you will be refactoring?" }, { "code": null, "e": 5950, "s": 5708, "text": "If enjoy reading on Medium and would like to support me further, you can use my referral link to sign up for a Medium membership. Doing so would support me financially with a portion of your membership fee which would be greatly appreciated." } ]
How to make .js variables accessible to .ejs files ? - GeeksforGeeks
08 Apr, 2021 EJS is a simple templating language that lets you generate HTML markup with plain JavaScript. It is possible to access JS variable in .ejs file. You just need to pass the JS object as second parameter of res.render() method. Let’s jump into deep. Project Structure: Final folder structure will be as shown below. Project | |-> node_modules |-> views |-> index.ejs |-> package.json |-> package-lock.json |-> server.js Step 1: Initiate new Node JS project. Open a command prompt and create a new folder and initiate it with empty npm project. mkdir Project cd Project npm init -y Step 2: Install require dependencies. Require dependencies: Express JSEJS Express JS EJS npm i express ejs Step 3: Create a new server.js file in the Project directory. This file contains an API endpoint that is responsible to render an EJS file that generates HTML markup dynamically. Here render method takes two parameters. The first parameter is the EJS file and the second is a JS Object which automatically destructor in the .ejs file. Here we pass .{firstName: “Geeks,”, lastName: “A Computer Science Portal”}as JS object. server.js const express = require('express');const path = require('path'); const ejs = require('ejs'); const app = express();const PORT = 3000; // Set EJS as templating engineapp.set('view engine', 'ejs'); app.get('/', (req,res)=>{ // render method takes two parameters // first parameter should be the .ejs file // second parameter should be an object // which is accessible in the .ejs file // this .ejs file should be in views folder // in the root directory. res.render('index.ejs', {firstName: "Geeks,", lastName: "A Computer Science Portal"});}) // Start the serverapp.listen(PORT, err =>{ err ? console.log("Error in server setup") : console.log("Server listening on Port", PORT)}); Step 4: The default behavior of EJS is that it looks into the ‘views’ folder for the templates to render. So, let’s make a ‘views’ folder in our main node project folder and make a file named “index.ejs” which is to be served on some desired request in our node project. The content of this page is: index.ejs <!DOCTYPE html><html> <body style="text-align: center"> <h1 style="color: green"> GeeksforGeeks </h1> <h3> Welcome <%= firstName %> <%= lastName %> </h3></body></html> Here the passed object will be destructors. So, we can access the object property directly not need to use dot operator. Step 5: Open command prompt on the root directory of your project and start the server using node server.js Output: If everything is going well you will see “Server listening on Port 3000”. Then open http://localhost:3000/ on your browser and you will see the following output on your screen. Output: Using array of .js in the .ejs file: We can also use the array in the ejs file as a variable, in this example that passes a JS array to the ejs file to render. server.js const author = { name : 'Geeksforgeeks', skills: ['DSA', 'Interview Experience', 'Web Developement', 'Puzzels',]} app.get('/', (req,res)=>{ // render method takes two parameters // first parameter should be the .ejs file // second parameter should be an object // which is accessible in the .ejs file // this .ejs file should be in views folder // in the root directory. res.render('index.ejs', {author: author} );}) index.ejs <!DOCTYPE html><html> <body> <h1 style="color: green"> GeeksForGeeks </h1> <h3> <%= author.name %> has skill on </h3> <ul> <% author.skills.forEach((skill)=>{%> <li><%=skill%></li> <%});%> </ul> </body></html> Output: EJS-Templating Language Express.js Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to build a basic CRUD app with Node.js and ReactJS ? How to connect Node.js with React.js ? Mongoose Populate() Method Express.js req.params Property How to Convert CSV to JSON file having Comma Separated values in Node.js ? Top 10 Front End Developer Skills That You Need in 2022 Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 24556, "s": 24528, "text": "\n08 Apr, 2021" }, { "code": null, "e": 24701, "s": 24556, "text": "EJS is a simple templating language that lets you generate HTML markup with plain JavaScript. It is possible to access JS variable in .ejs file." }, { "code": null, "e": 24804, "s": 24701, "text": "You just need to pass the JS object as second parameter of res.render() method. Let’s jump into deep. " }, { "code": null, "e": 24870, "s": 24804, "text": "Project Structure: Final folder structure will be as shown below." }, { "code": null, "e": 24976, "s": 24870, "text": "Project\n|\n|-> node_modules\n|-> views\n |-> index.ejs\n|-> package.json\n|-> package-lock.json\n|-> server.js" }, { "code": null, "e": 25100, "s": 24976, "text": "Step 1: Initiate new Node JS project. Open a command prompt and create a new folder and initiate it with empty npm project." }, { "code": null, "e": 25137, "s": 25100, "text": "mkdir Project\ncd Project\nnpm init -y" }, { "code": null, "e": 25175, "s": 25137, "text": "Step 2: Install require dependencies." }, { "code": null, "e": 25197, "s": 25175, "text": "Require dependencies:" }, { "code": null, "e": 25211, "s": 25197, "text": "Express JSEJS" }, { "code": null, "e": 25222, "s": 25211, "text": "Express JS" }, { "code": null, "e": 25226, "s": 25222, "text": "EJS" }, { "code": null, "e": 25244, "s": 25226, "text": "npm i express ejs" }, { "code": null, "e": 25579, "s": 25244, "text": "Step 3: Create a new server.js file in the Project directory. This file contains an API endpoint that is responsible to render an EJS file that generates HTML markup dynamically. Here render method takes two parameters. The first parameter is the EJS file and the second is a JS Object which automatically destructor in the .ejs file." }, { "code": null, "e": 25667, "s": 25579, "text": "Here we pass .{firstName: “Geeks,”, lastName: “A Computer Science Portal”}as JS object." }, { "code": null, "e": 25677, "s": 25667, "text": "server.js" }, { "code": "const express = require('express');const path = require('path'); const ejs = require('ejs'); const app = express();const PORT = 3000; // Set EJS as templating engineapp.set('view engine', 'ejs'); app.get('/', (req,res)=>{ // render method takes two parameters // first parameter should be the .ejs file // second parameter should be an object // which is accessible in the .ejs file // this .ejs file should be in views folder // in the root directory. res.render('index.ejs', {firstName: \"Geeks,\", lastName: \"A Computer Science Portal\"});}) // Start the serverapp.listen(PORT, err =>{ err ? console.log(\"Error in server setup\") : console.log(\"Server listening on Port\", PORT)});", "e": 26431, "s": 25677, "text": null }, { "code": null, "e": 26731, "s": 26431, "text": "Step 4: The default behavior of EJS is that it looks into the ‘views’ folder for the templates to render. So, let’s make a ‘views’ folder in our main node project folder and make a file named “index.ejs” which is to be served on some desired request in our node project. The content of this page is:" }, { "code": null, "e": 26741, "s": 26731, "text": "index.ejs" }, { "code": "<!DOCTYPE html><html> <body style=\"text-align: center\"> <h1 style=\"color: green\"> GeeksforGeeks </h1> <h3> Welcome <%= firstName %> <%= lastName %> </h3></body></html>", "e": 26944, "s": 26741, "text": null }, { "code": null, "e": 27065, "s": 26944, "text": "Here the passed object will be destructors. So, we can access the object property directly not need to use dot operator." }, { "code": null, "e": 27158, "s": 27065, "text": "Step 5: Open command prompt on the root directory of your project and start the server using" }, { "code": null, "e": 27173, "s": 27158, "text": "node server.js" }, { "code": null, "e": 27359, "s": 27173, "text": "Output: If everything is going well you will see “Server listening on Port 3000”. Then open http://localhost:3000/ on your browser and you will see the following output on your screen." }, { "code": null, "e": 27367, "s": 27359, "text": "Output:" }, { "code": null, "e": 27527, "s": 27367, "text": "Using array of .js in the .ejs file: We can also use the array in the ejs file as a variable, in this example that passes a JS array to the ejs file to render." }, { "code": null, "e": 27537, "s": 27527, "text": "server.js" }, { "code": "const author = { name : 'Geeksforgeeks', skills: ['DSA', 'Interview Experience', 'Web Developement', 'Puzzels',]} app.get('/', (req,res)=>{ // render method takes two parameters // first parameter should be the .ejs file // second parameter should be an object // which is accessible in the .ejs file // this .ejs file should be in views folder // in the root directory. res.render('index.ejs', {author: author} );})", "e": 27985, "s": 27537, "text": null }, { "code": null, "e": 27995, "s": 27985, "text": "index.ejs" }, { "code": "<!DOCTYPE html><html> <body> <h1 style=\"color: green\"> GeeksForGeeks </h1> <h3> <%= author.name %> has skill on </h3> <ul> <% author.skills.forEach((skill)=>{%> <li><%=skill%></li> <%});%> </ul> </body></html>", "e": 28261, "s": 27995, "text": null }, { "code": null, "e": 28269, "s": 28261, "text": "Output:" }, { "code": null, "e": 28293, "s": 28269, "text": "EJS-Templating Language" }, { "code": null, "e": 28304, "s": 28293, "text": "Express.js" }, { "code": null, "e": 28311, "s": 28304, "text": "Picked" }, { "code": null, "e": 28319, "s": 28311, "text": "Node.js" }, { "code": null, "e": 28336, "s": 28319, "text": "Web Technologies" }, { "code": null, "e": 28434, "s": 28336, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28443, "s": 28434, "text": "Comments" }, { "code": null, "e": 28456, "s": 28443, "text": "Old Comments" }, { "code": null, "e": 28513, "s": 28456, "text": "How to build a basic CRUD app with Node.js and ReactJS ?" }, { "code": null, "e": 28552, "s": 28513, "text": "How to connect Node.js with React.js ?" }, { "code": null, "e": 28579, "s": 28552, "text": "Mongoose Populate() Method" }, { "code": null, "e": 28610, "s": 28579, "text": "Express.js req.params Property" }, { "code": null, "e": 28685, "s": 28610, "text": "How to Convert CSV to JSON file having Comma Separated values in Node.js ?" }, { "code": null, "e": 28741, "s": 28685, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 28803, "s": 28741, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 28846, "s": 28803, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28896, "s": 28846, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Python Text Wrapping and Filling
In python the textwrap module is used to format and wrap plain texts. There are some options to format the texts by adjusting the line breaks in the input paragraph. To use these modules, we need to import the textwrap module in our code. import textwrap The Textwrapper instance attributes of the constructors are as follows − width The maximum length of lines. Default value is 70 expand_tabs If the value of this attribute is true, then all tabs will be replaced by spaces. Default value is True. tabsize When the expand_tabs attribute is true, it will help to set the tabsize with different values. Default value is 8. replace_whitespace All whitespace characters in the text will be replaced by single space, when the value is set to True, Default value is True. drop_whitespace After wrapping the text, the whitespaces at the beginning and the end will be dropped. Default value is True. initial_indent It prepends the given string to the first line of the wrapped text. The default value is ‘ ’ subsequent_indent It prepends the given string to all the lines of the wrapped text. The default value is ‘ ’ placeholder It appends the string at the end of the output file whether it has been truncated. Default value is [...] max_lines This value will determine the number of lines will be there after wrapping the text. If the value is None, then there is no limit. Default value is None. break_long_words It breaks the long words to fit into given width. The default value is True. break_on_hyphens It is used to wrap the text after the hyphens for compound words. Default value is True. There are some methods in the Textwrap module. These modules are − Module (textwrap.wrap(text, width = 70, **kwargs)) − This method wraps the input paragraph. It uses the line width to wrap the content. Default line width is 70. It returns a list of lines. In the list all wrapped lines are stored. Module (textwrap.fill(text, width = 70, **kwargs)) − The fill() method is similar to the wrap method, but it does not generate a list. It generates a string. It adds the new line character after exceeding the specified width. Module (textwrap.shorten(text, width, **kwargs)) − This method shortens or truncates the string. After truncation the length of the text will be same as the specified width. It will add [...] at the end of the string. Live Demo import textwrap python_desc = """Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It was created by Guido van Rossum during 1985- 1990. Like Perl, Python source code is also available under the GNU General Public License (GPL). This tutorial gives enough understanding on Python programming language.""" my_wrap = textwrap.TextWrapper(width = 40) wrap_list = my_wrap.wrap(text=python_desc) for line in wrap_list: print(line) single_line = """Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language.""" print('\n\n' + my_wrap.fill(text = single_line)) short_text = textwrap.shorten(text = python_desc, width=150) print('\n\n' + my_wrap.fill(text = short_text)) Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It was created by Guido van Rossum during 1985- 1990. Like Perl, Python source code is also available under the GNU General Public License (GPL). This tutorial gives enough understanding on Python programming language. Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. Python is a general-purpose interpreted, interactive, object-oriented, and high- level programming language. It was created by Guido van Rossum [...]
[ { "code": null, "e": 1228, "s": 1062, "text": "In python the textwrap module is used to format and wrap plain texts. There are some options to format the texts by adjusting the line breaks in the input paragraph." }, { "code": null, "e": 1301, "s": 1228, "text": "To use these modules, we need to import the textwrap module in our code." }, { "code": null, "e": 1318, "s": 1301, "text": "import textwrap\n" }, { "code": null, "e": 1391, "s": 1318, "text": "The Textwrapper instance attributes of the constructors are as follows −" }, { "code": null, "e": 1397, "s": 1391, "text": "width" }, { "code": null, "e": 1446, "s": 1397, "text": "The maximum length of lines. Default value is 70" }, { "code": null, "e": 1458, "s": 1446, "text": "expand_tabs" }, { "code": null, "e": 1563, "s": 1458, "text": "If the value of this attribute is true, then all tabs will be replaced by spaces. Default value is True." }, { "code": null, "e": 1571, "s": 1563, "text": "tabsize" }, { "code": null, "e": 1686, "s": 1571, "text": "When the expand_tabs attribute is true, it will help to set the tabsize with different values. Default value is 8." }, { "code": null, "e": 1705, "s": 1686, "text": "replace_whitespace" }, { "code": null, "e": 1831, "s": 1705, "text": "All whitespace characters in the text will be replaced by single space, when the value is set to True, Default value is True." }, { "code": null, "e": 1847, "s": 1831, "text": "drop_whitespace" }, { "code": null, "e": 1957, "s": 1847, "text": "After wrapping the text, the whitespaces at the beginning and the end will be dropped. Default value is True." }, { "code": null, "e": 1972, "s": 1957, "text": "initial_indent" }, { "code": null, "e": 2065, "s": 1972, "text": "It prepends the given string to the first line of the wrapped text. The default value is ‘ ’" }, { "code": null, "e": 2083, "s": 2065, "text": "subsequent_indent" }, { "code": null, "e": 2175, "s": 2083, "text": "It prepends the given string to all the lines of the wrapped text. The default value is ‘ ’" }, { "code": null, "e": 2187, "s": 2175, "text": "placeholder" }, { "code": null, "e": 2293, "s": 2187, "text": "It appends the string at the end of the output file whether it has been truncated. Default value is [...]" }, { "code": null, "e": 2303, "s": 2293, "text": "max_lines" }, { "code": null, "e": 2457, "s": 2303, "text": "This value will determine the number of lines will be there after wrapping the text. If the value is None, then there is no limit. Default value is None." }, { "code": null, "e": 2474, "s": 2457, "text": "break_long_words" }, { "code": null, "e": 2551, "s": 2474, "text": "It breaks the long words to fit into given width. The default value is True." }, { "code": null, "e": 2568, "s": 2551, "text": "break_on_hyphens" }, { "code": null, "e": 2657, "s": 2568, "text": "It is used to wrap the text after the hyphens for compound words. Default value is True." }, { "code": null, "e": 2724, "s": 2657, "text": "There are some methods in the Textwrap module. These modules are −" }, { "code": null, "e": 2777, "s": 2724, "text": "Module (textwrap.wrap(text, width = 70, **kwargs)) −" }, { "code": null, "e": 2956, "s": 2777, "text": "This method wraps the input paragraph. It uses the line width to wrap the content. Default line width is 70. It returns a list of lines. In the list all wrapped lines are stored." }, { "code": null, "e": 3010, "s": 2956, "text": "Module (textwrap.fill(text, width = 70, **kwargs)) − " }, { "code": null, "e": 3183, "s": 3010, "text": "The fill() method is similar to the wrap method, but it does not generate a list. It generates a string. It adds the new line character after exceeding the specified width." }, { "code": null, "e": 3234, "s": 3183, "text": "Module (textwrap.shorten(text, width, **kwargs)) −" }, { "code": null, "e": 3401, "s": 3234, "text": "This method shortens or truncates the string. After truncation the length of the text will be same as the specified width. It will add [...] at the end of the string." }, { "code": null, "e": 3412, "s": 3401, "text": " Live Demo" }, { "code": null, "e": 4285, "s": 3412, "text": "import textwrap\n\npython_desc = \"\"\"Python is a general-purpose interpreted, interactive, object-oriented, \n and high-level programming language. It was created by Guido van Rossum \n during 1985- 1990. Like Perl, Python source code is also available under \n the GNU General Public License (GPL). This tutorial gives enough \n understanding on Python programming language.\"\"\"\n\nmy_wrap = textwrap.TextWrapper(width = 40)\nwrap_list = my_wrap.wrap(text=python_desc)\n\nfor line in wrap_list:\n print(line)\n \nsingle_line = \"\"\"Python is a general-purpose interpreted, interactive, object-oriented, \n and high-level programming language.\"\"\"\n\nprint('\\n\\n' + my_wrap.fill(text = single_line))\n\nshort_text = textwrap.shorten(text = python_desc, width=150)\nprint('\\n\\n' + my_wrap.fill(text = short_text))" }, { "code": null, "e": 4873, "s": 4285, "text": "Python is a general-purpose interpreted,\ninteractive, object-oriented,\nand high-level programming language. It\nwas created by Guido van Rossum\nduring 1985- 1990. Like Perl, Python\nsource code is also available under\nthe GNU General Public License (GPL).\nThis tutorial gives enough\nunderstanding on Python programming\nlanguage.\n\nPython is a general-purpose interpreted,\ninteractive, object-oriented,\nand high-level programming language.\n\nPython is a general-purpose interpreted,\ninteractive, object-oriented, and high-\nlevel programming language. It was\ncreated by Guido van Rossum [...]\n" } ]
Matplotlib - Grids
The grid() function of axes object sets visibility of grid inside the figure to on or off. You can also display major / minor (or both) ticks of the grid. Additionally color, linestyle and linewidth properties can be set in the grid() function. import matplotlib.pyplot as plt import numpy as np fig, axes = plt.subplots(1,3, figsize = (12,4)) x = np.arange(1,11) axes[0].plot(x, x**3, 'g',lw=2) axes[0].grid(True) axes[0].set_title('default grid') axes[1].plot(x, np.exp(x), 'r') axes[1].grid(color='b', ls = '-.', lw = 0.25) axes[1].set_title('custom grid') axes[2].plot(x,x) axes[2].set_title('no grid') fig.tight_layout() plt.show() 63 Lectures 6 hours Abhilash Nelson 11 Lectures 4 hours DATAhill Solutions Srinivas Reddy 9 Lectures 2.5 hours DATAhill Solutions Srinivas Reddy 32 Lectures 4 hours Aipython 10 Lectures 2.5 hours Akbar Khan 63 Lectures 6 hours Anmol Print Add Notes Bookmark this page
[ { "code": null, "e": 2761, "s": 2516, "text": "The grid() function of axes object sets visibility of grid inside the figure to on or off. You can also display major / minor (or both) ticks of the grid. Additionally color, linestyle and linewidth properties can be set in the grid() function." }, { "code": null, "e": 3153, "s": 2761, "text": "import matplotlib.pyplot as plt\nimport numpy as np\nfig, axes = plt.subplots(1,3, figsize = (12,4))\nx = np.arange(1,11)\naxes[0].plot(x, x**3, 'g',lw=2)\naxes[0].grid(True)\naxes[0].set_title('default grid')\naxes[1].plot(x, np.exp(x), 'r')\naxes[1].grid(color='b', ls = '-.', lw = 0.25)\naxes[1].set_title('custom grid')\naxes[2].plot(x,x)\naxes[2].set_title('no grid')\nfig.tight_layout()\nplt.show()" }, { "code": null, "e": 3186, "s": 3153, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3203, "s": 3186, "text": " Abhilash Nelson" }, { "code": null, "e": 3236, "s": 3203, "text": "\n 11 Lectures \n 4 hours \n" }, { "code": null, "e": 3271, "s": 3236, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 3305, "s": 3271, "text": "\n 9 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3340, "s": 3305, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 3373, "s": 3340, "text": "\n 32 Lectures \n 4 hours \n" }, { "code": null, "e": 3383, "s": 3373, "text": " Aipython" }, { "code": null, "e": 3418, "s": 3383, "text": "\n 10 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3430, "s": 3418, "text": " Akbar Khan" }, { "code": null, "e": 3463, "s": 3430, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3470, "s": 3463, "text": " Anmol" }, { "code": null, "e": 3477, "s": 3470, "text": " Print" }, { "code": null, "e": 3488, "s": 3477, "text": " Add Notes" } ]
Node.js http.ServerResponse.statusMessage Property - GeeksforGeeks
20 Jan, 2021 The httpServerResponse.statusMessage is an inbuilt application programming interface of class ServerResponse within http module which is used to control the status message that will be sent to the client when the headers get flushed. Syntax: response.statusMessage Parameters: This method does not accept any arguments as a parameter. Return Value: This method returns the status message that will be sent to the client. Example 1: Filename: index.js Javascript // Node.js program to demonstrate the // response.statusMessage APi // Importing http module var http = require('http'); // Setting up PORT const PORT = process.env.PORT || 3000; // Creating http Server var httpServer = http.createServer(function(request, response){ response.writeHead(200, { 'Content-Length': Buffer.byteLength("GeeksforGeeks"), 'Content-Type': 'text/plain' }) // Getting the statusMessage // by using statusMessage API const value = response.statusMessage; // Display result // by using end() api response.end( "hello World", 'utf8', () => { console.log("displaying the result..."); httpServer.close(()=>{ console.log("server is closed") }) }); console.log("status message : " + value)}); // Listening to http Server httpServer.listen(PORT, () => { console.log("Server is running at port 3000..."); }); Run index.js file using below command: node index.js Console output: Server is running at port 3000... status message : OK displaying the result... server is closed Example 2: Filename: index.js Javascript // Node.js program to demonstrate the // response.statusMessage APi // Importing http module var http = require('http'); // Request and response handler const http2Handlers = (request, response) => { response.writeHead(200, { 'Content-Type': 'text/plain' }).end( "hello World", 'utf8', () => { console.log("displaying the result..."); }); // Getting the statusMessage // by using statusMessage API const value = response.statusMessage; httpServer.close(()=>{ console.log("server is closed") }) console.log("status message : " + value) }; // Creating http Server var httpServer = http.createServer( http2Handlers).listen(3000, () => { console.log("Server is running at port 3000..."); }); Run index.js file using below command: node index.js Console output: Server is running at port 3000... status message : OK displaying the result... server is closed Browser output: hello world Reference:https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_response_statusmessage Node.js-Methods Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Express.js express.Router() Function JWT Authentication with Node.js Express.js req.params Property Mongoose Populate() Method Difference between npm i and npm ci in Node.js Roadmap to Become a Web Developer in 2022 Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Convert a string to an integer in JavaScript
[ { "code": null, "e": 24922, "s": 24894, "text": "\n20 Jan, 2021" }, { "code": null, "e": 25156, "s": 24922, "text": "The httpServerResponse.statusMessage is an inbuilt application programming interface of class ServerResponse within http module which is used to control the status message that will be sent to the client when the headers get flushed." }, { "code": null, "e": 25164, "s": 25156, "text": "Syntax:" }, { "code": null, "e": 25187, "s": 25164, "text": "response.statusMessage" }, { "code": null, "e": 25257, "s": 25187, "text": "Parameters: This method does not accept any arguments as a parameter." }, { "code": null, "e": 25343, "s": 25257, "text": "Return Value: This method returns the status message that will be sent to the client." }, { "code": null, "e": 25373, "s": 25343, "text": "Example 1: Filename: index.js" }, { "code": null, "e": 25384, "s": 25373, "text": "Javascript" }, { "code": "// Node.js program to demonstrate the // response.statusMessage APi // Importing http module var http = require('http'); // Setting up PORT const PORT = process.env.PORT || 3000; // Creating http Server var httpServer = http.createServer(function(request, response){ response.writeHead(200, { 'Content-Length': Buffer.byteLength(\"GeeksforGeeks\"), 'Content-Type': 'text/plain' }) // Getting the statusMessage // by using statusMessage API const value = response.statusMessage; // Display result // by using end() api response.end( \"hello World\", 'utf8', () => { console.log(\"displaying the result...\"); httpServer.close(()=>{ console.log(\"server is closed\") }) }); console.log(\"status message : \" + value)}); // Listening to http Server httpServer.listen(PORT, () => { console.log(\"Server is running at port 3000...\"); });", "e": 26287, "s": 25384, "text": null }, { "code": null, "e": 26326, "s": 26287, "text": "Run index.js file using below command:" }, { "code": null, "e": 26340, "s": 26326, "text": "node index.js" }, { "code": null, "e": 26356, "s": 26340, "text": "Console output:" }, { "code": null, "e": 26452, "s": 26356, "text": "Server is running at port 3000...\nstatus message : OK\ndisplaying the result...\nserver is closed" }, { "code": null, "e": 26482, "s": 26452, "text": "Example 2: Filename: index.js" }, { "code": null, "e": 26493, "s": 26482, "text": "Javascript" }, { "code": "// Node.js program to demonstrate the // response.statusMessage APi // Importing http module var http = require('http'); // Request and response handler const http2Handlers = (request, response) => { response.writeHead(200, { 'Content-Type': 'text/plain' }).end( \"hello World\", 'utf8', () => { console.log(\"displaying the result...\"); }); // Getting the statusMessage // by using statusMessage API const value = response.statusMessage; httpServer.close(()=>{ console.log(\"server is closed\") }) console.log(\"status message : \" + value) }; // Creating http Server var httpServer = http.createServer( http2Handlers).listen(3000, () => { console.log(\"Server is running at port 3000...\"); });", "e": 27279, "s": 26493, "text": null }, { "code": null, "e": 27318, "s": 27279, "text": "Run index.js file using below command:" }, { "code": null, "e": 27332, "s": 27318, "text": "node index.js" }, { "code": null, "e": 27348, "s": 27332, "text": "Console output:" }, { "code": null, "e": 27444, "s": 27348, "text": "Server is running at port 3000...\nstatus message : OK\ndisplaying the result...\nserver is closed" }, { "code": null, "e": 27460, "s": 27444, "text": "Browser output:" }, { "code": null, "e": 27472, "s": 27460, "text": "hello world" }, { "code": null, "e": 27566, "s": 27472, "text": "Reference:https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_response_statusmessage" }, { "code": null, "e": 27582, "s": 27566, "text": "Node.js-Methods" }, { "code": null, "e": 27590, "s": 27582, "text": "Node.js" }, { "code": null, "e": 27607, "s": 27590, "text": "Web Technologies" }, { "code": null, "e": 27705, "s": 27607, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27714, "s": 27705, "text": "Comments" }, { "code": null, "e": 27727, "s": 27714, "text": "Old Comments" }, { "code": null, "e": 27764, "s": 27727, "text": "Express.js express.Router() Function" }, { "code": null, "e": 27796, "s": 27764, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 27827, "s": 27796, "text": "Express.js req.params Property" }, { "code": null, "e": 27854, "s": 27827, "text": "Mongoose Populate() Method" }, { "code": null, "e": 27901, "s": 27854, "text": "Difference between npm i and npm ci in Node.js" }, { "code": null, "e": 27943, "s": 27901, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 28005, "s": 27943, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 28048, "s": 28005, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28098, "s": 28048, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
HTML | DOM onunload Event - GeeksforGeeks
28 Jul, 2021 The onunload event in HTML occurs once the page is unloaded. for example, when the page is loading and the browser window has been closed by the user or submit a form, click on a link, etc. This event also occurs when the page is reloaded. Supported Tags <body> Syntax: In HTML: <element onunload="myScript"> In JavaScript: object.onunload = function(){myScript}; In JavaScript, using the addEventListener() method: object.addEventListener("unload", myScript); Example: Using the addEventListener() method html <!DOCTYPE html><html> <head> <title>HTML DOM onunload Event</title></head> <body id="bID" onunload="GFGfun()"> <center> <h1 style="color:green">GeeksforGeeks</h1> <h2>HTML DOM onunload Event</h2> </center> <script> document.getElementById( "bID").addEventListener("unload", GFGfun); function GFGfun() { alert("onunload event attribute called"); } </script> </body> </html> Output: Note: This event may not work always as expected.Supported Browsers: The browsers supported by HTML DOM onunload Event are listed below: Google Chrome Internet Explorer Firefox Apple Safari Opera Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. hritikbhatnagar2182 HTML-DOM HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments REST API (Introduction) How to auto-resize an image to fit a div container using CSS? Design a web page using HTML and CSS How to Show Images on Click using HTML ? HTML Course | First Web Page | Printing Hello World Express.js express.Router() Function Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React
[ { "code": null, "e": 24503, "s": 24475, "text": "\n28 Jul, 2021" }, { "code": null, "e": 24743, "s": 24503, "text": "The onunload event in HTML occurs once the page is unloaded. for example, when the page is loading and the browser window has been closed by the user or submit a form, click on a link, etc. This event also occurs when the page is reloaded." }, { "code": null, "e": 24758, "s": 24743, "text": "Supported Tags" }, { "code": null, "e": 24765, "s": 24758, "text": "<body>" }, { "code": null, "e": 24775, "s": 24765, "text": "Syntax: " }, { "code": null, "e": 24786, "s": 24775, "text": "In HTML: " }, { "code": null, "e": 24816, "s": 24786, "text": "<element onunload=\"myScript\">" }, { "code": null, "e": 24833, "s": 24816, "text": "In JavaScript: " }, { "code": null, "e": 24873, "s": 24833, "text": "object.onunload = function(){myScript};" }, { "code": null, "e": 24927, "s": 24873, "text": "In JavaScript, using the addEventListener() method: " }, { "code": null, "e": 24973, "s": 24927, "text": "object.addEventListener(\"unload\", myScript); " }, { "code": null, "e": 25020, "s": 24973, "text": "Example: Using the addEventListener() method " }, { "code": null, "e": 25025, "s": 25020, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>HTML DOM onunload Event</title></head> <body id=\"bID\" onunload=\"GFGfun()\"> <center> <h1 style=\"color:green\">GeeksforGeeks</h1> <h2>HTML DOM onunload Event</h2> </center> <script> document.getElementById( \"bID\").addEventListener(\"unload\", GFGfun); function GFGfun() { alert(\"onunload event attribute called\"); } </script> </body> </html>", "e": 25472, "s": 25025, "text": null }, { "code": null, "e": 25482, "s": 25472, "text": "Output: " }, { "code": null, "e": 25621, "s": 25482, "text": "Note: This event may not work always as expected.Supported Browsers: The browsers supported by HTML DOM onunload Event are listed below: " }, { "code": null, "e": 25635, "s": 25621, "text": "Google Chrome" }, { "code": null, "e": 25653, "s": 25635, "text": "Internet Explorer" }, { "code": null, "e": 25661, "s": 25653, "text": "Firefox" }, { "code": null, "e": 25674, "s": 25661, "text": "Apple Safari" }, { "code": null, "e": 25680, "s": 25674, "text": "Opera" }, { "code": null, "e": 25819, "s": 25682, "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": 25839, "s": 25819, "text": "hritikbhatnagar2182" }, { "code": null, "e": 25848, "s": 25839, "text": "HTML-DOM" }, { "code": null, "e": 25853, "s": 25848, "text": "HTML" }, { "code": null, "e": 25870, "s": 25853, "text": "Web Technologies" }, { "code": null, "e": 25875, "s": 25870, "text": "HTML" }, { "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": 26019, "s": 25995, "text": "REST API (Introduction)" }, { "code": null, "e": 26081, "s": 26019, "text": "How to auto-resize an image to fit a div container using CSS?" }, { "code": null, "e": 26118, "s": 26081, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 26159, "s": 26118, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 26211, "s": 26159, "text": "HTML Course | First Web Page | Printing Hello World" }, { "code": null, "e": 26248, "s": 26211, "text": "Express.js express.Router() Function" }, { "code": null, "e": 26281, "s": 26248, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26324, "s": 26281, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 26385, "s": 26324, "text": "Difference between var, let and const keywords in JavaScript" } ]
Difference between == and .Equals method in c#
The Equality Operator ( ==) is the comparison operator and the Equals() method in C# is used to compare the content of a string. The Equals() method compares only content. Live Demo using System; namespace ComparisionExample { class Program { static void Main(string[] args) { string str = "hello"; string str2 = str; Console.WriteLine("Using Equality operator: {0}", str == str2); Console.WriteLine("Using equals() method: {0}", str.Equals(str2)); Console.ReadKey(); } } } Using Equality operator: True Using equals() method: True The Equality operator is used to compare the reference identity. Let us see another example. Live Demo using System; namespace Demo { class Program { static void Main(string[] args) { object str = "hello"; char[] values = {'h','e','l','l','o'}; object str2 = new string(values); Console.WriteLine("Using Equality operator: {0}", str == str2); Console.WriteLine("Using equals() method: {0}", str.Equals(str2)); Console.ReadKey(); } } } Using Equality operator: False Using equals() method: True
[ { "code": null, "e": 1191, "s": 1062, "text": "The Equality Operator ( ==) is the comparison operator and the Equals() method in C# is used to compare the content of a string." }, { "code": null, "e": 1234, "s": 1191, "text": "The Equals() method compares only content." }, { "code": null, "e": 1245, "s": 1234, "text": " Live Demo" }, { "code": null, "e": 1600, "s": 1245, "text": "using System;\nnamespace ComparisionExample {\n class Program {\n static void Main(string[] args) {\n string str = \"hello\";\n string str2 = str;\n Console.WriteLine(\"Using Equality operator: {0}\", str == str2);\n Console.WriteLine(\"Using equals() method: {0}\", str.Equals(str2));\n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 1658, "s": 1600, "text": "Using Equality operator: True\nUsing equals() method: True" }, { "code": null, "e": 1723, "s": 1658, "text": "The Equality operator is used to compare the reference identity." }, { "code": null, "e": 1751, "s": 1723, "text": "Let us see another example." }, { "code": null, "e": 1762, "s": 1751, "text": " Live Demo" }, { "code": null, "e": 2166, "s": 1762, "text": "using System;\nnamespace Demo {\n class Program {\n static void Main(string[] args) {\n object str = \"hello\";\n char[] values = {'h','e','l','l','o'};\n object str2 = new string(values);\n Console.WriteLine(\"Using Equality operator: {0}\", str == str2);\n Console.WriteLine(\"Using equals() method: {0}\", str.Equals(str2));\n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 2225, "s": 2166, "text": "Using Equality operator: False\nUsing equals() method: True" } ]
Python | TextInput in kivy using .kv file - GeeksforGeeks
28 Feb, 2022 Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications. Kivy Tutorial – Learn Kivy with Examples. The TextInput widget provides a box for editable plain text. Unicode, multiline, cursor navigation, selection and clipboard features are supported. The TextInput uses two different coordinate systems: (x, y) – coordinates in pixels, mostly used for rendering on screen. (row, col) – cursor index in characters / lines, used for selection and cursor movement. Basic Approach: 1) import kivy 2) import kivyApp 3) import widget 4) import Relativelayout 5) import textinput 6) Set minimum version(optional) 7) Create Widget class 8) Create App class 9) create .kv file (name same as the app class): 1) create textinput 10) return Layout/widget/Class(according to requirement) 11) Run an instance of the class Implementation of the Approach # main.py file Python3 # Program to Show how to use textinput # (UX widget) in kivy using .kv file # import kivy module import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # this restrict the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require('1.9.0') # Widgets are elements# of a graphical user interface# that form part of the User Experience.from kivy.uix.widget import Widget # The TextInput widget provides a# box for editable plain textfrom kivy.uix.textinput import TextInput # This layout allows you to set relative coordinates for children. from kivy.uix.relativelayout import RelativeLayout # Create the widget classclass textinp(Widget): pass # Create the app classclass MainApp(App): # Building text input def build(self): return textinp() # Arranging that what you write will be shown to you # in IDLE def process(self): text = self.root.ids.input.text print(text) # Run the Appif __name__ == "__main__": MainApp().run() # main.kv file Python3 # .kv file implementation of the code <textinp>: title: 'InputDialog' auto_dismiss: False id: test1 # Using relative layout to arrange properly RelativeLayout: orientation: 'vertical' pos: self.pos size: root.size id: test2 # Defining text input in .kv # And giving it the look . pos and features TextInput: id: input hint_text:'Enter text' pos_hint: {'center_x': 0.5, 'center_y': 0.705} size_hint: 0.95, 0.5 on_text: app.process() Output: When you run the App you will see: After some input you will see: sumitgumber28 Python-gui Python-kivy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary How to Install PIP on Windows ? Read a file line by line in Python Enumerate() in Python Different ways to create Pandas Dataframe Create a Pandas DataFrame from Lists Python String | replace() Reading and Writing to text files in Python *args and **kwargs in Python How to drop one or multiple columns in Pandas Dataframe
[ { "code": null, "e": 24216, "s": 24188, "text": "\n28 Feb, 2022" }, { "code": null, "e": 24452, "s": 24216, "text": "Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications." }, { "code": null, "e": 24495, "s": 24452, "text": " Kivy Tutorial – Learn Kivy with Examples." }, { "code": null, "e": 24643, "s": 24495, "text": "The TextInput widget provides a box for editable plain text. Unicode, multiline, cursor navigation, selection and clipboard features are supported." }, { "code": null, "e": 24696, "s": 24643, "text": "The TextInput uses two different coordinate systems:" }, { "code": null, "e": 24765, "s": 24696, "text": "(x, y) – coordinates in pixels, mostly used for rendering on screen." }, { "code": null, "e": 24854, "s": 24765, "text": "(row, col) – cursor index in characters / lines, used for selection and cursor movement." }, { "code": null, "e": 25209, "s": 24854, "text": "Basic Approach:\n\n1) import kivy\n2) import kivyApp\n3) import widget\n4) import Relativelayout\n5) import textinput\n6) Set minimum version(optional)\n7) Create Widget class\n8) Create App class\n9) create .kv file (name same as the app class):\n 1) create textinput\n10) return Layout/widget/Class(according to requirement)\n11) Run an instance of the class" }, { "code": null, "e": 25240, "s": 25209, "text": "Implementation of the Approach" }, { "code": null, "e": 25255, "s": 25240, "text": "# main.py file" }, { "code": null, "e": 25263, "s": 25255, "text": "Python3" }, { "code": "# Program to Show how to use textinput # (UX widget) in kivy using .kv file # import kivy module import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # this restrict the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require('1.9.0') # Widgets are elements# of a graphical user interface# that form part of the User Experience.from kivy.uix.widget import Widget # The TextInput widget provides a# box for editable plain textfrom kivy.uix.textinput import TextInput # This layout allows you to set relative coordinates for children. from kivy.uix.relativelayout import RelativeLayout # Create the widget classclass textinp(Widget): pass # Create the app classclass MainApp(App): # Building text input def build(self): return textinp() # Arranging that what you write will be shown to you # in IDLE def process(self): text = self.root.ids.input.text print(text) # Run the Appif __name__ == \"__main__\": MainApp().run()", "e": 26388, "s": 25263, "text": null }, { "code": null, "e": 26403, "s": 26388, "text": "# main.kv file" }, { "code": null, "e": 26411, "s": 26403, "text": "Python3" }, { "code": "# .kv file implementation of the code <textinp>: title: 'InputDialog' auto_dismiss: False id: test1 # Using relative layout to arrange properly RelativeLayout: orientation: 'vertical' pos: self.pos size: root.size id: test2 # Defining text input in .kv # And giving it the look . pos and features TextInput: id: input hint_text:'Enter text' pos_hint: {'center_x': 0.5, 'center_y': 0.705} size_hint: 0.95, 0.5 on_text: app.process()", "e": 26967, "s": 26411, "text": null }, { "code": null, "e": 26975, "s": 26967, "text": "Output:" }, { "code": null, "e": 27010, "s": 26975, "text": "When you run the App you will see:" }, { "code": null, "e": 27041, "s": 27010, "text": "After some input you will see:" }, { "code": null, "e": 27055, "s": 27041, "text": "sumitgumber28" }, { "code": null, "e": 27066, "s": 27055, "text": "Python-gui" }, { "code": null, "e": 27078, "s": 27066, "text": "Python-kivy" }, { "code": null, "e": 27085, "s": 27078, "text": "Python" }, { "code": null, "e": 27183, "s": 27085, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27192, "s": 27183, "text": "Comments" }, { "code": null, "e": 27205, "s": 27192, "text": "Old Comments" }, { "code": null, "e": 27223, "s": 27205, "text": "Python Dictionary" }, { "code": null, "e": 27255, "s": 27223, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27290, "s": 27255, "text": "Read a file line by line in Python" }, { "code": null, "e": 27312, "s": 27290, "text": "Enumerate() in Python" }, { "code": null, "e": 27354, "s": 27312, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27391, "s": 27354, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 27417, "s": 27391, "text": "Python String | replace()" }, { "code": null, "e": 27461, "s": 27417, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 27490, "s": 27461, "text": "*args and **kwargs in Python" } ]
The Easiest Way to Get Fake Data. This simple method covers most use... | by Preston Badeer | Towards Data Science
A great rule of thumb for writing code, especially in Python, is to look for a module on PyPi or just using Google, before you start writing code yourself. If nobody else has done what you’re trying to do then you still might find articles, partial code, or general guidance. If somebody has done it before you could find everything you need or at least examples of how others accomplished it or tried to. In this case, generating fake data is something that many, many people have done before. A search for “fake data” on PyPi yields over 10,000 packages. In my opinion, Faker is the best among them. The only time this package won’t solve your needs is when you need fake data in some rare format or data type. Even then, I’d still recommend using Faker and reshaping what it generates, if possible. Here are some of the data generators available: Name Address Text (paragraphs, sentences) IP address SSN Birthday User-agent string Phone number License plate number Barcode ...and many more, see the full list here. All you have to do to is install it via pip on the command line: pip install faker Or if you’re in a Jupyter notebook, just add the exclamation point: !pip install faker Now for the good stuff! Generating 1000 fake user profiles is this easy (in bold is the Faker code, the rest is Pandas). from faker import Fakerimport pandas as pdfaker = Faker()df = pd.DataFrame()for i in range(1000): df = df.append(faker.profile(), ignore_index=True) And here’s a sample of what that data looks like: If you want to get an individual field instead of a full profile, it’s just as easy: from faker import Fakerfaker = Faker()# Get a random addressfaker.address()# Get a random person's namefaker.name() Again, there are way more fields available, you can find them all in the documentation. You can even make your own data providers, here’s a few already contributed by the community. Faker also supports multiple languages, running via the command line, and seeding the randomizer to get consistent results. Hopefully, this saves you some time! I use Faker to generate data for stress tests, speed tests, and even test model pipelines for errors.
[ { "code": null, "e": 328, "s": 172, "text": "A great rule of thumb for writing code, especially in Python, is to look for a module on PyPi or just using Google, before you start writing code yourself." }, { "code": null, "e": 448, "s": 328, "text": "If nobody else has done what you’re trying to do then you still might find articles, partial code, or general guidance." }, { "code": null, "e": 578, "s": 448, "text": "If somebody has done it before you could find everything you need or at least examples of how others accomplished it or tried to." }, { "code": null, "e": 729, "s": 578, "text": "In this case, generating fake data is something that many, many people have done before. A search for “fake data” on PyPi yields over 10,000 packages." }, { "code": null, "e": 974, "s": 729, "text": "In my opinion, Faker is the best among them. The only time this package won’t solve your needs is when you need fake data in some rare format or data type. Even then, I’d still recommend using Faker and reshaping what it generates, if possible." }, { "code": null, "e": 1022, "s": 974, "text": "Here are some of the data generators available:" }, { "code": null, "e": 1027, "s": 1022, "text": "Name" }, { "code": null, "e": 1035, "s": 1027, "text": "Address" }, { "code": null, "e": 1064, "s": 1035, "text": "Text (paragraphs, sentences)" }, { "code": null, "e": 1075, "s": 1064, "text": "IP address" }, { "code": null, "e": 1079, "s": 1075, "text": "SSN" }, { "code": null, "e": 1088, "s": 1079, "text": "Birthday" }, { "code": null, "e": 1106, "s": 1088, "text": "User-agent string" }, { "code": null, "e": 1119, "s": 1106, "text": "Phone number" }, { "code": null, "e": 1140, "s": 1119, "text": "License plate number" }, { "code": null, "e": 1148, "s": 1140, "text": "Barcode" }, { "code": null, "e": 1190, "s": 1148, "text": "...and many more, see the full list here." }, { "code": null, "e": 1255, "s": 1190, "text": "All you have to do to is install it via pip on the command line:" }, { "code": null, "e": 1273, "s": 1255, "text": "pip install faker" }, { "code": null, "e": 1341, "s": 1273, "text": "Or if you’re in a Jupyter notebook, just add the exclamation point:" }, { "code": null, "e": 1360, "s": 1341, "text": "!pip install faker" }, { "code": null, "e": 1481, "s": 1360, "text": "Now for the good stuff! Generating 1000 fake user profiles is this easy (in bold is the Faker code, the rest is Pandas)." }, { "code": null, "e": 1633, "s": 1481, "text": "from faker import Fakerimport pandas as pdfaker = Faker()df = pd.DataFrame()for i in range(1000): df = df.append(faker.profile(), ignore_index=True)" }, { "code": null, "e": 1683, "s": 1633, "text": "And here’s a sample of what that data looks like:" }, { "code": null, "e": 1768, "s": 1683, "text": "If you want to get an individual field instead of a full profile, it’s just as easy:" }, { "code": null, "e": 1884, "s": 1768, "text": "from faker import Fakerfaker = Faker()# Get a random addressfaker.address()# Get a random person's namefaker.name()" }, { "code": null, "e": 2066, "s": 1884, "text": "Again, there are way more fields available, you can find them all in the documentation. You can even make your own data providers, here’s a few already contributed by the community." }, { "code": null, "e": 2190, "s": 2066, "text": "Faker also supports multiple languages, running via the command line, and seeding the randomizer to get consistent results." } ]
Building a Numerical Integration Tool in Python — From Scratch | by Kasper Müller | Towards Data Science
Not so long ago I was doing some research in analytic number theory. It was merely for my own sake at home in the evening. It was just a hobby project to satisfy my curiosity. At some point, I was left with a nasty double integral and I wanted to check that what I had found was actually correct. To add some context for the interested reader, I was trying to find a formula for the number of twin primes below a given number using the prime counting function and some techniques from complex analysis... Phew!, now that that is out of the way, let’s move on with the story. So what does one do when faced with such a problem involving a highly discontinuous function? Well, you fetch your laptop, a big cup of coffee and open up a code editor of some sort. In my case, my go-to programming language is Python, so I created an empty python file expecting this to take only 10 to 15 minutes. I was wrong! The reason? Well, building the custom functions needed such as detecting if a number is a prime, counting them with a loop and topping with some complex discontinuous functions was a breeze. The problem was when I wanted to integrate them. “Normally, Python’s scientific or data related libraries saves the day, but this time it failed me.” Now, SciPy has a package (of course) for this sort of thing called quad. And that was why I initially thought that it was going to be easy. Normally, Python’s scientific or data related libraries saves the day and are usually very nice to use, but this time it failed me. The problem was that my integrand (of my double integral) had a pole in the integration interval. Say you want to calculate the following integral: I actually tried this example and it didn’t work. The function is perfectly finite in a neighborhood around zero but when I tried calculating it, I kept getting a value of nan. I immediately understood what was going on. SciPy is using something like Riemann sums or the Trapezoidal rule to calculate the integral and that requires the algorithm to divide the integration interval, into a lot of small intervals. Calculating the areas of the corresponding small rectangles requires it to calculate the function value of all these interval-endpoints — one of them was (very close to) zero! And of course, trying to divide by zero in Python throws a ZeroDivisonError. As it turns out, according to SciPy’s documentation at least, there should be some ways around it. One can, for example, specify known poles (which of course requires us to know the poles of the function which is not always the case), but again that didn’t work on my double integral (even though it actually does work for the simple example above). The point of all of this introduction is the following: A numeric integration tool should only care about convergence — not poles You shouldn’t have to find the poles yourself or even think of them You want something hackable that you can modify to fit your needs e.g. modify the error vs runtime parameter (we’ll get into this in a bit) The errors should be meaningful and understandable At this point, I was so frustrated, that I decided to build a tool myself. After realizing that I had to do this, I needed to go fetch some more coffee and think about a design for this tool. You can of course do this in many different ways. I went with the most lightweight approach because I believe that such a tool needs to adapt constantly to fit the user’s needs. Let’s build it! I decided to go for an object-oriented design choosing to build a class around the function to be integrated. I did this so that the user would be able to easily add more features to it in the future and to save meta-information about the calculation such as error intervals etc. Let’s start with the basics. First of all, this program only really depends on Numpy. However, for convenience, we will import quad: If you don’t have these packages installed, you can install them with pip install numpy quad or pip3 depending on your OS. For the code in this article to work, you need to run it with Python 3. Let’s create the Integrate class A few comments are in order here. First, I record the error and you will see why in a moment. Second, we have a sign-attribute defined. This is because when the bounds of the integral swap, then so does the sign of the value and we need to be able to calculate integrals when the lower limit is greater than the upper limit. This is of course just to show you how you could do this. And now for the main (single) integration method: I have used the trapezoidal rule here (if you don’t remember, this is basically an average of left and right Riemann sums), but that is no surprise. You might wonder why I have a big try/except clause lying around. That is actually one of the main points. What it does is that if there should be a division by zero hiding in there, then it will be gracefully ignored without input from the user. We also see that we have stored the error if one wants to calculate by interval arithmetic or just check how accurate the result is. That’s all well, but how do we use our tool? Say we wanna integrate the function from our example above. This becomes easy now, despite the “0/0” expression when x = 0. and now we get an answer of about 1.892166. Pretty good! But we are not done, remember? We have a double integral to solve, and no working tool for it yet. So we need to generalize this code to calculate a double integral, but first, let us make sure that we understand the possible errors that we might get. To do that, we need to build a custom error class in Python. This is easy, we just inherit from Exception: Moreover, since the input intervals should now be a parameter of type list of lists (or something like that), a possible solution is the following: Note! This is by no means performance code, and if we wanted, we could optimize this with e.g. vectorization in Numpy. That being said, you can adjust the precision parameter to fit your needs. The higher the value, the more accurate the integral is going to be, but the longer it will take to compute. That’s where the error attribute comes in. You can try as an exercise to optimize this code! If we wanted, we could of course generalize this to triple integrals, etc. but for the scope of this article, let’s stick to single and double ones. So let me show you how this works in action. Say you are working on a project in Python and all of a sudden, you come across the problem of approximating the following integral: Well, you now have the tool for the job. At the top of your file, import your new integral engine Further down in the project you can now solve it. This gives an output of The result is 3.1415926535897944The accuracy of this result is -1.7319479184152442e-14 This is pretty d... close! To compare against the real deal, the true beginning of pi is 3.141592653589793238... and our error range of course told us exactly that— namely, that we got the first 14 digits right (At least within our limits of integration — we need to be a little careful in our example because technically we are missing the “tails” of the function). Of course, increasing the precision parameter, or the limits of the integral for that matter, would give us even more digits right. But here’s the important take away: Even though the double integral above should be calculated over the entire real plane, we can make sure that within our interval we can get arbitrarily close to the true value — and we can check that because of our error attribute. So it is a matter of exchanging accuracy for runtime. Now I can get back to my work and hopefully, if you encounter some issues in this direction yourself or if you just want to learn more Python, please do not hesitate to use or extend this code. You can clone the full repository here. After 7 cups of coffee, I can now go to sleep with ease of mind. I only hope that I am not gonna be chased by mad Riemann sums in my dreams. Oh.. what about integrating with polar coordinates?... Maybe next time.
[ { "code": null, "e": 348, "s": 172, "text": "Not so long ago I was doing some research in analytic number theory. It was merely for my own sake at home in the evening. It was just a hobby project to satisfy my curiosity." }, { "code": null, "e": 747, "s": 348, "text": "At some point, I was left with a nasty double integral and I wanted to check that what I had found was actually correct. To add some context for the interested reader, I was trying to find a formula for the number of twin primes below a given number using the prime counting function and some techniques from complex analysis... Phew!, now that that is out of the way, let’s move on with the story." }, { "code": null, "e": 1063, "s": 747, "text": "So what does one do when faced with such a problem involving a highly discontinuous function? Well, you fetch your laptop, a big cup of coffee and open up a code editor of some sort. In my case, my go-to programming language is Python, so I created an empty python file expecting this to take only 10 to 15 minutes." }, { "code": null, "e": 1316, "s": 1063, "text": "I was wrong! The reason? Well, building the custom functions needed such as detecting if a number is a prime, counting them with a loop and topping with some complex discontinuous functions was a breeze. The problem was when I wanted to integrate them." }, { "code": null, "e": 1417, "s": 1316, "text": "“Normally, Python’s scientific or data related libraries saves the day, but this time it failed me.”" }, { "code": null, "e": 1787, "s": 1417, "text": "Now, SciPy has a package (of course) for this sort of thing called quad. And that was why I initially thought that it was going to be easy. Normally, Python’s scientific or data related libraries saves the day and are usually very nice to use, but this time it failed me. The problem was that my integrand (of my double integral) had a pole in the integration interval." }, { "code": null, "e": 1837, "s": 1787, "text": "Say you want to calculate the following integral:" }, { "code": null, "e": 2058, "s": 1837, "text": "I actually tried this example and it didn’t work. The function is perfectly finite in a neighborhood around zero but when I tried calculating it, I kept getting a value of nan. I immediately understood what was going on." }, { "code": null, "e": 2426, "s": 2058, "text": "SciPy is using something like Riemann sums or the Trapezoidal rule to calculate the integral and that requires the algorithm to divide the integration interval, into a lot of small intervals. Calculating the areas of the corresponding small rectangles requires it to calculate the function value of all these interval-endpoints — one of them was (very close to) zero!" }, { "code": null, "e": 2853, "s": 2426, "text": "And of course, trying to divide by zero in Python throws a ZeroDivisonError. As it turns out, according to SciPy’s documentation at least, there should be some ways around it. One can, for example, specify known poles (which of course requires us to know the poles of the function which is not always the case), but again that didn’t work on my double integral (even though it actually does work for the simple example above)." }, { "code": null, "e": 2909, "s": 2853, "text": "The point of all of this introduction is the following:" }, { "code": null, "e": 2983, "s": 2909, "text": "A numeric integration tool should only care about convergence — not poles" }, { "code": null, "e": 3051, "s": 2983, "text": "You shouldn’t have to find the poles yourself or even think of them" }, { "code": null, "e": 3191, "s": 3051, "text": "You want something hackable that you can modify to fit your needs e.g. modify the error vs runtime parameter (we’ll get into this in a bit)" }, { "code": null, "e": 3242, "s": 3191, "text": "The errors should be meaningful and understandable" }, { "code": null, "e": 3317, "s": 3242, "text": "At this point, I was so frustrated, that I decided to build a tool myself." }, { "code": null, "e": 3612, "s": 3317, "text": "After realizing that I had to do this, I needed to go fetch some more coffee and think about a design for this tool. You can of course do this in many different ways. I went with the most lightweight approach because I believe that such a tool needs to adapt constantly to fit the user’s needs." }, { "code": null, "e": 3628, "s": 3612, "text": "Let’s build it!" }, { "code": null, "e": 3908, "s": 3628, "text": "I decided to go for an object-oriented design choosing to build a class around the function to be integrated. I did this so that the user would be able to easily add more features to it in the future and to save meta-information about the calculation such as error intervals etc." }, { "code": null, "e": 4041, "s": 3908, "text": "Let’s start with the basics. First of all, this program only really depends on Numpy. However, for convenience, we will import quad:" }, { "code": null, "e": 4111, "s": 4041, "text": "If you don’t have these packages installed, you can install them with" }, { "code": null, "e": 4134, "s": 4111, "text": "pip install numpy quad" }, { "code": null, "e": 4164, "s": 4134, "text": "or pip3 depending on your OS." }, { "code": null, "e": 4236, "s": 4164, "text": "For the code in this article to work, you need to run it with Python 3." }, { "code": null, "e": 4269, "s": 4236, "text": "Let’s create the Integrate class" }, { "code": null, "e": 4652, "s": 4269, "text": "A few comments are in order here. First, I record the error and you will see why in a moment. Second, we have a sign-attribute defined. This is because when the bounds of the integral swap, then so does the sign of the value and we need to be able to calculate integrals when the lower limit is greater than the upper limit. This is of course just to show you how you could do this." }, { "code": null, "e": 4702, "s": 4652, "text": "And now for the main (single) integration method:" }, { "code": null, "e": 5098, "s": 4702, "text": "I have used the trapezoidal rule here (if you don’t remember, this is basically an average of left and right Riemann sums), but that is no surprise. You might wonder why I have a big try/except clause lying around. That is actually one of the main points. What it does is that if there should be a division by zero hiding in there, then it will be gracefully ignored without input from the user." }, { "code": null, "e": 5231, "s": 5098, "text": "We also see that we have stored the error if one wants to calculate by interval arithmetic or just check how accurate the result is." }, { "code": null, "e": 5336, "s": 5231, "text": "That’s all well, but how do we use our tool? Say we wanna integrate the function from our example above." }, { "code": null, "e": 5400, "s": 5336, "text": "This becomes easy now, despite the “0/0” expression when x = 0." }, { "code": null, "e": 5457, "s": 5400, "text": "and now we get an answer of about 1.892166. Pretty good!" }, { "code": null, "e": 5556, "s": 5457, "text": "But we are not done, remember? We have a double integral to solve, and no working tool for it yet." }, { "code": null, "e": 5816, "s": 5556, "text": "So we need to generalize this code to calculate a double integral, but first, let us make sure that we understand the possible errors that we might get. To do that, we need to build a custom error class in Python. This is easy, we just inherit from Exception:" }, { "code": null, "e": 5964, "s": 5816, "text": "Moreover, since the input intervals should now be a parameter of type list of lists (or something like that), a possible solution is the following:" }, { "code": null, "e": 6083, "s": 5964, "text": "Note! This is by no means performance code, and if we wanted, we could optimize this with e.g. vectorization in Numpy." }, { "code": null, "e": 6360, "s": 6083, "text": "That being said, you can adjust the precision parameter to fit your needs. The higher the value, the more accurate the integral is going to be, but the longer it will take to compute. That’s where the error attribute comes in. You can try as an exercise to optimize this code!" }, { "code": null, "e": 6509, "s": 6360, "text": "If we wanted, we could of course generalize this to triple integrals, etc. but for the scope of this article, let’s stick to single and double ones." }, { "code": null, "e": 6554, "s": 6509, "text": "So let me show you how this works in action." }, { "code": null, "e": 6687, "s": 6554, "text": "Say you are working on a project in Python and all of a sudden, you come across the problem of approximating the following integral:" }, { "code": null, "e": 6785, "s": 6687, "text": "Well, you now have the tool for the job. At the top of your file, import your new integral engine" }, { "code": null, "e": 6835, "s": 6785, "text": "Further down in the project you can now solve it." }, { "code": null, "e": 6859, "s": 6835, "text": "This gives an output of" }, { "code": null, "e": 6946, "s": 6859, "text": "The result is 3.1415926535897944The accuracy of this result is -1.7319479184152442e-14" }, { "code": null, "e": 7445, "s": 6946, "text": "This is pretty d... close! To compare against the real deal, the true beginning of pi is 3.141592653589793238... and our error range of course told us exactly that— namely, that we got the first 14 digits right (At least within our limits of integration — we need to be a little careful in our example because technically we are missing the “tails” of the function). Of course, increasing the precision parameter, or the limits of the integral for that matter, would give us even more digits right." }, { "code": null, "e": 7481, "s": 7445, "text": "But here’s the important take away:" }, { "code": null, "e": 7767, "s": 7481, "text": "Even though the double integral above should be calculated over the entire real plane, we can make sure that within our interval we can get arbitrarily close to the true value — and we can check that because of our error attribute. So it is a matter of exchanging accuracy for runtime." }, { "code": null, "e": 7961, "s": 7767, "text": "Now I can get back to my work and hopefully, if you encounter some issues in this direction yourself or if you just want to learn more Python, please do not hesitate to use or extend this code." }, { "code": null, "e": 8001, "s": 7961, "text": "You can clone the full repository here." }, { "code": null, "e": 8142, "s": 8001, "text": "After 7 cups of coffee, I can now go to sleep with ease of mind. I only hope that I am not gonna be chased by mad Riemann sums in my dreams." }, { "code": null, "e": 8197, "s": 8142, "text": "Oh.. what about integrating with polar coordinates?..." } ]
Find two numbers with the given LCM and minimum possible difference - GeeksforGeeks
20 Feb, 2022 Given an integer X, the task is to find two integers A and B such that LCM(A, B) = X and the difference between the A and B is minimum possible.Examples: Input: X = 6 Output: 2 3 LCM(2, 3) = 6 and (3 – 2) = 1 which is the minimum possible.Input X = 7 Output: 1 7 Approach: An approach to solve this problem is to find all the factors of the given number using the approach discussed in this article and then find the pair (A, B) that satisfies the given conditions and has the minimum possible difference.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the LCM of a and bint lcm(int a, int b){ return (a / __gcd(a, b) * b);} // Function to find and print the two numbersvoid findNums(int x){ int ans; // To find the factors for (int i = 1; i <= sqrt(x); i++) { // To check if i is a factor of x and // the minimum possible number // satisfying the given conditions if (x % i == 0 && lcm(i, x / i) == x) { ans = i; } } cout << ans << " " << (x / ans);} // Driver codeint main(){ int x = 12; findNums(x); return 0;} // Java implementation of the approachclass GFG{ // Function to return the LCM of a and b static int lcm(int a, int b) { return (a / __gcd(a, b) * b); } static int __gcd(int a, int b) { return b == 0 ? a : __gcd(b, a % b); } // Function to find and print the two numbers static void findNums(int x) { int ans = -1; // To find the factors for (int i = 1; i <= Math.sqrt(x); i++) { // To check if i is a factor of x and // the minimum possible number // satisfying the given conditions if (x % i == 0 && lcm(i, x / i) == x) { ans = i; } } System.out.print(ans + " " + (x / ans)); } // Driver code public static void main(String[] args) { int x = 12; findNums(x); }} // This code is contributed by 29AjayKumar # Python3 implementation of the approachfrom math import gcd as __gcd, sqrt, ceil # Function to return the LCM of a and bdef lcm(a, b): return (a // __gcd(a, b) * b) # Function to find and print the two numbersdef findNums(x): ans = 0 # To find the factors for i in range(1, ceil(sqrt(x))): # To check if i is a factor of x and # the minimum possible number # satisfying the given conditions if (x % i == 0 and lcm(i, x // i) == x): ans = i print(ans, (x//ans)) # Driver codex = 12 findNums(x) # This code is contributed by mohit kumar 29 // C# implementation of the approachusing System; class GFG{ // Function to return the LCM of a and b static int lcm(int a, int b) { return (a / __gcd(a, b) * b); } static int __gcd(int a, int b) { return b == 0 ? a : __gcd(b, a % b); } // Function to find and print the two numbers static void findNums(int x) { int ans = -1; // To find the factors for (int i = 1; i <= Math.Sqrt(x); i++) { // To check if i is a factor of x and // the minimum possible number // satisfying the given conditions if (x % i == 0 && lcm(i, x / i) == x) { ans = i; } } Console.Write(ans + " " + (x / ans)); } // Driver code public static void Main(String[] args) { int x = 12; findNums(x); }} // This code is contributed by 29AjayKumar <script>// Javascript implementation of the approach // Function to return the LCM of a and bfunction lcm(a,b){ return (a / __gcd(a, b) * b);} function __gcd(a,b){ return b == 0 ? a : __gcd(b, a % b);} // Function to find and print the two numbersfunction findNums(x){ let ans = -1; // To find the factors for (let i = 1; i <= Math.sqrt(x); i++) { // To check if i is a factor of x and // the minimum possible number // satisfying the given conditions if (x % i == 0 && lcm(i, Math.floor(x / i)) == x) { ans = i; } } document.write(ans + " " + Math.floor(x / ans));} // Driver codelet x = 12;findNums(x); // This code is contributed by patel2127</script> 3 4 Time Complexity: O(n1/2 * log(max(a, b))) Auxiliary Space: O(log(max(a, b))) mohit kumar 29 29AjayKumar Code_Mech patel2127 subham348 LCM Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program to find sum of elements in a given array Program for Decimal to Binary Conversion Program for factorial of a number Operators in C / C++ The Knight's tour problem | Backtracking-1 Efficient program to print all prime factors of a given number Find minimum number of coins that make a given value
[ { "code": null, "e": 24854, "s": 24826, "text": "\n20 Feb, 2022" }, { "code": null, "e": 25010, "s": 24854, "text": "Given an integer X, the task is to find two integers A and B such that LCM(A, B) = X and the difference between the A and B is minimum possible.Examples: " }, { "code": null, "e": 25121, "s": 25010, "text": "Input: X = 6 Output: 2 3 LCM(2, 3) = 6 and (3 – 2) = 1 which is the minimum possible.Input X = 7 Output: 1 7 " }, { "code": null, "e": 25418, "s": 25123, "text": "Approach: An approach to solve this problem is to find all the factors of the given number using the approach discussed in this article and then find the pair (A, B) that satisfies the given conditions and has the minimum possible difference.Below is the implementation of the above approach: " }, { "code": null, "e": 25422, "s": 25418, "text": "C++" }, { "code": null, "e": 25427, "s": 25422, "text": "Java" }, { "code": null, "e": 25435, "s": 25427, "text": "Python3" }, { "code": null, "e": 25438, "s": 25435, "text": "C#" }, { "code": null, "e": 25449, "s": 25438, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the LCM of a and bint lcm(int a, int b){ return (a / __gcd(a, b) * b);} // Function to find and print the two numbersvoid findNums(int x){ int ans; // To find the factors for (int i = 1; i <= sqrt(x); i++) { // To check if i is a factor of x and // the minimum possible number // satisfying the given conditions if (x % i == 0 && lcm(i, x / i) == x) { ans = i; } } cout << ans << \" \" << (x / ans);} // Driver codeint main(){ int x = 12; findNums(x); return 0;}", "e": 26093, "s": 25449, "text": null }, { "code": "// Java implementation of the approachclass GFG{ // Function to return the LCM of a and b static int lcm(int a, int b) { return (a / __gcd(a, b) * b); } static int __gcd(int a, int b) { return b == 0 ? a : __gcd(b, a % b); } // Function to find and print the two numbers static void findNums(int x) { int ans = -1; // To find the factors for (int i = 1; i <= Math.sqrt(x); i++) { // To check if i is a factor of x and // the minimum possible number // satisfying the given conditions if (x % i == 0 && lcm(i, x / i) == x) { ans = i; } } System.out.print(ans + \" \" + (x / ans)); } // Driver code public static void main(String[] args) { int x = 12; findNums(x); }} // This code is contributed by 29AjayKumar", "e": 27005, "s": 26093, "text": null }, { "code": "# Python3 implementation of the approachfrom math import gcd as __gcd, sqrt, ceil # Function to return the LCM of a and bdef lcm(a, b): return (a // __gcd(a, b) * b) # Function to find and print the two numbersdef findNums(x): ans = 0 # To find the factors for i in range(1, ceil(sqrt(x))): # To check if i is a factor of x and # the minimum possible number # satisfying the given conditions if (x % i == 0 and lcm(i, x // i) == x): ans = i print(ans, (x//ans)) # Driver codex = 12 findNums(x) # This code is contributed by mohit kumar 29", "e": 27603, "s": 27005, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to return the LCM of a and b static int lcm(int a, int b) { return (a / __gcd(a, b) * b); } static int __gcd(int a, int b) { return b == 0 ? a : __gcd(b, a % b); } // Function to find and print the two numbers static void findNums(int x) { int ans = -1; // To find the factors for (int i = 1; i <= Math.Sqrt(x); i++) { // To check if i is a factor of x and // the minimum possible number // satisfying the given conditions if (x % i == 0 && lcm(i, x / i) == x) { ans = i; } } Console.Write(ans + \" \" + (x / ans)); } // Driver code public static void Main(String[] args) { int x = 12; findNums(x); }} // This code is contributed by 29AjayKumar", "e": 28524, "s": 27603, "text": null }, { "code": "<script>// Javascript implementation of the approach // Function to return the LCM of a and bfunction lcm(a,b){ return (a / __gcd(a, b) * b);} function __gcd(a,b){ return b == 0 ? a : __gcd(b, a % b);} // Function to find and print the two numbersfunction findNums(x){ let ans = -1; // To find the factors for (let i = 1; i <= Math.sqrt(x); i++) { // To check if i is a factor of x and // the minimum possible number // satisfying the given conditions if (x % i == 0 && lcm(i, Math.floor(x / i)) == x) { ans = i; } } document.write(ans + \" \" + Math.floor(x / ans));} // Driver codelet x = 12;findNums(x); // This code is contributed by patel2127</script>", "e": 29315, "s": 28524, "text": null }, { "code": null, "e": 29319, "s": 29315, "text": "3 4" }, { "code": null, "e": 29363, "s": 29321, "text": "Time Complexity: O(n1/2 * log(max(a, b)))" }, { "code": null, "e": 29398, "s": 29363, "text": "Auxiliary Space: O(log(max(a, b)))" }, { "code": null, "e": 29413, "s": 29398, "text": "mohit kumar 29" }, { "code": null, "e": 29425, "s": 29413, "text": "29AjayKumar" }, { "code": null, "e": 29435, "s": 29425, "text": "Code_Mech" }, { "code": null, "e": 29445, "s": 29435, "text": "patel2127" }, { "code": null, "e": 29455, "s": 29445, "text": "subham348" }, { "code": null, "e": 29459, "s": 29455, "text": "LCM" }, { "code": null, "e": 29472, "s": 29459, "text": "Mathematical" }, { "code": null, "e": 29485, "s": 29472, "text": "Mathematical" }, { "code": null, "e": 29583, "s": 29485, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29607, "s": 29583, "text": "Merge two sorted arrays" }, { "code": null, "e": 29650, "s": 29607, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 29664, "s": 29650, "text": "Prime Numbers" }, { "code": null, "e": 29713, "s": 29664, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 29754, "s": 29713, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 29788, "s": 29754, "text": "Program for factorial of a number" }, { "code": null, "e": 29809, "s": 29788, "text": "Operators in C / C++" }, { "code": null, "e": 29852, "s": 29809, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 29915, "s": 29852, "text": "Efficient program to print all prime factors of a given number" } ]
Find the maximum subarray XOR in a given array - GeeksforGeeks
24 Jan, 2022 Given an array of integers. find the maximum XOR subarray value in given array. Expected time complexity O(n). Examples: Input: arr[] = {1, 2, 3, 4} Output: 7 The subarray {3, 4} has maximum XOR value Input: arr[] = {8, 1, 2, 12, 7, 6} Output: 15 The subarray {1, 2, 12} has maximum XOR value Input: arr[] = {4, 6} Output: 6 The subarray {6} has maximum XOR value A Simple Solution is to use two loops to find XOR of all subarrays and return the maximum. C++ Java Python3 C# PHP Javascript // A simple C++ program to find max subarray XOR#include<bits/stdc++.h>using namespace std; int maxSubarrayXOR(int arr[], int n){ int ans = INT_MIN; // Initialize result // Pick starting points of subarrays for (int i=0; i<n; i++) { int curr_xor = 0; // to store xor of current subarray // Pick ending points of subarrays starting with i for (int j=i; j<n; j++) { curr_xor = curr_xor ^ arr[j]; ans = max(ans, curr_xor); } } return ans;} // Driver program to test above functionsint main(){ int arr[] = {8, 1, 2, 12}; int n = sizeof(arr)/sizeof(arr[0]); cout << "Max subarray XOR is " << maxSubarrayXOR(arr, n); return 0;} // A simple Java program to find max subarray XORclass GFG { static int maxSubarrayXOR(int arr[], int n) { int ans = Integer.MIN_VALUE; // Initialize result // Pick starting points of subarrays for (int i=0; i<n; i++) { // to store xor of current subarray int curr_xor = 0; // Pick ending points of subarrays starting with i for (int j=i; j<n; j++) { curr_xor = curr_xor ^ arr[j]; ans = Math.max(ans, curr_xor); } } return ans; } // Driver program to test above functions public static void main(String args[]) { int arr[] = {8, 1, 2, 12}; int n = arr.length; System.out.println("Max subarray XOR is " + maxSubarrayXOR(arr, n)); }}//This code is contributed by Sumit Ghosh # A simple Python program# to find max subarray XOR def maxSubarrayXOR(arr,n): ans = -2147483648 #Initialize result # Pick starting points of subarrays for i in range(n): # to store xor of current subarray curr_xor = 0 # Pick ending points of # subarrays starting with i for j in range(i,n): curr_xor = curr_xor ^ arr[j] ans = max(ans, curr_xor) return ans # Driver code arr = [8, 1, 2, 12]n = len(arr) print("Max subarray XOR is ", maxSubarrayXOR(arr, n)) # This code is contributed# by Anant Agarwal. // A simple C# program to find// max subarray XORusing System; class GFG{ // Function to find max subarray static int maxSubarrayXOR(int []arr, int n) { int ans = int.MinValue; // Initialize result // Pick starting points of subarrays for (int i = 0; i < n; i++) { // to store xor of current subarray int curr_xor = 0; // Pick ending points of // subarrays starting with i for (int j = i; j < n; j++) { curr_xor = curr_xor ^ arr[j]; ans = Math.Max(ans, curr_xor); } } return ans; } // Driver code public static void Main() { int []arr = {8, 1, 2, 12}; int n = arr.Length; Console.WriteLine("Max subarray XOR is " + maxSubarrayXOR(arr, n)); }} // This code is contributed by Sam007. <?php// A simple PHP program to// find max subarray XOR function maxSubarrayXOR($arr, $n){ // Initialize result $ans = PHP_INT_MIN; // Pick starting points // of subarrays for ($i = 0; $i < $n; $i++) { // to store xor of // current subarray $curr_xor = 0; // Pick ending points of // subarrays starting with i for ($j = $i; $j < $n; $j++) { $curr_xor = $curr_xor ^ $arr[$j]; $ans = max($ans, $curr_xor); } } return $ans;} // Driver Code $arr = array(8, 1, 2, 12); $n = count($arr); echo "Max subarray XOR is " , maxSubarrayXOR($arr, $n); // This code is contributed by anuj_67.?> <script> // A simple Javascript program to find// max subarray XORfunction maxSubarrayXOR(arr, n){ // Initialize result let ans = Number.MIN_VALUE; // Pick starting points of subarrays for(let i = 0; i < n; i++) { // To store xor of current subarray let curr_xor = 0; // Pick ending points of subarrays // starting with i for(let j = i; j < n; j++) { curr_xor = curr_xor ^ arr[j]; ans = Math.max(ans, curr_xor); } } return ans;} // Driver codelet arr = [ 8, 1, 2, 12 ];let n = arr.length; document.write("Max subarray XOR is " + maxSubarrayXOR(arr, n)); // This code is contributed by divyesh072019 </script> Max subarray XOR is 15 Time Complexity of above solution is O(n2). An Efficient Solution can solve the above problem in O(n) time under the assumption that integers take fixed number of bits to store. The idea is to use Trie Data Structure. Below is algorithm. 1) Create an empty Trie. Every node of Trie is going to contain two children, for 0 and 1 value of bit. 2) Initialize pre_xor = 0 and insert into the Trie. 3) Initialize result = minus infinite 4) Traverse the given array and do following for every array element arr[i]. a) pre_xor = pre_xor ^ arr[i] pre_xor now contains xor of elements from arr[0] to arr[i]. b) Query the maximum xor value ending with arr[i] from Trie. c) Update result if the value obtained in step 4.b is more than current value of result. How does 4.b work? We can observe from above algorithm that we build a Trie that contains XOR of all prefixes of given array. To find the maximum XOR subarray ending with arr[i], there may be two cases. i) The prefix itself has the maximum XOR value ending with arr[i]. For example if i=2 in {8, 2, 1, 12}, then the maximum subarray xor ending with arr[2] is the whole prefix. ii) We need to remove some prefix (ending at index from 0 to i-1). For example if i=3 in {8, 2, 1, 12}, then the maximum subarray xor ending with arr[3] starts with arr[1] and we need to remove arr[0].To find the prefix to be removed, we find the entry in Trie that has maximum XOR value with current prefix. If we do XOR of such previous prefix with current prefix, we get the maximum XOR value ending with arr[i]. If there is no prefix to be removed (case i), then we return 0 (that’s why we inserted 0 in Trie). Below is the implementation of above idea : C++ Java Python3 C# // C++ program for a Trie based O(n) solution to find max// subarray XOR#include<bits/stdc++.h>using namespace std; // Assumed int size#define INT_SIZE 32 // A Trie Nodestruct TrieNode{ int value; // Only used in leaf nodes TrieNode *arr[2];}; // Utility function to create a Trie nodeTrieNode *newNode(){ TrieNode *temp = new TrieNode; temp->value = 0; temp->arr[0] = temp->arr[1] = NULL; return temp;} // Inserts pre_xor to trie with given rootvoid insert(TrieNode *root, int pre_xor){ TrieNode *temp = root; // Start from the msb, insert all bits of // pre_xor into Trie for (int i=INT_SIZE-1; i>=0; i--) { // Find current bit in given prefix bool val = pre_xor & (1<<i); // Create a new node if needed if (temp->arr[val] == NULL) temp->arr[val] = newNode(); temp = temp->arr[val]; } // Store value at leaf node temp->value = pre_xor;} // Finds the maximum XOR ending with last number in// prefix XOR 'pre_xor' and returns the XOR of this maximum// with pre_xor which is maximum XOR ending with last element// of pre_xor.int query(TrieNode *root, int pre_xor){ TrieNode *temp = root; for (int i=INT_SIZE-1; i>=0; i--) { // Find current bit in given prefix bool val = pre_xor & (1<<i); // Traverse Trie, first look for a // prefix that has opposite bit if (temp->arr[1-val]!=NULL) temp = temp->arr[1-val]; // If there is no prefix with opposite // bit, then look for same bit. else if (temp->arr[val] != NULL) temp = temp->arr[val]; } return pre_xor^(temp->value);} // Returns maximum XOR value of a subarray in arr[0..n-1]int maxSubarrayXOR(int arr[], int n){ // Create a Trie and insert 0 into it TrieNode *root = newNode(); insert(root, 0); // Initialize answer and xor of current prefix int result = INT_MIN, pre_xor =0; // Traverse all input array element for (int i=0; i<n; i++) { // update current prefix xor and insert it into Trie pre_xor = pre_xor^arr[i]; insert(root, pre_xor); // Query for current prefix xor in Trie and update // result if required result = max(result, query(root, pre_xor)); } return result;} // Driver program to test above functionsint main(){ int arr[] = {8, 1, 2, 12}; int n = sizeof(arr)/sizeof(arr[0]); cout << "Max subarray XOR is " << maxSubarrayXOR(arr, n); return 0;} // Java program for a Trie based O(n) solution to// find max subarray XORclass GFG{ // Assumed int size static final int INT_SIZE = 32; // A Trie Node static class TrieNode { int value; // Only used in leaf nodes TrieNode[] arr = new TrieNode[2]; public TrieNode() { value = 0; arr[0] = null; arr[1] = null; } } static TrieNode root; // Inserts pre_xor to trie with given root static void insert(int pre_xor) { TrieNode temp = root; // Start from the msb, insert all bits of // pre_xor into Trie for (int i=INT_SIZE-1; i>=0; i--) { // Find current bit in given prefix int val = (pre_xor & (1<<i)) >=1 ? 1 : 0; // Create a new node if needed if (temp.arr[val] == null) temp.arr[val] = new TrieNode(); temp = temp.arr[val]; } // Store value at leaf node temp.value = pre_xor; } // Finds the maximum XOR ending with last number in // prefix XOR 'pre_xor' and returns the XOR of this // maximum with pre_xor which is maximum XOR ending // with last element of pre_xor. static int query(int pre_xor) { TrieNode temp = root; for (int i=INT_SIZE-1; i>=0; i--) { // Find current bit in given prefix int val = (pre_xor & (1<<i)) >= 1 ? 1 : 0; // Traverse Trie, first look for a // prefix that has opposite bit if (temp.arr[1-val] != null) temp = temp.arr[1-val]; // If there is no prefix with opposite // bit, then look for same bit. else if (temp.arr[val] != null) temp = temp.arr[val]; } return pre_xor^(temp.value); } // Returns maximum XOR value of a subarray in // arr[0..n-1] static int maxSubarrayXOR(int arr[], int n) { // Create a Trie and insert 0 into it root = new TrieNode(); insert(0); // Initialize answer and xor of current prefix int result = Integer.MIN_VALUE; int pre_xor =0; // Traverse all input array element for (int i=0; i<n; i++) { // update current prefix xor and insert it // into Trie pre_xor = pre_xor^arr[i]; insert(pre_xor); // Query for current prefix xor in Trie and // update result if required result = Math.max(result, query(pre_xor)); } return result; } // Driver program to test above functions public static void main(String args[]) { int arr[] = {8, 1, 2, 12}; int n = arr.length; System.out.println("Max subarray XOR is " + maxSubarrayXOR(arr, n)); }}// This code is contributed by Sumit Ghosh """Python implementation for a Trie based solutionto find max subArray XOR""" """structure of Trie Node"""class Node: def __init__(self, data): self.data = data self.left = None # left node for 0 self.right = None # right node for 1 """ class for implementing Trie """ class Trie: def __init__(self): self.root = Node(0) """insert pre_xor to trie with given root""" def insert(self, pre_xor): self.temp = self.root """start from msb, insert all bits of pre_xor into the Trie""" for i in range(31, -1, -1): """Find current bit in prefix sum""" val = pre_xor & (1<<i) if val : """create new node if needed""" if not self.temp.right: self.temp.right = Node(0) self.temp = self.temp.right if not val: """create new node if needed""" if not self.temp.left: self.temp.left = Node(0) self.temp = self.temp.left """store value at leaf node""" self.temp.data = pre_xor """find the maximum xor ending with last number in prefix XOR and return the XOR of this""" def query(self, xor): self.temp = self.root for i in range(31, -1, -1): """find the current bit in prefix xor""" val = xor & (1<<i) """Traverse the trie, first look for opposite bit and then look for same bit""" if val: if self.temp.left: self.temp = self.temp.left elif self.temp.right: self.temp = self.temp.right else: if self.temp.right: self.temp = self.temp.right elif self.temp.left: self.temp = self.temp.left return xor ^ self.temp.data """returns maximum XOR value of subarray""" def maxSubArrayXOR(self, n, Arr): """insert 0 in the trie""" self.insert(0) """initialize result and pre_xor""" result = -float('inf') pre_xor = 0 """traverse all input array element""" for i in range(n): """update current prefix xor and insert it into Trie""" pre_xor = pre_xor ^ Arr[i] self.insert(pre_xor) """Query for current prefix xor in Trie and update result""" result = max(result, self.query(pre_xor)) return result """Driver program to test above functions"""if __name__ == "__main__": Arr = [8, 1, 2, 12] n = len(Arr) trie = Trie() print(trie.maxSubArrayXOR(n, Arr)) # This code is contributed by chaudhary_19 using System; // C# program for a Trie based O(n) solution to // find max subarray XORpublic class GFG{ // Assumed int size public const int INT_SIZE = 32; // A Trie Node public class TrieNode { public int value; // Only used in leaf nodes public TrieNode[] arr = new TrieNode[2]; public TrieNode() { value = 0; arr[0] = null; arr[1] = null; } } public static TrieNode root; // Inserts pre_xor to trie with given root public static void insert(int pre_xor) { TrieNode temp = root; // Start from the msb, insert all bits of // pre_xor into Trie for (int i = INT_SIZE-1; i >= 0; i--) { // Find current bit in given prefix int val = (pre_xor & (1 << i)) >= 1 ? 1 : 0; // Create a new node if needed if (temp.arr[val] == null) { temp.arr[val] = new TrieNode(); } temp = temp.arr[val]; } // Store value at leaf node temp.value = pre_xor; } // Finds the maximum XOR ending with last number in // prefix XOR 'pre_xor' and returns the XOR of this // maximum with pre_xor which is maximum XOR ending // with last element of pre_xor. public static int query(int pre_xor) { TrieNode temp = root; for (int i = INT_SIZE-1; i >= 0; i--) { // Find current bit in given prefix int val = (pre_xor & (1 << i)) >= 1 ? 1 : 0; // Traverse Trie, first look for a // prefix that has opposite bit if (temp.arr[1 - val] != null) { temp = temp.arr[1 - val]; } // If there is no prefix with opposite // bit, then look for same bit. else if (temp.arr[val] != null) { temp = temp.arr[val]; } } return pre_xor ^ (temp.value); } // Returns maximum XOR value of a subarray in // arr[0..n-1] public static int maxSubarrayXOR(int[] arr, int n) { // Create a Trie and insert 0 into it root = new TrieNode(); insert(0); // Initialize answer and xor of current prefix int result = int.MinValue; int pre_xor = 0; // Traverse all input array element for (int i = 0; i < n; i++) { // update current prefix xor and insert it // into Trie pre_xor = pre_xor ^ arr[i]; insert(pre_xor); // Query for current prefix xor in Trie and // update result if required result = Math.Max(result, query(pre_xor)); } return result; } // Driver program to test above functions public static void Main(string[] args) { int[] arr = new int[] {8, 1, 2, 12}; int n = arr.Length; Console.WriteLine("Max subarray XOR is " + maxSubarrayXOR(arr, n)); }} // This code is contributed by Shrikant13 Max subarray XOR is 15 Exercise: Extend the above solution so that it also prints starting and ending indexes of subarray with maximum value (Hint: we can add one more field to Trie node to achieve this Another Efficient Solution to the problem in O(n) time complexity can be achieved with the help of Kadane’s algorithm. The following algorithm is used to find the largest contagious max sum sub-array. Similarly, we can go through the array once and as we are going through it we can find the largest XOR value. 1)initialise max_now=0,max_ending=1; 2)Traverse the given array and do following for every array element arr[i]. a) max_now = bigger out of(arr[i],arr[i]^max_now) max_now now temprorarily contains bigger value out of current element and current Xor of all elements b) max_ending=bigger out of(max_now,max_ending) now if the max_now was bigger then the previous value of max_ending we update the max_ending else the max ending contains the biggest xor value. C++ C Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Functionint maxSubarrayXOR(int N, int arr[]){ int max_now = 0; // intitialise the 2 values int max_e = 1; for(int i = 0; i < N; i++){ max_e = max(arr[i], max_e ^ arr[i]); // check whether current element/Xor is bigger // then previous Xor value max_now = max(max_e, max_now); // update the maximum value } return max_now; // return the max value when loop is finished} // Driver codeint main (){ // Initialize the queries int inp_arr[] = {8, 1, 2, 12}; int n = sizeof(inp_arr)/sizeof(inp_arr[0]); cout << maxSubarrayXOR(n, inp_arr) << " is the biggest XOR value"; return 0;} // This code is contributed by Shubham Singh // C code to implement the above approach#include <stdio.h> #define MAX(a, b) ((a) > (b) ? (a) : (b)) // Functionint maxSubarrayXOR(int N, int arr[]){ int max_now = 0; // intitialise the 2 values int max_e = 1; for(int i = 0; i < N; i++){ max_e = MAX(arr[i], max_e ^ arr[i]); // check whether current element/Xor is bigger // then previous Xor value max_now = MAX(max_e, max_now); // update the maximum value } return max_now; // return the max value when loop is finished} // Driver codeint main (){ // Initialize the queries int inp_arr[] = {8, 1, 2, 12}; int n = sizeof(inp_arr)/sizeof(inp_arr[0]); printf("%d is the biggest XOR value", maxSubarrayXOR(n, inp_arr)); return 0;} // This code is contributed by Shubham Singh // Java code to implement the above approachimport java.util.*; class GFG{ // Function public static int maxSubarrayXOR(int N, int[] arr){ int max_now = 0; // intitialise the 2 values int max_e = 1; for(int i = 0; i < N; i++){ max_e = Math.max(arr[i], max_e ^ arr[i]); // check whether current element/Xor is bigger // then previous Xor value max_now = Math.max(max_e, max_now); // update the maximum value } return max_now; // return the max value when loop is finished } // Driver code public static void main (String[] args) { // Initialize the queries int[] inp_arr = {8, 1, 2, 12}; int n = inp_arr.length; System.out.println(maxSubarrayXOR(n, inp_arr) + " is the biggest XOR value"); }} // This code is contributed by Shubham Singh def maxSubarrayXOR(N, arr): max_now = 0 #intitialise the 2 values max_e = 1 for i in range(N): max_e = max(arr[i], max_e ^ arr[i])#check whether current element/Xor is bigger #then previous Xor value max_now = max(max_e, max_now) #update the maximum value return max_now #return the max value when loop is finished # driver codeinp_arr = [8, 1, 2, 12]n = len(inp_arr)print(maxSubarrayXOR(n, inp_arr), "is the biggest XOR " "value")# code contributed by# Pratyush Arora // C# code to implement the above approachusing System;public class GFG{ // Function public static int maxSubarrayXOR(int N, int[] arr){ int max_now = 0; // intitialise the 2 values int max_e = 1; for(int i = 0; i < N; i++){ max_e = Math.Max(arr[i], max_e ^ arr[i]); // check whether current element/Xor is bigger // then previous Xor value max_now = Math.Max(max_e, max_now); // update the maximum value } return max_now; // return the max value when loop is finished } // Driver code static public void Main () { // Initialize the queries int[] inp_arr = {8, 1, 2, 12}; int n = inp_arr.Length; Console.Write(maxSubarrayXOR(n, inp_arr) + " is the biggest XOR value"); }} // This code is contributed by Shubham Singh <script>// Javascript o implement the above approach// Functionfunction maxSubarrayXOR(N, arr){ var max_now = 0; // intitialise the 2 values var max_e = 1; for(var i = 0; i < N; i++){ max_e = Math.max(arr[i], max_e ^ arr[i]); // check whether current element/Xor is bigger // then previous Xor value max_now = Math.max(max_e, max_now); // update the maximum value } return max_now; // return the max value when loop is finished} // Driver code // Initialize the queriesvar inp_arr = [8, 1, 2, 12];var n = inp_arr.length;document.write(maxSubarrayXOR(n, inp_arr) +" is the biggest XOR value"); // This code is contributed by Shubham Singh</script> 12 is the biggest XOR value This article is contributed by Romil Punetha. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Sam007 vt_m shrikanth13 anish17122000 chaudhary_19 divyesh072019 arorapratyush01 sweetyty kalrap615 sumitgumber28 SHUBHAMSINGH10 Bitwise-XOR Advanced Data Structure Bit Magic Strings Strings Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Disjoint Set Data Structures Insert Operation in B-Tree Design a Chess Game Red-Black Tree | Set 3 (Delete) Binomial Heap Bitwise Operators in C/C++ Left Shift and Right Shift Operators in C/C++ Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Cyclic Redundancy Check and Modulo-2 Division Count set bits in an integer
[ { "code": null, "e": 24782, "s": 24754, "text": "\n24 Jan, 2022" }, { "code": null, "e": 24893, "s": 24782, "text": "Given an array of integers. find the maximum XOR subarray value in given array. Expected time complexity O(n)." }, { "code": null, "e": 24904, "s": 24893, "text": "Examples: " }, { "code": null, "e": 25149, "s": 24904, "text": "Input: arr[] = {1, 2, 3, 4}\nOutput: 7\nThe subarray {3, 4} has maximum XOR value\n\nInput: arr[] = {8, 1, 2, 12, 7, 6}\nOutput: 15\nThe subarray {1, 2, 12} has maximum XOR value\n\nInput: arr[] = {4, 6}\nOutput: 6\nThe subarray {6} has maximum XOR value" }, { "code": null, "e": 25240, "s": 25149, "text": "A Simple Solution is to use two loops to find XOR of all subarrays and return the maximum." }, { "code": null, "e": 25244, "s": 25240, "text": "C++" }, { "code": null, "e": 25249, "s": 25244, "text": "Java" }, { "code": null, "e": 25257, "s": 25249, "text": "Python3" }, { "code": null, "e": 25260, "s": 25257, "text": "C#" }, { "code": null, "e": 25264, "s": 25260, "text": "PHP" }, { "code": null, "e": 25275, "s": 25264, "text": "Javascript" }, { "code": "// A simple C++ program to find max subarray XOR#include<bits/stdc++.h>using namespace std; int maxSubarrayXOR(int arr[], int n){ int ans = INT_MIN; // Initialize result // Pick starting points of subarrays for (int i=0; i<n; i++) { int curr_xor = 0; // to store xor of current subarray // Pick ending points of subarrays starting with i for (int j=i; j<n; j++) { curr_xor = curr_xor ^ arr[j]; ans = max(ans, curr_xor); } } return ans;} // Driver program to test above functionsint main(){ int arr[] = {8, 1, 2, 12}; int n = sizeof(arr)/sizeof(arr[0]); cout << \"Max subarray XOR is \" << maxSubarrayXOR(arr, n); return 0;}", "e": 25990, "s": 25275, "text": null }, { "code": "// A simple Java program to find max subarray XORclass GFG { static int maxSubarrayXOR(int arr[], int n) { int ans = Integer.MIN_VALUE; // Initialize result // Pick starting points of subarrays for (int i=0; i<n; i++) { // to store xor of current subarray int curr_xor = 0; // Pick ending points of subarrays starting with i for (int j=i; j<n; j++) { curr_xor = curr_xor ^ arr[j]; ans = Math.max(ans, curr_xor); } } return ans; } // Driver program to test above functions public static void main(String args[]) { int arr[] = {8, 1, 2, 12}; int n = arr.length; System.out.println(\"Max subarray XOR is \" + maxSubarrayXOR(arr, n)); }}//This code is contributed by Sumit Ghosh", "e": 26899, "s": 25990, "text": null }, { "code": "# A simple Python program# to find max subarray XOR def maxSubarrayXOR(arr,n): ans = -2147483648 #Initialize result # Pick starting points of subarrays for i in range(n): # to store xor of current subarray curr_xor = 0 # Pick ending points of # subarrays starting with i for j in range(i,n): curr_xor = curr_xor ^ arr[j] ans = max(ans, curr_xor) return ans # Driver code arr = [8, 1, 2, 12]n = len(arr) print(\"Max subarray XOR is \", maxSubarrayXOR(arr, n)) # This code is contributed# by Anant Agarwal.", "e": 27517, "s": 26899, "text": null }, { "code": "// A simple C# program to find// max subarray XORusing System; class GFG{ // Function to find max subarray static int maxSubarrayXOR(int []arr, int n) { int ans = int.MinValue; // Initialize result // Pick starting points of subarrays for (int i = 0; i < n; i++) { // to store xor of current subarray int curr_xor = 0; // Pick ending points of // subarrays starting with i for (int j = i; j < n; j++) { curr_xor = curr_xor ^ arr[j]; ans = Math.Max(ans, curr_xor); } } return ans; } // Driver code public static void Main() { int []arr = {8, 1, 2, 12}; int n = arr.Length; Console.WriteLine(\"Max subarray XOR is \" + maxSubarrayXOR(arr, n)); }} // This code is contributed by Sam007.", "e": 28446, "s": 27517, "text": null }, { "code": "<?php// A simple PHP program to// find max subarray XOR function maxSubarrayXOR($arr, $n){ // Initialize result $ans = PHP_INT_MIN; // Pick starting points // of subarrays for ($i = 0; $i < $n; $i++) { // to store xor of // current subarray $curr_xor = 0; // Pick ending points of // subarrays starting with i for ($j = $i; $j < $n; $j++) { $curr_xor = $curr_xor ^ $arr[$j]; $ans = max($ans, $curr_xor); } } return $ans;} // Driver Code $arr = array(8, 1, 2, 12); $n = count($arr); echo \"Max subarray XOR is \" , maxSubarrayXOR($arr, $n); // This code is contributed by anuj_67.?>", "e": 29165, "s": 28446, "text": null }, { "code": "<script> // A simple Javascript program to find// max subarray XORfunction maxSubarrayXOR(arr, n){ // Initialize result let ans = Number.MIN_VALUE; // Pick starting points of subarrays for(let i = 0; i < n; i++) { // To store xor of current subarray let curr_xor = 0; // Pick ending points of subarrays // starting with i for(let j = i; j < n; j++) { curr_xor = curr_xor ^ arr[j]; ans = Math.max(ans, curr_xor); } } return ans;} // Driver codelet arr = [ 8, 1, 2, 12 ];let n = arr.length; document.write(\"Max subarray XOR is \" + maxSubarrayXOR(arr, n)); // This code is contributed by divyesh072019 </script>", "e": 29917, "s": 29165, "text": null }, { "code": null, "e": 29940, "s": 29917, "text": "Max subarray XOR is 15" }, { "code": null, "e": 29984, "s": 29940, "text": "Time Complexity of above solution is O(n2)." }, { "code": null, "e": 30180, "s": 29984, "text": "An Efficient Solution can solve the above problem in O(n) time under the assumption that integers take fixed number of bits to store. The idea is to use Trie Data Structure. Below is algorithm. " }, { "code": null, "e": 30766, "s": 30180, "text": "1) Create an empty Trie. Every node of Trie is going to \n contain two children, for 0 and 1 value of bit.\n2) Initialize pre_xor = 0 and insert into the Trie.\n3) Initialize result = minus infinite\n4) Traverse the given array and do following for every \n array element arr[i].\n a) pre_xor = pre_xor ^ arr[i]\n pre_xor now contains xor of elements from \n arr[0] to arr[i].\n b) Query the maximum xor value ending with arr[i] \n from Trie.\n c) Update result if the value obtained in step \n 4.b is more than current value of result." }, { "code": null, "e": 31659, "s": 30766, "text": "How does 4.b work? We can observe from above algorithm that we build a Trie that contains XOR of all prefixes of given array. To find the maximum XOR subarray ending with arr[i], there may be two cases. i) The prefix itself has the maximum XOR value ending with arr[i]. For example if i=2 in {8, 2, 1, 12}, then the maximum subarray xor ending with arr[2] is the whole prefix. ii) We need to remove some prefix (ending at index from 0 to i-1). For example if i=3 in {8, 2, 1, 12}, then the maximum subarray xor ending with arr[3] starts with arr[1] and we need to remove arr[0].To find the prefix to be removed, we find the entry in Trie that has maximum XOR value with current prefix. If we do XOR of such previous prefix with current prefix, we get the maximum XOR value ending with arr[i]. If there is no prefix to be removed (case i), then we return 0 (that’s why we inserted 0 in Trie). " }, { "code": null, "e": 31703, "s": 31659, "text": "Below is the implementation of above idea :" }, { "code": null, "e": 31707, "s": 31703, "text": "C++" }, { "code": null, "e": 31712, "s": 31707, "text": "Java" }, { "code": null, "e": 31720, "s": 31712, "text": "Python3" }, { "code": null, "e": 31723, "s": 31720, "text": "C#" }, { "code": "// C++ program for a Trie based O(n) solution to find max// subarray XOR#include<bits/stdc++.h>using namespace std; // Assumed int size#define INT_SIZE 32 // A Trie Nodestruct TrieNode{ int value; // Only used in leaf nodes TrieNode *arr[2];}; // Utility function to create a Trie nodeTrieNode *newNode(){ TrieNode *temp = new TrieNode; temp->value = 0; temp->arr[0] = temp->arr[1] = NULL; return temp;} // Inserts pre_xor to trie with given rootvoid insert(TrieNode *root, int pre_xor){ TrieNode *temp = root; // Start from the msb, insert all bits of // pre_xor into Trie for (int i=INT_SIZE-1; i>=0; i--) { // Find current bit in given prefix bool val = pre_xor & (1<<i); // Create a new node if needed if (temp->arr[val] == NULL) temp->arr[val] = newNode(); temp = temp->arr[val]; } // Store value at leaf node temp->value = pre_xor;} // Finds the maximum XOR ending with last number in// prefix XOR 'pre_xor' and returns the XOR of this maximum// with pre_xor which is maximum XOR ending with last element// of pre_xor.int query(TrieNode *root, int pre_xor){ TrieNode *temp = root; for (int i=INT_SIZE-1; i>=0; i--) { // Find current bit in given prefix bool val = pre_xor & (1<<i); // Traverse Trie, first look for a // prefix that has opposite bit if (temp->arr[1-val]!=NULL) temp = temp->arr[1-val]; // If there is no prefix with opposite // bit, then look for same bit. else if (temp->arr[val] != NULL) temp = temp->arr[val]; } return pre_xor^(temp->value);} // Returns maximum XOR value of a subarray in arr[0..n-1]int maxSubarrayXOR(int arr[], int n){ // Create a Trie and insert 0 into it TrieNode *root = newNode(); insert(root, 0); // Initialize answer and xor of current prefix int result = INT_MIN, pre_xor =0; // Traverse all input array element for (int i=0; i<n; i++) { // update current prefix xor and insert it into Trie pre_xor = pre_xor^arr[i]; insert(root, pre_xor); // Query for current prefix xor in Trie and update // result if required result = max(result, query(root, pre_xor)); } return result;} // Driver program to test above functionsint main(){ int arr[] = {8, 1, 2, 12}; int n = sizeof(arr)/sizeof(arr[0]); cout << \"Max subarray XOR is \" << maxSubarrayXOR(arr, n); return 0;}", "e": 34209, "s": 31723, "text": null }, { "code": "// Java program for a Trie based O(n) solution to// find max subarray XORclass GFG{ // Assumed int size static final int INT_SIZE = 32; // A Trie Node static class TrieNode { int value; // Only used in leaf nodes TrieNode[] arr = new TrieNode[2]; public TrieNode() { value = 0; arr[0] = null; arr[1] = null; } } static TrieNode root; // Inserts pre_xor to trie with given root static void insert(int pre_xor) { TrieNode temp = root; // Start from the msb, insert all bits of // pre_xor into Trie for (int i=INT_SIZE-1; i>=0; i--) { // Find current bit in given prefix int val = (pre_xor & (1<<i)) >=1 ? 1 : 0; // Create a new node if needed if (temp.arr[val] == null) temp.arr[val] = new TrieNode(); temp = temp.arr[val]; } // Store value at leaf node temp.value = pre_xor; } // Finds the maximum XOR ending with last number in // prefix XOR 'pre_xor' and returns the XOR of this // maximum with pre_xor which is maximum XOR ending // with last element of pre_xor. static int query(int pre_xor) { TrieNode temp = root; for (int i=INT_SIZE-1; i>=0; i--) { // Find current bit in given prefix int val = (pre_xor & (1<<i)) >= 1 ? 1 : 0; // Traverse Trie, first look for a // prefix that has opposite bit if (temp.arr[1-val] != null) temp = temp.arr[1-val]; // If there is no prefix with opposite // bit, then look for same bit. else if (temp.arr[val] != null) temp = temp.arr[val]; } return pre_xor^(temp.value); } // Returns maximum XOR value of a subarray in // arr[0..n-1] static int maxSubarrayXOR(int arr[], int n) { // Create a Trie and insert 0 into it root = new TrieNode(); insert(0); // Initialize answer and xor of current prefix int result = Integer.MIN_VALUE; int pre_xor =0; // Traverse all input array element for (int i=0; i<n; i++) { // update current prefix xor and insert it // into Trie pre_xor = pre_xor^arr[i]; insert(pre_xor); // Query for current prefix xor in Trie and // update result if required result = Math.max(result, query(pre_xor)); } return result; } // Driver program to test above functions public static void main(String args[]) { int arr[] = {8, 1, 2, 12}; int n = arr.length; System.out.println(\"Max subarray XOR is \" + maxSubarrayXOR(arr, n)); }}// This code is contributed by Sumit Ghosh", "e": 37157, "s": 34209, "text": null }, { "code": "\"\"\"Python implementation for a Trie based solutionto find max subArray XOR\"\"\" \"\"\"structure of Trie Node\"\"\"class Node: def __init__(self, data): self.data = data self.left = None # left node for 0 self.right = None # right node for 1 \"\"\" class for implementing Trie \"\"\" class Trie: def __init__(self): self.root = Node(0) \"\"\"insert pre_xor to trie with given root\"\"\" def insert(self, pre_xor): self.temp = self.root \"\"\"start from msb, insert all bits of pre_xor into the Trie\"\"\" for i in range(31, -1, -1): \"\"\"Find current bit in prefix sum\"\"\" val = pre_xor & (1<<i) if val : \"\"\"create new node if needed\"\"\" if not self.temp.right: self.temp.right = Node(0) self.temp = self.temp.right if not val: \"\"\"create new node if needed\"\"\" if not self.temp.left: self.temp.left = Node(0) self.temp = self.temp.left \"\"\"store value at leaf node\"\"\" self.temp.data = pre_xor \"\"\"find the maximum xor ending with last number in prefix XOR and return the XOR of this\"\"\" def query(self, xor): self.temp = self.root for i in range(31, -1, -1): \"\"\"find the current bit in prefix xor\"\"\" val = xor & (1<<i) \"\"\"Traverse the trie, first look for opposite bit and then look for same bit\"\"\" if val: if self.temp.left: self.temp = self.temp.left elif self.temp.right: self.temp = self.temp.right else: if self.temp.right: self.temp = self.temp.right elif self.temp.left: self.temp = self.temp.left return xor ^ self.temp.data \"\"\"returns maximum XOR value of subarray\"\"\" def maxSubArrayXOR(self, n, Arr): \"\"\"insert 0 in the trie\"\"\" self.insert(0) \"\"\"initialize result and pre_xor\"\"\" result = -float('inf') pre_xor = 0 \"\"\"traverse all input array element\"\"\" for i in range(n): \"\"\"update current prefix xor and insert it into Trie\"\"\" pre_xor = pre_xor ^ Arr[i] self.insert(pre_xor) \"\"\"Query for current prefix xor in Trie and update result\"\"\" result = max(result, self.query(pre_xor)) return result \"\"\"Driver program to test above functions\"\"\"if __name__ == \"__main__\": Arr = [8, 1, 2, 12] n = len(Arr) trie = Trie() print(trie.maxSubArrayXOR(n, Arr)) # This code is contributed by chaudhary_19", "e": 39869, "s": 37157, "text": null }, { "code": "using System; // C# program for a Trie based O(n) solution to // find max subarray XORpublic class GFG{ // Assumed int size public const int INT_SIZE = 32; // A Trie Node public class TrieNode { public int value; // Only used in leaf nodes public TrieNode[] arr = new TrieNode[2]; public TrieNode() { value = 0; arr[0] = null; arr[1] = null; } } public static TrieNode root; // Inserts pre_xor to trie with given root public static void insert(int pre_xor) { TrieNode temp = root; // Start from the msb, insert all bits of // pre_xor into Trie for (int i = INT_SIZE-1; i >= 0; i--) { // Find current bit in given prefix int val = (pre_xor & (1 << i)) >= 1 ? 1 : 0; // Create a new node if needed if (temp.arr[val] == null) { temp.arr[val] = new TrieNode(); } temp = temp.arr[val]; } // Store value at leaf node temp.value = pre_xor; } // Finds the maximum XOR ending with last number in // prefix XOR 'pre_xor' and returns the XOR of this // maximum with pre_xor which is maximum XOR ending // with last element of pre_xor. public static int query(int pre_xor) { TrieNode temp = root; for (int i = INT_SIZE-1; i >= 0; i--) { // Find current bit in given prefix int val = (pre_xor & (1 << i)) >= 1 ? 1 : 0; // Traverse Trie, first look for a // prefix that has opposite bit if (temp.arr[1 - val] != null) { temp = temp.arr[1 - val]; } // If there is no prefix with opposite // bit, then look for same bit. else if (temp.arr[val] != null) { temp = temp.arr[val]; } } return pre_xor ^ (temp.value); } // Returns maximum XOR value of a subarray in // arr[0..n-1] public static int maxSubarrayXOR(int[] arr, int n) { // Create a Trie and insert 0 into it root = new TrieNode(); insert(0); // Initialize answer and xor of current prefix int result = int.MinValue; int pre_xor = 0; // Traverse all input array element for (int i = 0; i < n; i++) { // update current prefix xor and insert it // into Trie pre_xor = pre_xor ^ arr[i]; insert(pre_xor); // Query for current prefix xor in Trie and // update result if required result = Math.Max(result, query(pre_xor)); } return result; } // Driver program to test above functions public static void Main(string[] args) { int[] arr = new int[] {8, 1, 2, 12}; int n = arr.Length; Console.WriteLine(\"Max subarray XOR is \" + maxSubarrayXOR(arr, n)); }} // This code is contributed by Shrikant13", "e": 42898, "s": 39869, "text": null }, { "code": null, "e": 42921, "s": 42898, "text": "Max subarray XOR is 15" }, { "code": null, "e": 43102, "s": 42921, "text": "Exercise: Extend the above solution so that it also prints starting and ending indexes of subarray with maximum value (Hint: we can add one more field to Trie node to achieve this " }, { "code": null, "e": 43413, "s": 43102, "text": "Another Efficient Solution to the problem in O(n) time complexity can be achieved with the help of Kadane’s algorithm. The following algorithm is used to find the largest contagious max sum sub-array. Similarly, we can go through the array once and as we are going through it we can find the largest XOR value." }, { "code": null, "e": 43922, "s": 43413, "text": "1)initialise max_now=0,max_ending=1;\n2)Traverse the given array and do following for every\n array element arr[i].\n a) max_now = bigger out of(arr[i],arr[i]^max_now)\n max_now now temprorarily contains bigger value out of\n current element and current Xor of all elements\n b) max_ending=bigger out of(max_now,max_ending) now if the max_now\n was bigger then the previous value of max_ending we update the max_ending\n else the max ending contains the biggest xor value." }, { "code": null, "e": 43926, "s": 43922, "text": "C++" }, { "code": null, "e": 43928, "s": 43926, "text": "C" }, { "code": null, "e": 43933, "s": 43928, "text": "Java" }, { "code": null, "e": 43941, "s": 43933, "text": "Python3" }, { "code": null, "e": 43944, "s": 43941, "text": "C#" }, { "code": null, "e": 43955, "s": 43944, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Functionint maxSubarrayXOR(int N, int arr[]){ int max_now = 0; // intitialise the 2 values int max_e = 1; for(int i = 0; i < N; i++){ max_e = max(arr[i], max_e ^ arr[i]); // check whether current element/Xor is bigger // then previous Xor value max_now = max(max_e, max_now); // update the maximum value } return max_now; // return the max value when loop is finished} // Driver codeint main (){ // Initialize the queries int inp_arr[] = {8, 1, 2, 12}; int n = sizeof(inp_arr)/sizeof(inp_arr[0]); cout << maxSubarrayXOR(n, inp_arr) << \" is the biggest XOR value\"; return 0;} // This code is contributed by Shubham Singh", "e": 44688, "s": 43955, "text": null }, { "code": "// C code to implement the above approach#include <stdio.h> #define MAX(a, b) ((a) > (b) ? (a) : (b)) // Functionint maxSubarrayXOR(int N, int arr[]){ int max_now = 0; // intitialise the 2 values int max_e = 1; for(int i = 0; i < N; i++){ max_e = MAX(arr[i], max_e ^ arr[i]); // check whether current element/Xor is bigger // then previous Xor value max_now = MAX(max_e, max_now); // update the maximum value } return max_now; // return the max value when loop is finished} // Driver codeint main (){ // Initialize the queries int inp_arr[] = {8, 1, 2, 12}; int n = sizeof(inp_arr)/sizeof(inp_arr[0]); printf(\"%d is the biggest XOR value\", maxSubarrayXOR(n, inp_arr)); return 0;} // This code is contributed by Shubham Singh", "e": 45497, "s": 44688, "text": null }, { "code": "// Java code to implement the above approachimport java.util.*; class GFG{ // Function public static int maxSubarrayXOR(int N, int[] arr){ int max_now = 0; // intitialise the 2 values int max_e = 1; for(int i = 0; i < N; i++){ max_e = Math.max(arr[i], max_e ^ arr[i]); // check whether current element/Xor is bigger // then previous Xor value max_now = Math.max(max_e, max_now); // update the maximum value } return max_now; // return the max value when loop is finished } // Driver code public static void main (String[] args) { // Initialize the queries int[] inp_arr = {8, 1, 2, 12}; int n = inp_arr.length; System.out.println(maxSubarrayXOR(n, inp_arr) + \" is the biggest XOR value\"); }} // This code is contributed by Shubham Singh", "e": 46356, "s": 45497, "text": null }, { "code": "def maxSubarrayXOR(N, arr): max_now = 0 #intitialise the 2 values max_e = 1 for i in range(N): max_e = max(arr[i], max_e ^ arr[i])#check whether current element/Xor is bigger #then previous Xor value max_now = max(max_e, max_now) #update the maximum value return max_now #return the max value when loop is finished # driver codeinp_arr = [8, 1, 2, 12]n = len(inp_arr)print(maxSubarrayXOR(n, inp_arr), \"is the biggest XOR \" \"value\")# code contributed by# Pratyush Arora", "e": 46899, "s": 46356, "text": null }, { "code": "// C# code to implement the above approachusing System;public class GFG{ // Function public static int maxSubarrayXOR(int N, int[] arr){ int max_now = 0; // intitialise the 2 values int max_e = 1; for(int i = 0; i < N; i++){ max_e = Math.Max(arr[i], max_e ^ arr[i]); // check whether current element/Xor is bigger // then previous Xor value max_now = Math.Max(max_e, max_now); // update the maximum value } return max_now; // return the max value when loop is finished } // Driver code static public void Main () { // Initialize the queries int[] inp_arr = {8, 1, 2, 12}; int n = inp_arr.Length; Console.Write(maxSubarrayXOR(n, inp_arr) + \" is the biggest XOR value\"); }} // This code is contributed by Shubham Singh", "e": 47676, "s": 46899, "text": null }, { "code": "<script>// Javascript o implement the above approach// Functionfunction maxSubarrayXOR(N, arr){ var max_now = 0; // intitialise the 2 values var max_e = 1; for(var i = 0; i < N; i++){ max_e = Math.max(arr[i], max_e ^ arr[i]); // check whether current element/Xor is bigger // then previous Xor value max_now = Math.max(max_e, max_now); // update the maximum value } return max_now; // return the max value when loop is finished} // Driver code // Initialize the queriesvar inp_arr = [8, 1, 2, 12];var n = inp_arr.length;document.write(maxSubarrayXOR(n, inp_arr) +\" is the biggest XOR value\"); // This code is contributed by Shubham Singh</script>", "e": 48376, "s": 47676, "text": null }, { "code": null, "e": 48404, "s": 48376, "text": "12 is the biggest XOR value" }, { "code": null, "e": 48575, "s": 48404, "text": "This article is contributed by Romil Punetha. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 48582, "s": 48575, "text": "Sam007" }, { "code": null, "e": 48587, "s": 48582, "text": "vt_m" }, { "code": null, "e": 48599, "s": 48587, "text": "shrikanth13" }, { "code": null, "e": 48613, "s": 48599, "text": "anish17122000" }, { "code": null, "e": 48626, "s": 48613, "text": "chaudhary_19" }, { "code": null, "e": 48640, "s": 48626, "text": "divyesh072019" }, { "code": null, "e": 48656, "s": 48640, "text": "arorapratyush01" }, { "code": null, "e": 48665, "s": 48656, "text": "sweetyty" }, { "code": null, "e": 48675, "s": 48665, "text": "kalrap615" }, { "code": null, "e": 48689, "s": 48675, "text": "sumitgumber28" }, { "code": null, "e": 48704, "s": 48689, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 48716, "s": 48704, "text": "Bitwise-XOR" }, { "code": null, "e": 48740, "s": 48716, "text": "Advanced Data Structure" }, { "code": null, "e": 48750, "s": 48740, "text": "Bit Magic" }, { "code": null, "e": 48758, "s": 48750, "text": "Strings" }, { "code": null, "e": 48766, "s": 48758, "text": "Strings" }, { "code": null, "e": 48776, "s": 48766, "text": "Bit Magic" }, { "code": null, "e": 48874, "s": 48776, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 48903, "s": 48874, "text": "Disjoint Set Data Structures" }, { "code": null, "e": 48930, "s": 48903, "text": "Insert Operation in B-Tree" }, { "code": null, "e": 48950, "s": 48930, "text": "Design a Chess Game" }, { "code": null, "e": 48982, "s": 48950, "text": "Red-Black Tree | Set 3 (Delete)" }, { "code": null, "e": 48996, "s": 48982, "text": "Binomial Heap" }, { "code": null, "e": 49023, "s": 48996, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 49069, "s": 49023, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 49137, "s": 49069, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 49183, "s": 49137, "text": "Cyclic Redundancy Check and Modulo-2 Division" } ]
SciPy Optimizers
Optimizers are a set of procedures defined in SciPy that either find the minimum value of a function, or the root of an equation. Essentially, all of the algorithms in Machine Learning are nothing more than a complex equation that needs to be minimized with the help of given data. NumPy is capable of finding roots for polynomials and linear equations, but it can not find roots for non linear equations, like this one: x + cos(x) For that you can use SciPy's optimze.root function. This function takes two required arguments: fun - a function representing an equation. x0 - an initial guess for the root. The function returns an object with information regarding the solution. The actual solution is given under attribute x of the returned object: Find root of the equation x + cos(x): Note: The returned object has much more information about the solution. Print all information about the solution (not just x which is the root) A function, in this context, represents a curve, curves have high points and low points. High points are called maxima. Low points are called minima. The highest point in the whole curve is called global maxima, whereas the rest of them are called local maxima. The lowest point in whole curve is called global minima, whereas the rest of them are called local minima. We can use scipy.optimize.minimize() function to minimize the function. The minimize() function takes the following arguments: fun - a function representing an equation. x0 - an initial guess for the root. method - name of the method to use. Legal values: 'CG' 'BFGS' 'Newton-CG' 'L-BFGS-B' 'TNC' 'COBYLA' 'SLSQP' callback - function called after each iteration of optimization. options - a dictionary defining extra params: Minimize the function x^2 + x + 2 with BFGS: Insert the missing parts to print the square root of the equation: from scipy.optimize import root from math import cos def eqn(x): return x + cos(x) myroot = (eqn, 0) print() 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: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 131, "s": 0, "text": "Optimizers are a set of procedures defined in SciPy that either find the minimum value of \na function, or the root of an equation." }, { "code": null, "e": 283, "s": 131, "text": "Essentially, all of the algorithms in Machine Learning are nothing more than a complex equation that needs to be minimized with the help of given data." }, { "code": null, "e": 423, "s": 283, "text": "NumPy is capable of finding roots for polynomials and linear equations, but it can not find roots for non \nlinear equations, like this one:" }, { "code": null, "e": 434, "s": 423, "text": "x + cos(x)" }, { "code": null, "e": 486, "s": 434, "text": "For that you can use SciPy's optimze.root function." }, { "code": null, "e": 530, "s": 486, "text": "This function takes two required arguments:" }, { "code": null, "e": 573, "s": 530, "text": "fun - a function representing an equation." }, { "code": null, "e": 609, "s": 573, "text": "x0 - an initial guess for the root." }, { "code": null, "e": 681, "s": 609, "text": "The function returns an object with information regarding the solution." }, { "code": null, "e": 753, "s": 681, "text": "The actual solution is given under attribute x \nof the returned object:" }, { "code": null, "e": 791, "s": 753, "text": "Find root of the equation x + cos(x):" }, { "code": null, "e": 866, "s": 791, "text": "Note: The returned object has much more information about \n the solution." }, { "code": null, "e": 938, "s": 866, "text": "Print all information about the solution (not just x which is the root)" }, { "code": null, "e": 1027, "s": 938, "text": "A function, in this context, represents a curve, curves have high points and low points." }, { "code": null, "e": 1058, "s": 1027, "text": "High points are called maxima." }, { "code": null, "e": 1088, "s": 1058, "text": "Low points are called minima." }, { "code": null, "e": 1200, "s": 1088, "text": "The highest point in the whole curve is called global maxima, whereas the rest of them are called local maxima." }, { "code": null, "e": 1307, "s": 1200, "text": "The lowest point in whole curve is called global minima, whereas the rest of them are called local minima." }, { "code": null, "e": 1379, "s": 1307, "text": "We can use scipy.optimize.minimize() function to minimize the function." }, { "code": null, "e": 1434, "s": 1379, "text": "The minimize() function takes the following arguments:" }, { "code": null, "e": 1477, "s": 1434, "text": "fun - a function representing an equation." }, { "code": null, "e": 1513, "s": 1477, "text": "x0 - an initial guess for the root." }, { "code": null, "e": 1649, "s": 1513, "text": "method - name of the method to use. Legal values:\n 'CG'\n 'BFGS'\n 'Newton-CG'\n 'L-BFGS-B'\n 'TNC'\n 'COBYLA'\n 'SLSQP'" }, { "code": null, "e": 1714, "s": 1649, "text": "callback - function called after each iteration of optimization." }, { "code": null, "e": 1761, "s": 1714, "text": "options - a dictionary defining extra params:\n" }, { "code": null, "e": 1806, "s": 1761, "text": "Minimize the function x^2 + x + 2 with BFGS:" }, { "code": null, "e": 1873, "s": 1806, "text": "Insert the missing parts to print the square root of the equation:" }, { "code": null, "e": 1988, "s": 1873, "text": "from scipy.optimize import root\nfrom math import cos\n\ndef eqn(x):\n return x + cos(x)\n\nmyroot = (eqn, 0)\n\nprint()\n" }, { "code": null, "e": 2007, "s": 1988, "text": "Start the Exercise" }, { "code": null, "e": 2040, "s": 2007, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 2082, "s": 2040, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 2189, "s": 2082, "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": 2208, "s": 2189, "text": "help@w3schools.com" } ]
howdoi in Python
C:\Py3Project>howdoi create a python list Running the above code gives us the following result − >>> l = [None] * 10 >>> l [None, None, None, None, None, None, None, None, None, None] c:\python3>howdoi print today's date in python Running the above code gives us the following result − for date in mylist : print str(date) c:\python3>howdoi create fibonnaci series in python Running the above code gives us the following result − def F(n): if n == 0: return 0 elif n == 1: return 1 else: return F(n-1)+F(n-2) c:\python3>howdoi use calendar in javascript Running the above code gives us the following result − You can choose from Material UI. http://www.material-ui.com/#/components/date-picker http://www.material-ui.com/#/components/time-picker c:\python3>howdoi go to north pole Running the above code gives us the following result − I believe the difference is because GPS uses the geographical North/South Pole rather than the magnetic ones. The further north you are, the bigger the difference is to where you are. The GPS satellite positions need to be absolute, and using a fluctuating point of reference like the magnetic poles is a big no-no.
[ { "code": null, "e": 1104, "s": 1062, "text": "C:\\Py3Project>howdoi create a python list" }, { "code": null, "e": 1159, "s": 1104, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1246, "s": 1159, "text": ">>> l = [None] * 10\n>>> l\n[None, None, None, None, None, None, None, None, None, None]" }, { "code": null, "e": 1293, "s": 1246, "text": "c:\\python3>howdoi print today's date in python" }, { "code": null, "e": 1348, "s": 1293, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1385, "s": 1348, "text": "for date in mylist :\nprint str(date)" }, { "code": null, "e": 1437, "s": 1385, "text": "c:\\python3>howdoi create fibonnaci series in python" }, { "code": null, "e": 1492, "s": 1437, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1580, "s": 1492, "text": "def F(n):\n if n == 0: return 0\n elif n == 1: return 1\n else: return F(n-1)+F(n-2)" }, { "code": null, "e": 1625, "s": 1580, "text": "c:\\python3>howdoi use calendar in javascript" }, { "code": null, "e": 1680, "s": 1625, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1817, "s": 1680, "text": "You can choose from Material UI.\nhttp://www.material-ui.com/#/components/date-picker\nhttp://www.material-ui.com/#/components/time-picker" }, { "code": null, "e": 1852, "s": 1817, "text": "c:\\python3>howdoi go to north pole" }, { "code": null, "e": 1907, "s": 1852, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2223, "s": 1907, "text": "I believe the difference is because GPS uses the geographical North/South Pole rather than the magnetic ones.\nThe further north you are, the bigger the difference is to where you are.\nThe GPS satellite positions need to be absolute, and using a fluctuating point of\nreference like the magnetic poles is a big no-no." } ]
C# Equivalent to Java Functional Interfaces
Equivalent of Java’s Functional Interfaces in C# is Delegates. Let us see the implementation of functional interface in Java − @FunctionalInterface public interface MyInterface { void invoke(); } public class Demo { void method(){ MyInterface x = () -> MyFunc (); x.invoke(); } void MyFunc() { } } The same implementation in C# delagates − public delegate void MyInterface (); public class Demo { internal virtual void method() { MyInterface x = () => MyFunc (); x(); } internal virtual void MyFunc() { } }
[ { "code": null, "e": 1125, "s": 1062, "text": "Equivalent of Java’s Functional Interfaces in C# is Delegates." }, { "code": null, "e": 1189, "s": 1125, "text": "Let us see the implementation of functional interface in Java −" }, { "code": null, "e": 1387, "s": 1189, "text": "@FunctionalInterface\npublic interface MyInterface {\n void invoke();\n}\npublic class Demo {\n void method(){\n MyInterface x = () -> MyFunc ();\n x.invoke();\n }\n void MyFunc() {\n }\n}" }, { "code": null, "e": 1429, "s": 1387, "text": "The same implementation in C# delagates −" }, { "code": null, "e": 1620, "s": 1429, "text": "public delegate void MyInterface ();\npublic class Demo {\n internal virtual void method() {\n MyInterface x = () => MyFunc ();\n x();\n }\n internal virtual void MyFunc() {\n }\n}" } ]
5-Minute Machine Learning. Bayes Theorem and Naive Bayes | by Andre Violante | Towards Data Science
Naive Bayes is a set of simple and efficient machine learning algorithms for solving a variety of classification and regression problems. If you haven’t been in a stats class for a while or seeing the word “bayesian” makes you uneasy then this is may be a good 5-minute introduction. I’m going to give an explanation of Bayes theorem and then Naive Bayes within 5 minutes using a fitness gym new years resolution example. I’ll also include some simple python code using Scikit-learn in my GitHub. Let’s get started! In order to explain Naive Bayes we need to first explain Bayes theorem. The foundation of Bayes theorem is conditional probability (figure 1). In fact, Bayes theorem (figure 1) is just an alternate or reverse way to calculate conditional probability. When the joint probability, P(A∩B), is hard to calculate or if the inverse or Bayes probability, P(B|A), is easier to calculate then Bayes theorem can be applied. Let’s quickly define some of the lingo in Bayes theorem: Class prior or prior probability: probability of event A occurring before knowing anything about event B. Predictor prior or evidence: same as class prior but for event B. Posterior probability: probability of event A after learning about event B. Likelihood: reverse of the posterior probability. What does all this have to do with Naive Bayes? Well, you need to know that the distinction between Bayes theorem and Naive Bayes is that Naive Bayes assumes conditional independence where Bayes theorem does not. This means the relationship between all input features are independent. Maybe not a great assumption, but this is is why the algorithm is called “naive”. This is also one reason the the algorithm is very fast. Even though the algorithm is “naive” it can still outperform complex models so don’t let the name dissuade you. I’ll show notation difference between Bayes theorem and Naive Bayes below. Let’s first work through yet another Bayes theorem example for our friends at Globo Gym. Here’s a simple example that will be relevant with all the New Years resolutions. Globo Gym wants to predict if a member will attend the gym given the weather conditions P(attend = yes | weather). Step 1- View or collect “raw” data. We have data where each row represents member attendance to Globo Gym given the weather. So observation 3 is a member that attended the gym when it was cloudy outside. weather attended0 sunny yes1 rainy no2 snowy no3 cloudy yes4 cloudy no Step 2 - Convert long data to a frequency table This provides the sum of attendance by weather condition. attended no yesweathercloudy 1 3rainy 2 1snowy 3 1sunny 1 3 Step 3 - Row and column sums to get probabilities weather probabilitiescloudy = 4/15 or 0.267rainy = 3/15 or 0.20snowy = 4/15 or 0.267sunny = 4/15 or 0.267attendance probabilitiesno = 7/15 or 0.467yes = 8/15 or 0.533 Looking at our class prior probability (probability of attendance), on average a member is 53% likely to attend the gym. Just FYI, Thats the exact business model for most gyms: hope a lot of people sign up but rarely attend. However, our question is whats the probability a member will attend the gym given the weather condition. Step 5 - Apply probabilities from frequency table to Bayes theorem Figure 2 shows our question put into Bayes theorem notation. Let’s assign each of the probabilities in figure 2 a value from our fequency table above and then rewrite the equation so its clear. Likelihood: P(sunny | yes) = 3/8 or 0.375 (Total sunny AND yes divided by total yes) Class Prior Probability: P(yes) = 8/15 or 0.533 Predictor Prior Probability: P(sunny) = 4/15 or 0.267 Figure 3 shows that a random member is 75% likely to attend the gym given its sunny. Thats higher than the overall average attendance of 53%! On the opposite spectrum, the probability of attending the gym when its snowy out is only 25% (0.125 ⋅ 0.533 / 0.267). Since this is a binary example (attend or not attend) and P(yes | sunny) = 0.75 or 75%, then the inverse P(no | sunny) is 0.25 or 25% since probabilities have to sum to 1 or 100%. Thats how to use Bayes theorem to find the posterior probability for classification. The Naive Bayes algorithm is similar to this which we’ll show next. Just to be clear, one obvious problem with our example is that given the weather we apply the same probability to all members which doesn’t make sense, but this is just a fun example. Now, let’s discuss additional features and using Naive Bayes. In nearly all cases you’ll have many features in a model. Example features for Globo Gym could be: age bins, membership type, gender, etc. Lets show how you would incorporate those features into Bayes theorem and Naive Bayes. Figure 4 below shows Bayes theorem simplified into the Naive Bayes algorithm incorporating multiple features. In Bayes theorem you would calculate a single conditional probability given all features (top). With Naive Bayes we simplify it by calculating the conditional probability for each feature and then multiply them together. Remember, this is why it’s called “naive” since all the features conditional probabilities are calculated independently of each other. The Naive Bayes algorithm is literally simplified by the help of independence and dropping the denominator. You can follow the steps above from Bayes theorem to apply these, now easy, calculations and hence the relationship between Bayes theorem and Naive Bayes! That was a quick 5-minute intro to Bayes theorem and Naive Bayes. We used the fun example of Globo Gym predicting gym attendance using Bayes theorem. We explained the difference between Bayes theorem and Naive Bayes, showed the simplified notation, and showed why it’s “naive” through the assumption of independence. There’s so much more to add here, but hopefully this gives you a some understanding of Bayes theorem and the Naive Bayes algorithm. I’ll add some good reading in the references below. I hope your curiosity of Naive Bayes has grown and that you’ll incorporate it into your next project. This guy is awesome! Articles by Jason Brownlee: Bayes Theorem for Machine Learning, Probability, and Develop Naive Bayes from ScratchFree pdf of Think Bayes book hereGitHub repo with simple codeScikit-learn documentation for Naive Bayes This guy is awesome! Articles by Jason Brownlee: Bayes Theorem for Machine Learning, Probability, and Develop Naive Bayes from Scratch Free pdf of Think Bayes book here GitHub repo with simple code Scikit-learn documentation for Naive Bayes
[ { "code": null, "e": 688, "s": 172, "text": "Naive Bayes is a set of simple and efficient machine learning algorithms for solving a variety of classification and regression problems. If you haven’t been in a stats class for a while or seeing the word “bayesian” makes you uneasy then this is may be a good 5-minute introduction. I’m going to give an explanation of Bayes theorem and then Naive Bayes within 5 minutes using a fitness gym new years resolution example. I’ll also include some simple python code using Scikit-learn in my GitHub. Let’s get started!" }, { "code": null, "e": 1102, "s": 688, "text": "In order to explain Naive Bayes we need to first explain Bayes theorem. The foundation of Bayes theorem is conditional probability (figure 1). In fact, Bayes theorem (figure 1) is just an alternate or reverse way to calculate conditional probability. When the joint probability, P(A∩B), is hard to calculate or if the inverse or Bayes probability, P(B|A), is easier to calculate then Bayes theorem can be applied." }, { "code": null, "e": 1159, "s": 1102, "text": "Let’s quickly define some of the lingo in Bayes theorem:" }, { "code": null, "e": 1265, "s": 1159, "text": "Class prior or prior probability: probability of event A occurring before knowing anything about event B." }, { "code": null, "e": 1331, "s": 1265, "text": "Predictor prior or evidence: same as class prior but for event B." }, { "code": null, "e": 1407, "s": 1331, "text": "Posterior probability: probability of event A after learning about event B." }, { "code": null, "e": 1457, "s": 1407, "text": "Likelihood: reverse of the posterior probability." }, { "code": null, "e": 2156, "s": 1457, "text": "What does all this have to do with Naive Bayes? Well, you need to know that the distinction between Bayes theorem and Naive Bayes is that Naive Bayes assumes conditional independence where Bayes theorem does not. This means the relationship between all input features are independent. Maybe not a great assumption, but this is is why the algorithm is called “naive”. This is also one reason the the algorithm is very fast. Even though the algorithm is “naive” it can still outperform complex models so don’t let the name dissuade you. I’ll show notation difference between Bayes theorem and Naive Bayes below. Let’s first work through yet another Bayes theorem example for our friends at Globo Gym." }, { "code": null, "e": 2353, "s": 2156, "text": "Here’s a simple example that will be relevant with all the New Years resolutions. Globo Gym wants to predict if a member will attend the gym given the weather conditions P(attend = yes | weather)." }, { "code": null, "e": 2389, "s": 2353, "text": "Step 1- View or collect “raw” data." }, { "code": null, "e": 2557, "s": 2389, "text": "We have data where each row represents member attendance to Globo Gym given the weather. So observation 3 is a member that attended the gym when it was cloudy outside." }, { "code": null, "e": 2666, "s": 2557, "text": " weather attended0 sunny yes1 rainy no2 snowy no3 cloudy yes4 cloudy no" }, { "code": null, "e": 2714, "s": 2666, "text": "Step 2 - Convert long data to a frequency table" }, { "code": null, "e": 2772, "s": 2714, "text": "This provides the sum of attendance by weather condition." }, { "code": null, "e": 2882, "s": 2772, "text": " attended no yesweathercloudy 1 3rainy 2 1snowy 3 1sunny 1 3" }, { "code": null, "e": 2932, "s": 2882, "text": "Step 3 - Row and column sums to get probabilities" }, { "code": null, "e": 3103, "s": 2932, "text": "weather probabilitiescloudy = 4/15 or 0.267rainy = 3/15 or 0.20snowy = 4/15 or 0.267sunny = 4/15 or 0.267attendance probabilitiesno = 7/15 or 0.467yes = 8/15 or 0.533" }, { "code": null, "e": 3433, "s": 3103, "text": "Looking at our class prior probability (probability of attendance), on average a member is 53% likely to attend the gym. Just FYI, Thats the exact business model for most gyms: hope a lot of people sign up but rarely attend. However, our question is whats the probability a member will attend the gym given the weather condition." }, { "code": null, "e": 3500, "s": 3433, "text": "Step 5 - Apply probabilities from frequency table to Bayes theorem" }, { "code": null, "e": 3694, "s": 3500, "text": "Figure 2 shows our question put into Bayes theorem notation. Let’s assign each of the probabilities in figure 2 a value from our fequency table above and then rewrite the equation so its clear." }, { "code": null, "e": 3779, "s": 3694, "text": "Likelihood: P(sunny | yes) = 3/8 or 0.375 (Total sunny AND yes divided by total yes)" }, { "code": null, "e": 3827, "s": 3779, "text": "Class Prior Probability: P(yes) = 8/15 or 0.533" }, { "code": null, "e": 3881, "s": 3827, "text": "Predictor Prior Probability: P(sunny) = 4/15 or 0.267" }, { "code": null, "e": 4142, "s": 3881, "text": "Figure 3 shows that a random member is 75% likely to attend the gym given its sunny. Thats higher than the overall average attendance of 53%! On the opposite spectrum, the probability of attending the gym when its snowy out is only 25% (0.125 ⋅ 0.533 / 0.267)." }, { "code": null, "e": 4322, "s": 4142, "text": "Since this is a binary example (attend or not attend) and P(yes | sunny) = 0.75 or 75%, then the inverse P(no | sunny) is 0.25 or 25% since probabilities have to sum to 1 or 100%." }, { "code": null, "e": 4721, "s": 4322, "text": "Thats how to use Bayes theorem to find the posterior probability for classification. The Naive Bayes algorithm is similar to this which we’ll show next. Just to be clear, one obvious problem with our example is that given the weather we apply the same probability to all members which doesn’t make sense, but this is just a fun example. Now, let’s discuss additional features and using Naive Bayes." }, { "code": null, "e": 4947, "s": 4721, "text": "In nearly all cases you’ll have many features in a model. Example features for Globo Gym could be: age bins, membership type, gender, etc. Lets show how you would incorporate those features into Bayes theorem and Naive Bayes." }, { "code": null, "e": 5676, "s": 4947, "text": "Figure 4 below shows Bayes theorem simplified into the Naive Bayes algorithm incorporating multiple features. In Bayes theorem you would calculate a single conditional probability given all features (top). With Naive Bayes we simplify it by calculating the conditional probability for each feature and then multiply them together. Remember, this is why it’s called “naive” since all the features conditional probabilities are calculated independently of each other. The Naive Bayes algorithm is literally simplified by the help of independence and dropping the denominator. You can follow the steps above from Bayes theorem to apply these, now easy, calculations and hence the relationship between Bayes theorem and Naive Bayes!" }, { "code": null, "e": 6279, "s": 5676, "text": "That was a quick 5-minute intro to Bayes theorem and Naive Bayes. We used the fun example of Globo Gym predicting gym attendance using Bayes theorem. We explained the difference between Bayes theorem and Naive Bayes, showed the simplified notation, and showed why it’s “naive” through the assumption of independence. There’s so much more to add here, but hopefully this gives you a some understanding of Bayes theorem and the Naive Bayes algorithm. I’ll add some good reading in the references below. I hope your curiosity of Naive Bayes has grown and that you’ll incorporate it into your next project." }, { "code": null, "e": 6517, "s": 6279, "text": "This guy is awesome! Articles by Jason Brownlee: Bayes Theorem for Machine Learning, Probability, and Develop Naive Bayes from ScratchFree pdf of Think Bayes book hereGitHub repo with simple codeScikit-learn documentation for Naive Bayes" }, { "code": null, "e": 6652, "s": 6517, "text": "This guy is awesome! Articles by Jason Brownlee: Bayes Theorem for Machine Learning, Probability, and Develop Naive Bayes from Scratch" }, { "code": null, "e": 6686, "s": 6652, "text": "Free pdf of Think Bayes book here" }, { "code": null, "e": 6715, "s": 6686, "text": "GitHub repo with simple code" } ]
Except not working in MySQL?
You cannot use except in MySQL. You can work with NOT IN operator to get the same result. Let us first create a table − mysql> create table DemoTable1 ( Number1 int ); Query OK, 0 rows affected (0.71 sec) Insert some records in the table using insert command − mysql> insert into DemoTable1 values(100); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable1 values(200); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable1 values(300); Query OK, 1 row affected (0.13 sec) Display all records from the table using select statement: mysql> select *from DemoTable1 This will produce the following output − +---------+ | Number1 | +---------+ | 100 | | 200 | | 300 | +---------+ 3 rows in set (0.00 sec) Following is the query to create second table − mysql> create table DemoTable2 ( Number1 int ); Query OK, 0 rows affected (0.52 sec) Insert some records in the table using insert command − mysql> insert into DemoTable2 values(100); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable2 values(400); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable2 values(300); Query OK, 1 row affected (0.11 sec) Display all records from the table using select statement − mysql> select *from DemoTable2; This will produce the following output − +---------+ | Number1 | +---------+ | 100 | | 400 | | 300 | +---------+ 3 rows in set (0.00 sec) Following is the query to learn how to use NOT IN operator in place of except − mysql> select Number1 from DemoTable1 where Number1 not in (SELECT Number1 FROM DemoTable2); This will produce the following output − +---------+ | Number1 | +---------+ | 200 | +---------+ 1 row in set (0.04 sec)
[ { "code": null, "e": 1182, "s": 1062, "text": "You cannot use except in MySQL. You can work with NOT IN operator to get the same result. Let us first create a table −" }, { "code": null, "e": 1270, "s": 1182, "text": "mysql> create table DemoTable1\n (\n Number1 int\n );\nQuery OK, 0 rows affected (0.71 sec)" }, { "code": null, "e": 1326, "s": 1270, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1565, "s": 1326, "text": "mysql> insert into DemoTable1 values(100);\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into DemoTable1 values(200);\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> insert into DemoTable1 values(300);\nQuery OK, 1 row affected (0.13 sec)" }, { "code": null, "e": 1624, "s": 1565, "text": "Display all records from the table using select statement:" }, { "code": null, "e": 1655, "s": 1624, "text": "mysql> select *from DemoTable1" }, { "code": null, "e": 1696, "s": 1655, "text": "This will produce the following output −" }, { "code": null, "e": 1805, "s": 1696, "text": "+---------+\n| Number1 |\n+---------+\n| 100 |\n| 200 |\n| 300 |\n+---------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 1853, "s": 1805, "text": "Following is the query to create second table −" }, { "code": null, "e": 1947, "s": 1853, "text": "mysql> create table DemoTable2\n (\n Number1 int\n );\nQuery OK, 0 rows affected (0.52 sec)" }, { "code": null, "e": 2003, "s": 1947, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 2242, "s": 2003, "text": "mysql> insert into DemoTable2 values(100);\nQuery OK, 1 row affected (0.17 sec)\n\nmysql> insert into DemoTable2 values(400);\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into DemoTable2 values(300);\nQuery OK, 1 row affected (0.11 sec)" }, { "code": null, "e": 2302, "s": 2242, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 2334, "s": 2302, "text": "mysql> select *from DemoTable2;" }, { "code": null, "e": 2375, "s": 2334, "text": "This will produce the following output −" }, { "code": null, "e": 2484, "s": 2375, "text": "+---------+\n| Number1 |\n+---------+\n| 100 |\n| 400 |\n| 300 |\n+---------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 2564, "s": 2484, "text": "Following is the query to learn how to use NOT IN operator in place of except −" }, { "code": null, "e": 2657, "s": 2564, "text": "mysql> select Number1 from DemoTable1\nwhere Number1 not in (SELECT Number1 FROM DemoTable2);" }, { "code": null, "e": 2698, "s": 2657, "text": "This will produce the following output −" }, { "code": null, "e": 2782, "s": 2698, "text": "+---------+\n| Number1 |\n+---------+\n| 200 |\n+---------+\n1 row in set (0.04 sec)" } ]
House Prices Prediction Using Deep Learning | by Mahsa Mir | Towards Data Science
In this tutorial, we’re going to create a model to predict House prices🏡 based on various factors across different markets. The goal of this statistical analysis is to help us understand the relationship between house features and how these variables are used to predict house price. Predict the house price Using two different models in terms of minimizing the difference between predicted and actual rating Data used: Kaggle-kc_house DatasetGitHub: you can find my source code here First, Let’s import the data and have a look to see what kind of data we are dealing with: #import required librariesimport pandas as pdimport numpy as npimport seaborn as snsimport matplotlib.pyplot as plt#import DataData = pd.read_csv('kc_house_data.csv')Data.head(5).T#get some information about our Data-SetData.info()Data.describe().transpose() The following features have been provided:✔️Date: Date house was sold✔️Price: Price is prediction target✔️Bedrooms: Number of Bedrooms/House✔️Bathrooms: Number of bathrooms/House✔️Sqft_Living: square footage of the home✔️Sqft_Lot: square footage of the lot✔️Floors: Total floors (levels) in house✔️Waterfront: House which has a view to a waterfront✔️View: Has been viewed✔️Condition: How good the condition is ( Overall )✔️Grade: grade given to the housing unit, based on King County grading system✔️Sqft_Above: square footage of house apart from basement✔️Sqft_Basement: square footage of the basement✔️Yr_Built: Built Year✔️Yr_Renovated: Year when house was renovated✔️Zipcode: Zip✔️Lat: Latitude coordinate✔️Long: Longitude coordinate✔️Sqft_Living15: Living room area in 2015(implies — some renovations) ✔️Sqft_Lot15: lotSize area in 2015(implies — some renovations) Let’s plot couple of features to get a better feel of the data #visualizing house pricesfig = plt.figure(figsize=(10,7))fig.add_subplot(2,1,1)sns.distplot(Data['price'])fig.add_subplot(2,1,2)sns.boxplot(Data['price'])plt.tight_layout()#visualizing square footage of (home,lot,above and basement)fig = plt.figure(figsize=(16,5))fig.add_subplot(2,2,1)sns.scatterplot(Data['sqft_above'], Data['price'])fig.add_subplot(2,2,2)sns.scatterplot(Data['sqft_lot'],Data['price'])fig.add_subplot(2,2,3)sns.scatterplot(Data['sqft_living'],Data['price'])fig.add_subplot(2,2,4)sns.scatterplot(Data['sqft_basement'],Data['price'])#visualizing bedrooms,bathrooms,floors,gradefig = plt.figure(figsize=(15,7))fig.add_subplot(2,2,1)sns.countplot(Data['bedrooms'])fig.add_subplot(2,2,2)sns.countplot(Data['floors'])fig.add_subplot(2,2,3)sns.countplot(Data['bathrooms'])fig.add_subplot(2,2,4)sns.countplot(Data['grade'])plt.tight_layout() With distribution plot of price, we can visualize that most of the prices are between 0 and around 1M with few outliers close to 8 million (fancy houses😉). It would make sense to drop those outliers in our analysis. It is quit useful to have a quick overview of different features distribution vs house price. Here, I’m breaking the date columns down to years and months to see how is the house price is changing. #let's break date to years, monthsData['date'] = pd.to_datetime(Data['date'])Data['month'] = Data['date'].apply(lambda date:date.month)Data['year'] = Data['date'].apply(lambda date:date.year)#data visualization house price vs months and yearsfig = plt.figure(figsize=(16,5))fig.add_subplot(1,2,1)Data.groupby('month').mean()['price'].plot()fig.add_subplot(1,2,2)Data.groupby('year').mean()['price'].plot() Let’s check if we have a Null Data and also drop some columns that we do not need (this data set does not have some missing values) # check if there are any Null valuesData.isnull().sum()# drop some unnecessary columnsData = Data.drop('date',axis=1)Data = Data.drop('id',axis=1)Data = Data.drop('zipcode',axis=1) Data is divided into the Train set and Test set. We use the Train set to make the algorithm learn the data’s behavior and then check the accuracy of our model on the Test set. Features (X): The columns that are inserted into our model will be used to make predictions. Prediction (y): Target variable that will be predicted by the features X = Data.drop('price',axis =1).valuesy = Data['price'].values#splitting Train and Test from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=101) Feature scaling will help us see all the variables from the same lens (same scale), it will also help our models learn faster. #standardization scaler - fit&transform on train, fit only on testfrom sklearn.preprocessing import StandardScalers_scaler = StandardScaler()X_train = s_scaler.fit_transform(X_train.astype(np.float))X_test = s_scaler.transform(X_test.astype(np.float)) Multiple Linear Regression is an extension of Simple Linear Regression (read more here) and assume that there is a linear relationship between a dependent variable Y and independent variables X Let’s wrap the training process in our Regression model: # Multiple Liner Regressionfrom sklearn.linear_model import LinearRegressionregressor = LinearRegression() regressor.fit(X_train, y_train)#evaluate the model (intercept and slope)print(regressor.intercept_)print(regressor.coef_)#predicting the test set resulty_pred = regressor.predict(X_test)#put results as a DataFramecoeff_df = pd.DataFrame(regressor.coef_, Data.drop('price',axis =1).columns, columns=['Coefficient']) coeff_df by visualizing the residual we can see that is normally distributed (proof of having linear relationship with the dependent variable) # visualizing residualsfig = plt.figure(figsize=(10,5))residuals = (y_test- y_pred)sns.distplot(residuals) Let’s compare actual output and predicted value to measure how far our predictions are from the real house prices. #compare actual output values with predicted valuesy_pred = regressor.predict(X_test)df = pd.DataFrame({'Actual': y_test, 'Predicted': y_pred})df1 = df.head(10)df1# evaluate the performance of the algorithm (MAE - MSE - RMSE)from sklearn import metricsprint('MAE:', metrics.mean_absolute_error(y_test, y_pred)) print('MSE:', metrics.mean_squared_error(y_test, y_pred)) print('RMSE:', np.sqrt(metrics.mean_squared_error(y_test, y_pred)))print('VarScore:',metrics.explained_variance_score(y_test,y_pred)) Let’s create a baseline neural network model for the regression problem. Starting with all of the needed functions and objects. # Creating a Neural Network Modelfrom tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import Dense, Activationfrom tensorflow.keras.optimizers import Adam Since we have 19 features, let’s insert 19 neurons as a start, 4 hidden layers and 1 output layer due to predict house Price. Also, ADAM optimization algorithm is used for optimizing loss function (Mean squared error) # having 19 neuron is based on the number of available featuresmodel = Sequential()model.add(Dense(19,activation='relu'))model.add(Dense(19,activation='relu'))model.add(Dense(19,activation='relu'))model.add(Dense(19,activation='relu'))model.add(Dense(1))model.compile(optimizer='Adam',loss='mes') Then, we train the model for 400 epochs, and each time record the training and validation accuracy in the history object. To keep track of how well the model is performing for each epoch, the model will run in both train and test data along with calculating the loss function. model.fit(x=X_train,y=y_train, validation_data=(X_test,y_test), batch_size=128,epochs=400)model.summary() loss_df = pd.DataFrame(model.history.history)loss_df.plot(figsize=(12,8)) y_pred = model.predict(X_test)from sklearn import metricsprint('MAE:', metrics.mean_absolute_error(y_test, y_pred)) print('MSE:', metrics.mean_squared_error(y_test, y_pred)) print('RMSE:', np.sqrt(metrics.mean_squared_error(y_test, y_pred)))print('VarScore:',metrics.explained_variance_score(y_test,y_pred))# Visualizing Our predictionsfig = plt.figure(figsize=(10,5))plt.scatter(y_test,y_pred)# Perfect predictionsplt.plot(y_test,y_test,'r') # visualizing residualsfig = plt.figure(figsize=(10,5))residuals = (y_test- y_pred)sns.distplot(residuals) We made it!💪 we have predicted the house price using two different ML model algorithms. The score of our Multiple Linear Regression is around 69%, so this model had room for improvement. Then we got an accuracy of ~81% with Keras Regression model. Also, notice that RMSE (loss function) is lower for Keras Regression model which shows that our prediction is closer to actual rating price. Without surprise, this score can be improved through feature selection or using other regression models. Thank you for reading🤓. Again feedback is always welcome!
[ { "code": null, "e": 296, "s": 172, "text": "In this tutorial, we’re going to create a model to predict House prices🏡 based on various factors across different markets." }, { "code": null, "e": 456, "s": 296, "text": "The goal of this statistical analysis is to help us understand the relationship between house features and how these variables are used to predict house price." }, { "code": null, "e": 480, "s": 456, "text": "Predict the house price" }, { "code": null, "e": 581, "s": 480, "text": "Using two different models in terms of minimizing the difference between predicted and actual rating" }, { "code": null, "e": 656, "s": 581, "text": "Data used: Kaggle-kc_house DatasetGitHub: you can find my source code here" }, { "code": null, "e": 747, "s": 656, "text": "First, Let’s import the data and have a look to see what kind of data we are dealing with:" }, { "code": null, "e": 1006, "s": 747, "text": "#import required librariesimport pandas as pdimport numpy as npimport seaborn as snsimport matplotlib.pyplot as plt#import DataData = pd.read_csv('kc_house_data.csv')Data.head(5).T#get some information about our Data-SetData.info()Data.describe().transpose()" }, { "code": null, "e": 1876, "s": 1006, "text": "The following features have been provided:✔️Date: Date house was sold✔️Price: Price is prediction target✔️Bedrooms: Number of Bedrooms/House✔️Bathrooms: Number of bathrooms/House✔️Sqft_Living: square footage of the home✔️Sqft_Lot: square footage of the lot✔️Floors: Total floors (levels) in house✔️Waterfront: House which has a view to a waterfront✔️View: Has been viewed✔️Condition: How good the condition is ( Overall )✔️Grade: grade given to the housing unit, based on King County grading system✔️Sqft_Above: square footage of house apart from basement✔️Sqft_Basement: square footage of the basement✔️Yr_Built: Built Year✔️Yr_Renovated: Year when house was renovated✔️Zipcode: Zip✔️Lat: Latitude coordinate✔️Long: Longitude coordinate✔️Sqft_Living15: Living room area in 2015(implies — some renovations) ✔️Sqft_Lot15: lotSize area in 2015(implies — some renovations)" }, { "code": null, "e": 1939, "s": 1876, "text": "Let’s plot couple of features to get a better feel of the data" }, { "code": null, "e": 2793, "s": 1939, "text": "#visualizing house pricesfig = plt.figure(figsize=(10,7))fig.add_subplot(2,1,1)sns.distplot(Data['price'])fig.add_subplot(2,1,2)sns.boxplot(Data['price'])plt.tight_layout()#visualizing square footage of (home,lot,above and basement)fig = plt.figure(figsize=(16,5))fig.add_subplot(2,2,1)sns.scatterplot(Data['sqft_above'], Data['price'])fig.add_subplot(2,2,2)sns.scatterplot(Data['sqft_lot'],Data['price'])fig.add_subplot(2,2,3)sns.scatterplot(Data['sqft_living'],Data['price'])fig.add_subplot(2,2,4)sns.scatterplot(Data['sqft_basement'],Data['price'])#visualizing bedrooms,bathrooms,floors,gradefig = plt.figure(figsize=(15,7))fig.add_subplot(2,2,1)sns.countplot(Data['bedrooms'])fig.add_subplot(2,2,2)sns.countplot(Data['floors'])fig.add_subplot(2,2,3)sns.countplot(Data['bathrooms'])fig.add_subplot(2,2,4)sns.countplot(Data['grade'])plt.tight_layout()" }, { "code": null, "e": 3009, "s": 2793, "text": "With distribution plot of price, we can visualize that most of the prices are between 0 and around 1M with few outliers close to 8 million (fancy houses😉). It would make sense to drop those outliers in our analysis." }, { "code": null, "e": 3103, "s": 3009, "text": "It is quit useful to have a quick overview of different features distribution vs house price." }, { "code": null, "e": 3207, "s": 3103, "text": "Here, I’m breaking the date columns down to years and months to see how is the house price is changing." }, { "code": null, "e": 3613, "s": 3207, "text": "#let's break date to years, monthsData['date'] = pd.to_datetime(Data['date'])Data['month'] = Data['date'].apply(lambda date:date.month)Data['year'] = Data['date'].apply(lambda date:date.year)#data visualization house price vs months and yearsfig = plt.figure(figsize=(16,5))fig.add_subplot(1,2,1)Data.groupby('month').mean()['price'].plot()fig.add_subplot(1,2,2)Data.groupby('year').mean()['price'].plot()" }, { "code": null, "e": 3745, "s": 3613, "text": "Let’s check if we have a Null Data and also drop some columns that we do not need (this data set does not have some missing values)" }, { "code": null, "e": 3926, "s": 3745, "text": "# check if there are any Null valuesData.isnull().sum()# drop some unnecessary columnsData = Data.drop('date',axis=1)Data = Data.drop('id',axis=1)Data = Data.drop('zipcode',axis=1)" }, { "code": null, "e": 4102, "s": 3926, "text": "Data is divided into the Train set and Test set. We use the Train set to make the algorithm learn the data’s behavior and then check the accuracy of our model on the Test set." }, { "code": null, "e": 4195, "s": 4102, "text": "Features (X): The columns that are inserted into our model will be used to make predictions." }, { "code": null, "e": 4266, "s": 4195, "text": "Prediction (y): Target variable that will be predicted by the features" }, { "code": null, "e": 4497, "s": 4266, "text": "X = Data.drop('price',axis =1).valuesy = Data['price'].values#splitting Train and Test from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=101)" }, { "code": null, "e": 4624, "s": 4497, "text": "Feature scaling will help us see all the variables from the same lens (same scale), it will also help our models learn faster." }, { "code": null, "e": 4876, "s": 4624, "text": "#standardization scaler - fit&transform on train, fit only on testfrom sklearn.preprocessing import StandardScalers_scaler = StandardScaler()X_train = s_scaler.fit_transform(X_train.astype(np.float))X_test = s_scaler.transform(X_test.astype(np.float))" }, { "code": null, "e": 5070, "s": 4876, "text": "Multiple Linear Regression is an extension of Simple Linear Regression (read more here) and assume that there is a linear relationship between a dependent variable Y and independent variables X" }, { "code": null, "e": 5127, "s": 5070, "text": "Let’s wrap the training process in our Regression model:" }, { "code": null, "e": 5559, "s": 5127, "text": "# Multiple Liner Regressionfrom sklearn.linear_model import LinearRegressionregressor = LinearRegression() regressor.fit(X_train, y_train)#evaluate the model (intercept and slope)print(regressor.intercept_)print(regressor.coef_)#predicting the test set resulty_pred = regressor.predict(X_test)#put results as a DataFramecoeff_df = pd.DataFrame(regressor.coef_, Data.drop('price',axis =1).columns, columns=['Coefficient']) coeff_df" }, { "code": null, "e": 5693, "s": 5559, "text": "by visualizing the residual we can see that is normally distributed (proof of having linear relationship with the dependent variable)" }, { "code": null, "e": 5800, "s": 5693, "text": "# visualizing residualsfig = plt.figure(figsize=(10,5))residuals = (y_test- y_pred)sns.distplot(residuals)" }, { "code": null, "e": 5915, "s": 5800, "text": "Let’s compare actual output and predicted value to measure how far our predictions are from the real house prices." }, { "code": null, "e": 6420, "s": 5915, "text": "#compare actual output values with predicted valuesy_pred = regressor.predict(X_test)df = pd.DataFrame({'Actual': y_test, 'Predicted': y_pred})df1 = df.head(10)df1# evaluate the performance of the algorithm (MAE - MSE - RMSE)from sklearn import metricsprint('MAE:', metrics.mean_absolute_error(y_test, y_pred)) print('MSE:', metrics.mean_squared_error(y_test, y_pred)) print('RMSE:', np.sqrt(metrics.mean_squared_error(y_test, y_pred)))print('VarScore:',metrics.explained_variance_score(y_test,y_pred))" }, { "code": null, "e": 6548, "s": 6420, "text": "Let’s create a baseline neural network model for the regression problem. Starting with all of the needed functions and objects." }, { "code": null, "e": 6725, "s": 6548, "text": "# Creating a Neural Network Modelfrom tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import Dense, Activationfrom tensorflow.keras.optimizers import Adam" }, { "code": null, "e": 6851, "s": 6725, "text": "Since we have 19 features, let’s insert 19 neurons as a start, 4 hidden layers and 1 output layer due to predict house Price." }, { "code": null, "e": 6943, "s": 6851, "text": "Also, ADAM optimization algorithm is used for optimizing loss function (Mean squared error)" }, { "code": null, "e": 7240, "s": 6943, "text": "# having 19 neuron is based on the number of available featuresmodel = Sequential()model.add(Dense(19,activation='relu'))model.add(Dense(19,activation='relu'))model.add(Dense(19,activation='relu'))model.add(Dense(19,activation='relu'))model.add(Dense(1))model.compile(optimizer='Adam',loss='mes')" }, { "code": null, "e": 7517, "s": 7240, "text": "Then, we train the model for 400 epochs, and each time record the training and validation accuracy in the history object. To keep track of how well the model is performing for each epoch, the model will run in both train and test data along with calculating the loss function." }, { "code": null, "e": 7641, "s": 7517, "text": "model.fit(x=X_train,y=y_train, validation_data=(X_test,y_test), batch_size=128,epochs=400)model.summary()" }, { "code": null, "e": 7715, "s": 7641, "text": "loss_df = pd.DataFrame(model.history.history)loss_df.plot(figsize=(12,8))" }, { "code": null, "e": 8160, "s": 7715, "text": "y_pred = model.predict(X_test)from sklearn import metricsprint('MAE:', metrics.mean_absolute_error(y_test, y_pred)) print('MSE:', metrics.mean_squared_error(y_test, y_pred)) print('RMSE:', np.sqrt(metrics.mean_squared_error(y_test, y_pred)))print('VarScore:',metrics.explained_variance_score(y_test,y_pred))# Visualizing Our predictionsfig = plt.figure(figsize=(10,5))plt.scatter(y_test,y_pred)# Perfect predictionsplt.plot(y_test,y_test,'r')" }, { "code": null, "e": 8267, "s": 8160, "text": "# visualizing residualsfig = plt.figure(figsize=(10,5))residuals = (y_test- y_pred)sns.distplot(residuals)" }, { "code": null, "e": 8355, "s": 8267, "text": "We made it!💪 we have predicted the house price using two different ML model algorithms." }, { "code": null, "e": 8656, "s": 8355, "text": "The score of our Multiple Linear Regression is around 69%, so this model had room for improvement. Then we got an accuracy of ~81% with Keras Regression model. Also, notice that RMSE (loss function) is lower for Keras Regression model which shows that our prediction is closer to actual rating price." }, { "code": null, "e": 8761, "s": 8656, "text": "Without surprise, this score can be improved through feature selection or using other regression models." } ]
Heart Disease Classification Project — Part I | by Muriel Kosaka | Towards Data Science
Cardiovascular disease or heart disease is the leading cause of death amongst women and men and amongst most racial/ethnic groups in the United States. Heart disease describes a range of conditions that affect your heart. Diseases under the heart disease umbrella include blood vessel diseases, such as coronary artery disease. From the CDC, roughly every 1 in 4 deaths each year are due to heart disease. The WHO states that human life style is the main reason behind this heart problem. Apart from this there are many key factors which warns that the person may/may not getting chance of heart disease. We will be using UCI’s heart disease dataset found here conducting exploratory data analysis (EDA), in part II we will building classification models and using ensembling methods to produce a highly accurate model. In the current dataset, publications of this study included 303 patients and chose 14 out of 76 features that are relevant in predicting heart disease. age: age in yearssex: sex (1 = male; 0 = female)cp: chest pain type — Value 1: typical angina, Value 2: atypical angina, Value 3: non-anginal pain, Value 4: asymptomatictrestbps: resting blood pressure (in mm Hg on admission to the hospital)chol: serum cholestoral in mg/dlfbs: (fasting blood sugar > 120 mg/dl) (1 = true; 0 = false)restecg: resting electrocardiographic results- Value 0: normal, Value 1: having ST-T wave abnormality (T wave inversions and/or ST elevation or depression of > 0.05 mV), Value 2: showing probable or definite left ventricular hypertrophy by Estes’ criteriathalach: maximum heart rate achievedexang: exercise induced angina (1 = yes; 0 = no)oldpeak = ST depression induced by exercise relative to restslope: the slope of the peak exercise ST segment- Value 1: upsloping, Value 2: flat, Value 3: downslopingca: number of major vessels (0–3) colored by flourosopythal: 3 = normal; 6 = fixed defect; 7 = reversable defecttarget: 1 = disease, 0 = no disease age: age in years sex: sex (1 = male; 0 = female) cp: chest pain type — Value 1: typical angina, Value 2: atypical angina, Value 3: non-anginal pain, Value 4: asymptomatic trestbps: resting blood pressure (in mm Hg on admission to the hospital) chol: serum cholestoral in mg/dl fbs: (fasting blood sugar > 120 mg/dl) (1 = true; 0 = false) restecg: resting electrocardiographic results- Value 0: normal, Value 1: having ST-T wave abnormality (T wave inversions and/or ST elevation or depression of > 0.05 mV), Value 2: showing probable or definite left ventricular hypertrophy by Estes’ criteria thalach: maximum heart rate achieved exang: exercise induced angina (1 = yes; 0 = no) oldpeak = ST depression induced by exercise relative to rest slope: the slope of the peak exercise ST segment- Value 1: upsloping, Value 2: flat, Value 3: downsloping ca: number of major vessels (0–3) colored by flourosopy thal: 3 = normal; 6 = fixed defect; 7 = reversable defect target: 1 = disease, 0 = no disease Continuous — age, trestbps, chol, thalach, oldpeakBinary — sex, fbs, exang, targetCategorical — cp, restecg, slope, ca, thal Continuous — age, trestbps, chol, thalach, oldpeak Binary — sex, fbs, exang, target Categorical — cp, restecg, slope, ca, thal Let’s get started with some EDA! First, we import the necessary libraries and read in our dataset import pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as snsimport plotly.graph_objects as go # To Generate Graphsimport plotly.express as px # To Generate box plot for statistical representation%matplotlib inlineimport plotly.express as pxdf=pd.read_csv('heart.csv')df.head() Descriptions of the variables are provided above, just to reiterate, target is our dependent variable where 0 = No Heart Disease and 1 = Heart Disease. Let’s check if there are any errors data values, such that the categorical variables have the correct number of categories as described above. After checking all variables, we found that thal and ca had one additional category within each. We will replace these values with NaN’s and then replace those values with median values df.thal.value_counts()#3 = normal; 6 = fixed defect; 7 = reversable defect# OUTPUT2 1663 1171 180 2Name: thal, dtype: int64# Replace 0 with NaNdf.loc[df['thal']==0, 'thal'] = np.NaNdf.ca.value_counts()# number of major vessels (0-3) colored by flourosopy# OUTPUT0 1751 652 383 204 5Name: ca, dtype: int64# Replace 4 with NaNdf.loc[df['ca']==4, 'ca'] = np.NaN# Replace NaN with median valuesdf=df.fillna(df.median()) Next, let’s check for outliers by visualizing a boxplot From this visualization we can see that chol has an extreme value which we will replace with its median value. Now we will create some more visualizations to understand the data more, using plotly. First let’s look at the distribution of our target variable: y=df.target.value_counts()x=['Disease','No Disease']fig=go.Figure( data=[go.Bar(x=x,y=y,text=y, textposition='auto',)], layout=go.Layout(title=go.layout.Title(text='Target Variable (Heart Disease) Distribution')))fig.update_xaxes(title_text='Target')fig.update_yaxes(title_text='Number of Individuals')fig.show() There is a slight class imbalance, but not severe enough to require upsampling/downsampling methods. Let’s see the distribution of age in our dataset: fig = px.histogram(df, x='age',color_discrete_sequence=['coral'])fig.update_xaxes(title_text='Age')fig.update_yaxes(title_text='Count')fig.update_layout(title_text='Distribution of Age')fig.show() From the above graph, we can see that most patients in the current dataset are between 50–60 years old. Let’s see the distribution of sex across our target variable: female=df.loc[df['sex']==0]female_values=female.target.value_counts()male=df.loc[df['sex']==1]male_values=male.target.value_counts()target=['No Disease','Disease']fig = go.Figure(data=[ go.Bar(name='female', x=female_values.index, y=female_values, text=female_values, textposition='auto'), go.Bar(name='male', x=male_values.index, y=male_values, text=male_values, textposition='auto'),])fig.update_xaxes(title_text='Target')fig.update_yaxes(title_text='Count')fig.update_layout(title_text='Distribution of Sex According to Target Variable')fig.update_layout(barmode='group')fig.show() From the above graph we can see that in heart disease group (1), there are more male patients than female patients. Next, let’s see how chest pain or angina (cps) varies amongst our target variable. Angina occurs when heart muscles don’t receive enough oxygen rich blood, causing major discomfort in the chest, often also spreading to the shoulders, arms, and neck. cp=['Typical Angina','Atypical Angina','Non-Anginal Pain','Asymptomatic']y1=df.loc[df['target']==0].cp.value_counts()y2=df.loc[df['target']==1].cp.value_counts()fig = go.Figure(data=[ go.Bar(name='Disease', x=cp, y=y2), go.Bar(name='No Disease', x=cp, y=y1)])fig.update_layout(barmode='group')fig.update_xaxes(title_text='Chest Pain Type')fig.update_yaxes(title_text='Count')fig.update_layout(title_text='Distribution of Target Variable According to Chest Pain Type')fig.show() From the above graph, a majority of non-disease patients experience typical angina which is described as tightness in the chest compared to disease patients. There also seems to be a balance in disease patients who’ve experienced atypical angina and non-anginal pain. Now let’s see how fasting blood sugar (fbs) varies amongst the target variable. Fbs is a diabetes indicator with fbs >120 mg/d is considered diabetic (True): dis=df.loc[df['target']==1]dis_values=dis.fbs.value_counts()nodis=df.loc[df['target']==0]nodis_values=nodis.fbs.value_counts()target=['No Disease','Disease']d=['False','True']fig = go.Figure(data=[ go.Bar(name='Disease', x=d, y=dis_values, text=dis_values, textposition='auto'), go.Bar(name='No Disease', x=d, y=nodis_values, text=nodis_values, textposition='auto'),])fig.update_layout(barmode='group')fig.update_xaxes(title_text='Fasting Blood Sugar (fbs)')fig.update_yaxes(title_text='Count')fig.update_layout(title_text='Distribution of Target Variable According to Fasting Blood Sugar')fig.show() Here, we see that the number for class true, is lower compared to class false. This provides an indication that fbs might not be a strong feature differentiating between heart disease an non-disease patient. In this article, we demonstrated some EDA techniques that can be conducted on UCI’s Heart Disease dataset in preparation for building a classification model. We’ve also created some visualizations to further understand the data and determine which variables may be influential in distinguishing between disease and non-disease patients. In Part II, I will be building a classification model and using ensemble methods to create a more accurate model. Thank you for reading :) All code is provided on my Github.
[ { "code": null, "e": 777, "s": 172, "text": "Cardiovascular disease or heart disease is the leading cause of death amongst women and men and amongst most racial/ethnic groups in the United States. Heart disease describes a range of conditions that affect your heart. Diseases under the heart disease umbrella include blood vessel diseases, such as coronary artery disease. From the CDC, roughly every 1 in 4 deaths each year are due to heart disease. The WHO states that human life style is the main reason behind this heart problem. Apart from this there are many key factors which warns that the person may/may not getting chance of heart disease." }, { "code": null, "e": 1144, "s": 777, "text": "We will be using UCI’s heart disease dataset found here conducting exploratory data analysis (EDA), in part II we will building classification models and using ensembling methods to produce a highly accurate model. In the current dataset, publications of this study included 303 patients and chose 14 out of 76 features that are relevant in predicting heart disease." }, { "code": null, "e": 2129, "s": 1144, "text": "age: age in yearssex: sex (1 = male; 0 = female)cp: chest pain type — Value 1: typical angina, Value 2: atypical angina, Value 3: non-anginal pain, Value 4: asymptomatictrestbps: resting blood pressure (in mm Hg on admission to the hospital)chol: serum cholestoral in mg/dlfbs: (fasting blood sugar > 120 mg/dl) (1 = true; 0 = false)restecg: resting electrocardiographic results- Value 0: normal, Value 1: having ST-T wave abnormality (T wave inversions and/or ST elevation or depression of > 0.05 mV), Value 2: showing probable or definite left ventricular hypertrophy by Estes’ criteriathalach: maximum heart rate achievedexang: exercise induced angina (1 = yes; 0 = no)oldpeak = ST depression induced by exercise relative to restslope: the slope of the peak exercise ST segment- Value 1: upsloping, Value 2: flat, Value 3: downslopingca: number of major vessels (0–3) colored by flourosopythal: 3 = normal; 6 = fixed defect; 7 = reversable defecttarget: 1 = disease, 0 = no disease" }, { "code": null, "e": 2147, "s": 2129, "text": "age: age in years" }, { "code": null, "e": 2179, "s": 2147, "text": "sex: sex (1 = male; 0 = female)" }, { "code": null, "e": 2301, "s": 2179, "text": "cp: chest pain type — Value 1: typical angina, Value 2: atypical angina, Value 3: non-anginal pain, Value 4: asymptomatic" }, { "code": null, "e": 2374, "s": 2301, "text": "trestbps: resting blood pressure (in mm Hg on admission to the hospital)" }, { "code": null, "e": 2407, "s": 2374, "text": "chol: serum cholestoral in mg/dl" }, { "code": null, "e": 2468, "s": 2407, "text": "fbs: (fasting blood sugar > 120 mg/dl) (1 = true; 0 = false)" }, { "code": null, "e": 2724, "s": 2468, "text": "restecg: resting electrocardiographic results- Value 0: normal, Value 1: having ST-T wave abnormality (T wave inversions and/or ST elevation or depression of > 0.05 mV), Value 2: showing probable or definite left ventricular hypertrophy by Estes’ criteria" }, { "code": null, "e": 2761, "s": 2724, "text": "thalach: maximum heart rate achieved" }, { "code": null, "e": 2810, "s": 2761, "text": "exang: exercise induced angina (1 = yes; 0 = no)" }, { "code": null, "e": 2871, "s": 2810, "text": "oldpeak = ST depression induced by exercise relative to rest" }, { "code": null, "e": 2977, "s": 2871, "text": "slope: the slope of the peak exercise ST segment- Value 1: upsloping, Value 2: flat, Value 3: downsloping" }, { "code": null, "e": 3033, "s": 2977, "text": "ca: number of major vessels (0–3) colored by flourosopy" }, { "code": null, "e": 3091, "s": 3033, "text": "thal: 3 = normal; 6 = fixed defect; 7 = reversable defect" }, { "code": null, "e": 3127, "s": 3091, "text": "target: 1 = disease, 0 = no disease" }, { "code": null, "e": 3252, "s": 3127, "text": "Continuous — age, trestbps, chol, thalach, oldpeakBinary — sex, fbs, exang, targetCategorical — cp, restecg, slope, ca, thal" }, { "code": null, "e": 3303, "s": 3252, "text": "Continuous — age, trestbps, chol, thalach, oldpeak" }, { "code": null, "e": 3336, "s": 3303, "text": "Binary — sex, fbs, exang, target" }, { "code": null, "e": 3379, "s": 3336, "text": "Categorical — cp, restecg, slope, ca, thal" }, { "code": null, "e": 3412, "s": 3379, "text": "Let’s get started with some EDA!" }, { "code": null, "e": 3477, "s": 3412, "text": "First, we import the necessary libraries and read in our dataset" }, { "code": null, "e": 3783, "s": 3477, "text": "import pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as snsimport plotly.graph_objects as go # To Generate Graphsimport plotly.express as px # To Generate box plot for statistical representation%matplotlib inlineimport plotly.express as pxdf=pd.read_csv('heart.csv')df.head()" }, { "code": null, "e": 3935, "s": 3783, "text": "Descriptions of the variables are provided above, just to reiterate, target is our dependent variable where 0 = No Heart Disease and 1 = Heart Disease." }, { "code": null, "e": 4264, "s": 3935, "text": "Let’s check if there are any errors data values, such that the categorical variables have the correct number of categories as described above. After checking all variables, we found that thal and ca had one additional category within each. We will replace these values with NaN’s and then replace those values with median values" }, { "code": null, "e": 4715, "s": 4264, "text": "df.thal.value_counts()#3 = normal; 6 = fixed defect; 7 = reversable defect# OUTPUT2 1663 1171 180 2Name: thal, dtype: int64# Replace 0 with NaNdf.loc[df['thal']==0, 'thal'] = np.NaNdf.ca.value_counts()# number of major vessels (0-3) colored by flourosopy# OUTPUT0 1751 652 383 204 5Name: ca, dtype: int64# Replace 4 with NaNdf.loc[df['ca']==4, 'ca'] = np.NaN# Replace NaN with median valuesdf=df.fillna(df.median())" }, { "code": null, "e": 4771, "s": 4715, "text": "Next, let’s check for outliers by visualizing a boxplot" }, { "code": null, "e": 4882, "s": 4771, "text": "From this visualization we can see that chol has an extreme value which we will replace with its median value." }, { "code": null, "e": 5030, "s": 4882, "text": "Now we will create some more visualizations to understand the data more, using plotly. First let’s look at the distribution of our target variable:" }, { "code": null, "e": 5365, "s": 5030, "text": "y=df.target.value_counts()x=['Disease','No Disease']fig=go.Figure( data=[go.Bar(x=x,y=y,text=y, textposition='auto',)], layout=go.Layout(title=go.layout.Title(text='Target Variable (Heart Disease) Distribution')))fig.update_xaxes(title_text='Target')fig.update_yaxes(title_text='Number of Individuals')fig.show()" }, { "code": null, "e": 5466, "s": 5365, "text": "There is a slight class imbalance, but not severe enough to require upsampling/downsampling methods." }, { "code": null, "e": 5516, "s": 5466, "text": "Let’s see the distribution of age in our dataset:" }, { "code": null, "e": 5713, "s": 5516, "text": "fig = px.histogram(df, x='age',color_discrete_sequence=['coral'])fig.update_xaxes(title_text='Age')fig.update_yaxes(title_text='Count')fig.update_layout(title_text='Distribution of Age')fig.show()" }, { "code": null, "e": 5817, "s": 5713, "text": "From the above graph, we can see that most patients in the current dataset are between 50–60 years old." }, { "code": null, "e": 5879, "s": 5817, "text": "Let’s see the distribution of sex across our target variable:" }, { "code": null, "e": 6470, "s": 5879, "text": "female=df.loc[df['sex']==0]female_values=female.target.value_counts()male=df.loc[df['sex']==1]male_values=male.target.value_counts()target=['No Disease','Disease']fig = go.Figure(data=[ go.Bar(name='female', x=female_values.index, y=female_values, text=female_values, textposition='auto'), go.Bar(name='male', x=male_values.index, y=male_values, text=male_values, textposition='auto'),])fig.update_xaxes(title_text='Target')fig.update_yaxes(title_text='Count')fig.update_layout(title_text='Distribution of Sex According to Target Variable')fig.update_layout(barmode='group')fig.show()" }, { "code": null, "e": 6586, "s": 6470, "text": "From the above graph we can see that in heart disease group (1), there are more male patients than female patients." }, { "code": null, "e": 6836, "s": 6586, "text": "Next, let’s see how chest pain or angina (cps) varies amongst our target variable. Angina occurs when heart muscles don’t receive enough oxygen rich blood, causing major discomfort in the chest, often also spreading to the shoulders, arms, and neck." }, { "code": null, "e": 7320, "s": 6836, "text": "cp=['Typical Angina','Atypical Angina','Non-Anginal Pain','Asymptomatic']y1=df.loc[df['target']==0].cp.value_counts()y2=df.loc[df['target']==1].cp.value_counts()fig = go.Figure(data=[ go.Bar(name='Disease', x=cp, y=y2), go.Bar(name='No Disease', x=cp, y=y1)])fig.update_layout(barmode='group')fig.update_xaxes(title_text='Chest Pain Type')fig.update_yaxes(title_text='Count')fig.update_layout(title_text='Distribution of Target Variable According to Chest Pain Type')fig.show()" }, { "code": null, "e": 7588, "s": 7320, "text": "From the above graph, a majority of non-disease patients experience typical angina which is described as tightness in the chest compared to disease patients. There also seems to be a balance in disease patients who’ve experienced atypical angina and non-anginal pain." }, { "code": null, "e": 7746, "s": 7588, "text": "Now let’s see how fasting blood sugar (fbs) varies amongst the target variable. Fbs is a diabetes indicator with fbs >120 mg/d is considered diabetic (True):" }, { "code": null, "e": 8353, "s": 7746, "text": "dis=df.loc[df['target']==1]dis_values=dis.fbs.value_counts()nodis=df.loc[df['target']==0]nodis_values=nodis.fbs.value_counts()target=['No Disease','Disease']d=['False','True']fig = go.Figure(data=[ go.Bar(name='Disease', x=d, y=dis_values, text=dis_values, textposition='auto'), go.Bar(name='No Disease', x=d, y=nodis_values, text=nodis_values, textposition='auto'),])fig.update_layout(barmode='group')fig.update_xaxes(title_text='Fasting Blood Sugar (fbs)')fig.update_yaxes(title_text='Count')fig.update_layout(title_text='Distribution of Target Variable According to Fasting Blood Sugar')fig.show()" }, { "code": null, "e": 8561, "s": 8353, "text": "Here, we see that the number for class true, is lower compared to class false. This provides an indication that fbs might not be a strong feature differentiating between heart disease an non-disease patient." }, { "code": null, "e": 9012, "s": 8561, "text": "In this article, we demonstrated some EDA techniques that can be conducted on UCI’s Heart Disease dataset in preparation for building a classification model. We’ve also created some visualizations to further understand the data and determine which variables may be influential in distinguishing between disease and non-disease patients. In Part II, I will be building a classification model and using ensemble methods to create a more accurate model." } ]
Count set bits in an integer in C++
We are given an integer number let’s say, num and the task is to firstly calculate the binary digit of a number and then calculate the total set bits of a number. Set bits in a binary number is represented by 1. Whenever we calculate the binary number of an integer value then it is formed as the combination of 0’s and 1’s. So, the digit 1 is known as set bit in the terms of the computer. Input − int number = 50 Output − Count of total set bits in a number are − 3 Explanation − Binary representation of a number 50 is 110010 and if we calculate it in 8-digit number then two 0’s will be appended in the beginning. So, the total set bits in a number are 3. Input − int number = 10 Output − Count of total set bits in a number are − 2 Explanation − Binary representation of a number 10 is 00001010 and if we calculate it in 8-digit number then four 0’s will be appended in the beginning. So, the total set bits in a number are 2. Input the number in a variable of integer type Input the number in a variable of integer type Declare a variable count to store the total count of set bits of type unsigned int Declare a variable count to store the total count of set bits of type unsigned int Start loop FOR from i to 1<<7 and i > 0 and i to i / 2 Start loop FOR from i to 1<<7 and i > 0 and i to i / 2 Inside the loop, check num & 1 == TRUE then print 1 else print 0 Inside the loop, check num & 1 == TRUE then print 1 else print 0 Start loop while to calculate the total count of bits till number isn’t 0 Start loop while to calculate the total count of bits till number isn’t 0 Inside the loop, set count = count + number & 1 and also set number >>=1 Inside the loop, set count = count + number & 1 and also set number >>=1 Print the count Print the count Live Demo #include<iostream> using namespace std; //Count total set bits in a number unsigned int bits(unsigned int number){ unsigned int count = 0; unsigned i; //display the total 8-bit number cout<<"8-bit digits of "<<number<<" is: "; for (i = 1 << 7; i > 0; i = i / 2){ (number & i)? cout<<"1": cout<<"0"; } //calculate the total set bits in a number while (number){ count += number & 1; number >>= 1; } cout<<"\nCount of total set bits in a number are: "<<count; } int main(){ int number = 50; bits(number); return 0; } If we run the above code it will generate the following output − 8-bit digits of 50 is: 00110010 Count of total set bits in a number are: 3
[ { "code": null, "e": 1225, "s": 1062, "text": "We are given an integer number let’s say, num and the task is to firstly calculate the binary digit of a number and then calculate the total set bits of a number." }, { "code": null, "e": 1453, "s": 1225, "text": "Set bits in a binary number is represented by 1. Whenever we calculate the binary number of an integer value then it is formed as the combination of 0’s and 1’s. So, the digit 1 is known as set bit in the terms of the computer." }, { "code": null, "e": 1477, "s": 1453, "text": "Input − int number = 50" }, { "code": null, "e": 1530, "s": 1477, "text": "Output − Count of total set bits in a number are − 3" }, { "code": null, "e": 1722, "s": 1530, "text": "Explanation − Binary representation of a number 50 is 110010 and if we calculate it in 8-digit number then two 0’s will be appended in the beginning. So, the total set bits in a number are 3." }, { "code": null, "e": 1746, "s": 1722, "text": "Input − int number = 10" }, { "code": null, "e": 1799, "s": 1746, "text": "Output − Count of total set bits in a number are − 2" }, { "code": null, "e": 1994, "s": 1799, "text": "Explanation − Binary representation of a number 10 is 00001010 and if we calculate it in 8-digit number then four 0’s will be appended in the beginning. So, the total set bits in a number are 2." }, { "code": null, "e": 2041, "s": 1994, "text": "Input the number in a variable of integer type" }, { "code": null, "e": 2088, "s": 2041, "text": "Input the number in a variable of integer type" }, { "code": null, "e": 2171, "s": 2088, "text": "Declare a variable count to store the total count of set bits of type unsigned int" }, { "code": null, "e": 2254, "s": 2171, "text": "Declare a variable count to store the total count of set bits of type unsigned int" }, { "code": null, "e": 2309, "s": 2254, "text": "Start loop FOR from i to 1<<7 and i > 0 and i to i / 2" }, { "code": null, "e": 2364, "s": 2309, "text": "Start loop FOR from i to 1<<7 and i > 0 and i to i / 2" }, { "code": null, "e": 2429, "s": 2364, "text": "Inside the loop, check num & 1 == TRUE then print 1 else print 0" }, { "code": null, "e": 2494, "s": 2429, "text": "Inside the loop, check num & 1 == TRUE then print 1 else print 0" }, { "code": null, "e": 2568, "s": 2494, "text": "Start loop while to calculate the total count of bits till number isn’t 0" }, { "code": null, "e": 2642, "s": 2568, "text": "Start loop while to calculate the total count of bits till number isn’t 0" }, { "code": null, "e": 2715, "s": 2642, "text": "Inside the loop, set count = count + number & 1 and also set number >>=1" }, { "code": null, "e": 2788, "s": 2715, "text": "Inside the loop, set count = count + number & 1 and also set number >>=1" }, { "code": null, "e": 2804, "s": 2788, "text": "Print the count" }, { "code": null, "e": 2820, "s": 2804, "text": "Print the count" }, { "code": null, "e": 2831, "s": 2820, "text": " Live Demo" }, { "code": null, "e": 3402, "s": 2831, "text": "#include<iostream>\nusing namespace std;\n//Count total set bits in a number\nunsigned int bits(unsigned int number){\n unsigned int count = 0;\n unsigned i;\n //display the total 8-bit number\n cout<<\"8-bit digits of \"<<number<<\" is: \";\n for (i = 1 << 7; i > 0; i = i / 2){\n (number & i)? cout<<\"1\": cout<<\"0\";\n }\n //calculate the total set bits in a number\n while (number){\n count += number & 1;\n number >>= 1;\n }\n cout<<\"\\nCount of total set bits in a number are: \"<<count;\n}\nint main(){\n int number = 50;\n bits(number);\n return 0;\n}" }, { "code": null, "e": 3467, "s": 3402, "text": "If we run the above code it will generate the following output −" }, { "code": null, "e": 3542, "s": 3467, "text": "8-bit digits of 50 is: 00110010\nCount of total set bits in a number are: 3" } ]
Check if one list is subset of other in Python
In text analytics and various other fields of data analytics it is often needed to find if a given list is already a part of a bigger list. In this article we will see the python programs to implement this requirement. We use a for loop to check if every element of the smaller list is present in the bigger list. The all function ensures each evaluation returns true. Live Demo Alist = ['Mon','Tue', 5, 'Sat', 9] Asub_list = ['Tue',5,9] # Given list and sublist print("Given list ",Alist) print("Given sublist",Asub_list) # With all if (all(x in Alist for x in Asub_list)): print("Sublist is part of bigger list") else: print("Sublist is not part of bigger list") # Checkign again Asub_list = ['Wed',5,9] print("New sublist",Asub_list) if (all(x in Alist for x in Asub_list)): print("Sublist is part of bigger list") else: print("Sublist is not part of bigger list") Running the above code gives us the following result − Given list ['Mon', 'Tue', 5, 'Sat', 9] Given sublist ['Tue', 5, 9] Sublist is part of bigger list New sublist ['Wed', 5, 9] Sublist is not part of bigger list In this approach we convert the lists into set and use the subset functions to validate if the small list is part of the bigger list or not. Live Demo Alist = ['Mon','Tue', 5, 'Sat', 9] Asub_list = ['Tue',5,9] # Given list and sublist print("Given list ",Alist) print("Given sublist",Asub_list) # With all if(set(Asub_list).issubset(set(Alist))): print("Sublist is part of bigger list") else: print("Sublist is not part of bigger list") # Checkign again Asub_list = ['Wed',5,9] print("New sublist",Asub_list) if(set(Asub_list).issubset(set(Alist))): print("Sublist is part of bigger list") else: print("Sublist is not part of bigger list") Running the above code gives us the following result − Given list ['Mon', 'Tue', 5, 'Sat', 9] Given sublist ['Tue', 5, 9] Sublist is part of bigger list New sublist ['Wed', 5, 9] Sublist is not part of bigger list The intersection function find the common elements between two sets. In this approach we convert the lists into sets and apply the intersection function. If the result of intersection is same as the sublist then we conclude the sublist is part of thelist. Live Demo Alist = ['Mon','Tue', 5, 'Sat', 9] Asub_list = ['Tue',5,9] # Given list and sublist print("Given list ",Alist) print("Given sublist",Asub_list) # With all if(set(Alist).intersection(Asub_list)== set(Asub_list)): print("Sublist is part of bigger list") else: print("Sublist is not part of bigger list") # Checkign again Asub_list = ['Wed',5,9] print("New sublist",Asub_list) if(set(Alist).intersection(Asub_list)== set(Asub_list)): print("Sublist is part of bigger list") else: print("Sublist is not part of bigger list") Running the above code gives us the following result − Given list ['Mon', 'Tue', 5, 'Sat', 9] Given sublist ['Tue', 5, 9] Sublist is part of bigger list New sublist ['Wed', 5, 9] Sublist is not part of bigger list
[ { "code": null, "e": 1281, "s": 1062, "text": "In text analytics and various other fields of data analytics it is often needed to find if a given list is already a part of a bigger list. In this article we will see the python programs to implement this requirement." }, { "code": null, "e": 1431, "s": 1281, "text": "We use a for loop to check if every element of the smaller list is present in the bigger list. The all function ensures each evaluation returns true." }, { "code": null, "e": 1442, "s": 1431, "text": " Live Demo" }, { "code": null, "e": 1946, "s": 1442, "text": "Alist = ['Mon','Tue', 5, 'Sat', 9]\nAsub_list = ['Tue',5,9]\n\n# Given list and sublist\nprint(\"Given list \",Alist)\nprint(\"Given sublist\",Asub_list)\n\n# With all\nif (all(x in Alist for x in Asub_list)):\n print(\"Sublist is part of bigger list\")\nelse:\n print(\"Sublist is not part of bigger list\")\n\n# Checkign again\nAsub_list = ['Wed',5,9]\nprint(\"New sublist\",Asub_list)\nif (all(x in Alist for x in Asub_list)):\n print(\"Sublist is part of bigger list\")\nelse:\n print(\"Sublist is not part of bigger list\")" }, { "code": null, "e": 2001, "s": 1946, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2160, "s": 2001, "text": "Given list ['Mon', 'Tue', 5, 'Sat', 9]\nGiven sublist ['Tue', 5, 9]\nSublist is part of bigger list\nNew sublist ['Wed', 5, 9]\nSublist is not part of bigger list" }, { "code": null, "e": 2301, "s": 2160, "text": "In this approach we convert the lists into set and use the subset functions to validate if the small list is part of the bigger list or not." }, { "code": null, "e": 2312, "s": 2301, "text": " Live Demo" }, { "code": null, "e": 2816, "s": 2312, "text": "Alist = ['Mon','Tue', 5, 'Sat', 9]\nAsub_list = ['Tue',5,9]\n\n# Given list and sublist\nprint(\"Given list \",Alist)\nprint(\"Given sublist\",Asub_list)\n\n# With all\nif(set(Asub_list).issubset(set(Alist))):\n print(\"Sublist is part of bigger list\")\nelse:\n print(\"Sublist is not part of bigger list\")\n\n# Checkign again\nAsub_list = ['Wed',5,9]\nprint(\"New sublist\",Asub_list)\nif(set(Asub_list).issubset(set(Alist))):\n print(\"Sublist is part of bigger list\")\nelse:\n print(\"Sublist is not part of bigger list\")" }, { "code": null, "e": 2871, "s": 2816, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 3030, "s": 2871, "text": "Given list ['Mon', 'Tue', 5, 'Sat', 9]\nGiven sublist ['Tue', 5, 9]\nSublist is part of bigger list\nNew sublist ['Wed', 5, 9]\nSublist is not part of bigger list" }, { "code": null, "e": 3286, "s": 3030, "text": "The intersection function find the common elements between two sets. In this approach we convert the lists into sets and apply the intersection function. If the result of intersection is same as the sublist then we conclude the sublist is part of thelist." }, { "code": null, "e": 3297, "s": 3286, "text": " Live Demo" }, { "code": null, "e": 3833, "s": 3297, "text": "Alist = ['Mon','Tue', 5, 'Sat', 9]\nAsub_list = ['Tue',5,9]\n\n# Given list and sublist\nprint(\"Given list \",Alist)\nprint(\"Given sublist\",Asub_list)\n\n# With all\nif(set(Alist).intersection(Asub_list)== set(Asub_list)):\n print(\"Sublist is part of bigger list\")\nelse:\n print(\"Sublist is not part of bigger list\")\n\n# Checkign again\nAsub_list = ['Wed',5,9]\nprint(\"New sublist\",Asub_list)\nif(set(Alist).intersection(Asub_list)== set(Asub_list)):\n print(\"Sublist is part of bigger list\")\nelse:\n print(\"Sublist is not part of bigger list\")" }, { "code": null, "e": 3888, "s": 3833, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 4047, "s": 3888, "text": "Given list ['Mon', 'Tue', 5, 'Sat', 9]\nGiven sublist ['Tue', 5, 9]\nSublist is part of bigger list\nNew sublist ['Wed', 5, 9]\nSublist is not part of bigger list" } ]
Data Handling Using Pandas: Cleaning and Processing | by Saptashwa Bhattacharyya | Towards Data Science
While practicing for some old Kaggle projects, I’ve realized that preparing data files before applying machine learning algorithms took a whole lot of time. This post is to review some of the beginner to advanced level data handling techniques with Pandas, written as a precursor of another post where I have used Global Terrorism Data and some advanced features of Pandas for data analysis. This post is all about data cleaning and processing. Let’s get started without any delay ! For this post, I have used IMDB movie-dataset to cover the most relevant data-cleaning and processing techniques. We can start of with knowing more about the data-set as below movies_df = pd.read_csv("movie_metadata.csv")print "data-frame shape: ", movies_df.shape >>> data-frame shape: (5043, 28) So the data-set has 5043 rows, 28 columns and, we can check the column names with print "column names: ", movies_df.columns.values>>> column names: ['color' 'director_name' 'num_critic_for_reviews' 'duration' 'director_facebook_likes' 'actor_3_facebook_likes' 'actor_2_name' 'actor_1_facebook_likes' 'gross' 'genres' 'actor_1_name' 'movie_title' 'num_voted_users' 'cast_total_facebook_likes' 'actor_3_name' 'facenumber_in_poster' 'plot_keywords' 'movie_imdb_link' 'num_user_for_reviews' 'language' 'country' 'content_rating' 'budget' 'title_year' 'actor_2_facebook_likes' 'imdb_score' 'aspect_ratio' 'movie_facebook_likes'] Before we can apply some ML algorithms to predict, let’s say ‘imdb_score’, we need to investigate the data-set bit more, as it is not so well processed like Boston House Data-Set. First, I will discuss on how to handle missing data. We can use pandas.DataFrame.isna() to detect missing values for an array like object. This returns a Boolean same-sized object where NA values, such as None or numpy.NaN, gets mapped to True and everything else is mapped to False. This does exactly the same with pandas.DataFrame.isnull() . print "null values: \n", print movies_df.isna() The above commands return the following output Rather than printing out the data-frame with True/False as entry, we can extract the relevant information by adding a .sum() along with the previous command. With this we can find total number of missing values for each column. print movies_df.isna().sum()>>>color 19director_name 104num_critic_for_reviews 50duration 15director_facebook_likes 104actor_3_facebook_likes 23actor_2_name 13actor_1_facebook_likes 7gross 884genres 0actor_1_name 7movie_title 0num_voted_users 0cast_total_facebook_likes 0actor_3_name 23facenumber_in_poster 13plot_keywords 153movie_imdb_link 0num_user_for_reviews 21language 12country 5content_rating 303budget 492title_year 108actor_2_facebook_likes 13imdb_score 0aspect_ratio 329movie_facebook_likes 0dtype: int64 Adding another .sum() returns the total number of null values in the data-set. print "total null values: ", movies_df.isna().sum().sum()>> total null values: 2698 One of the easiest ways to remove rows containing NA is to drop them, either when all column contain NA or any column contain NA. Let’s start with dropping rows that contain NA values in any of the columns. clean_movies_df = movies_df.dropna(how='any')print "new dataframe shape: ", clean_movies_df.shapeprint "old dataframe shape: ">>> new dataframe shape: (3756, 28)old dataframe shape: (5043, 28) So dropping rows containing NA values in any of the columns resulted in almost 1300 rows reduction. This can be important for data-sets with less number of rows where dropping all rows with any missing value can cost us losing necessary information. In that case we can use pandas.DataFrame.fillna() method to fill NA/NaN values using a specified method. Easiest way to fill all the NA/NaNs with some fixed value, for example 0. We can do that simply by movies_df.fillna(value=0, inplace = True) Instead of filling up all the missing values with zero, we can choose some specific columns and then use DataFrame.fillna() method as below — movies_df[['gross', 'budget']] = movies_df[['gross', 'budget']].fillna(value=0) For columns with ‘object’ dtypes, for example ‘language’ column, we can use some words like “no info” to fill up the missing entries. movies_df['language'].fillna("no info", inplace=True) Another method to fill the missing value could be ffill method, which propagates last valid observation to the next. Similarly bfill method uses next observation to fill gap. movies_df['language'].fillna(method='ffill', inplace=True) Another effective method is to use the mean of the column to fill the missing values as below movies_df['budget'].fillna(movies_df[budget].mean(), inplace=True) For more details on how to use Pandas to deal with missing values, you can check the Pandas user guide document on missing data. Apart from missing data, there can also be duplicate rows in a data-frame. To find whether a data-set contain duplicate rows or not we can use Pandas DataFrame.duplicated() either for all columns or for some selected columns. pandas.Dataframe.duplicated() returns a Boolean series denoting duplicate rows. Let’s first find how many duplicate rows are in this movies data-set. duplicate_rows_df = movies_df[movies_df.duplicated()]print "number of duplicate rows: ", duplicate_rows_df.shape>>> number of duplicate rows: (45, 28) So there are 45 rows with duplicate elements present in each column. We can check this for individual column too — duplicated_rows_df_imdb_link= movies_df[movies_df.duplicated(['movie_imdb_link'])]print duplicate_rows_df_imdb_link.shape>>> (124, 28) So there are 124 cases where imdb link is same, another way to check the same, is to use pandas.Series.unique() method. Let’s see: print len(movies_df.movie_imdb_link.unique())>>> 4919 So total number of unique links are 4919 and if you have noticed that duplicate links were 124, adding them gives (4919 + 124 = 5043) total number of rows. It is necessary to select the unique rows for better analysis, so at least we can drop the rows with same values in all column. We can do it simply using pandas.DataFrame.drop_duplicates() as below print "shape of dataframe after dropping duplicates", movies_df.drop_duplicates().shape >>> shape of dataframe after dropping duplicates (4998, 28) Another very important data processing technique is data bucketing or data binning. We will see an example here with binning IMDb-score using pandas.cut() method. Based on the score [0.,4., 7., 10.], I want to put movies in different buckets [‘shyyyte’, ‘moderate’, ‘good’]. As you can understand movies with score between 0–4 will be put into the ‘shyyyte’ bucket and so on. We can do this with the following lines of code op_labels = ['shyttte', 'moderate', 'good']category = [0.,4.,7.,10.]movies_df['imdb_labels'] = pd.cut(movies_df['imdb_score'], labels=op_labels, bins=category, include_lowest=False) Here a new column ‘imdb_labels’ is created containing the labels and let’s take a look on it — print movies_df[['movie_title', 'imdb_score', 'imdb_labels']][209:220]>>> movie_title imdb_score imdb_labels209 Rio 2 6.4 moderate210 X-Men 2 7.5 good211 Fast Five 7.3 good212 Sherlock Holmes:.. 7.5 good213 Clash of the... 5.8 moderate214 Total Recall 7.5 good215 The 13th Warrior 6.6 moderate216 The Bourne Legacy 6.7 moderate217 Batman & Robin 3.7 shyttte218 How the Grinch.. 6.0 moderate219 The Day After T.. 6.4 moderate To fully capitalize pandas.cut() method, you can check the docs. Most of the times for Exploratory Data Analysis (EDA), outlier detection is an important segment, as, outlier for particular features may distort the true picture, so we need to disregard them. Specifically, outliers can play havoc when we want to apply machine learning algorithm for prediction. At the same time outliers can even help us for anomaly detection. So let’s see how we can use Pandas to detect outliers in this particular data-frame. Seaborn Box Plot: Box plot is a standard way of visualizing distribution of data based on median, quartiles and outliers. Probably you already know what exactly are these quantities but still I made short review in the figure below. We can use python data visualization library Seaborn to plot such box plots. Let’s plot the distribution of number of actors who featured in the movie poster using a box plot. sns.boxplot(x=movies_df['facenumber_in_poster'], color='lime')plt.xlabel('No. of Actors Featured in Poster', fontsize=14)plt.show() The code above results in the plot below Let’s check the movie with maximum number of actors (faces) that featured in the movie poster. print movies_df[['movie_title', 'facenumber_in_poster']].iloc[movies_df['facenumber_in_poster'].idxmax()]>>>movie_title 500 Days of Summer facenumber_in_poster 43 So maximum number of faces (43) were featured in movie ‘500 Days of Summer’ . Let’s see a basic statistical details of this column ‘facenumber_in_poster’ with pandas.DataFrame.describe() method. print movies_df['facenumber_in_poster'].describe()>>>count 5030.000000mean 1.371173std 2.013576min 0.00000025% 0.00000050% 1.00000075% 2.000000max 43.000000 With this, probably the box plot makes a lot more sense to you know. Another way to detect outlier is to use Z Score. Let’s see how that works. Z Score and Outliers: Z score is a number (dimensionless) that signifies how much standard deviation a data point is, from the mean. Z score simply can be defined as — Z =(X-μ)/σ, where μ is the population mean and σ is the standard deviation, X is one element in the population. To plot the figure below, I have used normal distribution numpy.random.normal() and, in a normal distribution almost all the values — about 99.7%, fall within 3 σ deviation from the mean (for the plot here μ = 0). The way we can use Z score to reject outliers, is to consider the data points which are within 3 units of Z score. This can be done for all columns with ‘non object’ type data using scipy.stats as below. 1. Check the data types of all column in the data-frame (DataFrame.dtypes). print "data types: \n", movies_df.dtypes>>>data types: color objectdirector_name objectnum_critic_for_reviews float64duration float64director_facebook_likes float64actor_3_facebook_likes float64actor_2_name objectactor_1_facebook_likes float64gross float64genres objectactor_1_name objectmovie_title objectnum_voted_users int64cast_total_facebook_likes int64actor_3_name objectfacenumber_in_poster float64plot_keywords objectmovie_imdb_link objectnum_user_for_reviews float64language objectcountry objectcontent_rating objectbudget float64title_year float64actor_2_facebook_likes float64imdb_score float64aspect_ratio float64movie_facebook_likes int64 2. Create a new data-frame excluding all the ‘object’ types column DataFrame.select_dtypes print "shape before :", movies_df.shapemovies_df_num = movies_df.select_dtypes(exclude=['object'])print "shape after excluding object columns: ", movies_df_num.shape>>>shape before : (3756, 28)shape after excluding object columns: (3756, 16) 3. Select elements from each column that lie within 3 units of Z score movies_df_Zscore = movies_df_num[(np.abs(stats.zscore(movies_df_num))<3).all(axis=1)]print "shape after rejecting outliers: ", movies_df_Zscore.shape>>>shape after rejecting outliers: (3113, 16) We can check the effect of the above steps by plotting again the box plot for ‘facenumber_in_poster’. Here one can see the difference compared to figure 2, where we had the box plot considering all elements in the ‘facenumber_in_poster’ column. These are some ways one can prepare the data for analysis and applying machine learning algorithm for prediction. Effectively preparing the data-set can help a lot for comprehensive analysis and, I wish that this post will help you to prepare a data-set more methodically for further analysis. Depending upon the problem and data-set you may have to decide, choose and repeat these processes to interpret what are the effects, so, good luck exploring your data-set. Stay Strong and Cheers !! Codes used for this post are available on my Github. Find me in Linkedin.
[ { "code": null, "e": 654, "s": 171, "text": "While practicing for some old Kaggle projects, I’ve realized that preparing data files before applying machine learning algorithms took a whole lot of time. This post is to review some of the beginner to advanced level data handling techniques with Pandas, written as a precursor of another post where I have used Global Terrorism Data and some advanced features of Pandas for data analysis. This post is all about data cleaning and processing. Let’s get started without any delay !" }, { "code": null, "e": 830, "s": 654, "text": "For this post, I have used IMDB movie-dataset to cover the most relevant data-cleaning and processing techniques. We can start of with knowing more about the data-set as below" }, { "code": null, "e": 953, "s": 830, "text": "movies_df = pd.read_csv(\"movie_metadata.csv\")print \"data-frame shape: \", movies_df.shape >>> data-frame shape: (5043, 28)" }, { "code": null, "e": 1035, "s": 953, "text": "So the data-set has 5043 rows, 28 columns and, we can check the column names with" }, { "code": null, "e": 1578, "s": 1035, "text": "print \"column names: \", movies_df.columns.values>>> column names: ['color' 'director_name' 'num_critic_for_reviews' 'duration' 'director_facebook_likes' 'actor_3_facebook_likes' 'actor_2_name' 'actor_1_facebook_likes' 'gross' 'genres' 'actor_1_name' 'movie_title' 'num_voted_users' 'cast_total_facebook_likes' 'actor_3_name' 'facenumber_in_poster' 'plot_keywords' 'movie_imdb_link' 'num_user_for_reviews' 'language' 'country' 'content_rating' 'budget' 'title_year' 'actor_2_facebook_likes' 'imdb_score' 'aspect_ratio' 'movie_facebook_likes']" }, { "code": null, "e": 1811, "s": 1578, "text": "Before we can apply some ML algorithms to predict, let’s say ‘imdb_score’, we need to investigate the data-set bit more, as it is not so well processed like Boston House Data-Set. First, I will discuss on how to handle missing data." }, { "code": null, "e": 2102, "s": 1811, "text": "We can use pandas.DataFrame.isna() to detect missing values for an array like object. This returns a Boolean same-sized object where NA values, such as None or numpy.NaN, gets mapped to True and everything else is mapped to False. This does exactly the same with pandas.DataFrame.isnull() ." }, { "code": null, "e": 2150, "s": 2102, "text": "print \"null values: \\n\", print movies_df.isna()" }, { "code": null, "e": 2197, "s": 2150, "text": "The above commands return the following output" }, { "code": null, "e": 2425, "s": 2197, "text": "Rather than printing out the data-frame with True/False as entry, we can extract the relevant information by adding a .sum() along with the previous command. With this we can find total number of missing values for each column." }, { "code": null, "e": 3365, "s": 2425, "text": "print movies_df.isna().sum()>>>color 19director_name 104num_critic_for_reviews 50duration 15director_facebook_likes 104actor_3_facebook_likes 23actor_2_name 13actor_1_facebook_likes 7gross 884genres 0actor_1_name 7movie_title 0num_voted_users 0cast_total_facebook_likes 0actor_3_name 23facenumber_in_poster 13plot_keywords 153movie_imdb_link 0num_user_for_reviews 21language 12country 5content_rating 303budget 492title_year 108actor_2_facebook_likes 13imdb_score 0aspect_ratio 329movie_facebook_likes 0dtype: int64" }, { "code": null, "e": 3444, "s": 3365, "text": "Adding another .sum() returns the total number of null values in the data-set." }, { "code": null, "e": 3528, "s": 3444, "text": "print \"total null values: \", movies_df.isna().sum().sum()>> total null values: 2698" }, { "code": null, "e": 3735, "s": 3528, "text": "One of the easiest ways to remove rows containing NA is to drop them, either when all column contain NA or any column contain NA. Let’s start with dropping rows that contain NA values in any of the columns." }, { "code": null, "e": 3930, "s": 3735, "text": "clean_movies_df = movies_df.dropna(how='any')print \"new dataframe shape: \", clean_movies_df.shapeprint \"old dataframe shape: \">>> new dataframe shape: (3756, 28)old dataframe shape: (5043, 28)" }, { "code": null, "e": 4384, "s": 3930, "text": "So dropping rows containing NA values in any of the columns resulted in almost 1300 rows reduction. This can be important for data-sets with less number of rows where dropping all rows with any missing value can cost us losing necessary information. In that case we can use pandas.DataFrame.fillna() method to fill NA/NaN values using a specified method. Easiest way to fill all the NA/NaNs with some fixed value, for example 0. We can do that simply by" }, { "code": null, "e": 4427, "s": 4384, "text": "movies_df.fillna(value=0, inplace = True) " }, { "code": null, "e": 4569, "s": 4427, "text": "Instead of filling up all the missing values with zero, we can choose some specific columns and then use DataFrame.fillna() method as below —" }, { "code": null, "e": 4649, "s": 4569, "text": "movies_df[['gross', 'budget']] = movies_df[['gross', 'budget']].fillna(value=0)" }, { "code": null, "e": 4783, "s": 4649, "text": "For columns with ‘object’ dtypes, for example ‘language’ column, we can use some words like “no info” to fill up the missing entries." }, { "code": null, "e": 4837, "s": 4783, "text": "movies_df['language'].fillna(\"no info\", inplace=True)" }, { "code": null, "e": 5012, "s": 4837, "text": "Another method to fill the missing value could be ffill method, which propagates last valid observation to the next. Similarly bfill method uses next observation to fill gap." }, { "code": null, "e": 5071, "s": 5012, "text": "movies_df['language'].fillna(method='ffill', inplace=True)" }, { "code": null, "e": 5165, "s": 5071, "text": "Another effective method is to use the mean of the column to fill the missing values as below" }, { "code": null, "e": 5232, "s": 5165, "text": "movies_df['budget'].fillna(movies_df[budget].mean(), inplace=True)" }, { "code": null, "e": 5361, "s": 5232, "text": "For more details on how to use Pandas to deal with missing values, you can check the Pandas user guide document on missing data." }, { "code": null, "e": 5737, "s": 5361, "text": "Apart from missing data, there can also be duplicate rows in a data-frame. To find whether a data-set contain duplicate rows or not we can use Pandas DataFrame.duplicated() either for all columns or for some selected columns. pandas.Dataframe.duplicated() returns a Boolean series denoting duplicate rows. Let’s first find how many duplicate rows are in this movies data-set." }, { "code": null, "e": 5889, "s": 5737, "text": "duplicate_rows_df = movies_df[movies_df.duplicated()]print \"number of duplicate rows: \", duplicate_rows_df.shape>>> number of duplicate rows: (45, 28)" }, { "code": null, "e": 6004, "s": 5889, "text": "So there are 45 rows with duplicate elements present in each column. We can check this for individual column too —" }, { "code": null, "e": 6139, "s": 6004, "text": "duplicated_rows_df_imdb_link= movies_df[movies_df.duplicated(['movie_imdb_link'])]print duplicate_rows_df_imdb_link.shape>>> (124, 28)" }, { "code": null, "e": 6270, "s": 6139, "text": "So there are 124 cases where imdb link is same, another way to check the same, is to use pandas.Series.unique() method. Let’s see:" }, { "code": null, "e": 6324, "s": 6270, "text": "print len(movies_df.movie_imdb_link.unique())>>> 4919" }, { "code": null, "e": 6678, "s": 6324, "text": "So total number of unique links are 4919 and if you have noticed that duplicate links were 124, adding them gives (4919 + 124 = 5043) total number of rows. It is necessary to select the unique rows for better analysis, so at least we can drop the rows with same values in all column. We can do it simply using pandas.DataFrame.drop_duplicates() as below" }, { "code": null, "e": 6826, "s": 6678, "text": "print \"shape of dataframe after dropping duplicates\", movies_df.drop_duplicates().shape >>> shape of dataframe after dropping duplicates (4998, 28)" }, { "code": null, "e": 7250, "s": 6826, "text": "Another very important data processing technique is data bucketing or data binning. We will see an example here with binning IMDb-score using pandas.cut() method. Based on the score [0.,4., 7., 10.], I want to put movies in different buckets [‘shyyyte’, ‘moderate’, ‘good’]. As you can understand movies with score between 0–4 will be put into the ‘shyyyte’ bucket and so on. We can do this with the following lines of code" }, { "code": null, "e": 7432, "s": 7250, "text": "op_labels = ['shyttte', 'moderate', 'good']category = [0.,4.,7.,10.]movies_df['imdb_labels'] = pd.cut(movies_df['imdb_score'], labels=op_labels, bins=category, include_lowest=False)" }, { "code": null, "e": 7527, "s": 7432, "text": "Here a new column ‘imdb_labels’ is created containing the labels and let’s take a look on it —" }, { "code": null, "e": 8203, "s": 7527, "text": "print movies_df[['movie_title', 'imdb_score', 'imdb_labels']][209:220]>>> movie_title imdb_score imdb_labels209 Rio 2 6.4 moderate210 X-Men 2 7.5 good211 Fast Five 7.3 good212 Sherlock Holmes:.. 7.5 good213 Clash of the... 5.8 moderate214 Total Recall 7.5 good215 The 13th Warrior 6.6 moderate216 The Bourne Legacy 6.7 moderate217 Batman & Robin 3.7 shyttte218 How the Grinch.. 6.0 moderate219 The Day After T.. 6.4 moderate" }, { "code": null, "e": 8268, "s": 8203, "text": "To fully capitalize pandas.cut() method, you can check the docs." }, { "code": null, "e": 8716, "s": 8268, "text": "Most of the times for Exploratory Data Analysis (EDA), outlier detection is an important segment, as, outlier for particular features may distort the true picture, so we need to disregard them. Specifically, outliers can play havoc when we want to apply machine learning algorithm for prediction. At the same time outliers can even help us for anomaly detection. So let’s see how we can use Pandas to detect outliers in this particular data-frame." }, { "code": null, "e": 8734, "s": 8716, "text": "Seaborn Box Plot:" }, { "code": null, "e": 8949, "s": 8734, "text": "Box plot is a standard way of visualizing distribution of data based on median, quartiles and outliers. Probably you already know what exactly are these quantities but still I made short review in the figure below." }, { "code": null, "e": 9125, "s": 8949, "text": "We can use python data visualization library Seaborn to plot such box plots. Let’s plot the distribution of number of actors who featured in the movie poster using a box plot." }, { "code": null, "e": 9257, "s": 9125, "text": "sns.boxplot(x=movies_df['facenumber_in_poster'], color='lime')plt.xlabel('No. of Actors Featured in Poster', fontsize=14)plt.show()" }, { "code": null, "e": 9298, "s": 9257, "text": "The code above results in the plot below" }, { "code": null, "e": 9393, "s": 9298, "text": "Let’s check the movie with maximum number of actors (faces) that featured in the movie poster." }, { "code": null, "e": 9588, "s": 9393, "text": "print movies_df[['movie_title', 'facenumber_in_poster']].iloc[movies_df['facenumber_in_poster'].idxmax()]>>>movie_title 500 Days of Summer facenumber_in_poster 43" }, { "code": null, "e": 9783, "s": 9588, "text": "So maximum number of faces (43) were featured in movie ‘500 Days of Summer’ . Let’s see a basic statistical details of this column ‘facenumber_in_poster’ with pandas.DataFrame.describe() method." }, { "code": null, "e": 9997, "s": 9783, "text": "print movies_df['facenumber_in_poster'].describe()>>>count 5030.000000mean 1.371173std 2.013576min 0.00000025% 0.00000050% 1.00000075% 2.000000max 43.000000" }, { "code": null, "e": 10066, "s": 9997, "text": "With this, probably the box plot makes a lot more sense to you know." }, { "code": null, "e": 10141, "s": 10066, "text": "Another way to detect outlier is to use Z Score. Let’s see how that works." }, { "code": null, "e": 10163, "s": 10141, "text": "Z Score and Outliers:" }, { "code": null, "e": 10309, "s": 10163, "text": "Z score is a number (dimensionless) that signifies how much standard deviation a data point is, from the mean. Z score simply can be defined as —" }, { "code": null, "e": 10421, "s": 10309, "text": "Z =(X-μ)/σ, where μ is the population mean and σ is the standard deviation, X is one element in the population." }, { "code": null, "e": 10839, "s": 10421, "text": "To plot the figure below, I have used normal distribution numpy.random.normal() and, in a normal distribution almost all the values — about 99.7%, fall within 3 σ deviation from the mean (for the plot here μ = 0). The way we can use Z score to reject outliers, is to consider the data points which are within 3 units of Z score. This can be done for all columns with ‘non object’ type data using scipy.stats as below." }, { "code": null, "e": 10915, "s": 10839, "text": "1. Check the data types of all column in the data-frame (DataFrame.dtypes)." }, { "code": null, "e": 11979, "s": 10915, "text": "print \"data types: \\n\", movies_df.dtypes>>>data types: color objectdirector_name objectnum_critic_for_reviews float64duration float64director_facebook_likes float64actor_3_facebook_likes float64actor_2_name objectactor_1_facebook_likes float64gross float64genres objectactor_1_name objectmovie_title objectnum_voted_users int64cast_total_facebook_likes int64actor_3_name objectfacenumber_in_poster float64plot_keywords objectmovie_imdb_link objectnum_user_for_reviews float64language objectcountry objectcontent_rating objectbudget float64title_year float64actor_2_facebook_likes float64imdb_score float64aspect_ratio float64movie_facebook_likes int64" }, { "code": null, "e": 12070, "s": 11979, "text": "2. Create a new data-frame excluding all the ‘object’ types column DataFrame.select_dtypes" }, { "code": null, "e": 12313, "s": 12070, "text": "print \"shape before :\", movies_df.shapemovies_df_num = movies_df.select_dtypes(exclude=['object'])print \"shape after excluding object columns: \", movies_df_num.shape>>>shape before : (3756, 28)shape after excluding object columns: (3756, 16)" }, { "code": null, "e": 12384, "s": 12313, "text": "3. Select elements from each column that lie within 3 units of Z score" }, { "code": null, "e": 12580, "s": 12384, "text": "movies_df_Zscore = movies_df_num[(np.abs(stats.zscore(movies_df_num))<3).all(axis=1)]print \"shape after rejecting outliers: \", movies_df_Zscore.shape>>>shape after rejecting outliers: (3113, 16)" }, { "code": null, "e": 12825, "s": 12580, "text": "We can check the effect of the above steps by plotting again the box plot for ‘facenumber_in_poster’. Here one can see the difference compared to figure 2, where we had the box plot considering all elements in the ‘facenumber_in_poster’ column." }, { "code": null, "e": 13291, "s": 12825, "text": "These are some ways one can prepare the data for analysis and applying machine learning algorithm for prediction. Effectively preparing the data-set can help a lot for comprehensive analysis and, I wish that this post will help you to prepare a data-set more methodically for further analysis. Depending upon the problem and data-set you may have to decide, choose and repeat these processes to interpret what are the effects, so, good luck exploring your data-set." }, { "code": null, "e": 13317, "s": 13291, "text": "Stay Strong and Cheers !!" }, { "code": null, "e": 13370, "s": 13317, "text": "Codes used for this post are available on my Github." } ]
C# | Get the minimum value in the SortedSet - GeeksforGeeks
01 Feb, 2019 SortedSet class represents the collection of objects in sorted order. This class comes under the System.Collections.Generic namespace. SortedSet<T>.Min Property is used to get minimum value in the SortedSet<T>, as defined by the comparer. Properties: In C#, SortedSet class can be used to store, remove or view elements. It maintains ascending order and does not store duplicate elements. It is suggested to use SortedSet class if you have to store unique elements and maintain ascending order. Syntax: mySet.Min Here, mySet is the object of the SortedSet. Return Value: Minimum value in the SortedSet. Below programs illustrate the use of SortedSet<T>.Min Property: Example 1: // C# code to get the minimum value// in the SortedSetusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a SortedSet of integers SortedSet<int> mySet = new SortedSet<int>(); // Inserting elements into SortedSet for (int i = 0; i < 10; i++) { mySet.Add(i); } // Displaying the minimum value in the SortedSet Console.WriteLine("The minimum element in SortedSet is : " + mySet.Min); }} The minimum element in SortedSet is : 0 Example 2: // C# code to get the minimum value// in the SortedSetusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a SortedSet of strings SortedSet<string> mySet = new SortedSet<string>(); // Inserting elements into SortedSet mySet.Add("A"); mySet.Add("B"); mySet.Add("C"); mySet.Add("D"); mySet.Add("E"); mySet.Add("F"); // Displaying the minimum value in the SortedSet Console.WriteLine("The minimum element in SortedSet is : " + mySet.Min); }} The minimum element in SortedSet is : A Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.sortedset-1.min?view=netcore-2.1 CSharp-Generic-Namespace CSharp-Generic-SortedSet C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 50 C# Interview Questions & Answers Extension Method in C# HashSet in C# with Examples Partial Classes in C# C# | Inheritance Convert String to Character Array in C# Linked List Implementation in C# C# | How to insert an element in an Array? C# | List Class Difference between Hashtable and Dictionary in C#
[ { "code": null, "e": 23911, "s": 23883, "text": "\n01 Feb, 2019" }, { "code": null, "e": 24150, "s": 23911, "text": "SortedSet class represents the collection of objects in sorted order. This class comes under the System.Collections.Generic namespace. SortedSet<T>.Min Property is used to get minimum value in the SortedSet<T>, as defined by the comparer." }, { "code": null, "e": 24162, "s": 24150, "text": "Properties:" }, { "code": null, "e": 24232, "s": 24162, "text": "In C#, SortedSet class can be used to store, remove or view elements." }, { "code": null, "e": 24300, "s": 24232, "text": "It maintains ascending order and does not store duplicate elements." }, { "code": null, "e": 24406, "s": 24300, "text": "It is suggested to use SortedSet class if you have to store unique elements and maintain ascending order." }, { "code": null, "e": 24414, "s": 24406, "text": "Syntax:" }, { "code": null, "e": 24425, "s": 24414, "text": "mySet.Min\n" }, { "code": null, "e": 24469, "s": 24425, "text": "Here, mySet is the object of the SortedSet." }, { "code": null, "e": 24515, "s": 24469, "text": "Return Value: Minimum value in the SortedSet." }, { "code": null, "e": 24579, "s": 24515, "text": "Below programs illustrate the use of SortedSet<T>.Min Property:" }, { "code": null, "e": 24590, "s": 24579, "text": "Example 1:" }, { "code": "// C# code to get the minimum value// in the SortedSetusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a SortedSet of integers SortedSet<int> mySet = new SortedSet<int>(); // Inserting elements into SortedSet for (int i = 0; i < 10; i++) { mySet.Add(i); } // Displaying the minimum value in the SortedSet Console.WriteLine(\"The minimum element in SortedSet is : \" + mySet.Min); }}", "e": 25117, "s": 24590, "text": null }, { "code": null, "e": 25158, "s": 25117, "text": "The minimum element in SortedSet is : 0\n" }, { "code": null, "e": 25169, "s": 25158, "text": "Example 2:" }, { "code": "// C# code to get the minimum value// in the SortedSetusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a SortedSet of strings SortedSet<string> mySet = new SortedSet<string>(); // Inserting elements into SortedSet mySet.Add(\"A\"); mySet.Add(\"B\"); mySet.Add(\"C\"); mySet.Add(\"D\"); mySet.Add(\"E\"); mySet.Add(\"F\"); // Displaying the minimum value in the SortedSet Console.WriteLine(\"The minimum element in SortedSet is : \" + mySet.Min); }}", "e": 25767, "s": 25169, "text": null }, { "code": null, "e": 25808, "s": 25767, "text": "The minimum element in SortedSet is : A\n" }, { "code": null, "e": 25819, "s": 25808, "text": "Reference:" }, { "code": null, "e": 25923, "s": 25819, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.sortedset-1.min?view=netcore-2.1" }, { "code": null, "e": 25948, "s": 25923, "text": "CSharp-Generic-Namespace" }, { "code": null, "e": 25973, "s": 25948, "text": "CSharp-Generic-SortedSet" }, { "code": null, "e": 25976, "s": 25973, "text": "C#" }, { "code": null, "e": 26074, "s": 25976, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26083, "s": 26074, "text": "Comments" }, { "code": null, "e": 26096, "s": 26083, "text": "Old Comments" }, { "code": null, "e": 26136, "s": 26096, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 26159, "s": 26136, "text": "Extension Method in C#" }, { "code": null, "e": 26187, "s": 26159, "text": "HashSet in C# with Examples" }, { "code": null, "e": 26209, "s": 26187, "text": "Partial Classes in C#" }, { "code": null, "e": 26226, "s": 26209, "text": "C# | Inheritance" }, { "code": null, "e": 26266, "s": 26226, "text": "Convert String to Character Array in C#" }, { "code": null, "e": 26299, "s": 26266, "text": "Linked List Implementation in C#" }, { "code": null, "e": 26342, "s": 26299, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 26358, "s": 26342, "text": "C# | List Class" } ]
Bootstrap 4 - Collapse
Collapse component is used to show or hide the content by using .collapse class. The content can be collapsed by adding data-toggle="collapse" attribute anchor or button element. The id of these elements references to the id of the content to collapse the data. You can collapse the content with <a> tag by using href value of the ID of the content to collapse. The following example demonstrates this − <html lang = "en"> <head> <!-- Meta tags --> <meta charset = "utf-8"> <meta name = "viewport" content = "width = device-width, initial-scale = 1, shrink-to-fit = no"> <!-- Bootstrap CSS --> <link rel = "stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity = "sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin = "anonymous"> <title>Bootstrap 4 Example</title> </head> <body> <div class = "container"> <h2>Collapse with Link</h2> <p> <a class = "btn btn-info" data-toggle = "collapse" href = "#collapsewithlink" role = "button" aria-expanded = "false" aria-controls = "collapsewithlink">Click Me</a> </p> <div class = "collapse" id = "collapsewithlink"> <div class = "card card-body"> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation. </div> </div> </div> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src = "https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity = "sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin = "anonymous"> </script> <script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity = "sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin = "anonymous"> </script> <script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity = "sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin = "anonymous"> </script> </body> </html> It will produce the following result − Click Me You can collapse the content with <button> tag by using data-target attribute with value of the ID of the content to collapse. The following example demonstrates this − <html lang = "en"> <head> <!-- Meta tags --> <meta charset = "utf-8"> <meta name = "viewport" content = "width = device-width, initial-scale = 1, shrink-to-fit = no"> <!-- Bootstrap CSS --> <link rel = "stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity = "sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin = "anonymous"> <title>Bootstrap 4 Example</title> </head> <body> <div class = "container"> <h2>Collapse with Button</h2> <p> <button class = "btn btn-indo" type = "button" data-toggle = "collapse" data-target = "#collapsewithbutton" aria-expanded = "false" aria-controls = "collapsewithbutton">Click Me</button> </p> <div class = "collapse" id = "collapsewithbutton"> <div class = "card card-body"> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation. </div> </div> </div> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src = "https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity = "sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin = "anonymous"> </script> <script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity = "sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin = "anonymous"> </script> <script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity = "sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin = "anonymous"> </script> </body> </html> It will produce the following result − Click Me You can use collapsible content to make an accordion which is often used for content such as FAQs, overviews, etc. The below example specifies a simple accordion by extending the card component − <html lang = "en"> <head> <!-- Meta tags --> <meta charset = "utf-8"> <meta name = "viewport" content = "width = device-width, initial-scale = 1, shrink-to-fit = no"> <!-- Bootstrap CSS --> <link rel = "stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity = "sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin = "anonymous"> <title>Bootstrap 4 Example</title> </head> <body> <div class = "container"> <h2>Accordion </h2> <div id = "accordion"> <div class = "card"> <div class = "card-header"> <a class = "card-link" data-toggle = "collapse" href = "#collapseOne"> Accordion #1 </a> </div> <div id = "collapseOne" class = "collapse show" data-parent = "#accordion"> <div class = "card-body">Content for Accordion #1.</div> </div> </div> <div class = "card"> <div class = "card-header"> <a class = "collapsed card-link" data-toggle = "collapse" href = "#collapseTwo"> Accordion #2 </a> </div> <div id = "collapseTwo" class = "collapse" data-parent = "#accordion"> <div class = "card-body">Content for Accordion #2.</div> </div> </div> <div class = "card"> <div class = "card-header"> <a class = "collapsed card-link" data-toggle = "collapse" href = "#collapseThree"> Accordion #3 </a> </div> <div id = "collapseThree" class = "collapse" data-parent = "#accordion"> <div class = "card-body"> Content for Accordion #3.</div> </div> </div> </div> </div> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src = "https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity = "sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin = "anonymous"> </script> <script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity = "sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin = "anonymous"> </script> <script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity = "sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin = "anonymous"> </script> </body> </html> It will produce the following result − 26 Lectures 2 hours Anadi Sharma 54 Lectures 4.5 hours Frahaan Hussain 161 Lectures 14.5 hours Eduonix Learning Solutions 20 Lectures 4 hours Azaz Patel 15 Lectures 1.5 hours Muhammad Ismail 62 Lectures 8 hours Yossef Ayman Zedan Print Add Notes Bookmark this page
[ { "code": null, "e": 2078, "s": 1816, "text": "Collapse component is used to show or hide the content by using .collapse class. The content can be collapsed by adding data-toggle=\"collapse\" attribute anchor or button element. The id of these elements references to the id of the content to collapse the data." }, { "code": null, "e": 2178, "s": 2078, "text": "You can collapse the content with <a> tag by using href value of the ID of the content to collapse." }, { "code": null, "e": 2220, "s": 2178, "text": "The following example demonstrates this −" }, { "code": null, "e": 4278, "s": 2220, "text": "<html lang = \"en\">\n <head>\n <!-- Meta tags -->\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1, shrink-to-fit = no\">\n \n <!-- Bootstrap CSS -->\n <link rel = \"stylesheet\" \n href = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" \n integrity = \"sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO\" \n crossorigin = \"anonymous\">\n \n <title>Bootstrap 4 Example</title>\n </head>\n \n <body>\n <div class = \"container\">\n <h2>Collapse with Link</h2>\n <p>\n <a class = \"btn btn-info\" data-toggle = \"collapse\" \n href = \"#collapsewithlink\" role = \"button\" aria-expanded = \"false\" \n aria-controls = \"collapsewithlink\">Click Me</a>\n </p>\n \n <div class = \"collapse\" id = \"collapsewithlink\">\n <div class = \"card card-body\">\n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod \n tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim \n veniam, quis nostrud exercitation.\n </div>\n </div>\n </div>\n \n <!-- jQuery first, then Popper.js, then Bootstrap JS -->\n <script src = \"https://code.jquery.com/jquery-3.3.1.slim.min.js\" \n integrity = \"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js\" \n integrity = \"sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js\" \n integrity = \"sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy\" \n crossorigin = \"anonymous\">\n </script>\n \n </body>\n</html>" }, { "code": null, "e": 4317, "s": 4278, "text": "It will produce the following result −" }, { "code": null, "e": 4328, "s": 4317, "text": "\nClick Me\n" }, { "code": null, "e": 4455, "s": 4328, "text": "You can collapse the content with <button> tag by using data-target attribute with value of the ID of the content to collapse." }, { "code": null, "e": 4497, "s": 4455, "text": "The following example demonstrates this −" }, { "code": null, "e": 6572, "s": 4497, "text": "<html lang = \"en\">\n <head>\n <!-- Meta tags -->\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1, shrink-to-fit = no\">\n \n <!-- Bootstrap CSS -->\n <link rel = \"stylesheet\" \n href = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\"\n integrity = \"sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO\" \n crossorigin = \"anonymous\">\n <title>Bootstrap 4 Example</title>\n </head>\n \n <body>\n <div class = \"container\">\n <h2>Collapse with Button</h2>\n <p>\n <button class = \"btn btn-indo\" type = \"button\" data-toggle = \"collapse\" \n data-target = \"#collapsewithbutton\" aria-expanded = \"false\" \n aria-controls = \"collapsewithbutton\">Click Me</button>\n </p>\n \n <div class = \"collapse\" id = \"collapsewithbutton\">\n <div class = \"card card-body\">\n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod \n tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim \n veniam, quis nostrud exercitation.\n </div>\n </div>\n </div>\n \n <!-- jQuery first, then Popper.js, then Bootstrap JS -->\n <script src = \"https://code.jquery.com/jquery-3.3.1.slim.min.js\" \n integrity = \"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js\" \n integrity = \"sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js\" \n integrity = \"sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy\" \n crossorigin = \"anonymous\">\n </script>\n \n </body>\n</html>" }, { "code": null, "e": 6611, "s": 6572, "text": "It will produce the following result −" }, { "code": null, "e": 6622, "s": 6611, "text": "\nClick Me\n" }, { "code": null, "e": 6737, "s": 6622, "text": "You can use collapsible content to make an accordion which is often used for content such as FAQs, overviews, etc." }, { "code": null, "e": 6818, "s": 6737, "text": "The below example specifies a simple accordion by extending the card component −" }, { "code": null, "e": 9763, "s": 6818, "text": "<html lang = \"en\">\n <head>\n <!-- Meta tags -->\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1, shrink-to-fit = no\">\n \n <!-- Bootstrap CSS -->\n <link rel = \"stylesheet\" \n href = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" \n integrity = \"sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO\" \n crossorigin = \"anonymous\">\n \n <title>Bootstrap 4 Example</title>\n </head>\n \n <body>\n <div class = \"container\">\n <h2>Accordion </h2>\n <div id = \"accordion\">\n <div class = \"card\">\n <div class = \"card-header\">\n <a class = \"card-link\" data-toggle = \"collapse\" href = \"#collapseOne\">\n Accordion #1\n </a>\n </div>\n \n <div id = \"collapseOne\" class = \"collapse show\" data-parent = \"#accordion\">\n <div class = \"card-body\">Content for Accordion #1.</div>\n </div>\n </div>\n \n <div class = \"card\">\n <div class = \"card-header\">\n <a class = \"collapsed card-link\" data-toggle = \"collapse\" href = \"#collapseTwo\">\n Accordion #2\n </a>\n </div>\n \n <div id = \"collapseTwo\" class = \"collapse\" data-parent = \"#accordion\">\n <div class = \"card-body\">Content for Accordion #2.</div>\n </div>\n </div>\n \n <div class = \"card\">\n <div class = \"card-header\">\n <a class = \"collapsed card-link\" data-toggle = \"collapse\" href = \"#collapseThree\">\n Accordion #3\n </a>\n </div>\n \n <div id = \"collapseThree\" class = \"collapse\" data-parent = \"#accordion\">\n <div class = \"card-body\"> Content for Accordion #3.</div>\n </div>\n </div>\n \n </div>\n </div>\n \n <!-- jQuery first, then Popper.js, then Bootstrap JS -->\n <script src = \"https://code.jquery.com/jquery-3.3.1.slim.min.js\" \n integrity = \"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js\" \n integrity = \"sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js\" \n integrity = \"sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy\" \n crossorigin = \"anonymous\">\n </script>\n \n </body>\n</html>" }, { "code": null, "e": 9802, "s": 9763, "text": "It will produce the following result −" }, { "code": null, "e": 9835, "s": 9802, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 9849, "s": 9835, "text": " Anadi Sharma" }, { "code": null, "e": 9884, "s": 9849, "text": "\n 54 Lectures \n 4.5 hours \n" }, { "code": null, "e": 9901, "s": 9884, "text": " Frahaan Hussain" }, { "code": null, "e": 9938, "s": 9901, "text": "\n 161 Lectures \n 14.5 hours \n" }, { "code": null, "e": 9966, "s": 9938, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 9999, "s": 9966, "text": "\n 20 Lectures \n 4 hours \n" }, { "code": null, "e": 10011, "s": 9999, "text": " Azaz Patel" }, { "code": null, "e": 10046, "s": 10011, "text": "\n 15 Lectures \n 1.5 hours \n" }, { "code": null, "e": 10063, "s": 10046, "text": " Muhammad Ismail" }, { "code": null, "e": 10096, "s": 10063, "text": "\n 62 Lectures \n 8 hours \n" }, { "code": null, "e": 10116, "s": 10096, "text": " Yossef Ayman Zedan" }, { "code": null, "e": 10123, "s": 10116, "text": " Print" }, { "code": null, "e": 10134, "s": 10123, "text": " Add Notes" } ]
Creating an ECG Data Stream with Polar device | by Pareeknikhil | Towards Data Science
With a plethora of Biofeedback apps emerging in the health and fitness space, wearable biosensing devices are becoming pivotal in determining the “Active” state of the users. The active state of the user could be defined as the mood; between happy-sad-neutral or stress state; between relaxed-stressed-neutral, or even health state; healthy-risky, depending upon the scope of the application being developed. But a common physiological indicator that pins all the aforementioned use-cases is cardiovascular data. And this article aims to give you a brief summary on filtering raw cardiovascular data from BCI/Fitness tracking devices such as Polar H10 and OpenBCI-Cyton into noise-free data. Most of the Biofeedback systems rely on two key physiological measurements as indicators of the active state of the user: Cardiovascular activity and Breathing capacity. These signals could further be split into specific metrics such as Heart Rate Variability (HRV), RR interval, Tidal Volume, etc. but we would stick with processing raw cardiovascular activity here (For a detailed read on indicators — here). And Electrocardiograph (ECG) is the savior here in providing the most accurate electrical activity of the heart in real-time as compared to techniques such as Photoplethysmography (PPG). Essentially ECG signals convey information about the structure and function of the heart and further, we are specifically interested in capturing a biomedical signal — the QRS complex of the heart which is useful in diagnosing cardiac arrhythmias, conduction abnormalities, ventricular hypertrophy, myocardial infarction, electrolyte derangements, and other disease states. Polar mobile SDK enables you to read and interpret live data from Polar heart rate sensors, including ECG data, acceleration data and heart rate broadcast. — Polar SDK official documentation The SDK will work with 3 devices in the Heart Rate Sensors category that Polar has developed so far. The following three elucidate the features of each of these devices in descending order of cost and capabilities: The first one is Polar H10 which is globally recognized for its accuracy and high quality. If you are looking for an accurate heart rate sensor that could be worn on the chest, this is the one !! Also for the purpose of demonstration, all the visualization and the code that is used in this tutorial have been developed on Polar H10. Following are its capabilities as listed on the official PolarH10 page. Electrocardiography & RR intervals Heart rate broadcast — Heart Beat Acceleration Sensor memory read Device ID The second one is the Optical Heart Rate Sensor, OH1. The advantage of the optical technology is its ability to be worn on the arm as well as on the temple along with the chest, therefore one could use the device while swimming as well. The code and visualization showcased in this tutorial would work very well with the Polar OH1 as well. Following are its capabilities as listed on the official Polar OH1 page. Photoplethysmogram (PPG) Heart rate broadcast — Heart Beat Acceleration Sensor memory read Device ID Similar to Polar H10, this model is a chest strap Heart Rate Sensor but without the ECG raw data broadcasting, capabilities and therefore is not eligible for the purpose of live ECG visualization in this tutorial. Following are its capabilities as listed on the official Polar H9 page. RR intervals Heart rate broadcast — Heart Beat Device ID The data-format and types are different for different devices produced by Polar and we would be referencing the same from the official Polar documentation for the same in this tutorial: Polar H10 heart rate sensor available data types(From version 3.0.35 onwards): Polar H10 heart rate sensor available data types(From version 3.0.35 onwards): Heart rate as beats per minute. RR Interval in ms and 1/1024 format. Electrocardiography (ECG) data in μV. The default epoch for the timestamp is 1.1.2000. Accelerometer data with sample rates of 25Hz, 50Hz, 100Hz, and 200Hz and range of 2G, 4G, and 8G (2G is sufficient if you would like to pick up respiration data from the chest). Axis specific acceleration data in mG. Recording supports RR, HR with one-second sample time, or HR with five-second sample time. List, read, and remove for stored internal recording (sensor supports only one recording at the time). — Source: Official Polar Github repo 2. Polar OH1 Optical heart rate sensor available data types(From version 2.0.8 onwards): The Polar OH1 Optical heart rate sensor is a rechargeable device that measures the user’s heart rate with LED technology. Heart rate as beats per minute. Photoplethysmography (PPG) values. PP interval (milliseconds) representing cardiac pulse-to-pulse interval extracted from the PPG signal. Accelerometer data with a sample rate of 50Hz and a range of 8G. Axis specific acceleration data in mG. List, read, and remove stored exercise. Recording of exercise requires that the sensor is registered to Polar Flow account. — Source: Official Polar Github repo A Python-based application for visualizing ECG with Polar-H10 tracker in real-time is available here. The communication with the Polar device is via a Bluetooth service protocol, knows as GATT (Generic Attribute Profile). It defines the way that two Bluetooth Low Energy devices transfer data back and forth using concepts called Services and Characteristics. Furthermore, along with the GATT protocol, a special protocol — Heart Rate GATT Service Protocol that the device manufacturer follows to allow users to obtain specific responses such as Hear Beat, Raw ECG data, battery level, etc. via an API would be used in this tutorial. For each of these features such as Heart Beat, ECG, battery level, etc. we will use predefined UUID (Universal Unique Identifier) mapping and write it on the device to obtain real-time data. Let’s get started ❤ We will use the Bleak library for the Bluetooth Low Energy (BLE) connection. And also Asyncio for the asynchronous programming of the application. import asyncioimport mathimport osimport signalimport sysimport timeimport pandas as pdfrom bleak import BleakClientfrom bleak.uuids import uuid16_dictimport matplotlib.pyplot as pltimport matplotlib We will further define the UUID’s for all the features we want to extract from the Polar device: """ Predefined UUID (Universal Unique Identifier) mapping are based on Heart Rate GATT service Protocol that mostFitness/Heart Rate device manufacturer follow (Polar H10 in this case) to obtain a specific response input fromthe device acting as an API """## UUID mappinguuid16_dict = {v: k for k, v in uuid16_dict.items()}## This is the device MAC ID, please update with your device IDADDRESS = "D4:52:48:88:EA:04"## UUID for model number ##MODEL_NBR_UUID = "0000{0:x}-0000-1000-8000-00805f9b34fb".format(uuid16_dict.get("Model Number String"))## UUID for manufacturer name ##MANUFACTURER_NAME_UUID = "0000{0:x}-0000-1000-8000-00805f9b34fb".format(uuid16_dict.get("Manufacturer Name String"))## UUID for battery level ##BATTERY_LEVEL_UUID = "0000{0:x}-0000-1000-8000-00805f9b34fb".format(uuid16_dict.get("Battery Level"))## UUID for connection establsihment with device ##PMD_SERVICE = "FB005C80-02E7-F387-1CAD-8ACD2D8DF0C8"## UUID for Request of stream settings ##PMD_CONTROL = "FB005C81-02E7-F387-1CAD-8ACD2D8DF0C8"## UUID for Request of start stream ##PMD_DATA = "FB005C82-02E7-F387-1CAD-8ACD2D8DF0C8"## UUID for Request of ECG Stream ##ECG_WRITE = bytearray([0x02, 0x00, 0x00, 0x01, 0x82, 0x00, 0x01, 0x01, 0x0E, 0x00])## For Plolar H10 sampling frequency ##ECG_SAMPLING_FREQ = 130## Resource allocation for data collectionecg_session_data = []ecg_session_time = [] The data from the Polar device is received as a stream and in hexadecimal bytes and we would require to decode and build a streaming service for the same in decimal bytes. The following functions do the same: def data_conv(sender, data): if data[0] == 0x00: timestamp = convert_to_unsigned_long(data, 1, 8) step = 3 samples = data[10:] offset = 0 while offset < len(samples): ecg = convert_array_to_signed_int(samples, offset, step) offset += step ecg_session_data.extend([ecg]) ecg_session_time.extend([timestamp])def convert_array_to_signed_int(data, offset, length): return int.from_bytes(bytearray(data[offset : offset + length]), byteorder="little", signed=True,)def convert_to_unsigned_long(data, offset, length): return int.from_bytes(bytearray(data[offset : offset + length]), byteorder="little", signed=False,) Now comes the last bit to write an async method that would write and assemble all necessary UUID’s on the device and open the ECG stream from Polar. This is a fairly simple task, but a lengthy one, and it would be convenient for the readers here to direct you to my Github repo for a complete working application. On running the main.py, one could replicate the plot shown below. Building a live data-stream and filtering signals for Polar devices are vital in building real-time biofeedback applications and are fairly simple tasks with a little time and sufficient documentation. Luckily we have both !! How to create a real-time data-stream with Polar devices — Accelerometer How to create a real-time data-stream with OpenBCI devices — ECG Getting the beat right !! — Processing ECG data with band-pass filters Special thanks to my very good friend Deepesh for helping me develop the code and his enthusiasm towards helping others selflessly. 1. Polar documentation, Polar docs, Github2. N.Pareek, Getting the beat right !! (2021), Towards Data Science3. Mohamed Elgendi,Carlo Menon, Assessing Anxiety Disorders Using Wearable Devices: Challenges and Future Directions (2019) ,Brain Sciences4. Inma Mohino-Herranz, Roberto Gil-Pita, Manuel Rosa-Zurera, Fernando Seoane, Activity Recognition Using Wearable Physiological Measurements: Selection of Features from a Comprehensive Literature Study (2019) ,NCBI5. National Centre for Adaptive Neurotechnologies (NCAN), Contributions:OpenBCI Module6. Adafruit, Introductin to Bluetooth Low Energy
[ { "code": null, "e": 864, "s": 172, "text": "With a plethora of Biofeedback apps emerging in the health and fitness space, wearable biosensing devices are becoming pivotal in determining the “Active” state of the users. The active state of the user could be defined as the mood; between happy-sad-neutral or stress state; between relaxed-stressed-neutral, or even health state; healthy-risky, depending upon the scope of the application being developed. But a common physiological indicator that pins all the aforementioned use-cases is cardiovascular data. And this article aims to give you a brief summary on filtering raw cardiovascular data from BCI/Fitness tracking devices such as Polar H10 and OpenBCI-Cyton into noise-free data." }, { "code": null, "e": 1836, "s": 864, "text": "Most of the Biofeedback systems rely on two key physiological measurements as indicators of the active state of the user: Cardiovascular activity and Breathing capacity. These signals could further be split into specific metrics such as Heart Rate Variability (HRV), RR interval, Tidal Volume, etc. but we would stick with processing raw cardiovascular activity here (For a detailed read on indicators — here). And Electrocardiograph (ECG) is the savior here in providing the most accurate electrical activity of the heart in real-time as compared to techniques such as Photoplethysmography (PPG). Essentially ECG signals convey information about the structure and function of the heart and further, we are specifically interested in capturing a biomedical signal — the QRS complex of the heart which is useful in diagnosing cardiac arrhythmias, conduction abnormalities, ventricular hypertrophy, myocardial infarction, electrolyte derangements, and other disease states." }, { "code": null, "e": 2027, "s": 1836, "text": "Polar mobile SDK enables you to read and interpret live data from Polar heart rate sensors, including ECG data, acceleration data and heart rate broadcast. — Polar SDK official documentation" }, { "code": null, "e": 2242, "s": 2027, "text": "The SDK will work with 3 devices in the Heart Rate Sensors category that Polar has developed so far. The following three elucidate the features of each of these devices in descending order of cost and capabilities:" }, { "code": null, "e": 2648, "s": 2242, "text": "The first one is Polar H10 which is globally recognized for its accuracy and high quality. If you are looking for an accurate heart rate sensor that could be worn on the chest, this is the one !! Also for the purpose of demonstration, all the visualization and the code that is used in this tutorial have been developed on Polar H10. Following are its capabilities as listed on the official PolarH10 page." }, { "code": null, "e": 2683, "s": 2648, "text": "Electrocardiography & RR intervals" }, { "code": null, "e": 2717, "s": 2683, "text": "Heart rate broadcast — Heart Beat" }, { "code": null, "e": 2730, "s": 2717, "text": "Acceleration" }, { "code": null, "e": 2749, "s": 2730, "text": "Sensor memory read" }, { "code": null, "e": 2759, "s": 2749, "text": "Device ID" }, { "code": null, "e": 3172, "s": 2759, "text": "The second one is the Optical Heart Rate Sensor, OH1. The advantage of the optical technology is its ability to be worn on the arm as well as on the temple along with the chest, therefore one could use the device while swimming as well. The code and visualization showcased in this tutorial would work very well with the Polar OH1 as well. Following are its capabilities as listed on the official Polar OH1 page." }, { "code": null, "e": 3197, "s": 3172, "text": "Photoplethysmogram (PPG)" }, { "code": null, "e": 3231, "s": 3197, "text": "Heart rate broadcast — Heart Beat" }, { "code": null, "e": 3244, "s": 3231, "text": "Acceleration" }, { "code": null, "e": 3263, "s": 3244, "text": "Sensor memory read" }, { "code": null, "e": 3273, "s": 3263, "text": "Device ID" }, { "code": null, "e": 3559, "s": 3273, "text": "Similar to Polar H10, this model is a chest strap Heart Rate Sensor but without the ECG raw data broadcasting, capabilities and therefore is not eligible for the purpose of live ECG visualization in this tutorial. Following are its capabilities as listed on the official Polar H9 page." }, { "code": null, "e": 3572, "s": 3559, "text": "RR intervals" }, { "code": null, "e": 3606, "s": 3572, "text": "Heart rate broadcast — Heart Beat" }, { "code": null, "e": 3616, "s": 3606, "text": "Device ID" }, { "code": null, "e": 3802, "s": 3616, "text": "The data-format and types are different for different devices produced by Polar and we would be referencing the same from the official Polar documentation for the same in this tutorial:" }, { "code": null, "e": 3881, "s": 3802, "text": "Polar H10 heart rate sensor available data types(From version 3.0.35 onwards):" }, { "code": null, "e": 3960, "s": 3881, "text": "Polar H10 heart rate sensor available data types(From version 3.0.35 onwards):" }, { "code": null, "e": 3992, "s": 3960, "text": "Heart rate as beats per minute." }, { "code": null, "e": 4029, "s": 3992, "text": "RR Interval in ms and 1/1024 format." }, { "code": null, "e": 4067, "s": 4029, "text": "Electrocardiography (ECG) data in μV." }, { "code": null, "e": 4116, "s": 4067, "text": "The default epoch for the timestamp is 1.1.2000." }, { "code": null, "e": 4294, "s": 4116, "text": "Accelerometer data with sample rates of 25Hz, 50Hz, 100Hz, and 200Hz and range of 2G, 4G, and 8G (2G is sufficient if you would like to pick up respiration data from the chest)." }, { "code": null, "e": 4333, "s": 4294, "text": "Axis specific acceleration data in mG." }, { "code": null, "e": 4424, "s": 4333, "text": "Recording supports RR, HR with one-second sample time, or HR with five-second sample time." }, { "code": null, "e": 4564, "s": 4424, "text": "List, read, and remove for stored internal recording (sensor supports only one recording at the time). — Source: Official Polar Github repo" }, { "code": null, "e": 4653, "s": 4564, "text": "2. Polar OH1 Optical heart rate sensor available data types(From version 2.0.8 onwards):" }, { "code": null, "e": 4775, "s": 4653, "text": "The Polar OH1 Optical heart rate sensor is a rechargeable device that measures the user’s heart rate with LED technology." }, { "code": null, "e": 4807, "s": 4775, "text": "Heart rate as beats per minute." }, { "code": null, "e": 4842, "s": 4807, "text": "Photoplethysmography (PPG) values." }, { "code": null, "e": 4945, "s": 4842, "text": "PP interval (milliseconds) representing cardiac pulse-to-pulse interval extracted from the PPG signal." }, { "code": null, "e": 5010, "s": 4945, "text": "Accelerometer data with a sample rate of 50Hz and a range of 8G." }, { "code": null, "e": 5049, "s": 5010, "text": "Axis specific acceleration data in mG." }, { "code": null, "e": 5210, "s": 5049, "text": "List, read, and remove stored exercise. Recording of exercise requires that the sensor is registered to Polar Flow account. — Source: Official Polar Github repo" }, { "code": null, "e": 5570, "s": 5210, "text": "A Python-based application for visualizing ECG with Polar-H10 tracker in real-time is available here. The communication with the Polar device is via a Bluetooth service protocol, knows as GATT (Generic Attribute Profile). It defines the way that two Bluetooth Low Energy devices transfer data back and forth using concepts called Services and Characteristics." }, { "code": null, "e": 6035, "s": 5570, "text": "Furthermore, along with the GATT protocol, a special protocol — Heart Rate GATT Service Protocol that the device manufacturer follows to allow users to obtain specific responses such as Hear Beat, Raw ECG data, battery level, etc. via an API would be used in this tutorial. For each of these features such as Heart Beat, ECG, battery level, etc. we will use predefined UUID (Universal Unique Identifier) mapping and write it on the device to obtain real-time data." }, { "code": null, "e": 6055, "s": 6035, "text": "Let’s get started ❤" }, { "code": null, "e": 6202, "s": 6055, "text": "We will use the Bleak library for the Bluetooth Low Energy (BLE) connection. And also Asyncio for the asynchronous programming of the application." }, { "code": null, "e": 6402, "s": 6202, "text": "import asyncioimport mathimport osimport signalimport sysimport timeimport pandas as pdfrom bleak import BleakClientfrom bleak.uuids import uuid16_dictimport matplotlib.pyplot as pltimport matplotlib" }, { "code": null, "e": 6499, "s": 6402, "text": "We will further define the UUID’s for all the features we want to extract from the Polar device:" }, { "code": null, "e": 7870, "s": 6499, "text": "\"\"\" Predefined UUID (Universal Unique Identifier) mapping are based on Heart Rate GATT service Protocol that mostFitness/Heart Rate device manufacturer follow (Polar H10 in this case) to obtain a specific response input fromthe device acting as an API \"\"\"## UUID mappinguuid16_dict = {v: k for k, v in uuid16_dict.items()}## This is the device MAC ID, please update with your device IDADDRESS = \"D4:52:48:88:EA:04\"## UUID for model number ##MODEL_NBR_UUID = \"0000{0:x}-0000-1000-8000-00805f9b34fb\".format(uuid16_dict.get(\"Model Number String\"))## UUID for manufacturer name ##MANUFACTURER_NAME_UUID = \"0000{0:x}-0000-1000-8000-00805f9b34fb\".format(uuid16_dict.get(\"Manufacturer Name String\"))## UUID for battery level ##BATTERY_LEVEL_UUID = \"0000{0:x}-0000-1000-8000-00805f9b34fb\".format(uuid16_dict.get(\"Battery Level\"))## UUID for connection establsihment with device ##PMD_SERVICE = \"FB005C80-02E7-F387-1CAD-8ACD2D8DF0C8\"## UUID for Request of stream settings ##PMD_CONTROL = \"FB005C81-02E7-F387-1CAD-8ACD2D8DF0C8\"## UUID for Request of start stream ##PMD_DATA = \"FB005C82-02E7-F387-1CAD-8ACD2D8DF0C8\"## UUID for Request of ECG Stream ##ECG_WRITE = bytearray([0x02, 0x00, 0x00, 0x01, 0x82, 0x00, 0x01, 0x01, 0x0E, 0x00])## For Plolar H10 sampling frequency ##ECG_SAMPLING_FREQ = 130## Resource allocation for data collectionecg_session_data = []ecg_session_time = []" }, { "code": null, "e": 8079, "s": 7870, "text": "The data from the Polar device is received as a stream and in hexadecimal bytes and we would require to decode and build a streaming service for the same in decimal bytes. The following functions do the same:" }, { "code": null, "e": 8804, "s": 8079, "text": "def data_conv(sender, data): if data[0] == 0x00: timestamp = convert_to_unsigned_long(data, 1, 8) step = 3 samples = data[10:] offset = 0 while offset < len(samples): ecg = convert_array_to_signed_int(samples, offset, step) offset += step ecg_session_data.extend([ecg]) ecg_session_time.extend([timestamp])def convert_array_to_signed_int(data, offset, length): return int.from_bytes(bytearray(data[offset : offset + length]), byteorder=\"little\", signed=True,)def convert_to_unsigned_long(data, offset, length): return int.from_bytes(bytearray(data[offset : offset + length]), byteorder=\"little\", signed=False,)" }, { "code": null, "e": 9184, "s": 8804, "text": "Now comes the last bit to write an async method that would write and assemble all necessary UUID’s on the device and open the ECG stream from Polar. This is a fairly simple task, but a lengthy one, and it would be convenient for the readers here to direct you to my Github repo for a complete working application. On running the main.py, one could replicate the plot shown below." }, { "code": null, "e": 9410, "s": 9184, "text": "Building a live data-stream and filtering signals for Polar devices are vital in building real-time biofeedback applications and are fairly simple tasks with a little time and sufficient documentation. Luckily we have both !!" }, { "code": null, "e": 9483, "s": 9410, "text": "How to create a real-time data-stream with Polar devices — Accelerometer" }, { "code": null, "e": 9548, "s": 9483, "text": "How to create a real-time data-stream with OpenBCI devices — ECG" }, { "code": null, "e": 9619, "s": 9548, "text": "Getting the beat right !! — Processing ECG data with band-pass filters" }, { "code": null, "e": 9751, "s": 9619, "text": "Special thanks to my very good friend Deepesh for helping me develop the code and his enthusiasm towards helping others selflessly." } ]
Trapping Rain Water in Python
Suppose we have an array of n non-negative integers. These are representing an elevation map where the width of each bar is 1, we have to compute how much water it is able to trap after raining. So the map will be like − Here we can see there are 6 blue boxes, so the output will be 6. To solve this, we will follow these steps − Define a stack st, water := 0 and i := 0 Define a stack st, water := 0 and i := 0 while i < size of heightif is stack is empty or height[stack top] >= height[i], then push i into stack, increase i by 1otherwisex := stack top element, delete top from stackif stack is not empty, thentemp := min of height[stack top element] and height[i]dest := i – stack top element – 1water := water + dist * (temp – height[x]) while i < size of height if is stack is empty or height[stack top] >= height[i], then push i into stack, increase i by 1 if is stack is empty or height[stack top] >= height[i], then push i into stack, increase i by 1 otherwisex := stack top element, delete top from stackif stack is not empty, thentemp := min of height[stack top element] and height[i]dest := i – stack top element – 1water := water + dist * (temp – height[x]) otherwise x := stack top element, delete top from stack x := stack top element, delete top from stack if stack is not empty, thentemp := min of height[stack top element] and height[i]dest := i – stack top element – 1water := water + dist * (temp – height[x]) if stack is not empty, then temp := min of height[stack top element] and height[i] temp := min of height[stack top element] and height[i] dest := i – stack top element – 1 dest := i – stack top element – 1 water := water + dist * (temp – height[x]) water := water + dist * (temp – height[x]) return water return water Let us see the following implementation to get a better understanding − Live Demo class Solution(object): def trap(self, height): stack = [] water = 0 i=0 while i<len(height): if len(stack) == 0 or height[stack[-1]]>=height[i]: stack.append(i) i+=1 else: x = stack[-1] stack.pop() if len(stack) != 0: temp = min(height[stack[-1]],height[i]) dist = i - stack[-1]-1 water += dist*(temp - height[x]) return water ob = Solution() print(ob.trap([0,1,0,2,1,0,1,3,2,1,2,1])) [0,1,0,2,1,0,1,3,2,1,2,1] 6
[ { "code": null, "e": 1283, "s": 1062, "text": "Suppose we have an array of n non-negative integers. These are representing an elevation map where the width of each bar is 1, we have to compute how much water it is able to trap after raining. So the map will be like −" }, { "code": null, "e": 1348, "s": 1283, "text": "Here we can see there are 6 blue boxes, so the output will be 6." }, { "code": null, "e": 1392, "s": 1348, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1433, "s": 1392, "text": "Define a stack st, water := 0 and i := 0" }, { "code": null, "e": 1474, "s": 1433, "text": "Define a stack st, water := 0 and i := 0" }, { "code": null, "e": 1804, "s": 1474, "text": "while i < size of heightif is stack is empty or height[stack top] >= height[i], then push i into stack,\nincrease i by 1otherwisex := stack top element, delete top from stackif stack is not empty, thentemp := min of height[stack top element] and height[i]dest := i – stack top element – 1water := water + dist * (temp – height[x])" }, { "code": null, "e": 1829, "s": 1804, "text": "while i < size of height" }, { "code": null, "e": 1925, "s": 1829, "text": "if is stack is empty or height[stack top] >= height[i], then push i into stack,\nincrease i by 1" }, { "code": null, "e": 2021, "s": 1925, "text": "if is stack is empty or height[stack top] >= height[i], then push i into stack,\nincrease i by 1" }, { "code": null, "e": 2232, "s": 2021, "text": "otherwisex := stack top element, delete top from stackif stack is not empty, thentemp := min of height[stack top element] and height[i]dest := i – stack top element – 1water := water + dist * (temp – height[x])" }, { "code": null, "e": 2242, "s": 2232, "text": "otherwise" }, { "code": null, "e": 2288, "s": 2242, "text": "x := stack top element, delete top from stack" }, { "code": null, "e": 2334, "s": 2288, "text": "x := stack top element, delete top from stack" }, { "code": null, "e": 2491, "s": 2334, "text": "if stack is not empty, thentemp := min of height[stack top element] and height[i]dest := i – stack top element – 1water := water + dist * (temp – height[x])" }, { "code": null, "e": 2519, "s": 2491, "text": "if stack is not empty, then" }, { "code": null, "e": 2574, "s": 2519, "text": "temp := min of height[stack top element] and height[i]" }, { "code": null, "e": 2629, "s": 2574, "text": "temp := min of height[stack top element] and height[i]" }, { "code": null, "e": 2663, "s": 2629, "text": "dest := i – stack top element – 1" }, { "code": null, "e": 2697, "s": 2663, "text": "dest := i – stack top element – 1" }, { "code": null, "e": 2740, "s": 2697, "text": "water := water + dist * (temp – height[x])" }, { "code": null, "e": 2783, "s": 2740, "text": "water := water + dist * (temp – height[x])" }, { "code": null, "e": 2796, "s": 2783, "text": "return water" }, { "code": null, "e": 2809, "s": 2796, "text": "return water" }, { "code": null, "e": 2881, "s": 2809, "text": "Let us see the following implementation to get a better understanding −" }, { "code": null, "e": 2892, "s": 2881, "text": " Live Demo" }, { "code": null, "e": 3434, "s": 2892, "text": "class Solution(object):\n def trap(self, height):\n stack = []\n water = 0\n i=0\n while i<len(height):\n if len(stack) == 0 or height[stack[-1]]>=height[i]:\n stack.append(i)\n i+=1\n else:\n x = stack[-1]\n stack.pop()\n if len(stack) != 0:\n temp = min(height[stack[-1]],height[i])\n dist = i - stack[-1]-1\n water += dist*(temp - height[x])\n return water\nob = Solution()\nprint(ob.trap([0,1,0,2,1,0,1,3,2,1,2,1]))" }, { "code": null, "e": 3460, "s": 3434, "text": "[0,1,0,2,1,0,1,3,2,1,2,1]" }, { "code": null, "e": 3462, "s": 3460, "text": "6" } ]
Python | Filter tuples according to list element presence - GeeksforGeeks
11 Nov, 2019 Sometimes, while working with records, we can have a problem in which we have to filter all the tuples from a list of tuples, which contains atleast one element from a list. This can have application in many domains working with data. Let’s discuss certain ways in which this task can be performed. Method #1 : Using list comprehensionUsing list comprehension is brute force method to perform this task in a shorthand. In this, we just check for each tuple and check if it contains any element from the target list. # Python3 code to demonstrate working of# Filter tuples according to list element presence# using list comprehension # initialize list of tupletest_list = [(1, 4, 6), (5, 8), (2, 9), (1, 10)] # initialize target list tar_list = [6, 10] # printing original tuples listprint("The original list : " + str(test_list)) # Filter tuples according to list element presence# using list comprehensionres = [tup for tup in test_list if any(i in tup for i in tar_list)] # printing resultprint("Filtered tuple from list are : " + str(res)) The original list : [(1, 4, 6), (5, 8), (2, 9), (1, 10)] Filtered tuple from list are : [(1, 4, 6), (1, 10)] Method #2 : Using set() + list comprehensionAbove approach can be optimized by converting the containers to a set() reducing duplicates and performing a & operation to fetch the desired records. # Python3 code to demonstrate working of# Filter tuples according to list element presence# using set() + list comprehension # initialize list of tupletest_list = [(1, 4, 6), (5, 8), (2, 9), (1, 10)] # initialize target list tar_list = [6, 10] # printing original tuples listprint("The original list : " + str(test_list)) # Filter tuples according to list element presence# using set() + list comprehensionres = [tup for tup in test_list if (set(tar_list) & set(tup))] # printing resultprint("Filtered tuple from list are : " + str(res)) The original list : [(1, 4, 6), (5, 8), (2, 9), (1, 10)] Filtered tuple from list are : [(1, 4, 6), (1, 10)] 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. 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 Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python program to check whether a number is Prime or not
[ { "code": null, "e": 24491, "s": 24463, "text": "\n11 Nov, 2019" }, { "code": null, "e": 24790, "s": 24491, "text": "Sometimes, while working with records, we can have a problem in which we have to filter all the tuples from a list of tuples, which contains atleast one element from a list. This can have application in many domains working with data. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 25007, "s": 24790, "text": "Method #1 : Using list comprehensionUsing list comprehension is brute force method to perform this task in a shorthand. In this, we just check for each tuple and check if it contains any element from the target list." }, { "code": "# Python3 code to demonstrate working of# Filter tuples according to list element presence# using list comprehension # initialize list of tupletest_list = [(1, 4, 6), (5, 8), (2, 9), (1, 10)] # initialize target list tar_list = [6, 10] # printing original tuples listprint(\"The original list : \" + str(test_list)) # Filter tuples according to list element presence# using list comprehensionres = [tup for tup in test_list if any(i in tup for i in tar_list)] # printing resultprint(\"Filtered tuple from list are : \" + str(res))", "e": 25539, "s": 25007, "text": null }, { "code": null, "e": 25649, "s": 25539, "text": "The original list : [(1, 4, 6), (5, 8), (2, 9), (1, 10)]\nFiltered tuple from list are : [(1, 4, 6), (1, 10)]\n" }, { "code": null, "e": 25846, "s": 25651, "text": "Method #2 : Using set() + list comprehensionAbove approach can be optimized by converting the containers to a set() reducing duplicates and performing a & operation to fetch the desired records." }, { "code": "# Python3 code to demonstrate working of# Filter tuples according to list element presence# using set() + list comprehension # initialize list of tupletest_list = [(1, 4, 6), (5, 8), (2, 9), (1, 10)] # initialize target list tar_list = [6, 10] # printing original tuples listprint(\"The original list : \" + str(test_list)) # Filter tuples according to list element presence# using set() + list comprehensionres = [tup for tup in test_list if (set(tar_list) & set(tup))] # printing resultprint(\"Filtered tuple from list are : \" + str(res))", "e": 26389, "s": 25846, "text": null }, { "code": null, "e": 26499, "s": 26389, "text": "The original list : [(1, 4, 6), (5, 8), (2, 9), (1, 10)]\nFiltered tuple from list are : [(1, 4, 6), (1, 10)]\n" }, { "code": null, "e": 26520, "s": 26499, "text": "Python list-programs" }, { "code": null, "e": 26542, "s": 26520, "text": "Python tuple-programs" }, { "code": null, "e": 26549, "s": 26542, "text": "Python" }, { "code": null, "e": 26565, "s": 26549, "text": "Python Programs" }, { "code": null, "e": 26663, "s": 26565, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26672, "s": 26663, "text": "Comments" }, { "code": null, "e": 26685, "s": 26672, "text": "Old Comments" }, { "code": null, "e": 26703, "s": 26685, "text": "Python Dictionary" }, { "code": null, "e": 26738, "s": 26703, "text": "Read a file line by line in Python" }, { "code": null, "e": 26760, "s": 26738, "text": "Enumerate() in Python" }, { "code": null, "e": 26792, "s": 26760, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26822, "s": 26792, "text": "Iterate over a list in Python" }, { "code": null, "e": 26865, "s": 26822, "text": "Python program to convert a list to string" }, { "code": null, "e": 26887, "s": 26865, "text": "Defaultdict in Python" }, { "code": null, "e": 26926, "s": 26887, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26972, "s": 26926, "text": "Python | Split string into list of characters" } ]
How to store a Sparse Vector efficiently?
07 Jul, 2021 A sparse vector is a vector that has a large number of zeros so it takes unwanted space to store these zeroes.The task is to store a given sparse vector efficiently without storing the zeros. Examples: Input: vector = { 2, 0, 0, 0, 0, 3, 0, 4, 0, 0, 0, 1, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 0, 5 } Output: {2, 3, 4, 1, 5, 4, 2, 3, 1, 5} Approach: To store the sparse vector efficiently, a vector of pairs can be used. The First element of pair will be the index of sparse vector element(which is non-zero) and the second element will be the actual element. Below is the implementation of the above approach: C++ Java Python3 Javascript // C++ program to store sparse vectors// with the help of vector of pair #include <bits/stdc++.h>using namespace std; // Store the sparse vector// as a vector of pairsvector<pair<int, int> >convertSparseVector(vector<int> v){ vector<pair<int, int> > res; for (int i = 0; i < v.size(); i++) { if (v[i] != 0) { res.push_back(make_pair(i, v[i])); } } return res;} // Print the vector of pairsvoid print(vector<pair<int, int> > res){ for (auto x : res) { cout << "index: " << x.first << " -> value: " << x.second << endl; }} // Driver functionint main(){ // Get the sparse vector vector<int> v{ 2, 0, 0, 0, 0, 3, 0, 4, 0, 0, 0, 1, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 0, 5 }; // Get the stored vector of pairs vector<pair<int, int> > res = convertSparseVector(v); // Print the vector of pairs print(res); return 0;} // Java program to store sparse vectors// with the help of ArrayList of pairimport java.util.ArrayList; class GFG{ static class Pair{ int first, second; public Pair(int first, int second) { this.first = first; this.second = second; }} // Store the sparse ArrayList// as a ArrayList of pairsstatic ArrayList<Pair> convertSparseVector(int[] v){ ArrayList<Pair> res = new ArrayList<>(); for(int i = 0; i < v.length; i++) { if (v[i] != 0) { res.add(new Pair(i, v[i])); } } return res;} // Print the ArrayList of pairsstatic void print(ArrayList<Pair> res){ for(Pair x : res) { System.out.printf("index: %d -> value: %d\n", x.first, x.second); }} // Driver codepublic static void main(String[] args){ // Get the sparse ArrayList int[] v = { 2, 0, 0, 0, 0, 3, 0, 4, 0, 0, 0, 1, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 0, 5 }; // Get the stored ArrayList of pairs ArrayList<Pair> res = convertSparseVector(v); // Print the ArrayList of pairs print(res);}} // This code is contributed by sanjeev2552 # Python3 program to store sparse vectors# with the help of vector of pair # Store the sparse vector# as a vector of pairsdef convertSparseVector(v): res = [] for i in range(len(v)): if (v[i] != 0): res.append([i, v[i]]) return res # Print the vector of pairsdef printf(res): for x in res: print("index:", x[0], " -> value:", x[1]) # Driver Codeif __name__ == '__main__': # Get the sparse vector v = [2, 0, 0, 0, 0, 3, 0, 4, 0, 0, 0, 1, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 0, 5] # Get the stored vector of pairs res = convertSparseVector(v) # Print the vector of pairs printf(res) # This code is contributed by Surendra_Gangwar <script> // JavaScript program to store sparse vectors// with the help of vector of pair // Store the sparse vector// as a vector of pairsfunction convertSparseVector(v) { let res = []; for (let i = 0; i < v.length; i++) { if (v[i] != 0) { res.push([i, v[i]]); } } return res;} // Print the vector of pairsfunction print(res) { for (let x of res) { document.write("index: " + x[0] + " -> value: " + x[1] + "<br>"); }} // Driver function // Get the sparse vectorlet v = [2, 0, 0, 0, 0, 3, 0, 4, 0, 0, 0, 1, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 0, 5]; // Get the stored vector of pairslet res = convertSparseVector(v); // Print the vector of pairsprint(res); // This code is contributed by _saurabh_jaiswal </script> index: 0 -> value: 2 index: 5 -> value: 3 index: 7 -> value: 4 index: 11 -> value: 1 index: 12 -> value: 5 index: 22 -> value: 4 index: 26 -> value: 2 index: 33 -> value: 3 index: 37 -> value: 1 index: 42 -> value: 5 SURENDRA_GANGWAR sanjeev2552 _saurabh_jaiswal surindertarika1234 cpp-vector Arrays Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Window Sliding Technique Search, insert and delete in an unsorted array What is Data Structure: Types, Classifications and Applications Next Greater Element Chocolate Distribution Problem Find duplicates in O(n) time and O(1) extra space | Set 1 Find subarray with given sum | Set 1 (Nonnegative Numbers) Move all negative numbers to beginning and positive to end with constant extra space Count pairs with given sum
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Jul, 2021" }, { "code": null, "e": 220, "s": 28, "text": "A sparse vector is a vector that has a large number of zeros so it takes unwanted space to store these zeroes.The task is to store a given sparse vector efficiently without storing the zeros." }, { "code": null, "e": 232, "s": 220, "text": "Examples: " }, { "code": null, "e": 580, "s": 232, "text": "Input: vector = { 2, 0, 0, 0, 0, \n 3, 0, 4, 0, 0, \n 0, 1, 5, 0, 0, \n 0, 0, 0, 0, 0, \n 0, 0, 4, 0, 0, \n 0, 2, 0, 0, 0, \n 0, 0, 0, 3, 0, \n 0, 0, 1, 0, 0, \n 0, 0, 5 }\nOutput: {2, 3, 4, 1, 5, \n 4, 2, 3, 1, 5}" }, { "code": null, "e": 801, "s": 580, "text": "Approach: To store the sparse vector efficiently, a vector of pairs can be used. The First element of pair will be the index of sparse vector element(which is non-zero) and the second element will be the actual element. " }, { "code": null, "e": 853, "s": 801, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 857, "s": 853, "text": "C++" }, { "code": null, "e": 862, "s": 857, "text": "Java" }, { "code": null, "e": 870, "s": 862, "text": "Python3" }, { "code": null, "e": 881, "s": 870, "text": "Javascript" }, { "code": "// C++ program to store sparse vectors// with the help of vector of pair #include <bits/stdc++.h>using namespace std; // Store the sparse vector// as a vector of pairsvector<pair<int, int> >convertSparseVector(vector<int> v){ vector<pair<int, int> > res; for (int i = 0; i < v.size(); i++) { if (v[i] != 0) { res.push_back(make_pair(i, v[i])); } } return res;} // Print the vector of pairsvoid print(vector<pair<int, int> > res){ for (auto x : res) { cout << \"index: \" << x.first << \" -> value: \" << x.second << endl; }} // Driver functionint main(){ // Get the sparse vector vector<int> v{ 2, 0, 0, 0, 0, 3, 0, 4, 0, 0, 0, 1, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 0, 5 }; // Get the stored vector of pairs vector<pair<int, int> > res = convertSparseVector(v); // Print the vector of pairs print(res); return 0;}", "e": 1994, "s": 881, "text": null }, { "code": "// Java program to store sparse vectors// with the help of ArrayList of pairimport java.util.ArrayList; class GFG{ static class Pair{ int first, second; public Pair(int first, int second) { this.first = first; this.second = second; }} // Store the sparse ArrayList// as a ArrayList of pairsstatic ArrayList<Pair> convertSparseVector(int[] v){ ArrayList<Pair> res = new ArrayList<>(); for(int i = 0; i < v.length; i++) { if (v[i] != 0) { res.add(new Pair(i, v[i])); } } return res;} // Print the ArrayList of pairsstatic void print(ArrayList<Pair> res){ for(Pair x : res) { System.out.printf(\"index: %d -> value: %d\\n\", x.first, x.second); }} // Driver codepublic static void main(String[] args){ // Get the sparse ArrayList int[] v = { 2, 0, 0, 0, 0, 3, 0, 4, 0, 0, 0, 1, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 0, 5 }; // Get the stored ArrayList of pairs ArrayList<Pair> res = convertSparseVector(v); // Print the ArrayList of pairs print(res);}} // This code is contributed by sanjeev2552", "e": 3297, "s": 1994, "text": null }, { "code": "# Python3 program to store sparse vectors# with the help of vector of pair # Store the sparse vector# as a vector of pairsdef convertSparseVector(v): res = [] for i in range(len(v)): if (v[i] != 0): res.append([i, v[i]]) return res # Print the vector of pairsdef printf(res): for x in res: print(\"index:\", x[0], \" -> value:\", x[1]) # Driver Codeif __name__ == '__main__': # Get the sparse vector v = [2, 0, 0, 0, 0, 3, 0, 4, 0, 0, 0, 1, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 0, 5] # Get the stored vector of pairs res = convertSparseVector(v) # Print the vector of pairs printf(res) # This code is contributed by Surendra_Gangwar", "e": 4116, "s": 3297, "text": null }, { "code": "<script> // JavaScript program to store sparse vectors// with the help of vector of pair // Store the sparse vector// as a vector of pairsfunction convertSparseVector(v) { let res = []; for (let i = 0; i < v.length; i++) { if (v[i] != 0) { res.push([i, v[i]]); } } return res;} // Print the vector of pairsfunction print(res) { for (let x of res) { document.write(\"index: \" + x[0] + \" -> value: \" + x[1] + \"<br>\"); }} // Driver function // Get the sparse vectorlet v = [2, 0, 0, 0, 0, 3, 0, 4, 0, 0, 0, 1, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 0, 5]; // Get the stored vector of pairslet res = convertSparseVector(v); // Print the vector of pairsprint(res); // This code is contributed by _saurabh_jaiswal </script>", "e": 4964, "s": 4116, "text": null }, { "code": null, "e": 5181, "s": 4964, "text": "index: 0 -> value: 2\nindex: 5 -> value: 3\nindex: 7 -> value: 4\nindex: 11 -> value: 1\nindex: 12 -> value: 5\nindex: 22 -> value: 4\nindex: 26 -> value: 2\nindex: 33 -> value: 3\nindex: 37 -> value: 1\nindex: 42 -> value: 5" }, { "code": null, "e": 5200, "s": 5183, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 5212, "s": 5200, "text": "sanjeev2552" }, { "code": null, "e": 5229, "s": 5212, "text": "_saurabh_jaiswal" }, { "code": null, "e": 5248, "s": 5229, "text": "surindertarika1234" }, { "code": null, "e": 5259, "s": 5248, "text": "cpp-vector" }, { "code": null, "e": 5266, "s": 5259, "text": "Arrays" }, { "code": null, "e": 5273, "s": 5266, "text": "Arrays" }, { "code": null, "e": 5371, "s": 5273, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5403, "s": 5371, "text": "Introduction to Data Structures" }, { "code": null, "e": 5428, "s": 5403, "text": "Window Sliding Technique" }, { "code": null, "e": 5475, "s": 5428, "text": "Search, insert and delete in an unsorted array" }, { "code": null, "e": 5539, "s": 5475, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 5560, "s": 5539, "text": "Next Greater Element" }, { "code": null, "e": 5591, "s": 5560, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 5649, "s": 5591, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 5708, "s": 5649, "text": "Find subarray with given sum | Set 1 (Nonnegative Numbers)" }, { "code": null, "e": 5793, "s": 5708, "text": "Move all negative numbers to beginning and positive to end with constant extra space" } ]
JavaFX | TextInputDialog
24 Oct, 2019 TextInputDialog is a part of JavaFX library. TextInputDialog is a dialog that allows the user to enter a text, and the dialog contains a header text, a TextField and confirmation buttons. Constructor of the TextInputDialog class are: TextInputDialog(): creates a text input dialog with no initial text.TextInputDialog(String txt): creates a text input dialog with initial text txt. TextInputDialog(): creates a text input dialog with no initial text. TextInputDialog(String txt): creates a text input dialog with initial text txt. Commonly used methods: Below programs illustrate the TextInputDialog class: Program to create a TextInputDialog and add it to the stage: This program creates a TextInputDialog with an initial text and a header text. The header text is set using setHeaderText() function. Button is indicated by the name d and text input dialog will have name td. The button will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a tile pane is created, on which addChildren() method is called to attach the button inside the scene. Finally, the show() method is called to display the final results. The TextInputDialog will be shown on the click of the button.// Java Program to create a text input// dialog and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.*;import javafx.stage.Stage;import javafx.scene.control.Alert.AlertType;import java.time.LocalDate;public class TextInputDialog_1 extends Application { // launch the application public void start(Stage s) { // set title for the stage s.setTitle("creating textInput dialog"); // create a tile pane TilePane r = new TilePane(); // create a text input dialog TextInputDialog td = new TextInputDialog("enter any text"); // setHeaderText td.setHeaderText("enter your name"); // create a button Button d = new Button("click"); // create a event handler EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { // show the text input dialog td.show(); } }; // set on action of event d.setOnAction(event); // add button and label r.getChildren().add(d); // create a scene Scene sc = new Scene(r, 500, 300); // set the scene s.setScene(sc); s.show(); } public static void main(String args[]) { // launch the application launch(args); }}Output:Program to create a TextInputDialog and add a label to display the text entered: This program creates a TextInputDialog (td). Button indicated by the name d and TextInputDialog will have name td. The button will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a tile pane is created, on which addChildren() method is called to attach the button inside the scene. Finally, the show() method is called to display the final results.when the button will be clicked the text input dialog will be shown. A label named l will be created that will be added to the scene which will show the text that the user inputs in the dialog.// Java Program to create a text input dialog// and add a label to display the text enteredimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.*;import javafx.stage.Stage;import javafx.scene.control.Alert.AlertType;import java.time.LocalDate;public class TextInputDialog_2 extends Application { // launch the application public void start(Stage s) { // set title for the stage s.setTitle("creating textInput dialog"); // create a tile pane TilePane r = new TilePane(); // create a label to show the input in text dialog Label l = new Label("no text input"); // create a text input dialog TextInputDialog td = new TextInputDialog(); // create a button Button d = new Button("click"); // create a event handler EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { // show the text input dialog td.showAndWait(); // set the text of the label l.setText(td.getEditor().getText()); } }; // set on action of event d.setOnAction(event); // add button and label r.getChildren().add(d); r.getChildren().add(l); // create a scene Scene sc = new Scene(r, 500, 300); // set the scene s.setScene(sc); s.show(); } public static void main(String args[]) { // launch the application launch(args); }}Output:Note : The above programs might not run in an online IDE please use an offline IDE.Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/TextInputDialog.htmlMy Personal Notes arrow_drop_upSave Program to create a TextInputDialog and add it to the stage: This program creates a TextInputDialog with an initial text and a header text. The header text is set using setHeaderText() function. Button is indicated by the name d and text input dialog will have name td. The button will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a tile pane is created, on which addChildren() method is called to attach the button inside the scene. Finally, the show() method is called to display the final results. The TextInputDialog will be shown on the click of the button.// Java Program to create a text input// dialog and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.*;import javafx.stage.Stage;import javafx.scene.control.Alert.AlertType;import java.time.LocalDate;public class TextInputDialog_1 extends Application { // launch the application public void start(Stage s) { // set title for the stage s.setTitle("creating textInput dialog"); // create a tile pane TilePane r = new TilePane(); // create a text input dialog TextInputDialog td = new TextInputDialog("enter any text"); // setHeaderText td.setHeaderText("enter your name"); // create a button Button d = new Button("click"); // create a event handler EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { // show the text input dialog td.show(); } }; // set on action of event d.setOnAction(event); // add button and label r.getChildren().add(d); // create a scene Scene sc = new Scene(r, 500, 300); // set the scene s.setScene(sc); s.show(); } public static void main(String args[]) { // launch the application launch(args); }}Output: // Java Program to create a text input// dialog and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.*;import javafx.stage.Stage;import javafx.scene.control.Alert.AlertType;import java.time.LocalDate;public class TextInputDialog_1 extends Application { // launch the application public void start(Stage s) { // set title for the stage s.setTitle("creating textInput dialog"); // create a tile pane TilePane r = new TilePane(); // create a text input dialog TextInputDialog td = new TextInputDialog("enter any text"); // setHeaderText td.setHeaderText("enter your name"); // create a button Button d = new Button("click"); // create a event handler EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { // show the text input dialog td.show(); } }; // set on action of event d.setOnAction(event); // add button and label r.getChildren().add(d); // create a scene Scene sc = new Scene(r, 500, 300); // set the scene s.setScene(sc); s.show(); } public static void main(String args[]) { // launch the application launch(args); }} Output: Program to create a TextInputDialog and add a label to display the text entered: This program creates a TextInputDialog (td). Button indicated by the name d and TextInputDialog will have name td. The button will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a tile pane is created, on which addChildren() method is called to attach the button inside the scene. Finally, the show() method is called to display the final results.when the button will be clicked the text input dialog will be shown. A label named l will be created that will be added to the scene which will show the text that the user inputs in the dialog.// Java Program to create a text input dialog// and add a label to display the text enteredimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.*;import javafx.stage.Stage;import javafx.scene.control.Alert.AlertType;import java.time.LocalDate;public class TextInputDialog_2 extends Application { // launch the application public void start(Stage s) { // set title for the stage s.setTitle("creating textInput dialog"); // create a tile pane TilePane r = new TilePane(); // create a label to show the input in text dialog Label l = new Label("no text input"); // create a text input dialog TextInputDialog td = new TextInputDialog(); // create a button Button d = new Button("click"); // create a event handler EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { // show the text input dialog td.showAndWait(); // set the text of the label l.setText(td.getEditor().getText()); } }; // set on action of event d.setOnAction(event); // add button and label r.getChildren().add(d); r.getChildren().add(l); // create a scene Scene sc = new Scene(r, 500, 300); // set the scene s.setScene(sc); s.show(); } public static void main(String args[]) { // launch the application launch(args); }}Output: // Java Program to create a text input dialog// and add a label to display the text enteredimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.*;import javafx.stage.Stage;import javafx.scene.control.Alert.AlertType;import java.time.LocalDate;public class TextInputDialog_2 extends Application { // launch the application public void start(Stage s) { // set title for the stage s.setTitle("creating textInput dialog"); // create a tile pane TilePane r = new TilePane(); // create a label to show the input in text dialog Label l = new Label("no text input"); // create a text input dialog TextInputDialog td = new TextInputDialog(); // create a button Button d = new Button("click"); // create a event handler EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { // show the text input dialog td.showAndWait(); // set the text of the label l.setText(td.getEditor().getText()); } }; // set on action of event d.setOnAction(event); // add button and label r.getChildren().add(d); r.getChildren().add(l); // create a scene Scene sc = new Scene(r, 500, 300); // set the scene s.setScene(sc); s.show(); } public static void main(String args[]) { // launch the application launch(args); }} Output: Note : The above programs might not run in an online IDE please use an offline IDE. Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/TextInputDialog.html ManasChhabra2 JavaFX Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Interfaces in Java HashMap in Java with Examples Stream In Java Collections in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java Stack Class in Java Introduction to Java Initialize an ArrayList in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n24 Oct, 2019" }, { "code": null, "e": 242, "s": 54, "text": "TextInputDialog is a part of JavaFX library. TextInputDialog is a dialog that allows the user to enter a text, and the dialog contains a header text, a TextField and confirmation buttons." }, { "code": null, "e": 288, "s": 242, "text": "Constructor of the TextInputDialog class are:" }, { "code": null, "e": 436, "s": 288, "text": "TextInputDialog(): creates a text input dialog with no initial text.TextInputDialog(String txt): creates a text input dialog with initial text txt." }, { "code": null, "e": 505, "s": 436, "text": "TextInputDialog(): creates a text input dialog with no initial text." }, { "code": null, "e": 585, "s": 505, "text": "TextInputDialog(String txt): creates a text input dialog with initial text txt." }, { "code": null, "e": 608, "s": 585, "text": "Commonly used methods:" }, { "code": null, "e": 661, "s": 608, "text": "Below programs illustrate the TextInputDialog class:" }, { "code": null, "e": 5520, "s": 661, "text": "Program to create a TextInputDialog and add it to the stage: This program creates a TextInputDialog with an initial text and a header text. The header text is set using setHeaderText() function. Button is indicated by the name d and text input dialog will have name td. The button will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a tile pane is created, on which addChildren() method is called to attach the button inside the scene. Finally, the show() method is called to display the final results. The TextInputDialog will be shown on the click of the button.// Java Program to create a text input// dialog and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.*;import javafx.stage.Stage;import javafx.scene.control.Alert.AlertType;import java.time.LocalDate;public class TextInputDialog_1 extends Application { // launch the application public void start(Stage s) { // set title for the stage s.setTitle(\"creating textInput dialog\"); // create a tile pane TilePane r = new TilePane(); // create a text input dialog TextInputDialog td = new TextInputDialog(\"enter any text\"); // setHeaderText td.setHeaderText(\"enter your name\"); // create a button Button d = new Button(\"click\"); // create a event handler EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { // show the text input dialog td.show(); } }; // set on action of event d.setOnAction(event); // add button and label r.getChildren().add(d); // create a scene Scene sc = new Scene(r, 500, 300); // set the scene s.setScene(sc); s.show(); } public static void main(String args[]) { // launch the application launch(args); }}Output:Program to create a TextInputDialog and add a label to display the text entered: This program creates a TextInputDialog (td). Button indicated by the name d and TextInputDialog will have name td. The button will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a tile pane is created, on which addChildren() method is called to attach the button inside the scene. Finally, the show() method is called to display the final results.when the button will be clicked the text input dialog will be shown. A label named l will be created that will be added to the scene which will show the text that the user inputs in the dialog.// Java Program to create a text input dialog// and add a label to display the text enteredimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.*;import javafx.stage.Stage;import javafx.scene.control.Alert.AlertType;import java.time.LocalDate;public class TextInputDialog_2 extends Application { // launch the application public void start(Stage s) { // set title for the stage s.setTitle(\"creating textInput dialog\"); // create a tile pane TilePane r = new TilePane(); // create a label to show the input in text dialog Label l = new Label(\"no text input\"); // create a text input dialog TextInputDialog td = new TextInputDialog(); // create a button Button d = new Button(\"click\"); // create a event handler EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { // show the text input dialog td.showAndWait(); // set the text of the label l.setText(td.getEditor().getText()); } }; // set on action of event d.setOnAction(event); // add button and label r.getChildren().add(d); r.getChildren().add(l); // create a scene Scene sc = new Scene(r, 500, 300); // set the scene s.setScene(sc); s.show(); } public static void main(String args[]) { // launch the application launch(args); }}Output:Note : The above programs might not run in an online IDE please use an offline IDE.Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/TextInputDialog.htmlMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 7727, "s": 5520, "text": "Program to create a TextInputDialog and add it to the stage: This program creates a TextInputDialog with an initial text and a header text. The header text is set using setHeaderText() function. Button is indicated by the name d and text input dialog will have name td. The button will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a tile pane is created, on which addChildren() method is called to attach the button inside the scene. Finally, the show() method is called to display the final results. The TextInputDialog will be shown on the click of the button.// Java Program to create a text input// dialog and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.*;import javafx.stage.Stage;import javafx.scene.control.Alert.AlertType;import java.time.LocalDate;public class TextInputDialog_1 extends Application { // launch the application public void start(Stage s) { // set title for the stage s.setTitle(\"creating textInput dialog\"); // create a tile pane TilePane r = new TilePane(); // create a text input dialog TextInputDialog td = new TextInputDialog(\"enter any text\"); // setHeaderText td.setHeaderText(\"enter your name\"); // create a button Button d = new Button(\"click\"); // create a event handler EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { // show the text input dialog td.show(); } }; // set on action of event d.setOnAction(event); // add button and label r.getChildren().add(d); // create a scene Scene sc = new Scene(r, 500, 300); // set the scene s.setScene(sc); s.show(); } public static void main(String args[]) { // launch the application launch(args); }}Output:" }, { "code": "// Java Program to create a text input// dialog and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.*;import javafx.stage.Stage;import javafx.scene.control.Alert.AlertType;import java.time.LocalDate;public class TextInputDialog_1 extends Application { // launch the application public void start(Stage s) { // set title for the stage s.setTitle(\"creating textInput dialog\"); // create a tile pane TilePane r = new TilePane(); // create a text input dialog TextInputDialog td = new TextInputDialog(\"enter any text\"); // setHeaderText td.setHeaderText(\"enter your name\"); // create a button Button d = new Button(\"click\"); // create a event handler EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { // show the text input dialog td.show(); } }; // set on action of event d.setOnAction(event); // add button and label r.getChildren().add(d); // create a scene Scene sc = new Scene(r, 500, 300); // set the scene s.setScene(sc); s.show(); } public static void main(String args[]) { // launch the application launch(args); }}", "e": 9270, "s": 7727, "text": null }, { "code": null, "e": 9278, "s": 9270, "text": "Output:" }, { "code": null, "e": 11717, "s": 9278, "text": "Program to create a TextInputDialog and add a label to display the text entered: This program creates a TextInputDialog (td). Button indicated by the name d and TextInputDialog will have name td. The button will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a tile pane is created, on which addChildren() method is called to attach the button inside the scene. Finally, the show() method is called to display the final results.when the button will be clicked the text input dialog will be shown. A label named l will be created that will be added to the scene which will show the text that the user inputs in the dialog.// Java Program to create a text input dialog// and add a label to display the text enteredimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.*;import javafx.stage.Stage;import javafx.scene.control.Alert.AlertType;import java.time.LocalDate;public class TextInputDialog_2 extends Application { // launch the application public void start(Stage s) { // set title for the stage s.setTitle(\"creating textInput dialog\"); // create a tile pane TilePane r = new TilePane(); // create a label to show the input in text dialog Label l = new Label(\"no text input\"); // create a text input dialog TextInputDialog td = new TextInputDialog(); // create a button Button d = new Button(\"click\"); // create a event handler EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { // show the text input dialog td.showAndWait(); // set the text of the label l.setText(td.getEditor().getText()); } }; // set on action of event d.setOnAction(event); // add button and label r.getChildren().add(d); r.getChildren().add(l); // create a scene Scene sc = new Scene(r, 500, 300); // set the scene s.setScene(sc); s.show(); } public static void main(String args[]) { // launch the application launch(args); }}Output:" }, { "code": "// Java Program to create a text input dialog// and add a label to display the text enteredimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.*;import javafx.stage.Stage;import javafx.scene.control.Alert.AlertType;import java.time.LocalDate;public class TextInputDialog_2 extends Application { // launch the application public void start(Stage s) { // set title for the stage s.setTitle(\"creating textInput dialog\"); // create a tile pane TilePane r = new TilePane(); // create a label to show the input in text dialog Label l = new Label(\"no text input\"); // create a text input dialog TextInputDialog td = new TextInputDialog(); // create a button Button d = new Button(\"click\"); // create a event handler EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { // show the text input dialog td.showAndWait(); // set the text of the label l.setText(td.getEditor().getText()); } }; // set on action of event d.setOnAction(event); // add button and label r.getChildren().add(d); r.getChildren().add(l); // create a scene Scene sc = new Scene(r, 500, 300); // set the scene s.setScene(sc); s.show(); } public static void main(String args[]) { // launch the application launch(args); }}", "e": 13435, "s": 11717, "text": null }, { "code": null, "e": 13443, "s": 13435, "text": "Output:" }, { "code": null, "e": 13527, "s": 13443, "text": "Note : The above programs might not run in an online IDE please use an offline IDE." }, { "code": null, "e": 13624, "s": 13527, "text": "Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/TextInputDialog.html" }, { "code": null, "e": 13638, "s": 13624, "text": "ManasChhabra2" }, { "code": null, "e": 13645, "s": 13638, "text": "JavaFX" }, { "code": null, "e": 13650, "s": 13645, "text": "Java" }, { "code": null, "e": 13655, "s": 13650, "text": "Java" }, { "code": null, "e": 13753, "s": 13655, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 13772, "s": 13753, "text": "Interfaces in Java" }, { "code": null, "e": 13802, "s": 13772, "text": "HashMap in Java with Examples" }, { "code": null, "e": 13817, "s": 13802, "text": "Stream In Java" }, { "code": null, "e": 13837, "s": 13817, "text": "Collections in Java" }, { "code": null, "e": 13861, "s": 13837, "text": "Singleton Class in Java" }, { "code": null, "e": 13893, "s": 13861, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 13905, "s": 13893, "text": "Set in Java" }, { "code": null, "e": 13925, "s": 13905, "text": "Stack Class in Java" }, { "code": null, "e": 13946, "s": 13925, "text": "Introduction to Java" } ]
Add data to existing data in a MySQL Database?
You can use CONCAT() function for this. Let us first create a table − mysql> create table DemoTable ( UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY, UserName varchar(100) ); Query OK, 0 rows affected (0.43 sec) Insert records in the table using insert command − mysql> insert into DemoTable(UserName) values('John'); Query OK, 1 row affected (0.24 sec) mysql> insert into DemoTable(UserName) values('Chris'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable(UserName) values('Robert'); Query OK, 1 row affected (0.11 sec) Display all records from the table using select statement − mysql> select *from DemoTable; This will produce the following output − +--------+----------+ | UserId | UserName | +--------+----------+ | 1 | John | | 2 | Chris | | 3 | Robert | +--------+----------+ 3 rows in set (0.00 sec) Here is the query to add data to existing data in MySQL database. The UserId 1 is concatenated with the name “Smith” to the already existed name− mysql> update DemoTable set UserName=concat(UserName,' Smith') where UserId=1; Query OK, 1 row affected (0.12 sec) Rows matched: 1 Changed: 1 Warnings: 0 Let us check the table records once again − mysql> select *from DemoTable; This will produce the following output − +--------+------------+ | UserId | UserName | +--------+------------+ | 1 | John Smith | | 2 | Chris | | 3 | Robert | +--------+------------+ 3 rows in set (0.00 sec)
[ { "code": null, "e": 1132, "s": 1062, "text": "You can use CONCAT() function for this. Let us first create a table −" }, { "code": null, "e": 1286, "s": 1132, "text": "mysql> create table DemoTable\n (\n UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n UserName varchar(100)\n );\nQuery OK, 0 rows affected (0.43 sec)" }, { "code": null, "e": 1337, "s": 1286, "text": "Insert records in the table using insert command −" }, { "code": null, "e": 1613, "s": 1337, "text": "mysql> insert into DemoTable(UserName) values('John');\nQuery OK, 1 row affected (0.24 sec)\nmysql> insert into DemoTable(UserName) values('Chris');\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into DemoTable(UserName) values('Robert');\nQuery OK, 1 row affected (0.11 sec)" }, { "code": null, "e": 1673, "s": 1613, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1704, "s": 1673, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 1745, "s": 1704, "text": "This will produce the following output −" }, { "code": null, "e": 1924, "s": 1745, "text": "+--------+----------+\n| UserId | UserName |\n+--------+----------+\n| 1 | John |\n| 2 | Chris |\n| 3 | Robert |\n+--------+----------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 2070, "s": 1924, "text": "Here is the query to add data to existing data in MySQL database. The UserId 1 is concatenated with the name “Smith” to the already existed name−" }, { "code": null, "e": 2224, "s": 2070, "text": "mysql> update DemoTable\nset UserName=concat(UserName,' Smith') where UserId=1;\nQuery OK, 1 row affected (0.12 sec)\nRows matched: 1 Changed: 1 Warnings: 0" }, { "code": null, "e": 2268, "s": 2224, "text": "Let us check the table records once again −" }, { "code": null, "e": 2299, "s": 2268, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 2340, "s": 2299, "text": "This will produce the following output −" }, { "code": null, "e": 2533, "s": 2340, "text": "+--------+------------+\n| UserId | UserName |\n+--------+------------+\n| 1 | John Smith |\n| 2 | Chris |\n| 3 | Robert |\n+--------+------------+\n3 rows in set (0.00 sec)" } ]
Gradient Descent Optimizers for Neural Net Training | by Daryl Chang | Towards Data Science
co-authored with Apurva Pathak Welcome to another instalment in our Deep Learning Experiments series, where we run experiments to evaluate commonly-held assumptions about training neural networks. Our goal is to better understand the different design choices that affect model training and evaluation. To do so, we come up with questions about each design choice and then run experiments to answer them. In this article, we seek to better understand the impact of using different optimizers: How do different optimizers perform in practice? How sensitive is each optimizer to parameter choices such as learning rate or momentum? How quickly does each optimizer converge? How much of a performance difference does choosing a good optimizer make? To answer these questions, we evaluate the following optimizers: Stochastic gradient descent (SGD) SGD with momentum SGD with Nesterov momentum RMSprop Adam Adagrad Cyclic Learning Rate We train a neural net using different optimizers and compare their performance. The code for these experiments can be found on Github. Dataset: we use the Cats and Dogs dataset, which consists of 23,262 images of cats and dogs, split about 50/50 between the two classes. Since the images are differently-sized, we resize them all to the same size. We use 20% of the dataset as validation data (dev set) and the rest as training data. Evaluation metric: we use the binary cross-entropy loss on the validation data as our primary metric to measure model performance. Base model: we also define a base model that is inspired by VGG16, where we apply (convolution ->max-pool -> ReLU -> batch-norm -> dropout) operations repeatedly. Then, we flatten the output volume and feed it into two fully-connected layers (dense -> ReLU -> batch-norm) with 256 units each, and dropout after the first FC layer. Finally, we feed the result into a one-neuron layer with a sigmoid activation, resulting in an output between 0 and 1 that tells us whether the model predicts a cat (0) or dog (1). Training: we use a batch size of 32 and the default weight initialization (Glorot uniform). The default optimizer is SGD with a learning rate of 0.01. We train until the validation loss fails to improve over 50 iterations. We first start off with vanilla stochastic gradient descent. This is defined by the following update equation: where w is the weight vector and dw is the gradient of the loss function with respect to the weights. This update rule takes a step in the direction of greatest decrease in the loss function, helping us find a set of weights that minimizes the loss. Note that in pure SGD, the update is applied per example, but more commonly it is computed on a batch of examples (called a mini-batch). First, we explore how learning rate affects SGD. It is well known that choosing a learning rate that is too low will cause the model to converge slowly, whereas a learning rate that is too high may cause it to not converge at all. To verify this experimentally, we vary the learning rate along a log scale between 0.001 and 0.1. Let’s first plot the training losses. We indeed observe that performance is optimal when the learning rate is neither too small nor too large (the red line). Initially, increasing the learning rate speeds up convergence, but after learning rate 0.0316, convergence actually becomes slower. This may be because taking a larger step may actually overshoot the minimum loss, as illustrated in figure 4, resulting in a higher loss. Let’s now plot the validation losses. We observe that validation performance suffers when we pick a learning rate that is either too small or too big. Too small (e.g. 0.001) and the validation loss does not decrease at all, or does so very slowly. Too large (e.g. 0.1) and the validation loss does not attain as low a minimum as it could with a smaller learning rate. Let’s now plot the best training and validation loss attained by each learning rate*: The data above confirm the ‘Goldilocks’ theory of picking a learning rate that is neither too small nor too large, since the best learning rate (3.2e-2) is in the middle of the range of values we tried. *Typically, we would expect the validation loss to be higher than the training loss, since the model has not seen the validation data before. However, we see above that the validation loss is surprisingly sometimes lower than the training loss. This could be due to dropout, since neurons are dropped only at training time and not during evaluation, resulting in better performance during evaluation than during training. The effect may be particularly pronounced when the dropout rate is high, as it is in our model (0.6 dropout on FC layers). Best validation loss: 0.1899 Associated training loss: 0.1945 Epochs to converge to minimum: 535 Params: learning rate 0.032 Choosing a good learning rate (not too big, not too small) is critical for ensuring optimal performance on SGD. SGD with momentum is a variant of SGD that typically converges more quickly than vanilla SGD. It is typically defined as follows: Deep Learning by Goodfellow et al. explains the physical intuition behind the algorithm [0]: Formally, the momentum algorithm introduces a variable v that plays the role of velocity — it is the direction and speed at which the parameters move through parameter space. The velocity is set to an exponentially decaying average of the negative gradient. In other words, the parameters move through the parameter space at a velocity that changes over time. The change in velocity is dictated by two terms: α, the learning rate, which determines to what degree the gradient acts upon the velocity β, the rate at which the velocity decays over time Thus, the velocity is an exponential average of the gradients, which incorporates new gradients and naturally decays old gradients over time. One can imagine a ball rolling down a hill, gathering velocity as it descends. Gravity exerts force on the ball, causing it to accelerate or decelerate, as represented by the gradient term α * dw. The ball also encounters viscous drag, causing its velocity to decay, as represented by β. One effect of momentum is to accelerate updates along dimensions where the gradient direction is consistent. For example, consider the effect of momentum when the gradient is a constant c: Whereas vanilla SGD would make an update of -αc each time, SGD with momentum would accelerate over time, eventually reaching a terminal velocity that is 1/1-β times greater than the vanilla update (derived using the formula for an infinite series). For example, if we set the momentum to β=0.9, then the update eventually becomes 10 times as large as the vanilla update. Another effect of momentum is that it dampens oscillations. For example, consider a case when the gradient zigzags and changes direction often along a certain dimension: The momentum term dampens the oscillations because the oscillating terms cancel out when we add them into the velocity. This allows the update to be dominated by dimensions where the gradient points consistently in the same direction. Let’s look at the effect of momentum at learning rate 0.01. We try out momentum values [0, 0.5, 0.9, 0.95, 0.99]. Above, we can see that increasing momentum up to 0.9 helps model training converge more quickly, since training and validation loss decrease at a faster rate. However, once we go past 0.9, we observe that training loss and validation loss actually suffer, with model training entirely failing to converge at momentum 0.99. Why does this happen? This could be because excessively large momentum prevents the model from adapting to new directions in the gradient updates. Another potential reason is that the weight updates become so large that it overshoots the minima. However, this remains an area for future investigation. Do we observe the decrease in oscillation that is touted as a benefit of momentum? To measure this, we can compute an oscillation proportion for each update step — i.e. what proportion of parameter updates in the current update have the opposite sign compared to the previous update. Indeed, increasing the momentum decreases the proportion of parameters that oscillate: What about the size of the updates — does the acceleration property of momentum increase the average size of the updates? Interestingly, the higher the momentum, the larger the initial updates but the smaller the later updates: Thus, increasing the momentum results in taking larger initial steps but smaller later steps. Why would this be the case? This is likely because momentum initially benefits from acceleration, causing the initial steps to be larger. Later, the momentum causes oscillations to cancel out, which could make the later steps smaller. One data point that supports this interpretation is the distance traversed per epoch (defined as the Euclidean distance between the weights at the beginning of the epoch and the weights at the end of the epoch). We see that even though larger momentum values take smaller later steps, they actually traverse more distance: This indicates that even though increasing the momentum values causes the later update steps to become smaller, the distance traversed is actually greater because the steps are more efficient — they do not cancel each other out as often. Now, let’s look at the effect of momentum on a small learning rate (0.001). Surprisingly, increasing momentum on small learning rates helps it converge, when it didn’t before! Now, let’s look at a large learning rate. When the learning rate is large, increasing the momentum degrades performance, and can even result in the model failing to converge (see flat lines above corresponding to momentum 0.9 and 0.95). Now, to generalize our observations, let’s look at the minimum training loss and validation loss across all learning rates and momentums: We see that the learning rate and the momentum are closely linked —the higher the learning rate, the lower the range of ‘acceptable’ momentum values (i.e. values that don’t cause the model training to diverge). Conversely, the higher the momentum, the lower the range of acceptable learning rates. Altogether, the behavior across all the learning rates suggests that increasing momentum has an effect akin to increasing the learning rate. It helps smaller learning rates converge (Figure 14) but may cause larger ones to diverge (Figure 15). This makes sense if we consider the terminal velocity interpretation from Figure 9 — adding momentum can cause the updates to reach a terminal velocity much greater than than the vanilla updates themselves. Note, however, that this does not mean that increasing momentum is the same as increasing the learning rate — there are simply some similarities in terms of convergence/divergence behavior between increasing momentum and increasing the learning rate. More concretely, as we can see in Figures 12 and 13, momentum also decreases oscillations, and front-loads the large updates at the beginning of training — we would not observe the same behaviors if we simply increased the learning rate. There is another way to define momentum, expressed as follows: Andrew Ng uses this definition of momentum in his Deep Learning Specialization on Coursera. In this formulation, the velocity term is an exponentially moving average of the gradients, controlled by the parameter beta. The update is applied to the weights, with the size of the update controlled by the learning rate alpha. Note that this formulation is mathematically the same as the first formulation when expanded, except that all the terms are multiplied by 1-beta. How does this formulation of momentum work in practice? Surprisingly, using this alternative formulation, it looks like increasing the momentum actually slows down convergence! Why would this be the case? This formulation of momentum, while dampening oscillations, does not enjoy the same benefit of acceleration that the other formulation does. If we consider a toy example where the gradient is always a constant c, we see that the velocity never accelerates: Indeed, Andrew Ng suggests that the main benefit of this formulation of momentum is not acceleration, but the fact that it dampens oscillations, allowing you to use a larger learning rate and therefore converge more quickly. Based on our experiments, increasing momentum by itself (in this formulation) without increasing the learning rate is not enough to guarantee faster convergence. Best validation loss: 0.2046 Associated training loss: 0.2252 Epochs to converge to minimum: 402 Params: learning rate 0.01, momentum 0.5 Momentum causes model training to converge more quickly, but is not guaranteed to improve the final training or validation loss, based on the parameters we tested. The higher the learning rate, the lower the range of acceptable momentum values (ones where model training converges). One issue with momentum is that while the gradient always points in the direction of greatest loss decrease, the momentum may not. To correct for this, Nesterov momentum computes the gradient at a lookahead point (w + velocity) instead of w. This gives the gradient a chance to correct for the momentum term. To illustrate how Nesterov can help training converge more quickly, let’s look at a dummy example where the optimizer tries to descend a bowl-shaped loss surface, with the minimum at the center of the bowl. As the illustrations show, Nesterov converges more quickly because it computes the gradient at a lookahead point, thus ensuring that the update approaches the minimizer more quickly. Let’s try out Nesterov on a subset of the learning rates and momentums we used for regular momentum, and see if it speeds up convergence. Let’s take a look at learning rate 0.001 and momentum 0.95: Here, Nesterov does indeed seem to speed up convergence rapidly! How about if we increase the momentum to 0.99? Now, Nesterov actually converges more slowly on the training loss, and though it initially converges more quickly on validation loss, it slows down and is overtaken by momentum after around 50 epochs. How should we measure speed of convergence over all the training runs? Let’s take the loss that regular momentum achieves after 50 epochs, then determine how many epochs Nesterov takes to reach that same loss. We define the convergence ratio as this number of epochs divided by 50. If it less than one, then Nesterov converges more quickly than regular momentum; conversely, if it is greater, then Nesterov converges more slowly. We see that in most cases (10/14) adding Nesterov causes the training loss to decrease more quickly, as seen in Table 5. The same applies to a lesser extent (8/12) for the validation loss, in Table 6. There does not seem to be a clear relationship between the speedup from adding Nesterov and the other parameters (learning rate and momentum), though this can be an area for future investigation. Best validation loss: 0.2020 Associated training loss: 0.1945 Epochs to converge to minimum: 414 Params: learning rate 0.003, momentum 0.95 Nesterov momentum computes the gradient at a lookahead point in order to account for the effect of momentum. Nesterov generally converges more quickly compared to regular momentum. In RMSpropr, we do the following for each weight parameter: Keep a moving average of the squared gradient. Divide the gradient by the square root of the moving average, then apply the update. The update equations are as follows: Here, rho is a hyperparameter that defines how quickly the moving average adapts to new terms — the higher rho is, the more slowly the moving average changes. Epsilon is a small number meant to prevent division by zero. Alpha is the learning rate, w_i is weight i, a_i is the moving average, and dw_i is the gradient for weight i. What is RMSprop trying to do on a conceptual level? RMSprop is trying to normalize each element of the update so that no one element is excessively large or small. As an example, consider a weight parameter where the gradients are [5, 5, 5] (and assume that α=1). The denominator in the second equation is then 5, so the updates applied would be -[1, 1, 1]. Now, consider a weight parameter where the gradients are [0.5, 0.5, 0.5]; the denominator would be 0.5, giving the same updates -[1, 1, 1] as the previous case! In other words, RMSprop cares more about the sign (+ or -) of each weight than the magnitude, and tries to normalize the size of the update step for each of these weights. This is different from vanilla SGD, which applies larger updates for weight parameters with larger gradients. Considering the above example where the gradient is [5, 5, 5], we can see that the resulting updates would be -[5, 5, 5], whereas for the [0.5, 0.5, 0.5] case the updates would be -[0.5, 0.5, 0.5]. Let’s try out RMSprop while varying the learning rate α (default 0.001) and the coefficient ρ (default 0.9). Let’s first try setting ρ = 0 and vary the learning rate: First lesson learned — it looks like RMSProp with ρ=0 does not perform well. This results in the update being as follows: Why this fails to perform well is an area for future investigation. Let’s try again over nonzero rho values. We first plot the train and validation losses for a small learning rate (1e-3). Increasing rho seems to reduce both the training loss and validation loss, but with diminishing returns — the validation loss ceases to improve when increasing rho from 0.95 to 0.99. Let’s now take a look at what happens when we use a larger learning rate. Here, the training and validation losses entirely fail to converge! Let’s take a look at the minimum training and validation losses across all parameters: From the plots above, we find that once the learning rate reaches 0.01 or higher, RMSprop fails to converge.Thus, the optimal learning rate found here is around ten times as small as the optimal learning rate on SGD! One hypothesis is that the denominator term is much smaller than one, so it effectively scales up the update. Thus, we need to adjust the learning rate downward to compensate. Regarding ρ, we can see from the graphs above the RMS performs the best on our data with high ρ values (0.9 to 1). Even though the Keras docs recommend using the default value of ρ=0.9, it’s worth exploring other values as well — when we increased rho from 0.9 to 0.95, it substantially improved the best attained validation loss from 0.2226 to 0.2061. Best validation loss: 0.2061 Associated training loss: 0.2408 Epochs to converge to minimum: 338 Params: learning rate 0.001, rho 0.95 RMSprop seems to work at much smaller learning rates than vanilla SGD (about ten times smaller). This is likely because we divide the original update (dw) by the averaged gradient. Additionally, it seems to pay off to explore different values of ρ, contrary to the Keras docs’ recommendation to use the default value. Adam is sometimes regarded as the optimizer of choice, as it has been shown to converge more quickly than SGD and other optimization methods [1]. essentially a combination of SGD with momentum and RMSProp. It uses the following update equations: Essentially, we keep a velocity term similar to the one in momentum — it is an exponential average of the gradient updates. We also keep a squared term, which is an exponential average of the squares of the gradients, similar to RMSprop. We also correct these terms by (1 — beta); otherwise, the exponential average will start off with lower values at the beginning, since there are no previous terms to average over. Then we divide the corrected velocity by the square root of the corrected square term, and use that as our update. It has been suggested that the learning rate is more important than the β1 and β2 parameters, so let’s try varying the learning rate first, on a log scale from 1e-4 to 1: We did not plot learning rates above 0.03, since they failed to converge. We see that as we increase the learning rate, the training and validation loss decrease more quickly — but only up to a certain point. Once we increase the learning rate beyond 0.001, the training and validation loss both start to become worse. This could be due to the ‘overshooting’ behavior illustrated in Figure 4. So, which of the learning rates is the best? Let’s find out by plotting the best validation loss of each one. We see that the validation loss on learning rate 0.001 (which happens to be the default learning rate) seems to be the best, at 0.2059. The corresponding training loss is 0.2077. However, this is still worse than the best SGD run, which achieved a validation loss of 0.1899 and training loss of 0.1945. Can we somehow beat that? Let’s try varying β1 and β2 and see. We try the following values for β1 and β2: beta_1_values = [0.5, 0.9, 0.95]beta_2_values = [0.9, 0.99, 0.999] The best run is β1=0.5 and β2=0.999, which achieves a training loss of 0.2071 and validation loss of 0.2021. We can compare this against the default Keras params for Adam (β1=0.9 and β2=0.999), which achieves 0.2077 and 0.2059, respectively. Thus, it pays off slightly to experiment with different values of beta_1 and beta_2, contrary to the recommendation in the Keras docs — but the improvement is not large. Surprisingly, we were not able to beat the best SGD performance! It turns out that others have noticed that Adam sometimes works worse than SGD with momentum or other optimization algorithms [2]. While the reasons for this are beyond the scope of this article, it suggests that it pays off to experiment with different optimizers to find the one that works the best for your data. Best validation loss: 0.2021 Associated training loss: 0.2071 Epochs to converge to minimum: 255 Params: learning rate 0.001, β1=0.5, and β2=0.999 Adam is not guaranteed to achieve the best training and validation performance compared to other optimizers, as we found that SGD outperforms Adam. Trying out non-default values for β1 and β2 can slightly improve the model’s performance. Adagrad accumulates the squares of gradients, and divides the update by the square root of this accumulator term. This is similar to RMSprop, but the difference is that it simply accumulates the squares of the gradients, without using an exponential average. This should result in the size of the updates decaying over time. Let’s try Adagrad at different learning rates, from 0.001 to 1. The best training and validation loss are 0.2057 and 0.2310, using a learning rate of 3e-1. Interestingly, if we compare with SGD using the same learning rates, we notice that Adagrad keeps pace with SGD initially but starts to fall behind in later epochs. This is likely because Adagrad initially is dividing by a small number, since the gradient accumulator term has not accumulated many gradients yet. This makes the update comparable to that of SGD in the initial epochs. However, as the accumulator term accumulates more gradient, the size of the Adagrad updates decreases, and so the loss begins to flatten or even rise as it becomes more difficult to reach the minimizer. Surprisingly, we observe the opposite effect when we use a large learning rate (3e-1): At large learning rates, Adagrad actually converges more quickly than SGD! One possible explanation is that while large learning rates cause SGD to take excessively large update steps, Adagrad divides the updates by the accumulator terms, essentially making the updates smaller and more ‘optimal.’ Let’s look at the minimum training and validation losses across all params: We can see that the best learning rate for Adagrad, 0.316, is significantly larger than that for SGD, which was 0.03. As mentioned above, this is most likely because Adagrad divides by the accumulator terms, causing the effective size of the updates to be smaller. Best validation loss: 0.2310 Associated training loss: 0.2057 Epochs to converge to minimum: 406 Params: learning rate 0.312 Adagrad accumulates the squares of gradients, then divides the update by the square root of the accumulator term. The size of Adagrad updates decreases over time. The optimal learning rate for Adagrad is larger than for SGD (at least 10x in our case). Cyclic Learning Rate is a method that lets the learning rate vary cyclically between a min and max value [4]. It claims to eliminate the need to tune the learning rate, and can help the model training converge more quickly. We try the cyclic learning rate with reasonable learning rate bounds (base_lr=0.1, max_lr=0.4), and a step size equal to 4 epochs, which is within the 4–8 range suggested by the author. We observe cyclic oscillations in the training loss, due to the cyclic changes in the learning rate. We also see these oscillations to a lesser extend in the validation loss. Best validation loss: 0.2318 Associated training loss: 0.2267 Epochs to converge to minimum: 280 Params: Used the settings mentioned above. However, we may be able to obtain better performance by tuning the cycle policy (e.g. by allowing the max and min bounds to decay) or by tuning the max and min bounds themselves. Note that this tuning may offset the time savings that CLR purports to offer. CLR varies the learning rate cyclically between a min and max bound. CLR may potentially eliminate the need to tune the learning rate while attaining similar performance. However, we did not attain similar performance. So, after all the experiments above, which optimizer ended up working the best? Let’s take the best run from each optimizer, i.e. the one with the lowest validation loss: Surprisingly, SGD achieves the best validation loss, and by a significant margin. Then, we have SGD with Nesterov momentum, Adam, SGD with momentum, and RMSprop, which all perform similarly to one another. Finally, Adagrad and CLR come in last, with losses significantly higher than the others. What about training loss? Let’s plot the training loss for the runs selected above: Here, we see some correlation with the validation loss, but Adagrad and CLR perform better than their validation losses would imply. What about convergence? Let’s first take a look at how many epochs it takes each optimizer to converge to its minimum validation loss: Adam is clearly the fastest, while SGD is the slowest. However, this may not be a fair comparison, since the minimum validation loss for each optimizer is different. How about measuring how many epochs it takes each optimizer to reach a fixed validation loss? Let’s take the worst minimum validation loss of 0.2318 (the one achieved by CLR), and compute how many epochs it takes each optimizer to reach that loss. Again, we can see that Adam does converge more quickly to the given loss than any other optimizer, which is one of its purported advantages. Surprisingly, SGD with momentum seems to converge more slowly than vanilla SGD! This is because the learning rate used by the best SGD with momentum run is lower than that used by the best vanilla SGD run. If we hold the learning rate constant, we see that momentum does in fact speed up convergence: As seen above, the best vanilla SGD run (blue) converges more quickly than the best SGD with momentum run (orange), since the learning rate is higher at 0.03 compared to the latter’s 0.01. However, when hold the learning rate constant by comparing with vanilla SGD at learning rate 0.01 (green), we see that adding momentum does indeed speed up convergence. As mentioned in the Adam section, others have also noticed that Adam sometimes works worse than SGD with momentum or other optimization algorithms [2]. To quote Vitaly Bushaev’s article on Adam, “after a while people started noticing that despite superior training time, Adam in some areas does not converge to an optimal solution, so for some tasks (such as image classification on popular CIFAR datasets) state-of-the-art results are still only achieved by applying SGD with momentum.” [2] Though the exact reasons are beyond the scope of this article, others have shown that Adam may converge to sub-optimal solutions, even on convex functions. Overall, we can conclude that: You should tune your learning rate — it makes a large difference in your model’s performance, even more so than the choice of optimizer. On our data, vanilla SGD performed the best, but Adam achieved performance that was almost as good, while converging more quickly. It is worth trying out different values for rho in RMSprop and the beta values in Adam, even though Keras recommends using the default params. [0] https://www.deeplearningbook.org/contents/optimization.html [1] Diederik P. Kingma and Jimmy Lei Ba. Adam : A method for stochastic optimization. 2014. arXiv:1412.6980v9 [2] https://towardsdatascience.com/adam-latest-trends-in-deep-learning-optimization-6be9a291375c [3] https://ruder.io/optimizing-gradient-descent/index.html#adagrad [4] Leslie N. Smith. https://arxiv.org/pdf/1506.01186.pdf
[ { "code": null, "e": 203, "s": 172, "text": "co-authored with Apurva Pathak" }, { "code": null, "e": 576, "s": 203, "text": "Welcome to another instalment in our Deep Learning Experiments series, where we run experiments to evaluate commonly-held assumptions about training neural networks. Our goal is to better understand the different design choices that affect model training and evaluation. To do so, we come up with questions about each design choice and then run experiments to answer them." }, { "code": null, "e": 664, "s": 576, "text": "In this article, we seek to better understand the impact of using different optimizers:" }, { "code": null, "e": 713, "s": 664, "text": "How do different optimizers perform in practice?" }, { "code": null, "e": 801, "s": 713, "text": "How sensitive is each optimizer to parameter choices such as learning rate or momentum?" }, { "code": null, "e": 843, "s": 801, "text": "How quickly does each optimizer converge?" }, { "code": null, "e": 917, "s": 843, "text": "How much of a performance difference does choosing a good optimizer make?" }, { "code": null, "e": 982, "s": 917, "text": "To answer these questions, we evaluate the following optimizers:" }, { "code": null, "e": 1016, "s": 982, "text": "Stochastic gradient descent (SGD)" }, { "code": null, "e": 1034, "s": 1016, "text": "SGD with momentum" }, { "code": null, "e": 1061, "s": 1034, "text": "SGD with Nesterov momentum" }, { "code": null, "e": 1069, "s": 1061, "text": "RMSprop" }, { "code": null, "e": 1074, "s": 1069, "text": "Adam" }, { "code": null, "e": 1082, "s": 1074, "text": "Adagrad" }, { "code": null, "e": 1103, "s": 1082, "text": "Cyclic Learning Rate" }, { "code": null, "e": 1238, "s": 1103, "text": "We train a neural net using different optimizers and compare their performance. The code for these experiments can be found on Github." }, { "code": null, "e": 1537, "s": 1238, "text": "Dataset: we use the Cats and Dogs dataset, which consists of 23,262 images of cats and dogs, split about 50/50 between the two classes. Since the images are differently-sized, we resize them all to the same size. We use 20% of the dataset as validation data (dev set) and the rest as training data." }, { "code": null, "e": 1668, "s": 1537, "text": "Evaluation metric: we use the binary cross-entropy loss on the validation data as our primary metric to measure model performance." }, { "code": null, "e": 2180, "s": 1668, "text": "Base model: we also define a base model that is inspired by VGG16, where we apply (convolution ->max-pool -> ReLU -> batch-norm -> dropout) operations repeatedly. Then, we flatten the output volume and feed it into two fully-connected layers (dense -> ReLU -> batch-norm) with 256 units each, and dropout after the first FC layer. Finally, we feed the result into a one-neuron layer with a sigmoid activation, resulting in an output between 0 and 1 that tells us whether the model predicts a cat (0) or dog (1)." }, { "code": null, "e": 2403, "s": 2180, "text": "Training: we use a batch size of 32 and the default weight initialization (Glorot uniform). The default optimizer is SGD with a learning rate of 0.01. We train until the validation loss fails to improve over 50 iterations." }, { "code": null, "e": 2514, "s": 2403, "text": "We first start off with vanilla stochastic gradient descent. This is defined by the following update equation:" }, { "code": null, "e": 2901, "s": 2514, "text": "where w is the weight vector and dw is the gradient of the loss function with respect to the weights. This update rule takes a step in the direction of greatest decrease in the loss function, helping us find a set of weights that minimizes the loss. Note that in pure SGD, the update is applied per example, but more commonly it is computed on a batch of examples (called a mini-batch)." }, { "code": null, "e": 3132, "s": 2901, "text": "First, we explore how learning rate affects SGD. It is well known that choosing a learning rate that is too low will cause the model to converge slowly, whereas a learning rate that is too high may cause it to not converge at all." }, { "code": null, "e": 3268, "s": 3132, "text": "To verify this experimentally, we vary the learning rate along a log scale between 0.001 and 0.1. Let’s first plot the training losses." }, { "code": null, "e": 3658, "s": 3268, "text": "We indeed observe that performance is optimal when the learning rate is neither too small nor too large (the red line). Initially, increasing the learning rate speeds up convergence, but after learning rate 0.0316, convergence actually becomes slower. This may be because taking a larger step may actually overshoot the minimum loss, as illustrated in figure 4, resulting in a higher loss." }, { "code": null, "e": 3696, "s": 3658, "text": "Let’s now plot the validation losses." }, { "code": null, "e": 4026, "s": 3696, "text": "We observe that validation performance suffers when we pick a learning rate that is either too small or too big. Too small (e.g. 0.001) and the validation loss does not decrease at all, or does so very slowly. Too large (e.g. 0.1) and the validation loss does not attain as low a minimum as it could with a smaller learning rate." }, { "code": null, "e": 4112, "s": 4026, "text": "Let’s now plot the best training and validation loss attained by each learning rate*:" }, { "code": null, "e": 4315, "s": 4112, "text": "The data above confirm the ‘Goldilocks’ theory of picking a learning rate that is neither too small nor too large, since the best learning rate (3.2e-2) is in the middle of the range of values we tried." }, { "code": null, "e": 4860, "s": 4315, "text": "*Typically, we would expect the validation loss to be higher than the training loss, since the model has not seen the validation data before. However, we see above that the validation loss is surprisingly sometimes lower than the training loss. This could be due to dropout, since neurons are dropped only at training time and not during evaluation, resulting in better performance during evaluation than during training. The effect may be particularly pronounced when the dropout rate is high, as it is in our model (0.6 dropout on FC layers)." }, { "code": null, "e": 4889, "s": 4860, "text": "Best validation loss: 0.1899" }, { "code": null, "e": 4922, "s": 4889, "text": "Associated training loss: 0.1945" }, { "code": null, "e": 4957, "s": 4922, "text": "Epochs to converge to minimum: 535" }, { "code": null, "e": 4985, "s": 4957, "text": "Params: learning rate 0.032" }, { "code": null, "e": 5097, "s": 4985, "text": "Choosing a good learning rate (not too big, not too small) is critical for ensuring optimal performance on SGD." }, { "code": null, "e": 5227, "s": 5097, "text": "SGD with momentum is a variant of SGD that typically converges more quickly than vanilla SGD. It is typically defined as follows:" }, { "code": null, "e": 5320, "s": 5227, "text": "Deep Learning by Goodfellow et al. explains the physical intuition behind the algorithm [0]:" }, { "code": null, "e": 5578, "s": 5320, "text": "Formally, the momentum algorithm introduces a variable v that plays the role of velocity — it is the direction and speed at which the parameters move through parameter space. The velocity is set to an exponentially decaying average of the negative gradient." }, { "code": null, "e": 5729, "s": 5578, "text": "In other words, the parameters move through the parameter space at a velocity that changes over time. The change in velocity is dictated by two terms:" }, { "code": null, "e": 5819, "s": 5729, "text": "α, the learning rate, which determines to what degree the gradient acts upon the velocity" }, { "code": null, "e": 5870, "s": 5819, "text": "β, the rate at which the velocity decays over time" }, { "code": null, "e": 6012, "s": 5870, "text": "Thus, the velocity is an exponential average of the gradients, which incorporates new gradients and naturally decays old gradients over time." }, { "code": null, "e": 6300, "s": 6012, "text": "One can imagine a ball rolling down a hill, gathering velocity as it descends. Gravity exerts force on the ball, causing it to accelerate or decelerate, as represented by the gradient term α * dw. The ball also encounters viscous drag, causing its velocity to decay, as represented by β." }, { "code": null, "e": 6489, "s": 6300, "text": "One effect of momentum is to accelerate updates along dimensions where the gradient direction is consistent. For example, consider the effect of momentum when the gradient is a constant c:" }, { "code": null, "e": 6860, "s": 6489, "text": "Whereas vanilla SGD would make an update of -αc each time, SGD with momentum would accelerate over time, eventually reaching a terminal velocity that is 1/1-β times greater than the vanilla update (derived using the formula for an infinite series). For example, if we set the momentum to β=0.9, then the update eventually becomes 10 times as large as the vanilla update." }, { "code": null, "e": 7030, "s": 6860, "text": "Another effect of momentum is that it dampens oscillations. For example, consider a case when the gradient zigzags and changes direction often along a certain dimension:" }, { "code": null, "e": 7265, "s": 7030, "text": "The momentum term dampens the oscillations because the oscillating terms cancel out when we add them into the velocity. This allows the update to be dominated by dimensions where the gradient points consistently in the same direction." }, { "code": null, "e": 7379, "s": 7265, "text": "Let’s look at the effect of momentum at learning rate 0.01. We try out momentum values [0, 0.5, 0.9, 0.95, 0.99]." }, { "code": null, "e": 8004, "s": 7379, "text": "Above, we can see that increasing momentum up to 0.9 helps model training converge more quickly, since training and validation loss decrease at a faster rate. However, once we go past 0.9, we observe that training loss and validation loss actually suffer, with model training entirely failing to converge at momentum 0.99. Why does this happen? This could be because excessively large momentum prevents the model from adapting to new directions in the gradient updates. Another potential reason is that the weight updates become so large that it overshoots the minima. However, this remains an area for future investigation." }, { "code": null, "e": 8375, "s": 8004, "text": "Do we observe the decrease in oscillation that is touted as a benefit of momentum? To measure this, we can compute an oscillation proportion for each update step — i.e. what proportion of parameter updates in the current update have the opposite sign compared to the previous update. Indeed, increasing the momentum decreases the proportion of parameters that oscillate:" }, { "code": null, "e": 8603, "s": 8375, "text": "What about the size of the updates — does the acceleration property of momentum increase the average size of the updates? Interestingly, the higher the momentum, the larger the initial updates but the smaller the later updates:" }, { "code": null, "e": 8932, "s": 8603, "text": "Thus, increasing the momentum results in taking larger initial steps but smaller later steps. Why would this be the case? This is likely because momentum initially benefits from acceleration, causing the initial steps to be larger. Later, the momentum causes oscillations to cancel out, which could make the later steps smaller." }, { "code": null, "e": 9255, "s": 8932, "text": "One data point that supports this interpretation is the distance traversed per epoch (defined as the Euclidean distance between the weights at the beginning of the epoch and the weights at the end of the epoch). We see that even though larger momentum values take smaller later steps, they actually traverse more distance:" }, { "code": null, "e": 9493, "s": 9255, "text": "This indicates that even though increasing the momentum values causes the later update steps to become smaller, the distance traversed is actually greater because the steps are more efficient — they do not cancel each other out as often." }, { "code": null, "e": 9569, "s": 9493, "text": "Now, let’s look at the effect of momentum on a small learning rate (0.001)." }, { "code": null, "e": 9711, "s": 9569, "text": "Surprisingly, increasing momentum on small learning rates helps it converge, when it didn’t before! Now, let’s look at a large learning rate." }, { "code": null, "e": 9906, "s": 9711, "text": "When the learning rate is large, increasing the momentum degrades performance, and can even result in the model failing to converge (see flat lines above corresponding to momentum 0.9 and 0.95)." }, { "code": null, "e": 10044, "s": 9906, "text": "Now, to generalize our observations, let’s look at the minimum training loss and validation loss across all learning rates and momentums:" }, { "code": null, "e": 10342, "s": 10044, "text": "We see that the learning rate and the momentum are closely linked —the higher the learning rate, the lower the range of ‘acceptable’ momentum values (i.e. values that don’t cause the model training to diverge). Conversely, the higher the momentum, the lower the range of acceptable learning rates." }, { "code": null, "e": 10793, "s": 10342, "text": "Altogether, the behavior across all the learning rates suggests that increasing momentum has an effect akin to increasing the learning rate. It helps smaller learning rates converge (Figure 14) but may cause larger ones to diverge (Figure 15). This makes sense if we consider the terminal velocity interpretation from Figure 9 — adding momentum can cause the updates to reach a terminal velocity much greater than than the vanilla updates themselves." }, { "code": null, "e": 11282, "s": 10793, "text": "Note, however, that this does not mean that increasing momentum is the same as increasing the learning rate — there are simply some similarities in terms of convergence/divergence behavior between increasing momentum and increasing the learning rate. More concretely, as we can see in Figures 12 and 13, momentum also decreases oscillations, and front-loads the large updates at the beginning of training — we would not observe the same behaviors if we simply increased the learning rate." }, { "code": null, "e": 11345, "s": 11282, "text": "There is another way to define momentum, expressed as follows:" }, { "code": null, "e": 11814, "s": 11345, "text": "Andrew Ng uses this definition of momentum in his Deep Learning Specialization on Coursera. In this formulation, the velocity term is an exponentially moving average of the gradients, controlled by the parameter beta. The update is applied to the weights, with the size of the update controlled by the learning rate alpha. Note that this formulation is mathematically the same as the first formulation when expanded, except that all the terms are multiplied by 1-beta." }, { "code": null, "e": 11870, "s": 11814, "text": "How does this formulation of momentum work in practice?" }, { "code": null, "e": 11991, "s": 11870, "text": "Surprisingly, using this alternative formulation, it looks like increasing the momentum actually slows down convergence!" }, { "code": null, "e": 12276, "s": 11991, "text": "Why would this be the case? This formulation of momentum, while dampening oscillations, does not enjoy the same benefit of acceleration that the other formulation does. If we consider a toy example where the gradient is always a constant c, we see that the velocity never accelerates:" }, { "code": null, "e": 12663, "s": 12276, "text": "Indeed, Andrew Ng suggests that the main benefit of this formulation of momentum is not acceleration, but the fact that it dampens oscillations, allowing you to use a larger learning rate and therefore converge more quickly. Based on our experiments, increasing momentum by itself (in this formulation) without increasing the learning rate is not enough to guarantee faster convergence." }, { "code": null, "e": 12692, "s": 12663, "text": "Best validation loss: 0.2046" }, { "code": null, "e": 12725, "s": 12692, "text": "Associated training loss: 0.2252" }, { "code": null, "e": 12760, "s": 12725, "text": "Epochs to converge to minimum: 402" }, { "code": null, "e": 12801, "s": 12760, "text": "Params: learning rate 0.01, momentum 0.5" }, { "code": null, "e": 12965, "s": 12801, "text": "Momentum causes model training to converge more quickly, but is not guaranteed to improve the final training or validation loss, based on the parameters we tested." }, { "code": null, "e": 13084, "s": 12965, "text": "The higher the learning rate, the lower the range of acceptable momentum values (ones where model training converges)." }, { "code": null, "e": 13393, "s": 13084, "text": "One issue with momentum is that while the gradient always points in the direction of greatest loss decrease, the momentum may not. To correct for this, Nesterov momentum computes the gradient at a lookahead point (w + velocity) instead of w. This gives the gradient a chance to correct for the momentum term." }, { "code": null, "e": 13600, "s": 13393, "text": "To illustrate how Nesterov can help training converge more quickly, let’s look at a dummy example where the optimizer tries to descend a bowl-shaped loss surface, with the minimum at the center of the bowl." }, { "code": null, "e": 13783, "s": 13600, "text": "As the illustrations show, Nesterov converges more quickly because it computes the gradient at a lookahead point, thus ensuring that the update approaches the minimizer more quickly." }, { "code": null, "e": 13981, "s": 13783, "text": "Let’s try out Nesterov on a subset of the learning rates and momentums we used for regular momentum, and see if it speeds up convergence. Let’s take a look at learning rate 0.001 and momentum 0.95:" }, { "code": null, "e": 14093, "s": 13981, "text": "Here, Nesterov does indeed seem to speed up convergence rapidly! How about if we increase the momentum to 0.99?" }, { "code": null, "e": 14294, "s": 14093, "text": "Now, Nesterov actually converges more slowly on the training loss, and though it initially converges more quickly on validation loss, it slows down and is overtaken by momentum after around 50 epochs." }, { "code": null, "e": 14724, "s": 14294, "text": "How should we measure speed of convergence over all the training runs? Let’s take the loss that regular momentum achieves after 50 epochs, then determine how many epochs Nesterov takes to reach that same loss. We define the convergence ratio as this number of epochs divided by 50. If it less than one, then Nesterov converges more quickly than regular momentum; conversely, if it is greater, then Nesterov converges more slowly." }, { "code": null, "e": 14925, "s": 14724, "text": "We see that in most cases (10/14) adding Nesterov causes the training loss to decrease more quickly, as seen in Table 5. The same applies to a lesser extent (8/12) for the validation loss, in Table 6." }, { "code": null, "e": 15121, "s": 14925, "text": "There does not seem to be a clear relationship between the speedup from adding Nesterov and the other parameters (learning rate and momentum), though this can be an area for future investigation." }, { "code": null, "e": 15150, "s": 15121, "text": "Best validation loss: 0.2020" }, { "code": null, "e": 15183, "s": 15150, "text": "Associated training loss: 0.1945" }, { "code": null, "e": 15218, "s": 15183, "text": "Epochs to converge to minimum: 414" }, { "code": null, "e": 15261, "s": 15218, "text": "Params: learning rate 0.003, momentum 0.95" }, { "code": null, "e": 15370, "s": 15261, "text": "Nesterov momentum computes the gradient at a lookahead point in order to account for the effect of momentum." }, { "code": null, "e": 15442, "s": 15370, "text": "Nesterov generally converges more quickly compared to regular momentum." }, { "code": null, "e": 15502, "s": 15442, "text": "In RMSpropr, we do the following for each weight parameter:" }, { "code": null, "e": 15549, "s": 15502, "text": "Keep a moving average of the squared gradient." }, { "code": null, "e": 15634, "s": 15549, "text": "Divide the gradient by the square root of the moving average, then apply the update." }, { "code": null, "e": 15671, "s": 15634, "text": "The update equations are as follows:" }, { "code": null, "e": 16002, "s": 15671, "text": "Here, rho is a hyperparameter that defines how quickly the moving average adapts to new terms — the higher rho is, the more slowly the moving average changes. Epsilon is a small number meant to prevent division by zero. Alpha is the learning rate, w_i is weight i, a_i is the moving average, and dw_i is the gradient for weight i." }, { "code": null, "e": 16693, "s": 16002, "text": "What is RMSprop trying to do on a conceptual level? RMSprop is trying to normalize each element of the update so that no one element is excessively large or small. As an example, consider a weight parameter where the gradients are [5, 5, 5] (and assume that α=1). The denominator in the second equation is then 5, so the updates applied would be -[1, 1, 1]. Now, consider a weight parameter where the gradients are [0.5, 0.5, 0.5]; the denominator would be 0.5, giving the same updates -[1, 1, 1] as the previous case! In other words, RMSprop cares more about the sign (+ or -) of each weight than the magnitude, and tries to normalize the size of the update step for each of these weights." }, { "code": null, "e": 17001, "s": 16693, "text": "This is different from vanilla SGD, which applies larger updates for weight parameters with larger gradients. Considering the above example where the gradient is [5, 5, 5], we can see that the resulting updates would be -[5, 5, 5], whereas for the [0.5, 0.5, 0.5] case the updates would be -[0.5, 0.5, 0.5]." }, { "code": null, "e": 17168, "s": 17001, "text": "Let’s try out RMSprop while varying the learning rate α (default 0.001) and the coefficient ρ (default 0.9). Let’s first try setting ρ = 0 and vary the learning rate:" }, { "code": null, "e": 17290, "s": 17168, "text": "First lesson learned — it looks like RMSProp with ρ=0 does not perform well. This results in the update being as follows:" }, { "code": null, "e": 17358, "s": 17290, "text": "Why this fails to perform well is an area for future investigation." }, { "code": null, "e": 17479, "s": 17358, "text": "Let’s try again over nonzero rho values. We first plot the train and validation losses for a small learning rate (1e-3)." }, { "code": null, "e": 17662, "s": 17479, "text": "Increasing rho seems to reduce both the training loss and validation loss, but with diminishing returns — the validation loss ceases to improve when increasing rho from 0.95 to 0.99." }, { "code": null, "e": 17736, "s": 17662, "text": "Let’s now take a look at what happens when we use a larger learning rate." }, { "code": null, "e": 17804, "s": 17736, "text": "Here, the training and validation losses entirely fail to converge!" }, { "code": null, "e": 17891, "s": 17804, "text": "Let’s take a look at the minimum training and validation losses across all parameters:" }, { "code": null, "e": 18284, "s": 17891, "text": "From the plots above, we find that once the learning rate reaches 0.01 or higher, RMSprop fails to converge.Thus, the optimal learning rate found here is around ten times as small as the optimal learning rate on SGD! One hypothesis is that the denominator term is much smaller than one, so it effectively scales up the update. Thus, we need to adjust the learning rate downward to compensate." }, { "code": null, "e": 18637, "s": 18284, "text": "Regarding ρ, we can see from the graphs above the RMS performs the best on our data with high ρ values (0.9 to 1). Even though the Keras docs recommend using the default value of ρ=0.9, it’s worth exploring other values as well — when we increased rho from 0.9 to 0.95, it substantially improved the best attained validation loss from 0.2226 to 0.2061." }, { "code": null, "e": 18666, "s": 18637, "text": "Best validation loss: 0.2061" }, { "code": null, "e": 18699, "s": 18666, "text": "Associated training loss: 0.2408" }, { "code": null, "e": 18734, "s": 18699, "text": "Epochs to converge to minimum: 338" }, { "code": null, "e": 18772, "s": 18734, "text": "Params: learning rate 0.001, rho 0.95" }, { "code": null, "e": 18953, "s": 18772, "text": "RMSprop seems to work at much smaller learning rates than vanilla SGD (about ten times smaller). This is likely because we divide the original update (dw) by the averaged gradient." }, { "code": null, "e": 19090, "s": 18953, "text": "Additionally, it seems to pay off to explore different values of ρ, contrary to the Keras docs’ recommendation to use the default value." }, { "code": null, "e": 19336, "s": 19090, "text": "Adam is sometimes regarded as the optimizer of choice, as it has been shown to converge more quickly than SGD and other optimization methods [1]. essentially a combination of SGD with momentum and RMSProp. It uses the following update equations:" }, { "code": null, "e": 19869, "s": 19336, "text": "Essentially, we keep a velocity term similar to the one in momentum — it is an exponential average of the gradient updates. We also keep a squared term, which is an exponential average of the squares of the gradients, similar to RMSprop. We also correct these terms by (1 — beta); otherwise, the exponential average will start off with lower values at the beginning, since there are no previous terms to average over. Then we divide the corrected velocity by the square root of the corrected square term, and use that as our update." }, { "code": null, "e": 20040, "s": 19869, "text": "It has been suggested that the learning rate is more important than the β1 and β2 parameters, so let’s try varying the learning rate first, on a log scale from 1e-4 to 1:" }, { "code": null, "e": 20433, "s": 20040, "text": "We did not plot learning rates above 0.03, since they failed to converge. We see that as we increase the learning rate, the training and validation loss decrease more quickly — but only up to a certain point. Once we increase the learning rate beyond 0.001, the training and validation loss both start to become worse. This could be due to the ‘overshooting’ behavior illustrated in Figure 4." }, { "code": null, "e": 20543, "s": 20433, "text": "So, which of the learning rates is the best? Let’s find out by plotting the best validation loss of each one." }, { "code": null, "e": 20909, "s": 20543, "text": "We see that the validation loss on learning rate 0.001 (which happens to be the default learning rate) seems to be the best, at 0.2059. The corresponding training loss is 0.2077. However, this is still worse than the best SGD run, which achieved a validation loss of 0.1899 and training loss of 0.1945. Can we somehow beat that? Let’s try varying β1 and β2 and see." }, { "code": null, "e": 20952, "s": 20909, "text": "We try the following values for β1 and β2:" }, { "code": null, "e": 21019, "s": 20952, "text": "beta_1_values = [0.5, 0.9, 0.95]beta_2_values = [0.9, 0.99, 0.999]" }, { "code": null, "e": 21431, "s": 21019, "text": "The best run is β1=0.5 and β2=0.999, which achieves a training loss of 0.2071 and validation loss of 0.2021. We can compare this against the default Keras params for Adam (β1=0.9 and β2=0.999), which achieves 0.2077 and 0.2059, respectively. Thus, it pays off slightly to experiment with different values of beta_1 and beta_2, contrary to the recommendation in the Keras docs — but the improvement is not large." }, { "code": null, "e": 21812, "s": 21431, "text": "Surprisingly, we were not able to beat the best SGD performance! It turns out that others have noticed that Adam sometimes works worse than SGD with momentum or other optimization algorithms [2]. While the reasons for this are beyond the scope of this article, it suggests that it pays off to experiment with different optimizers to find the one that works the best for your data." }, { "code": null, "e": 21841, "s": 21812, "text": "Best validation loss: 0.2021" }, { "code": null, "e": 21874, "s": 21841, "text": "Associated training loss: 0.2071" }, { "code": null, "e": 21909, "s": 21874, "text": "Epochs to converge to minimum: 255" }, { "code": null, "e": 21959, "s": 21909, "text": "Params: learning rate 0.001, β1=0.5, and β2=0.999" }, { "code": null, "e": 22107, "s": 21959, "text": "Adam is not guaranteed to achieve the best training and validation performance compared to other optimizers, as we found that SGD outperforms Adam." }, { "code": null, "e": 22197, "s": 22107, "text": "Trying out non-default values for β1 and β2 can slightly improve the model’s performance." }, { "code": null, "e": 22311, "s": 22197, "text": "Adagrad accumulates the squares of gradients, and divides the update by the square root of this accumulator term." }, { "code": null, "e": 22522, "s": 22311, "text": "This is similar to RMSprop, but the difference is that it simply accumulates the squares of the gradients, without using an exponential average. This should result in the size of the updates decaying over time." }, { "code": null, "e": 22586, "s": 22522, "text": "Let’s try Adagrad at different learning rates, from 0.001 to 1." }, { "code": null, "e": 22843, "s": 22586, "text": "The best training and validation loss are 0.2057 and 0.2310, using a learning rate of 3e-1. Interestingly, if we compare with SGD using the same learning rates, we notice that Adagrad keeps pace with SGD initially but starts to fall behind in later epochs." }, { "code": null, "e": 23265, "s": 22843, "text": "This is likely because Adagrad initially is dividing by a small number, since the gradient accumulator term has not accumulated many gradients yet. This makes the update comparable to that of SGD in the initial epochs. However, as the accumulator term accumulates more gradient, the size of the Adagrad updates decreases, and so the loss begins to flatten or even rise as it becomes more difficult to reach the minimizer." }, { "code": null, "e": 23352, "s": 23265, "text": "Surprisingly, we observe the opposite effect when we use a large learning rate (3e-1):" }, { "code": null, "e": 23650, "s": 23352, "text": "At large learning rates, Adagrad actually converges more quickly than SGD! One possible explanation is that while large learning rates cause SGD to take excessively large update steps, Adagrad divides the updates by the accumulator terms, essentially making the updates smaller and more ‘optimal.’" }, { "code": null, "e": 23726, "s": 23650, "text": "Let’s look at the minimum training and validation losses across all params:" }, { "code": null, "e": 23991, "s": 23726, "text": "We can see that the best learning rate for Adagrad, 0.316, is significantly larger than that for SGD, which was 0.03. As mentioned above, this is most likely because Adagrad divides by the accumulator terms, causing the effective size of the updates to be smaller." }, { "code": null, "e": 24020, "s": 23991, "text": "Best validation loss: 0.2310" }, { "code": null, "e": 24053, "s": 24020, "text": "Associated training loss: 0.2057" }, { "code": null, "e": 24088, "s": 24053, "text": "Epochs to converge to minimum: 406" }, { "code": null, "e": 24116, "s": 24088, "text": "Params: learning rate 0.312" }, { "code": null, "e": 24230, "s": 24116, "text": "Adagrad accumulates the squares of gradients, then divides the update by the square root of the accumulator term." }, { "code": null, "e": 24279, "s": 24230, "text": "The size of Adagrad updates decreases over time." }, { "code": null, "e": 24368, "s": 24279, "text": "The optimal learning rate for Adagrad is larger than for SGD (at least 10x in our case)." }, { "code": null, "e": 24592, "s": 24368, "text": "Cyclic Learning Rate is a method that lets the learning rate vary cyclically between a min and max value [4]. It claims to eliminate the need to tune the learning rate, and can help the model training converge more quickly." }, { "code": null, "e": 24778, "s": 24592, "text": "We try the cyclic learning rate with reasonable learning rate bounds (base_lr=0.1, max_lr=0.4), and a step size equal to 4 epochs, which is within the 4–8 range suggested by the author." }, { "code": null, "e": 24953, "s": 24778, "text": "We observe cyclic oscillations in the training loss, due to the cyclic changes in the learning rate. We also see these oscillations to a lesser extend in the validation loss." }, { "code": null, "e": 24982, "s": 24953, "text": "Best validation loss: 0.2318" }, { "code": null, "e": 25015, "s": 24982, "text": "Associated training loss: 0.2267" }, { "code": null, "e": 25050, "s": 25015, "text": "Epochs to converge to minimum: 280" }, { "code": null, "e": 25350, "s": 25050, "text": "Params: Used the settings mentioned above. However, we may be able to obtain better performance by tuning the cycle policy (e.g. by allowing the max and min bounds to decay) or by tuning the max and min bounds themselves. Note that this tuning may offset the time savings that CLR purports to offer." }, { "code": null, "e": 25419, "s": 25350, "text": "CLR varies the learning rate cyclically between a min and max bound." }, { "code": null, "e": 25569, "s": 25419, "text": "CLR may potentially eliminate the need to tune the learning rate while attaining similar performance. However, we did not attain similar performance." }, { "code": null, "e": 25740, "s": 25569, "text": "So, after all the experiments above, which optimizer ended up working the best? Let’s take the best run from each optimizer, i.e. the one with the lowest validation loss:" }, { "code": null, "e": 26035, "s": 25740, "text": "Surprisingly, SGD achieves the best validation loss, and by a significant margin. Then, we have SGD with Nesterov momentum, Adam, SGD with momentum, and RMSprop, which all perform similarly to one another. Finally, Adagrad and CLR come in last, with losses significantly higher than the others." }, { "code": null, "e": 26119, "s": 26035, "text": "What about training loss? Let’s plot the training loss for the runs selected above:" }, { "code": null, "e": 26252, "s": 26119, "text": "Here, we see some correlation with the validation loss, but Adagrad and CLR perform better than their validation losses would imply." }, { "code": null, "e": 26387, "s": 26252, "text": "What about convergence? Let’s first take a look at how many epochs it takes each optimizer to converge to its minimum validation loss:" }, { "code": null, "e": 26442, "s": 26387, "text": "Adam is clearly the fastest, while SGD is the slowest." }, { "code": null, "e": 26801, "s": 26442, "text": "However, this may not be a fair comparison, since the minimum validation loss for each optimizer is different. How about measuring how many epochs it takes each optimizer to reach a fixed validation loss? Let’s take the worst minimum validation loss of 0.2318 (the one achieved by CLR), and compute how many epochs it takes each optimizer to reach that loss." }, { "code": null, "e": 27243, "s": 26801, "text": "Again, we can see that Adam does converge more quickly to the given loss than any other optimizer, which is one of its purported advantages. Surprisingly, SGD with momentum seems to converge more slowly than vanilla SGD! This is because the learning rate used by the best SGD with momentum run is lower than that used by the best vanilla SGD run. If we hold the learning rate constant, we see that momentum does in fact speed up convergence:" }, { "code": null, "e": 27601, "s": 27243, "text": "As seen above, the best vanilla SGD run (blue) converges more quickly than the best SGD with momentum run (orange), since the learning rate is higher at 0.03 compared to the latter’s 0.01. However, when hold the learning rate constant by comparing with vanilla SGD at learning rate 0.01 (green), we see that adding momentum does indeed speed up convergence." }, { "code": null, "e": 28249, "s": 27601, "text": "As mentioned in the Adam section, others have also noticed that Adam sometimes works worse than SGD with momentum or other optimization algorithms [2]. To quote Vitaly Bushaev’s article on Adam, “after a while people started noticing that despite superior training time, Adam in some areas does not converge to an optimal solution, so for some tasks (such as image classification on popular CIFAR datasets) state-of-the-art results are still only achieved by applying SGD with momentum.” [2] Though the exact reasons are beyond the scope of this article, others have shown that Adam may converge to sub-optimal solutions, even on convex functions." }, { "code": null, "e": 28280, "s": 28249, "text": "Overall, we can conclude that:" }, { "code": null, "e": 28417, "s": 28280, "text": "You should tune your learning rate — it makes a large difference in your model’s performance, even more so than the choice of optimizer." }, { "code": null, "e": 28548, "s": 28417, "text": "On our data, vanilla SGD performed the best, but Adam achieved performance that was almost as good, while converging more quickly." }, { "code": null, "e": 28691, "s": 28548, "text": "It is worth trying out different values for rho in RMSprop and the beta values in Adam, even though Keras recommends using the default params." }, { "code": null, "e": 28755, "s": 28691, "text": "[0] https://www.deeplearningbook.org/contents/optimization.html" }, { "code": null, "e": 28865, "s": 28755, "text": "[1] Diederik P. Kingma and Jimmy Lei Ba. Adam : A method for stochastic optimization. 2014. arXiv:1412.6980v9" }, { "code": null, "e": 28962, "s": 28865, "text": "[2] https://towardsdatascience.com/adam-latest-trends-in-deep-learning-optimization-6be9a291375c" }, { "code": null, "e": 29030, "s": 28962, "text": "[3] https://ruder.io/optimizing-gradient-descent/index.html#adagrad" } ]
Check Constraint in MS SQL Server - GeeksforGeeks
26 Aug, 2020 Check Constraint :It is used alongside relational operators to check whether a value satisfies the condition or not (boolean). If the condition is satisfied, the boolean expression sets to True otherwise False. The check constraint does not have a specific syntax. It is used along with the create table syntax. Syntax : Create table Marks name varchar2(30), rollnumber number primary key, marks int check (marks<=75) A table named Student is created along with the condition that marks must not be greater than 75. A user inserts a few values as shown below – Table – Marks The values are inserted as per the conditions mentioned in the create table syntax. The user tries inserting a few more values yet errors occur as shown below – Example-1: Insert into Student values('Maya', '117', '80') Output –The value results in an error as the value is greater than 75.Example-2: Insert into Student values('Maya' '111', '74') Output –An error is displayed. This is due to the primary key used for rollnumber. Primary key forbids the use of duplicates in a table.Check constraint in case of NULL : Insert into Student values('Riya', '112', 'NULL') Output –In SQL, NULL is used incase of unknown value. Therefore it is considered as False. SQL-Server DBMS SQL DBMS SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Second Normal Form (2NF) Introduction of Relational Algebra in DBMS What is Temporary Table in SQL? Types of Functional dependencies in DBMS Difference between Where and Having Clause in SQL SQL | DDL, DQL, DML, DCL and TCL Commands How to find Nth highest salary from a table SQL | ALTER (RENAME) How to Update Multiple Columns in Single Update Statement in SQL? What is Temporary Table in SQL?
[ { "code": null, "e": 23913, "s": 23885, "text": "\n26 Aug, 2020" }, { "code": null, "e": 24225, "s": 23913, "text": "Check Constraint :It is used alongside relational operators to check whether a value satisfies the condition or not (boolean). If the condition is satisfied, the boolean expression sets to True otherwise False. The check constraint does not have a specific syntax. It is used along with the create table syntax." }, { "code": null, "e": 24234, "s": 24225, "text": "Syntax :" }, { "code": null, "e": 24334, "s": 24234, "text": "Create table Marks \nname varchar2(30), \nrollnumber number primary key, \nmarks int check (marks<=75)" }, { "code": null, "e": 24477, "s": 24334, "text": "A table named Student is created along with the condition that marks must not be greater than 75. A user inserts a few values as shown below –" }, { "code": null, "e": 24491, "s": 24477, "text": "Table – Marks" }, { "code": null, "e": 24652, "s": 24491, "text": "The values are inserted as per the conditions mentioned in the create table syntax. The user tries inserting a few more values yet errors occur as shown below –" }, { "code": null, "e": 24663, "s": 24652, "text": "Example-1:" }, { "code": null, "e": 24712, "s": 24663, "text": "Insert into Student \nvalues('Maya', '117', '80')" }, { "code": null, "e": 24793, "s": 24712, "text": "Output –The value results in an error as the value is greater than 75.Example-2:" }, { "code": null, "e": 24841, "s": 24793, "text": "Insert into Student \nvalues('Maya' '111', '74')" }, { "code": null, "e": 25012, "s": 24841, "text": "Output –An error is displayed. This is due to the primary key used for rollnumber. Primary key forbids the use of duplicates in a table.Check constraint in case of NULL :" }, { "code": null, "e": 25063, "s": 25012, "text": "Insert into Student \nvalues('Riya', '112', 'NULL')" }, { "code": null, "e": 25154, "s": 25063, "text": "Output –In SQL, NULL is used incase of unknown value. Therefore it is considered as False." }, { "code": null, "e": 25165, "s": 25154, "text": "SQL-Server" }, { "code": null, "e": 25170, "s": 25165, "text": "DBMS" }, { "code": null, "e": 25174, "s": 25170, "text": "SQL" }, { "code": null, "e": 25179, "s": 25174, "text": "DBMS" }, { "code": null, "e": 25183, "s": 25179, "text": "SQL" }, { "code": null, "e": 25281, "s": 25183, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25290, "s": 25281, "text": "Comments" }, { "code": null, "e": 25303, "s": 25290, "text": "Old Comments" }, { "code": null, "e": 25328, "s": 25303, "text": "Second Normal Form (2NF)" }, { "code": null, "e": 25371, "s": 25328, "text": "Introduction of Relational Algebra in DBMS" }, { "code": null, "e": 25403, "s": 25371, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 25444, "s": 25403, "text": "Types of Functional dependencies in DBMS" }, { "code": null, "e": 25494, "s": 25444, "text": "Difference between Where and Having Clause in SQL" }, { "code": null, "e": 25536, "s": 25494, "text": "SQL | DDL, DQL, DML, DCL and TCL Commands" }, { "code": null, "e": 25580, "s": 25536, "text": "How to find Nth highest salary from a table" }, { "code": null, "e": 25601, "s": 25580, "text": "SQL | ALTER (RENAME)" }, { "code": null, "e": 25667, "s": 25601, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" } ]
Determining Optimal Distribution Centers locations using Weighted K-Means | by Jaswanth Badvelu | Towards Data Science
Everyone here must have heard of Amazon and its growth in recent years. One of the main reasons for the success of Amazon is its supply chain management. All the people who have ordered at least once from Amazon should be familiar with their popular 1-day shipping. Ever wondered how companies like Amazon can deliver products so quickly to any location in the USA? This is not a simple task to achieve, considering the vast magnitude of land in the USA and the number of orders they receive each day from all corners of the country. It turns out, most of the products you order are directly shipping from your state, not from somewhere else. All companies like Walmart, Amazon store surplus products, which customers don’t need immediately in the distribution centers based on customer demand anticipation. All the services such as product mixing, order fulfillment, cross-docking, packaging are done in distribution centers. These DC’s are located so they can be used to deliver goods to the maximum area possible in the shortest time. For any company to become successful, an effective supply chain strategy is a must, and DC’s play a crucial role in the supply chain strategy. The total COVID 19 cases count has passed the 7 million mark on 24th September in the USA. On the other hand, many countries like the UK claim that their COVID -19 vaccine development is in the final stages and will be released by the end of 2020. I thought it would be interesting to find out when the vaccine is finally released and distributed across all the hospitals, including clinical centers treating COVID-19 patients in the USA. If the US government is planning to make use of Distribution Center’s to supply vaccination to all hospitals treating COVID-19 patients, Where should DC’s be located? How many DC’s are needed? First, I started with some web scrapping from Wikipedia to get all hospitals in the USA with their Address and County Name. And matched the county name of the hospital regions with the active COVID-19 cases in that region. To make it easier for plotting and finding distance, I found latitudes and longitudes for all the addresses using geocoding, for which I clearly explained steps in my previous blog. towardsdatascience.com The glimpse of data set after finding latitudes and longitudes for all the hospitals Now that we have latitudes and longitudes, it is very easy to plot them. The image below represents all the hospitals in the USA with active COVID-19 cases generated using folium maps in python. Here, the points with bigger circles represent the regions with more COVID-19 active cases. It can be clearly seen that some regions in California have the highest number of active cases. Back to our problem, where we are trying to find the optimal locations for Distribution Centers to supply vaccines to all hospitals. Here, determining DC’s location for specific hospitals is similar to dividing all the hospitals into different clusters and locating one centroid point for each cluster of hospitals. This situation is very similar to the K-Means clustering algorithm. Therefore K-Means clustering can be applied. How (Standard) K-Means Clustering works? K-Means clustering is a popular unsupervised ML algorithm used for partitioning data into K clusters. The algorithm works iteratively to assign each data point to one of the K groups. The data is randomly divided into K groups with a mean centroid point assigned to each group, and the algorithm iterates to find: The distance between all the data points to the centroid points and forms new clusters by reassigning the data points to its nearest centroid.Again new centroid points are found by taking the mean of distances. The distance between all the data points to the centroid points and forms new clusters by reassigning the data points to its nearest centroid. Again new centroid points are found by taking the mean of distances. This process is iterated repeatedly until the Sum of Squared distances are minimized, or the predefined limit is reached. An important step to be performed before starting the k-means is to decide on the number of clusters. The number of K is a predefined hyperparameter that should be tuned to get an optimal result. This can be done using the elbow method, which will be briefly explained later in the article. This is a versatile algorithm that can be used for any grouping. Some examples of use cases are Grouping Inventory based on demand or customer segmentation based on purchases. Problem Solving: The only problem we have here is more preference should be given to the locations with more active COVID-19 cases. This is where Weighted K-Means Clustering comes in to play. The standard K-means approach would not work because it fails to consider the fact that some regions where hospitals are located have more active COVID-19 cases, which implies having a higher volume demand for the vaccine to be supplied. How Weighted K-Means differs from Standard K-Means? The weighted K-Means work the same as standard K-Means clustering. The only difference would be instead of just calculating centroid points based on the mean of distances. The weighted average should be used. Thus, the bigger the weight of the data point, the nearer centroid will be pulled. The image below shows the illustration of Standard K-Means vs. weighted K-Means. Here, in the right image, the weight of data points is higher for W2 and W3. So, the centroid is pulled them instead of being located in the center. The weighted can be given to any variable we want from the dataset, like urban cities or the city's total populations. In our case, the weightage will be given to the total active COVID-19 cases per county. So they should be given more preference. One more problem is that we cannot use traditional Euclidean distance as a distance metric to find centroid points because we have latitudes and longitudes that represent earth spherical dimensions instead of 2D (x,y) coordinates in euclidean distances. Many options are available to calculate the distance between two spherical points like Haversine distance or Great circle distance. We will be using Haversine distance. Haversine Distance The haversine distance d can be found using the following formulae, where φ represents latitudes, and λ represents longitudes. a = sin2(( φB — φA) /2) + cos φA * cos φB * sin2((λB — λA) /2) c = 2 * atan2( √a, √(1−a) ) d = R ⋅ c (R = Radius of earth, i.e, 6,371 KM) Luckily, We don’t need to use all these formulae to calculate haversine distance because, in python, there is a library named haversine which directly calculates the distance between location coordinates with one line of code from haversine import haversinehaversine((31.215827,-85.363433),(28.703230,-81.815668)) Using Weighted K-Means with Haversine distance as a distance metric, a modified Weighted K-Means algorithm is created, which can be found in my Github repository. Finally, we need to determine the optimal number of distribution centers to fulfill the demand better and minimize delivery expenses. i.e., the optimal number of K. This can be determined using the Elbow method. Elbow Method In cluster analysis, the elbow method is a heuristic used in determining the optimal number of clusters in a data set. The Within-Cluster-Sum of Squared Errors (SSE) for different values of ‘k’ is calculated. For whichever ‘k’ value the WSS becomes first starts to diminish, that particular ‘k’ is chosen. Typically, the K value where it forms an elbow shape is considered as an optimal value. The SSE is nothing but the sum of squares of each data point's distances in all clusters to their respective centroids. The below plot represents the SSE vs. the number of clusters for our data. Since the decrease in SSE value is no longer significant after 4 clusters. The K=4 can be considered as our optimum K-Value. Finally, we found that 4 is the optimal number of Distribution Centers required. After implementing our algorithm with 4 clusters, the location of DC’s found are shown below: The recommended DC locations found after implementing the algorithm are: Riverside, CaliforniaDallas, TexasUrbana, IllinoisPetersburg, Virginia. Riverside, California Dallas, Texas Urbana, Illinois Petersburg, Virginia. In this article, an application of the weighted K-means clustering algorithm to determine optimal Distribution locations is demonstrated. To summarize, in this modified K-Means clustering, the centroids are calculated by considering the weighted average instead of the mean, and haversine distance is used instead of euclidean distance. I hope that’s useful! Feel free to direct message me on LinkedIn if you have any questions. And code can be found in my Github repository.
[ { "code": null, "e": 538, "s": 172, "text": "Everyone here must have heard of Amazon and its growth in recent years. One of the main reasons for the success of Amazon is its supply chain management. All the people who have ordered at least once from Amazon should be familiar with their popular 1-day shipping. Ever wondered how companies like Amazon can deliver products so quickly to any location in the USA?" }, { "code": null, "e": 980, "s": 538, "text": "This is not a simple task to achieve, considering the vast magnitude of land in the USA and the number of orders they receive each day from all corners of the country. It turns out, most of the products you order are directly shipping from your state, not from somewhere else. All companies like Walmart, Amazon store surplus products, which customers don’t need immediately in the distribution centers based on customer demand anticipation." }, { "code": null, "e": 1353, "s": 980, "text": "All the services such as product mixing, order fulfillment, cross-docking, packaging are done in distribution centers. These DC’s are located so they can be used to deliver goods to the maximum area possible in the shortest time. For any company to become successful, an effective supply chain strategy is a must, and DC’s play a crucial role in the supply chain strategy." }, { "code": null, "e": 1985, "s": 1353, "text": "The total COVID 19 cases count has passed the 7 million mark on 24th September in the USA. On the other hand, many countries like the UK claim that their COVID -19 vaccine development is in the final stages and will be released by the end of 2020. I thought it would be interesting to find out when the vaccine is finally released and distributed across all the hospitals, including clinical centers treating COVID-19 patients in the USA. If the US government is planning to make use of Distribution Center’s to supply vaccination to all hospitals treating COVID-19 patients, Where should DC’s be located? How many DC’s are needed?" }, { "code": null, "e": 2390, "s": 1985, "text": "First, I started with some web scrapping from Wikipedia to get all hospitals in the USA with their Address and County Name. And matched the county name of the hospital regions with the active COVID-19 cases in that region. To make it easier for plotting and finding distance, I found latitudes and longitudes for all the addresses using geocoding, for which I clearly explained steps in my previous blog." }, { "code": null, "e": 2413, "s": 2390, "text": "towardsdatascience.com" }, { "code": null, "e": 2498, "s": 2413, "text": "The glimpse of data set after finding latitudes and longitudes for all the hospitals" }, { "code": null, "e": 2693, "s": 2498, "text": "Now that we have latitudes and longitudes, it is very easy to plot them. The image below represents all the hospitals in the USA with active COVID-19 cases generated using folium maps in python." }, { "code": null, "e": 3310, "s": 2693, "text": "Here, the points with bigger circles represent the regions with more COVID-19 active cases. It can be clearly seen that some regions in California have the highest number of active cases. Back to our problem, where we are trying to find the optimal locations for Distribution Centers to supply vaccines to all hospitals. Here, determining DC’s location for specific hospitals is similar to dividing all the hospitals into different clusters and locating one centroid point for each cluster of hospitals. This situation is very similar to the K-Means clustering algorithm. Therefore K-Means clustering can be applied." }, { "code": null, "e": 3351, "s": 3310, "text": "How (Standard) K-Means Clustering works?" }, { "code": null, "e": 3665, "s": 3351, "text": "K-Means clustering is a popular unsupervised ML algorithm used for partitioning data into K clusters. The algorithm works iteratively to assign each data point to one of the K groups. The data is randomly divided into K groups with a mean centroid point assigned to each group, and the algorithm iterates to find:" }, { "code": null, "e": 3876, "s": 3665, "text": "The distance between all the data points to the centroid points and forms new clusters by reassigning the data points to its nearest centroid.Again new centroid points are found by taking the mean of distances." }, { "code": null, "e": 4019, "s": 3876, "text": "The distance between all the data points to the centroid points and forms new clusters by reassigning the data points to its nearest centroid." }, { "code": null, "e": 4088, "s": 4019, "text": "Again new centroid points are found by taking the mean of distances." }, { "code": null, "e": 4210, "s": 4088, "text": "This process is iterated repeatedly until the Sum of Squared distances are minimized, or the predefined limit is reached." }, { "code": null, "e": 4501, "s": 4210, "text": "An important step to be performed before starting the k-means is to decide on the number of clusters. The number of K is a predefined hyperparameter that should be tuned to get an optimal result. This can be done using the elbow method, which will be briefly explained later in the article." }, { "code": null, "e": 4677, "s": 4501, "text": "This is a versatile algorithm that can be used for any grouping. Some examples of use cases are Grouping Inventory based on demand or customer segmentation based on purchases." }, { "code": null, "e": 4694, "s": 4677, "text": "Problem Solving:" }, { "code": null, "e": 4869, "s": 4694, "text": "The only problem we have here is more preference should be given to the locations with more active COVID-19 cases. This is where Weighted K-Means Clustering comes in to play." }, { "code": null, "e": 5107, "s": 4869, "text": "The standard K-means approach would not work because it fails to consider the fact that some regions where hospitals are located have more active COVID-19 cases, which implies having a higher volume demand for the vaccine to be supplied." }, { "code": null, "e": 5159, "s": 5107, "text": "How Weighted K-Means differs from Standard K-Means?" }, { "code": null, "e": 5681, "s": 5159, "text": "The weighted K-Means work the same as standard K-Means clustering. The only difference would be instead of just calculating centroid points based on the mean of distances. The weighted average should be used. Thus, the bigger the weight of the data point, the nearer centroid will be pulled. The image below shows the illustration of Standard K-Means vs. weighted K-Means. Here, in the right image, the weight of data points is higher for W2 and W3. So, the centroid is pulled them instead of being located in the center." }, { "code": null, "e": 5929, "s": 5681, "text": "The weighted can be given to any variable we want from the dataset, like urban cities or the city's total populations. In our case, the weightage will be given to the total active COVID-19 cases per county. So they should be given more preference." }, { "code": null, "e": 6352, "s": 5929, "text": "One more problem is that we cannot use traditional Euclidean distance as a distance metric to find centroid points because we have latitudes and longitudes that represent earth spherical dimensions instead of 2D (x,y) coordinates in euclidean distances. Many options are available to calculate the distance between two spherical points like Haversine distance or Great circle distance. We will be using Haversine distance." }, { "code": null, "e": 6371, "s": 6352, "text": "Haversine Distance" }, { "code": null, "e": 6498, "s": 6371, "text": "The haversine distance d can be found using the following formulae, where φ represents latitudes, and λ represents longitudes." }, { "code": null, "e": 6561, "s": 6498, "text": "a = sin2(( φB — φA) /2) + cos φA * cos φB * sin2((λB — λA) /2)" }, { "code": null, "e": 6589, "s": 6561, "text": "c = 2 * atan2( √a, √(1−a) )" }, { "code": null, "e": 6636, "s": 6589, "text": "d = R ⋅ c (R = Radius of earth, i.e, 6,371 KM)" }, { "code": null, "e": 6862, "s": 6636, "text": "Luckily, We don’t need to use all these formulae to calculate haversine distance because, in python, there is a library named haversine which directly calculates the distance between location coordinates with one line of code" }, { "code": null, "e": 6950, "s": 6862, "text": "from haversine import haversinehaversine((31.215827,-85.363433),(28.703230,-81.815668))" }, { "code": null, "e": 7113, "s": 6950, "text": "Using Weighted K-Means with Haversine distance as a distance metric, a modified Weighted K-Means algorithm is created, which can be found in my Github repository." }, { "code": null, "e": 7325, "s": 7113, "text": "Finally, we need to determine the optimal number of distribution centers to fulfill the demand better and minimize delivery expenses. i.e., the optimal number of K. This can be determined using the Elbow method." }, { "code": null, "e": 7338, "s": 7325, "text": "Elbow Method" }, { "code": null, "e": 8052, "s": 7338, "text": "In cluster analysis, the elbow method is a heuristic used in determining the optimal number of clusters in a data set. The Within-Cluster-Sum of Squared Errors (SSE) for different values of ‘k’ is calculated. For whichever ‘k’ value the WSS becomes first starts to diminish, that particular ‘k’ is chosen. Typically, the K value where it forms an elbow shape is considered as an optimal value. The SSE is nothing but the sum of squares of each data point's distances in all clusters to their respective centroids. The below plot represents the SSE vs. the number of clusters for our data. Since the decrease in SSE value is no longer significant after 4 clusters. The K=4 can be considered as our optimum K-Value." }, { "code": null, "e": 8227, "s": 8052, "text": "Finally, we found that 4 is the optimal number of Distribution Centers required. After implementing our algorithm with 4 clusters, the location of DC’s found are shown below:" }, { "code": null, "e": 8300, "s": 8227, "text": "The recommended DC locations found after implementing the algorithm are:" }, { "code": null, "e": 8372, "s": 8300, "text": "Riverside, CaliforniaDallas, TexasUrbana, IllinoisPetersburg, Virginia." }, { "code": null, "e": 8394, "s": 8372, "text": "Riverside, California" }, { "code": null, "e": 8408, "s": 8394, "text": "Dallas, Texas" }, { "code": null, "e": 8425, "s": 8408, "text": "Urbana, Illinois" }, { "code": null, "e": 8447, "s": 8425, "text": "Petersburg, Virginia." }, { "code": null, "e": 8784, "s": 8447, "text": "In this article, an application of the weighted K-means clustering algorithm to determine optimal Distribution locations is demonstrated. To summarize, in this modified K-Means clustering, the centroids are calculated by considering the weighted average instead of the mean, and haversine distance is used instead of euclidean distance." } ]
Tryit Editor v3.6 - Show React
import React from 'react'; import ReactDOM from 'react-dom/client'; class Header extends React.Component { constructor(props) { super(props); this.state = {favoritecolor: "red"}; } componentDidMount() { setTimeout(() => { this.setState({favoritecolor: "yellow"}) }, 1000) } getSnapshotBeforeUpdate(prevProps, prevState) { document.getElementById("div1").innerHTML = "Before the update, the favorite was " + prevState.favoritecolor; } componentDidUpdate() { document.getElementById("div2").innerHTML = "The updated favorite is " + this.state.favoritecolor; } render() { return ( <div> <h1>My Favorite Color is {this.state.favoritecolor}</h1> <div id="div1"></div> <div id="div2"></div> </div> ); } } const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<Header />); <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" />
[ { "code": null, "e": 892, "s": 0, "text": "\nimport React from 'react';\nimport ReactDOM from 'react-dom/client';\n\nclass Header extends React.Component {\n constructor(props) {\n super(props);\n this.state = {favoritecolor: \"red\"};\n }\n componentDidMount() {\n setTimeout(() => {\n this.setState({favoritecolor: \"yellow\"})\n }, 1000)\n }\n getSnapshotBeforeUpdate(prevProps, prevState) {\n document.getElementById(\"div1\").innerHTML =\n \"Before the update, the favorite was \" + prevState.favoritecolor;\n }\n componentDidUpdate() {\n document.getElementById(\"div2\").innerHTML =\n \"The updated favorite is \" + this.state.favoritecolor;\n }\n render() {\n return (\n <div>\n <h1>My Favorite Color is {this.state.favoritecolor}</h1>\n <div id=\"div1\"></div>\n <div id=\"div2\"></div>\n </div>\n );\n }\n}\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(<Header />);\n\n" } ]
How to split images into different channels in OpenCV using C++?
There are three channels in an RGB image- red, green and blue. The color space where red, green and blue channels represent images is called RGB color space. In OpenCV, BGR sequence is used instead of RGB. This means the first channel is blue, the second channel is green, and the third channel is red. To split an RGB image into different channels, we need to define a matrix of 3 channels. We use 'Mat different_Channels[3]' to define a three-channel matrix. Next, we split the loaded image using OpenCV 'split()' function. The format of this function is 'split(Source Matrix, Destination Matrix)'. This function split the images of the source matrix into the channels the image and save them in the destination matrix. This line is operating – 'split(myImage, different_Channels);' The split function has already loaded the blue, green and red channel into the 'different_channels' matrix. Using the following lines, we loaded the images stored in different channels into new matrices. Mat b = different_Channels[0];//loading blue channels// Mat g = different_Channels[1];//loading green channels// Mat r = different_Channels[2];//loading red channels// And finally we showed each channel differently using the following lines − imshow("Blue Channel",b);//showing Blue channel// imshow("Green Channel",g);//showing Green channel// imshow("Red Channel",r);//showing Red channel// This is how we can split an images into its channels. The following program splits an RGB image into blue, green, and red channel. #include<iostream> #include<opencv2/highgui/highgui.hpp> #include<opencv2/imgproc/imgproc.hpp> using namespace cv; using namespace std; int main(int argc,const char** argv) { Mat myImage;//declaring a matrix to load the image// Mat different_Channels[3];//declaring a matrix with three channels// myImage= imread("RGB.png");//loading the image in myImage matrix// split(myImage, different_Channels);//splitting images into 3 different channels// Mat b = different_Channels[0];//loading blue channels// Mat g = different_Channels[1];//loading green channels// Mat r = different_Channels[2];//loading red channels// imshow("Blue Channel",b);//showing Blue channel// imshow("Green Channel",g);//showing Green channel// imshow("Red Channel",r);//showing Red channel// imshow("Actual_Image", myImage);//showing actual image// waitKey(0);//wait for key stroke destroyAllWindows();//closing all windows// return 0; }
[ { "code": null, "e": 1523, "s": 1062, "text": "There are three channels in an RGB image- red, green and blue. The color space where red, green and blue channels represent images is called RGB color space. In OpenCV, BGR sequence is used instead of RGB. This means the first channel is blue, the second channel is green, and the third channel is red. To split an RGB image into different channels, we need to define a matrix of 3 channels. We use 'Mat different_Channels[3]' to define a three-channel matrix." }, { "code": null, "e": 1847, "s": 1523, "text": "Next, we split the loaded image using OpenCV 'split()' function. The format of this function is 'split(Source Matrix, Destination Matrix)'. This function split the images of the source matrix into the channels the image and save them in the destination matrix. This line is operating – 'split(myImage, different_Channels);'" }, { "code": null, "e": 2051, "s": 1847, "text": "The split function has already loaded the blue, green and red channel into the 'different_channels' matrix. Using the following lines, we loaded the images stored in different channels into new matrices." }, { "code": null, "e": 2219, "s": 2051, "text": "Mat b = different_Channels[0];//loading blue channels//\nMat g = different_Channels[1];//loading green channels//\nMat r = different_Channels[2];//loading red channels//" }, { "code": null, "e": 2294, "s": 2219, "text": "And finally we showed each channel differently using the following lines −" }, { "code": null, "e": 2444, "s": 2294, "text": "imshow(\"Blue Channel\",b);//showing Blue channel//\nimshow(\"Green Channel\",g);//showing Green channel//\nimshow(\"Red Channel\",r);//showing Red channel//" }, { "code": null, "e": 2498, "s": 2444, "text": "This is how we can split an images into its channels." }, { "code": null, "e": 2575, "s": 2498, "text": "The following program splits an RGB image into blue, green, and red channel." }, { "code": null, "e": 3533, "s": 2575, "text": "#include<iostream>\n#include<opencv2/highgui/highgui.hpp>\n#include<opencv2/imgproc/imgproc.hpp>\nusing namespace cv;\nusing namespace std;\nint main(int argc,const char** argv) {\n Mat myImage;//declaring a matrix to load the image//\n Mat different_Channels[3];//declaring a matrix with three channels// \n myImage= imread(\"RGB.png\");//loading the image in myImage matrix//\n split(myImage, different_Channels);//splitting images into 3 different channels// \n Mat b = different_Channels[0];//loading blue channels//\n Mat g = different_Channels[1];//loading green channels//\n Mat r = different_Channels[2];//loading red channels// \n imshow(\"Blue Channel\",b);//showing Blue channel//\n imshow(\"Green Channel\",g);//showing Green channel//\n imshow(\"Red Channel\",r);//showing Red channel//\n imshow(\"Actual_Image\", myImage);//showing actual image//\n waitKey(0);//wait for key stroke\n destroyAllWindows();//closing all windows//\n return 0;\n}" } ]
HTML <tt> Tag - GeeksforGeeks
17 Mar, 2022 The <tt> tag is the abbreviation of teletype text. This tag is depreciated from HTML 5. It was used for marking Keyboard input. It was mainly used for formatting purposes. This tag was used in HTML 4 (Not Supported in HTML5).Syntax: <tt> Contents... </tt> Below example illustrates the <tt> tag in HTML: Example: HTML <html> <body> <h1>GeeksforGeeks</h1> <h2>tt Tag</h2> <!-- HTML tt Tag is used here--> <tt>GfG stands for GeeksforGeeks</tt> <p><tt>It is a computer science portal for geeks</tt></p> </body> </html> Output: Supported Browsers: Google Chrome Internet Explorer Firefox Opera Safari Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. arorakashish0911 shubhamyadav4 HTML-Tags HTML HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to set the default value for an HTML <select> element ? How to update Node.js and NPM to next version ? How to set input type date in dd-mm-yyyy format using HTML ? Types of CSS (Cascading Style Sheet) Hide or show elements in HTML using display property How to Insert Form Data into Database using PHP ? CSS to put icon inside an input element in a form REST API (Introduction)
[ { "code": null, "e": 22710, "s": 22682, "text": "\n17 Mar, 2022" }, { "code": null, "e": 22944, "s": 22710, "text": "The <tt> tag is the abbreviation of teletype text. This tag is depreciated from HTML 5. It was used for marking Keyboard input. It was mainly used for formatting purposes. This tag was used in HTML 4 (Not Supported in HTML5).Syntax: " }, { "code": null, "e": 22967, "s": 22944, "text": "<tt> Contents... </tt>" }, { "code": null, "e": 23015, "s": 22967, "text": "Below example illustrates the <tt> tag in HTML:" }, { "code": null, "e": 23025, "s": 23015, "text": "Example: " }, { "code": null, "e": 23030, "s": 23025, "text": "HTML" }, { "code": "<html> <body> <h1>GeeksforGeeks</h1> <h2>tt Tag</h2> <!-- HTML tt Tag is used here--> <tt>GfG stands for GeeksforGeeks</tt> <p><tt>It is a computer science portal for geeks</tt></p> </body> </html> ", "e": 23331, "s": 23030, "text": null }, { "code": null, "e": 23340, "s": 23331, "text": "Output: " }, { "code": null, "e": 23361, "s": 23340, "text": "Supported Browsers: " }, { "code": null, "e": 23375, "s": 23361, "text": "Google Chrome" }, { "code": null, "e": 23393, "s": 23375, "text": "Internet Explorer" }, { "code": null, "e": 23401, "s": 23393, "text": "Firefox" }, { "code": null, "e": 23407, "s": 23401, "text": "Opera" }, { "code": null, "e": 23414, "s": 23407, "text": "Safari" }, { "code": null, "e": 23553, "s": 23416, "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": 23570, "s": 23553, "text": "arorakashish0911" }, { "code": null, "e": 23584, "s": 23570, "text": "shubhamyadav4" }, { "code": null, "e": 23594, "s": 23584, "text": "HTML-Tags" }, { "code": null, "e": 23599, "s": 23594, "text": "HTML" }, { "code": null, "e": 23604, "s": 23599, "text": "HTML" }, { "code": null, "e": 23702, "s": 23604, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 23711, "s": 23702, "text": "Comments" }, { "code": null, "e": 23724, "s": 23711, "text": "Old Comments" }, { "code": null, "e": 23786, "s": 23724, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 23836, "s": 23786, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 23896, "s": 23836, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 23944, "s": 23896, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 24005, "s": 23944, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 24042, "s": 24005, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 24095, "s": 24042, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 24145, "s": 24095, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 24195, "s": 24145, "text": "CSS to put icon inside an input element in a form" } ]
vector::begin() and vector::end() in C++ STL
17 Jun, 2022 Vectors are the same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. begin() function is used to return an iterator pointing to the first element of the vector container. begin() function returns a bidirectional iterator to the first element of the container. Syntax : vectorname.begin() Parameters: No parameters are passed. Return Type: This function returns a bidirectional iterator pointing to the first element. Examples: Input : myvector{1, 2, 3, 4, 5}; myvector.begin(); Output : returns an iterator to the element 1 Input : myvector{"This", "is", "Geeksforgeeks"}; myvector.begin(); Output : returns an iterator to the element This It has a no exception throw guarantee. Shows error when a parameter is passed. CPP // INTEGER VECTOR EXAMPLE// CPP program to illustrate// Implementation of begin() function#include <iostream>#include <vector>using namespace std; int main(){ // declaration of vector container vector<int> myvector{ 1, 2, 3, 4, 5 }; // using begin() to print vector for (auto it = myvector.begin(); it != myvector.end(); ++it) cout << ' ' << *it; return 0;} Output: 1 2 3 4 5 CPP // STRING VECTOR EXAMPLE// CPP program to illustrate// Implementation of begin() function#include <iostream>#include <string>#include <vector>using namespace std; int main(){ // declaration of vector container vector<string> myvector{ "This", "is", "Geeksforgeeks" }; // using begin() to print vector for (auto it = myvector.begin(); it != myvector.end(); ++it) cout << ' ' << *it; return 0;} Output: This is Geeksforgeeks Time Complexity: O(1) end() function is used to return an iterator pointing next to last element of the vector container. end() function returns a bidirectional iterator. Syntax : vectorname.end() Parameters : No parameters are passed. Return Type: This function returns a bidirectional iterator pointing to next to last element. Examples: Input : myvector{1, 2, 3, 4, 5}; myvector.end(); Output : returns an iterator after 5 Input : myvector{"computer", "science", "portal"}; myvector.end(); Output : returns an iterator after portal Errors and Exceptions It has a no exception throw guarantee. Shows error when a parameter is passed. It has a no exception throw guarantee. Shows error when a parameter is passed. CPP // INTEGER VECTOR EXAMPLE// CPP program to illustrate// Implementation of end() function#include <iostream>#include <vector>using namespace std; int main(){ // declaration of vector container vector<int> myvector{ 1, 2, 3, 4, 5 }; // using end() to print vector for (auto it = myvector.begin(); it != myvector.end(); ++it) cout << ' ' << *it; return 0;} Output: 1 2 3 4 5 CPP // STRING VECTOR EXAMPLE// CPP program to illustrate// Implementation of end() function#include <iostream>#include <string>#include <vector>using namespace std; int main(){ // declaration of vector container vector<string> myvector{ "computer", "science", "portal" }; // using end() to print vector for (auto it = myvector.begin(); it != myvector.end(); ++it) cout << ' ' << *it; return 0;} Output: computer science portal Time Complexity: O(1) Let us see the differences in a tabular form is as follows: Its syntax is -: iterator begin(); Its syntax is -: iterator end(); jjaydeepjha mayank007rawa cpp-vector STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Sorting a vector in C++ Polymorphism in C++ Friend class and function in C++ std::string class in C++ Pair in C++ Standard Template Library (STL) Queue in C++ Standard Template Library (STL) Unordered Sets in C++ Standard Template Library List in C++ Standard Template Library (STL) std::find in C++ Inline Functions in C++
[ { "code": null, "e": 52, "s": 24, "text": "\n17 Jun, 2022" }, { "code": null, "e": 244, "s": 52, "text": "Vectors are the same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container." }, { "code": null, "e": 435, "s": 244, "text": "begin() function is used to return an iterator pointing to the first element of the vector container. begin() function returns a bidirectional iterator to the first element of the container." }, { "code": null, "e": 445, "s": 435, "text": "Syntax : " }, { "code": null, "e": 596, "s": 445, "text": "vectorname.begin()\n\nParameters: No parameters are passed.\n\nReturn Type: \nThis function returns a bidirectional\niterator pointing to the first element." }, { "code": null, "e": 608, "s": 596, "text": "Examples: " }, { "code": null, "e": 842, "s": 608, "text": "Input : myvector{1, 2, 3, 4, 5};\n myvector.begin();\nOutput : returns an iterator to the element 1\n\nInput : myvector{\"This\", \"is\", \"Geeksforgeeks\"};\n myvector.begin();\nOutput : returns an iterator to the element This" }, { "code": null, "e": 882, "s": 842, "text": "It has a no exception throw guarantee. " }, { "code": null, "e": 923, "s": 882, "text": "Shows error when a parameter is passed. " }, { "code": null, "e": 927, "s": 923, "text": "CPP" }, { "code": "// INTEGER VECTOR EXAMPLE// CPP program to illustrate// Implementation of begin() function#include <iostream>#include <vector>using namespace std; int main(){ // declaration of vector container vector<int> myvector{ 1, 2, 3, 4, 5 }; // using begin() to print vector for (auto it = myvector.begin(); it != myvector.end(); ++it) cout << ' ' << *it; return 0;}", "e": 1316, "s": 927, "text": null }, { "code": null, "e": 1325, "s": 1316, "text": "Output: " }, { "code": null, "e": 1335, "s": 1325, "text": "1 2 3 4 5" }, { "code": null, "e": 1339, "s": 1335, "text": "CPP" }, { "code": "// STRING VECTOR EXAMPLE// CPP program to illustrate// Implementation of begin() function#include <iostream>#include <string>#include <vector>using namespace std; int main(){ // declaration of vector container vector<string> myvector{ \"This\", \"is\", \"Geeksforgeeks\" }; // using begin() to print vector for (auto it = myvector.begin(); it != myvector.end(); ++it) cout << ' ' << *it; return 0;}", "e": 1791, "s": 1339, "text": null }, { "code": null, "e": 1800, "s": 1791, "text": "Output: " }, { "code": null, "e": 1822, "s": 1800, "text": "This is Geeksforgeeks" }, { "code": null, "e": 1844, "s": 1822, "text": "Time Complexity: O(1)" }, { "code": null, "e": 1993, "s": 1844, "text": "end() function is used to return an iterator pointing next to last element of the vector container. end() function returns a bidirectional iterator." }, { "code": null, "e": 2003, "s": 1993, "text": "Syntax : " }, { "code": null, "e": 2155, "s": 2003, "text": "vectorname.end()\n\nParameters :\nNo parameters are passed.\n\nReturn Type:\nThis function returns a bidirectional\niterator pointing to next to last element." }, { "code": null, "e": 2167, "s": 2155, "text": "Examples: " }, { "code": null, "e": 2383, "s": 2167, "text": "Input : myvector{1, 2, 3, 4, 5};\n myvector.end();\nOutput : returns an iterator after 5\n\nInput : myvector{\"computer\", \"science\", \"portal\"};\n myvector.end();\nOutput : returns an iterator after portal" }, { "code": null, "e": 2405, "s": 2383, "text": "Errors and Exceptions" }, { "code": null, "e": 2484, "s": 2405, "text": "It has a no exception throw guarantee. Shows error when a parameter is passed." }, { "code": null, "e": 2524, "s": 2484, "text": "It has a no exception throw guarantee. " }, { "code": null, "e": 2564, "s": 2524, "text": "Shows error when a parameter is passed." }, { "code": null, "e": 2568, "s": 2564, "text": "CPP" }, { "code": "// INTEGER VECTOR EXAMPLE// CPP program to illustrate// Implementation of end() function#include <iostream>#include <vector>using namespace std; int main(){ // declaration of vector container vector<int> myvector{ 1, 2, 3, 4, 5 }; // using end() to print vector for (auto it = myvector.begin(); it != myvector.end(); ++it) cout << ' ' << *it; return 0;}", "e": 2953, "s": 2568, "text": null }, { "code": null, "e": 2962, "s": 2953, "text": "Output: " }, { "code": null, "e": 2972, "s": 2962, "text": "1 2 3 4 5" }, { "code": null, "e": 2976, "s": 2972, "text": "CPP" }, { "code": "// STRING VECTOR EXAMPLE// CPP program to illustrate// Implementation of end() function#include <iostream>#include <string>#include <vector>using namespace std; int main(){ // declaration of vector container vector<string> myvector{ \"computer\", \"science\", \"portal\" }; // using end() to print vector for (auto it = myvector.begin(); it != myvector.end(); ++it) cout << ' ' << *it; return 0;}", "e": 3426, "s": 2976, "text": null }, { "code": null, "e": 3435, "s": 3426, "text": "Output: " }, { "code": null, "e": 3459, "s": 3435, "text": "computer science portal" }, { "code": null, "e": 3482, "s": 3459, "text": "Time Complexity: O(1) " }, { "code": null, "e": 3542, "s": 3482, "text": "Let us see the differences in a tabular form is as follows:" }, { "code": null, "e": 3559, "s": 3542, "text": "Its syntax is -:" }, { "code": null, "e": 3577, "s": 3559, "text": "iterator begin();" }, { "code": null, "e": 3594, "s": 3577, "text": "Its syntax is -:" }, { "code": null, "e": 3610, "s": 3594, "text": "iterator end();" }, { "code": null, "e": 3622, "s": 3610, "text": "jjaydeepjha" }, { "code": null, "e": 3636, "s": 3622, "text": "mayank007rawa" }, { "code": null, "e": 3647, "s": 3636, "text": "cpp-vector" }, { "code": null, "e": 3651, "s": 3647, "text": "STL" }, { "code": null, "e": 3655, "s": 3651, "text": "C++" }, { "code": null, "e": 3659, "s": 3655, "text": "STL" }, { "code": null, "e": 3663, "s": 3659, "text": "CPP" }, { "code": null, "e": 3761, "s": 3663, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3785, "s": 3761, "text": "Sorting a vector in C++" }, { "code": null, "e": 3805, "s": 3785, "text": "Polymorphism in C++" }, { "code": null, "e": 3838, "s": 3805, "text": "Friend class and function in C++" }, { "code": null, "e": 3863, "s": 3838, "text": "std::string class in C++" }, { "code": null, "e": 3907, "s": 3863, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 3952, "s": 3907, "text": "Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 4000, "s": 3952, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 4044, "s": 4000, "text": "List in C++ Standard Template Library (STL)" }, { "code": null, "e": 4061, "s": 4044, "text": "std::find in C++" } ]
pandas.isna() function in Python
14 Aug, 2020 This method is used to detect missing values for an array-like object. This function takes a scalar or array-like object and indicates whether values are missing (“NaN“ in numeric arrays, “None“ or “NaN“ in object arrays, “NaT“ in datetimelike). Syntax : pandas.isna(obj) Argument : obj : scalar or array-like, Object to check for null or missing values. Below is the implementation of the above method with some examples : Example 1 : Python3 # importing packageimport numpyimport pandas # string "deep" is not nan valueprint(pandas.isna("deep")) # numpy.nan represents a nan valueprint(pandas.isna(numpy.nan)) Output : False True Example 2 : Python3 # importing packageimport numpyimport pandas # create and view dataarray = numpy.array([[1, numpy.nan, 3], [4, 5, numpy.nan]]) print(array) # numpy.nan represents a nan valueprint(pandas.isna(array)) Output : [[ 1. nan 3.] [ 4. 5. nan]] [[False True False] [False False True]] Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Aug, 2020" }, { "code": null, "e": 274, "s": 28, "text": "This method is used to detect missing values for an array-like object. This function takes a scalar or array-like object and indicates whether values are missing (“NaN“ in numeric arrays, “None“ or “NaN“ in object arrays, “NaT“ in datetimelike)." }, { "code": null, "e": 300, "s": 274, "text": "Syntax : pandas.isna(obj)" }, { "code": null, "e": 311, "s": 300, "text": "Argument :" }, { "code": null, "e": 383, "s": 311, "text": "obj : scalar or array-like, Object to check for null or missing values." }, { "code": null, "e": 452, "s": 383, "text": "Below is the implementation of the above method with some examples :" }, { "code": null, "e": 464, "s": 452, "text": "Example 1 :" }, { "code": null, "e": 472, "s": 464, "text": "Python3" }, { "code": "# importing packageimport numpyimport pandas # string \"deep\" is not nan valueprint(pandas.isna(\"deep\")) # numpy.nan represents a nan valueprint(pandas.isna(numpy.nan))", "e": 642, "s": 472, "text": null }, { "code": null, "e": 651, "s": 642, "text": "Output :" }, { "code": null, "e": 663, "s": 651, "text": "False\nTrue\n" }, { "code": null, "e": 675, "s": 663, "text": "Example 2 :" }, { "code": null, "e": 683, "s": 675, "text": "Python3" }, { "code": "# importing packageimport numpyimport pandas # create and view dataarray = numpy.array([[1, numpy.nan, 3], [4, 5, numpy.nan]]) print(array) # numpy.nan represents a nan valueprint(pandas.isna(array))", "e": 907, "s": 683, "text": null }, { "code": null, "e": 916, "s": 907, "text": "Output :" }, { "code": null, "e": 991, "s": 916, "text": "[[ 1. nan 3.]\n [ 4. 5. nan]]\n[[False True False]\n [False False True]]\n" }, { "code": null, "e": 1005, "s": 991, "text": "Python-pandas" }, { "code": null, "e": 1012, "s": 1005, "text": "Python" } ]
time.Time.AddDate() Function in Golang with Examples
19 Apr, 2020 In Go language, time packages supplies functionality for determining as well as viewing time. The Time.AddDate() function in Go language is used to check the time which is equivalent to adding the stated number of years, months, and days to the given “t”.For example, if the parameters of the method are like (-2, 4, 5) and the stated t is February 3, 2018 then the output will be June 8, 2016. Like Date method here also if the range of months, days or years are outside the normal range then its automatically converted to normalized range. Moreover, this function is defined under the time package. Here, you need to import “time” package in order to use these functions. Syntax: func (t Time) AddDate(years int, months int, days int) Time Here, “t” is the stated time. Return Value: It returns the result of adding stated t to the stated number of years, months, and days. Example 1: // Golang program to illustrate the usage of// Time.AddDate() function // Including main packagepackage main // Importing fmt and timeimport "fmt"import "time" // Calling mainfunc main() { // Declaring Time in UTC Time := time.Date(2018, 6, 4, 0, 0, 0, 0, time.UTC) // Calling AddDate method with all // its parameters t1 := Time.AddDate(1, 2, 5) t2 := Time.AddDate(5, -2, 9) t3 := Time.AddDate(0, 3, -3) t4 := Time.AddDate(1, 0, 0) // Prints output fmt.Printf("%v\n", Time) fmt.Printf("%v\n", t1) fmt.Printf("%v\n", t2) fmt.Printf("%v\n", t3) fmt.Printf("%v\n", t4)} Output: 2018-06-04 00:00:00 +0000 UTC 2019-08-09 00:00:00 +0000 UTC 2023-04-13 00:00:00 +0000 UTC 2018-09-01 00:00:00 +0000 UTC 2019-06-04 00:00:00 +0000 UTC Here, the output returned is in UTC as defined above. Example 2: // Golang program to illustrate the usage of// Time.AddDate() function // Including main packagepackage main // Importing fmt and timeimport "fmt"import "time" // Calling mainfunc main() { // Declaring Time in UTC Time := time.Date(2020, 15, 34, 0, 0, 0, 0, time.UTC) // Calling AddDate method with all // its parameters t1 := Time.AddDate(3, 13, 35) t2 := Time.AddDate(2, -24, 29) t3 := Time.AddDate(4, 32, -31) t4 := Time.AddDate(5, 10, -11) // Prints output fmt.Printf("%v\n", Time) fmt.Printf("%v\n", t1) fmt.Printf("%v\n", t2) fmt.Printf("%v\n", t3) fmt.Printf("%v\n", t4)} Output: 2021-04-03 00:00:00 +0000 UTC 2025-06-07 00:00:00 +0000 UTC 2021-05-02 00:00:00 +0000 UTC 2027-11-02 00:00:00 +0000 UTC 2027-01-23 00:00:00 +0000 UTC Here, the range used is outside the usual range but they are normalized while converted. GoLang-time Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. strings.Replace() Function in Golang With Examples fmt.Sprintf() Function in Golang With Examples Arrays in Go Golang Maps How to Split a String in Golang? Interfaces in Golang Slices in Golang Different Ways to Find the Type of Variable in Golang How to Parse JSON in Golang? How to convert a string in lower case in Golang?
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Apr, 2020" }, { "code": null, "e": 703, "s": 28, "text": "In Go language, time packages supplies functionality for determining as well as viewing time. The Time.AddDate() function in Go language is used to check the time which is equivalent to adding the stated number of years, months, and days to the given “t”.For example, if the parameters of the method are like (-2, 4, 5) and the stated t is February 3, 2018 then the output will be June 8, 2016. Like Date method here also if the range of months, days or years are outside the normal range then its automatically converted to normalized range. Moreover, this function is defined under the time package. Here, you need to import “time” package in order to use these functions." }, { "code": null, "e": 711, "s": 703, "text": "Syntax:" }, { "code": null, "e": 772, "s": 711, "text": "func (t Time) AddDate(years int, months int, days int) Time\n" }, { "code": null, "e": 802, "s": 772, "text": "Here, “t” is the stated time." }, { "code": null, "e": 906, "s": 802, "text": "Return Value: It returns the result of adding stated t to the stated number of years, months, and days." }, { "code": null, "e": 917, "s": 906, "text": "Example 1:" }, { "code": "// Golang program to illustrate the usage of// Time.AddDate() function // Including main packagepackage main // Importing fmt and timeimport \"fmt\"import \"time\" // Calling mainfunc main() { // Declaring Time in UTC Time := time.Date(2018, 6, 4, 0, 0, 0, 0, time.UTC) // Calling AddDate method with all // its parameters t1 := Time.AddDate(1, 2, 5) t2 := Time.AddDate(5, -2, 9) t3 := Time.AddDate(0, 3, -3) t4 := Time.AddDate(1, 0, 0) // Prints output fmt.Printf(\"%v\\n\", Time) fmt.Printf(\"%v\\n\", t1) fmt.Printf(\"%v\\n\", t2) fmt.Printf(\"%v\\n\", t3) fmt.Printf(\"%v\\n\", t4)}", "e": 1536, "s": 917, "text": null }, { "code": null, "e": 1544, "s": 1536, "text": "Output:" }, { "code": null, "e": 1695, "s": 1544, "text": "2018-06-04 00:00:00 +0000 UTC\n2019-08-09 00:00:00 +0000 UTC\n2023-04-13 00:00:00 +0000 UTC\n2018-09-01 00:00:00 +0000 UTC\n2019-06-04 00:00:00 +0000 UTC\n" }, { "code": null, "e": 1749, "s": 1695, "text": "Here, the output returned is in UTC as defined above." }, { "code": null, "e": 1760, "s": 1749, "text": "Example 2:" }, { "code": "// Golang program to illustrate the usage of// Time.AddDate() function // Including main packagepackage main // Importing fmt and timeimport \"fmt\"import \"time\" // Calling mainfunc main() { // Declaring Time in UTC Time := time.Date(2020, 15, 34, 0, 0, 0, 0, time.UTC) // Calling AddDate method with all // its parameters t1 := Time.AddDate(3, 13, 35) t2 := Time.AddDate(2, -24, 29) t3 := Time.AddDate(4, 32, -31) t4 := Time.AddDate(5, 10, -11) // Prints output fmt.Printf(\"%v\\n\", Time) fmt.Printf(\"%v\\n\", t1) fmt.Printf(\"%v\\n\", t2) fmt.Printf(\"%v\\n\", t3) fmt.Printf(\"%v\\n\", t4)}", "e": 2390, "s": 1760, "text": null }, { "code": null, "e": 2398, "s": 2390, "text": "Output:" }, { "code": null, "e": 2549, "s": 2398, "text": "2021-04-03 00:00:00 +0000 UTC\n2025-06-07 00:00:00 +0000 UTC\n2021-05-02 00:00:00 +0000 UTC\n2027-11-02 00:00:00 +0000 UTC\n2027-01-23 00:00:00 +0000 UTC\n" }, { "code": null, "e": 2638, "s": 2549, "text": "Here, the range used is outside the usual range but they are normalized while converted." }, { "code": null, "e": 2650, "s": 2638, "text": "GoLang-time" }, { "code": null, "e": 2662, "s": 2650, "text": "Go Language" }, { "code": null, "e": 2760, "s": 2662, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2811, "s": 2760, "text": "strings.Replace() Function in Golang With Examples" }, { "code": null, "e": 2858, "s": 2811, "text": "fmt.Sprintf() Function in Golang With Examples" }, { "code": null, "e": 2871, "s": 2858, "text": "Arrays in Go" }, { "code": null, "e": 2883, "s": 2871, "text": "Golang Maps" }, { "code": null, "e": 2916, "s": 2883, "text": "How to Split a String in Golang?" }, { "code": null, "e": 2937, "s": 2916, "text": "Interfaces in Golang" }, { "code": null, "e": 2954, "s": 2937, "text": "Slices in Golang" }, { "code": null, "e": 3008, "s": 2954, "text": "Different Ways to Find the Type of Variable in Golang" }, { "code": null, "e": 3037, "s": 3008, "text": "How to Parse JSON in Golang?" } ]
Pandas – Groupby multiple values and plotting results
24 Jan, 2022 In this article, we will learn how to groupby multiple values and plotting the results in one go. Here, we take “exercise.csv” file of a dataset from seaborn library then formed different groupby data and visualize the result. For this procedure, the steps required are given below : Import libraries for data and its visualization. Create and import the data with multiple columns. Form a grouby object by grouping multiple values. Visualize the grouped data. Below is the implementation with some examples : Example 1 : In this example, we take the “exercise.csv” file of a dataset from the seaborn library then formed groupby data by grouping two columns “pulse” and “diet” together on the basis of a column “time” and at last visualize the result. Python3 # importing packagesimport seaborn # load dataset and viewdata = seaborn.load_dataset('exercise')print(data) # multiple groupby (pulse and diet both)df = data.groupby(['pulse', 'diet']).count()['time']print(df) # plot the resultdf.plot()plt.xticks(rotation=45)plt.show() Output : Unnamed: 0 id diet pulse time kind 0 0 1 low fat 85 1 min rest 1 1 1 low fat 85 15 min rest 2 2 1 low fat 88 30 min rest 3 3 2 low fat 90 1 min rest 4 4 2 low fat 92 15 min rest .. ... .. ... ... ... ... 85 85 29 no fat 135 15 min running 86 86 29 no fat 130 30 min running 87 87 30 no fat 99 1 min running 88 88 30 no fat 111 15 min running 89 89 30 no fat 150 30 min running [90 rows x 6 columns] pulse diet 80 no fat NaN low fat 1.0 82 no fat NaN low fat 1.0 83 no fat 2.0 ... 140 low fat NaN 143 no fat 1.0 low fat NaN 150 no fat 1.0 low fat NaN Name: time, Length: 78, dtype: float64 Example 2: This example is the modification of the above example for better visualization. Python3 # importing packagesimport seaborn # load datasetdata = seaborn.load_dataset('exercise') # multiple groupby (pulse and diet both)df = data.groupby(['pulse', 'diet']).count()['time'] # plot the resultdf.unstack().plot()plt.xticks(rotation=45)plt.show() Output : Example 3: In this example, we take “exercise.csv” file of a dataset from seaborn library then formed groupby data by grouping three columns “pulse”, “diet” , and “time” together on the basis of a column “kind” and at last visualize the result. Python3 # importing packagesimport seaborn # load dataset and viewdata = seaborn.load_dataset('exercise')print(data) # multiple groupby (pulse, diet and time)df = data.groupby(['pulse', 'diet', 'time']).count()['kind']print(df) # plot the resultdf.plot()plt.xticks(rotation=30)plt.show() Output : Unnamed: 0 id diet pulse time kind 0 0 1 low fat 85 1 min rest 1 1 1 low fat 85 15 min rest 2 2 1 low fat 88 30 min rest 3 3 2 low fat 90 1 min rest 4 4 2 low fat 92 15 min rest .. ... .. ... ... ... ... 85 85 29 no fat 135 15 min running 86 86 29 no fat 130 30 min running 87 87 30 no fat 99 1 min running 88 88 30 no fat 111 15 min running 89 89 30 no fat 150 30 min running [90 rows x 6 columns] pulse diet time 80 no fat 1 min NaN 15 min NaN 30 min NaN low fat 1 min 1.0 15 min NaN ... 150 no fat 15 min NaN 30 min 1.0 low fat 1 min NaN 15 min NaN 30 min NaN Name: kind, Length: 234, dtype: float64 Example 4: This example is the modification of the above example for better visualization. Python3 # importing packagesimport seaborn # load datasetdata = seaborn.load_dataset('exercise') # multiple groupby (pulse, diet, and time)df = data.groupby(['pulse', 'diet', 'time']).count()['kind'] # plot the resultdf.unsatck().plot()plt.xticks(rotation=30)plt.show() Output : varshagumber28 Python Pandas-exercise Python pandas-groupby Python-pandas Python-Seaborn 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 Jan, 2022" }, { "code": null, "e": 256, "s": 28, "text": "In this article, we will learn how to groupby multiple values and plotting the results in one go. Here, we take “exercise.csv” file of a dataset from seaborn library then formed different groupby data and visualize the result. " }, { "code": null, "e": 313, "s": 256, "text": "For this procedure, the steps required are given below :" }, { "code": null, "e": 362, "s": 313, "text": "Import libraries for data and its visualization." }, { "code": null, "e": 412, "s": 362, "text": "Create and import the data with multiple columns." }, { "code": null, "e": 462, "s": 412, "text": "Form a grouby object by grouping multiple values." }, { "code": null, "e": 490, "s": 462, "text": "Visualize the grouped data." }, { "code": null, "e": 540, "s": 490, "text": "Below is the implementation with some examples : " }, { "code": null, "e": 552, "s": 540, "text": "Example 1 :" }, { "code": null, "e": 782, "s": 552, "text": "In this example, we take the “exercise.csv” file of a dataset from the seaborn library then formed groupby data by grouping two columns “pulse” and “diet” together on the basis of a column “time” and at last visualize the result." }, { "code": null, "e": 790, "s": 782, "text": "Python3" }, { "code": "# importing packagesimport seaborn # load dataset and viewdata = seaborn.load_dataset('exercise')print(data) # multiple groupby (pulse and diet both)df = data.groupby(['pulse', 'diet']).count()['time']print(df) # plot the resultdf.plot()plt.xticks(rotation=45)plt.show()", "e": 1061, "s": 790, "text": null }, { "code": null, "e": 1070, "s": 1061, "text": "Output :" }, { "code": null, "e": 2013, "s": 1070, "text": " Unnamed: 0 id diet pulse time kind\n0 0 1 low fat 85 1 min rest\n1 1 1 low fat 85 15 min rest\n2 2 1 low fat 88 30 min rest\n3 3 2 low fat 90 1 min rest\n4 4 2 low fat 92 15 min rest\n.. ... .. ... ... ... ...\n85 85 29 no fat 135 15 min running\n86 86 29 no fat 130 30 min running\n87 87 30 no fat 99 1 min running\n88 88 30 no fat 111 15 min running\n89 89 30 no fat 150 30 min running\n\n[90 rows x 6 columns]\npulse diet \n80 no fat NaN\n low fat 1.0\n82 no fat NaN\n low fat 1.0\n83 no fat 2.0\n ... \n140 low fat NaN\n143 no fat 1.0\n low fat NaN\n150 no fat 1.0\n low fat NaN\nName: time, Length: 78, dtype: float64" }, { "code": null, "e": 2104, "s": 2013, "text": "Example 2: This example is the modification of the above example for better visualization." }, { "code": null, "e": 2112, "s": 2104, "text": "Python3" }, { "code": "# importing packagesimport seaborn # load datasetdata = seaborn.load_dataset('exercise') # multiple groupby (pulse and diet both)df = data.groupby(['pulse', 'diet']).count()['time'] # plot the resultdf.unstack().plot()plt.xticks(rotation=45)plt.show()", "e": 2364, "s": 2112, "text": null }, { "code": null, "e": 2373, "s": 2364, "text": "Output :" }, { "code": null, "e": 2384, "s": 2373, "text": "Example 3:" }, { "code": null, "e": 2618, "s": 2384, "text": "In this example, we take “exercise.csv” file of a dataset from seaborn library then formed groupby data by grouping three columns “pulse”, “diet” , and “time” together on the basis of a column “kind” and at last visualize the result." }, { "code": null, "e": 2626, "s": 2618, "text": "Python3" }, { "code": "# importing packagesimport seaborn # load dataset and viewdata = seaborn.load_dataset('exercise')print(data) # multiple groupby (pulse, diet and time)df = data.groupby(['pulse', 'diet', 'time']).count()['kind']print(df) # plot the resultdf.plot()plt.xticks(rotation=30)plt.show()", "e": 2906, "s": 2626, "text": null }, { "code": null, "e": 2915, "s": 2906, "text": "Output :" }, { "code": null, "e": 3951, "s": 2915, "text": "Unnamed: 0 id diet pulse time kind\n0 0 1 low fat 85 1 min rest\n1 1 1 low fat 85 15 min rest\n2 2 1 low fat 88 30 min rest\n3 3 2 low fat 90 1 min rest\n4 4 2 low fat 92 15 min rest\n.. ... .. ... ... ... ...\n85 85 29 no fat 135 15 min running\n86 86 29 no fat 130 30 min running\n87 87 30 no fat 99 1 min running\n88 88 30 no fat 111 15 min running\n89 89 30 no fat 150 30 min running\n\n[90 rows x 6 columns]\npulse diet time \n80 no fat 1 min NaN\n 15 min NaN\n 30 min NaN\n low fat 1 min 1.0\n 15 min NaN\n ... \n150 no fat 15 min NaN\n 30 min 1.0\n low fat 1 min NaN\n 15 min NaN\n 30 min NaN\nName: kind, Length: 234, dtype: float64" }, { "code": null, "e": 4042, "s": 3951, "text": "Example 4: This example is the modification of the above example for better visualization." }, { "code": null, "e": 4050, "s": 4042, "text": "Python3" }, { "code": "# importing packagesimport seaborn # load datasetdata = seaborn.load_dataset('exercise') # multiple groupby (pulse, diet, and time)df = data.groupby(['pulse', 'diet', 'time']).count()['kind'] # plot the resultdf.unsatck().plot()plt.xticks(rotation=30)plt.show()", "e": 4312, "s": 4050, "text": null }, { "code": null, "e": 4321, "s": 4312, "text": "Output :" }, { "code": null, "e": 4336, "s": 4321, "text": "varshagumber28" }, { "code": null, "e": 4359, "s": 4336, "text": "Python Pandas-exercise" }, { "code": null, "e": 4381, "s": 4359, "text": "Python pandas-groupby" }, { "code": null, "e": 4395, "s": 4381, "text": "Python-pandas" }, { "code": null, "e": 4410, "s": 4395, "text": "Python-Seaborn" }, { "code": null, "e": 4417, "s": 4410, "text": "Python" } ]
Print first letter of each word in a string using regex
11 Dec, 2018 Given a string, extract the first letter of each word in it. “Words” are defined as contiguous strings of alphabetic characters i.e. any upper or lower case characters a-z or A-Z. Examples: Input : Geeks for geeks Output :Gfg Input : United Kingdom Output : UK Below is the Regular expression to extract the first letter of each word. It uses ‘/b'(one of boundary matchers). Please refer How to write Regular Expressions? to learn it. \b[a-zA-Z] // Java program to demonstrate extracting first// letter of each word using Regex import java.util.regex.Matcher;import java.util.regex.Pattern; public class Test { public static void main(String[] args) { String s1 = "Geeks for Geeks"; String s2 = "A Computer Science Portal for Geeks"; Pattern p = Pattern.compile("\\b[a-zA-Z]"); Matcher m1 = p.matcher(s1); Matcher m2 = p.matcher(s2); System.out.println("First letter of each word from string \"" + s1 + "\" : "); while (m1.find()) System.out.print(m1.group()); System.out.println(); System.out.println("First letter of each word from string \"" + s2 + "\" : "); while (m2.find()) System.out.print(m2.group()); }} Output: First letter of each word from string "Geeks for Geeks" : GfG First letter of each word from string "A Computer Science Portal for Geeks" : ACSPfG Next Article: Extracting each word from a String using Regex in Java This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. java-regular-expression Java-String-Programs Java-Strings Java Java-Strings Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Dec, 2018" }, { "code": null, "e": 208, "s": 28, "text": "Given a string, extract the first letter of each word in it. “Words” are defined as contiguous strings of alphabetic characters i.e. any upper or lower case characters a-z or A-Z." }, { "code": null, "e": 218, "s": 208, "text": "Examples:" }, { "code": null, "e": 299, "s": 218, "text": "Input : Geeks for geeks\nOutput :Gfg\n \nInput : United Kingdom\nOutput : UK\n" }, { "code": null, "e": 473, "s": 299, "text": "Below is the Regular expression to extract the first letter of each word. It uses ‘/b'(one of boundary matchers). Please refer How to write Regular Expressions? to learn it." }, { "code": null, "e": 485, "s": 473, "text": "\\b[a-zA-Z]\n" }, { "code": "// Java program to demonstrate extracting first// letter of each word using Regex import java.util.regex.Matcher;import java.util.regex.Pattern; public class Test { public static void main(String[] args) { String s1 = \"Geeks for Geeks\"; String s2 = \"A Computer Science Portal for Geeks\"; Pattern p = Pattern.compile(\"\\\\b[a-zA-Z]\"); Matcher m1 = p.matcher(s1); Matcher m2 = p.matcher(s2); System.out.println(\"First letter of each word from string \\\"\" + s1 + \"\\\" : \"); while (m1.find()) System.out.print(m1.group()); System.out.println(); System.out.println(\"First letter of each word from string \\\"\" + s2 + \"\\\" : \"); while (m2.find()) System.out.print(m2.group()); }}", "e": 1337, "s": 485, "text": null }, { "code": null, "e": 1345, "s": 1337, "text": "Output:" }, { "code": null, "e": 1495, "s": 1345, "text": "First letter of each word from string \"Geeks for Geeks\" : \nGfG\nFirst letter of each word from string \"A Computer Science Portal for Geeks\" : \nACSPfG\n" }, { "code": null, "e": 1564, "s": 1495, "text": "Next Article: Extracting each word from a String using Regex in Java" }, { "code": null, "e": 1866, "s": 1564, "text": "This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 1991, "s": 1866, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 2015, "s": 1991, "text": "java-regular-expression" }, { "code": null, "e": 2036, "s": 2015, "text": "Java-String-Programs" }, { "code": null, "e": 2049, "s": 2036, "text": "Java-Strings" }, { "code": null, "e": 2054, "s": 2049, "text": "Java" }, { "code": null, "e": 2067, "s": 2054, "text": "Java-Strings" }, { "code": null, "e": 2072, "s": 2067, "text": "Java" } ]
How to iterate over the keys and values with ng-repeat in AngularJS ?
22 Nov, 2019 The task is to iterate over a JS object (its keys and values) using the ng-repeat directive. This can be done using parenthesis in the ng-repeat directive to explicitly ask for a key-value pair parameter from angularJS. Here the variable key contains the key of the object and value contains the value of the object. Syntax: <element ng-repeat="(key, value) in JSObject"> Contents... </element> Example 1: In this example, we will simply display all the keys and values of a JS object using ng-repeat. In first iteration, key = name and value = “GeeksforGeeks”. In 2nd iteration, key = location and value = “Noida India Sector 136′′...This keeps on iterating until all the keys and their values are covered at least once similar to a for-each loop. Program:<!DOCTYPE html><html ng-app="myApp"> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js"> </script></head> <body ng-controller="MyController"> <center> <h1 style="color: green;"> GeeksforGeeks </h1> <div ng-repeat="(key, value) in gfg"> <!-- First Iteration--> <p>{{key}} - {{value}}</p> </div> </center></body><script type="text/javascript"> var myApp = angular.module('myApp', []); myApp.controller('MyController', ['$scope', function($scope) { $scope.gfg = { Name: "GeeksforGeeks", Location: "Noida India Sector 136", Type: "Edu-Tech", } }]);</script> </html> <!DOCTYPE html><html ng-app="myApp"> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js"> </script></head> <body ng-controller="MyController"> <center> <h1 style="color: green;"> GeeksforGeeks </h1> <div ng-repeat="(key, value) in gfg"> <!-- First Iteration--> <p>{{key}} - {{value}}</p> </div> </center></body><script type="text/javascript"> var myApp = angular.module('myApp', []); myApp.controller('MyController', ['$scope', function($scope) { $scope.gfg = { Name: "GeeksforGeeks", Location: "Noida India Sector 136", Type: "Edu-Tech", } }]);</script> </html> Output: On loading the page, we see that all the key-value pairs of the objects are already listed there. This is because the ng-repeat is called on load as the HTML gets loaded. Example 2: In this example, we will loop over a nested object using ng-repeat directive. In the first iteration, key = diamond and value = {hardness:”Ultra Hard”, goodFor:”Display, cutting”} in the next iteration key = gold and value is its respective object. This keeps on iterating like a for-each loop over the key-value pairs of the object materials. Program:<!DOCTYPE html><html ng-app="myApp"> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js"> </script></head> <body ng-controller="MyController"> <center> <h1 style="color: green;"> GeeksforGeeks </h1> <div ng-repeat="(key, value) in materials"> <h1>{{key}}</h1> <div ng-repeat="(key1, value1) in value"> <!-- since the "value" variable itself is an object. We can iterate over its keys and values again using ng-repeat. --> <p>{{key1}} - {{value1}}</p> </div> </div> </center></body><script type="text/javascript"> var myApp = angular.module('myApp', []); myApp.controller('MyController', ['$scope', function($scope) { $scope.materials = { diamond: { hardness: "Ultra Hard", goodFor: "Display, cutting" }, gold: { hardness: "Hard", goodFor: "Jewelry" }, silver: { hardness: "comparatively soft", goodFor: "Jewelry, Display" } } }]);</script> </html> <!DOCTYPE html><html ng-app="myApp"> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js"> </script></head> <body ng-controller="MyController"> <center> <h1 style="color: green;"> GeeksforGeeks </h1> <div ng-repeat="(key, value) in materials"> <h1>{{key}}</h1> <div ng-repeat="(key1, value1) in value"> <!-- since the "value" variable itself is an object. We can iterate over its keys and values again using ng-repeat. --> <p>{{key1}} - {{value1}}</p> </div> </div> </center></body><script type="text/javascript"> var myApp = angular.module('myApp', []); myApp.controller('MyController', ['$scope', function($scope) { $scope.materials = { diamond: { hardness: "Ultra Hard", goodFor: "Display, cutting" }, gold: { hardness: "Hard", goodFor: "Jewelry" }, silver: { hardness: "comparatively soft", goodFor: "Jewelry, Display" } } }]);</script> </html> Output: AngularJS-Misc Picked AngularJS Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Auth Guards in Angular 9/10/11 Routing in Angular 9/10 How to bundle an Angular app for production? What is AOT and JIT Compiler in Angular ? Angular PrimeNG Dropdown Component Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Nov, 2019" }, { "code": null, "e": 345, "s": 28, "text": "The task is to iterate over a JS object (its keys and values) using the ng-repeat directive. This can be done using parenthesis in the ng-repeat directive to explicitly ask for a key-value pair parameter from angularJS. Here the variable key contains the key of the object and value contains the value of the object." }, { "code": null, "e": 353, "s": 345, "text": "Syntax:" }, { "code": null, "e": 423, "s": 353, "text": "<element ng-repeat=\"(key, value) in JSObject\"> Contents... </element>" }, { "code": null, "e": 777, "s": 423, "text": "Example 1: In this example, we will simply display all the keys and values of a JS object using ng-repeat. In first iteration, key = name and value = “GeeksforGeeks”. In 2nd iteration, key = location and value = “Noida India Sector 136′′...This keeps on iterating until all the keys and their values are covered at least once similar to a for-each loop." }, { "code": null, "e": 1530, "s": 777, "text": "Program:<!DOCTYPE html><html ng-app=\"myApp\"> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js\"> </script></head> <body ng-controller=\"MyController\"> <center> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <div ng-repeat=\"(key, value) in gfg\"> <!-- First Iteration--> <p>{{key}} - {{value}}</p> </div> </center></body><script type=\"text/javascript\"> var myApp = angular.module('myApp', []); myApp.controller('MyController', ['$scope', function($scope) { $scope.gfg = { Name: \"GeeksforGeeks\", Location: \"Noida India Sector 136\", Type: \"Edu-Tech\", } }]);</script> </html>" }, { "code": "<!DOCTYPE html><html ng-app=\"myApp\"> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js\"> </script></head> <body ng-controller=\"MyController\"> <center> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <div ng-repeat=\"(key, value) in gfg\"> <!-- First Iteration--> <p>{{key}} - {{value}}</p> </div> </center></body><script type=\"text/javascript\"> var myApp = angular.module('myApp', []); myApp.controller('MyController', ['$scope', function($scope) { $scope.gfg = { Name: \"GeeksforGeeks\", Location: \"Noida India Sector 136\", Type: \"Edu-Tech\", } }]);</script> </html>", "e": 2275, "s": 1530, "text": null }, { "code": null, "e": 2454, "s": 2275, "text": "Output: On loading the page, we see that all the key-value pairs of the objects are already listed there. This is because the ng-repeat is called on load as the HTML gets loaded." }, { "code": null, "e": 2809, "s": 2454, "text": "Example 2: In this example, we will loop over a nested object using ng-repeat directive. In the first iteration, key = diamond and value = {hardness:”Ultra Hard”, goodFor:”Display, cutting”} in the next iteration key = gold and value is its respective object. This keeps on iterating like a for-each loop over the key-value pairs of the object materials." }, { "code": null, "e": 4036, "s": 2809, "text": "Program:<!DOCTYPE html><html ng-app=\"myApp\"> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js\"> </script></head> <body ng-controller=\"MyController\"> <center> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <div ng-repeat=\"(key, value) in materials\"> <h1>{{key}}</h1> <div ng-repeat=\"(key1, value1) in value\"> <!-- since the \"value\" variable itself is an object. We can iterate over its keys and values again using ng-repeat. --> <p>{{key1}} - {{value1}}</p> </div> </div> </center></body><script type=\"text/javascript\"> var myApp = angular.module('myApp', []); myApp.controller('MyController', ['$scope', function($scope) { $scope.materials = { diamond: { hardness: \"Ultra Hard\", goodFor: \"Display, cutting\" }, gold: { hardness: \"Hard\", goodFor: \"Jewelry\" }, silver: { hardness: \"comparatively soft\", goodFor: \"Jewelry, Display\" } } }]);</script> </html>" }, { "code": "<!DOCTYPE html><html ng-app=\"myApp\"> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js\"> </script></head> <body ng-controller=\"MyController\"> <center> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <div ng-repeat=\"(key, value) in materials\"> <h1>{{key}}</h1> <div ng-repeat=\"(key1, value1) in value\"> <!-- since the \"value\" variable itself is an object. We can iterate over its keys and values again using ng-repeat. --> <p>{{key1}} - {{value1}}</p> </div> </div> </center></body><script type=\"text/javascript\"> var myApp = angular.module('myApp', []); myApp.controller('MyController', ['$scope', function($scope) { $scope.materials = { diamond: { hardness: \"Ultra Hard\", goodFor: \"Display, cutting\" }, gold: { hardness: \"Hard\", goodFor: \"Jewelry\" }, silver: { hardness: \"comparatively soft\", goodFor: \"Jewelry, Display\" } } }]);</script> </html>", "e": 5255, "s": 4036, "text": null }, { "code": null, "e": 5263, "s": 5255, "text": "Output:" }, { "code": null, "e": 5278, "s": 5263, "text": "AngularJS-Misc" }, { "code": null, "e": 5285, "s": 5278, "text": "Picked" }, { "code": null, "e": 5295, "s": 5285, "text": "AngularJS" }, { "code": null, "e": 5312, "s": 5295, "text": "Web Technologies" }, { "code": null, "e": 5339, "s": 5312, "text": "Web technologies Questions" }, { "code": null, "e": 5437, "s": 5339, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5468, "s": 5437, "text": "Auth Guards in Angular 9/10/11" }, { "code": null, "e": 5492, "s": 5468, "text": "Routing in Angular 9/10" }, { "code": null, "e": 5537, "s": 5492, "text": "How to bundle an Angular app for production?" }, { "code": null, "e": 5579, "s": 5537, "text": "What is AOT and JIT Compiler in Angular ?" }, { "code": null, "e": 5614, "s": 5579, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 5647, "s": 5614, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 5709, "s": 5647, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 5770, "s": 5709, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 5820, "s": 5770, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Python sympy | Matrix.diagonalize() method
30 Dec, 2020 With the help of sympy.Matrix().diagonalize() method, we can diagonalize a matrix. diagonalize() returns a tuple , where is diagonal and . Syntax: Matrix().diagonalize() Returns: Returns a tuple of matrix where the second element represents the diagonal of the matrix. Example #1: # import sympy from sympy import * M = Matrix([[3, -2, 4, -2], [5, 3, -3, -2], [5, -2, 2, -2], [5, -2, -3, 3]]) print("Matrix : {} ".format(M)) # Use sympy.diagonalize() method P, D = M.diagonalize() print("Diagonal of a matrix : {}".format(D)) Output: Matrix : Matrix([[3, -2, 4, -2], [5, 3, -3, -2], [5, -2, 2, -2], [5, -2, -3, 3]])Diagonal of a matrix : Matrix([[-2, 0, 0, 0], [0, 3, 0, 0], [0, 0, 5, 0], [0, 0, 0, 5]]) Example #2: # import sympy from sympy import * M = Matrix([[1, -3, 3], [3, -5, 3], [6, -6, 4]]) print("Matrix : {} ".format(M)) # Use sympy.diagonalize() method P, D = M.diagonalize() print("Diagonal of a matrix : {}".format(D)) Output: Matrix : Matrix([[1, -3, 3], [3, -5, 3], [6, -6, 4]])Diagonal of a matrix : Matrix([[-2, 0, 0], [0, -2, 0], [0, 0, 4]]) Python matrix-program SymPy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Iterate over a list in Python Python Classes and Objects Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Dec, 2020" }, { "code": null, "e": 168, "s": 28, "text": "With the help of sympy.Matrix().diagonalize() method, we can diagonalize a matrix. diagonalize() returns a tuple , where is diagonal and ." }, { "code": null, "e": 199, "s": 168, "text": "Syntax: Matrix().diagonalize()" }, { "code": null, "e": 298, "s": 199, "text": "Returns: Returns a tuple of matrix where the second element represents the diagonal of the matrix." }, { "code": null, "e": 310, "s": 298, "text": "Example #1:" }, { "code": "# import sympy from sympy import * M = Matrix([[3, -2, 4, -2], [5, 3, -3, -2], [5, -2, 2, -2], [5, -2, -3, 3]]) print(\"Matrix : {} \".format(M)) # Use sympy.diagonalize() method P, D = M.diagonalize() print(\"Diagonal of a matrix : {}\".format(D)) ", "e": 664, "s": 310, "text": null }, { "code": null, "e": 672, "s": 664, "text": "Output:" }, { "code": null, "e": 842, "s": 672, "text": "Matrix : Matrix([[3, -2, 4, -2], [5, 3, -3, -2], [5, -2, 2, -2], [5, -2, -3, 3]])Diagonal of a matrix : Matrix([[-2, 0, 0, 0], [0, 3, 0, 0], [0, 0, 5, 0], [0, 0, 0, 5]])" }, { "code": null, "e": 854, "s": 842, "text": "Example #2:" }, { "code": "# import sympy from sympy import * M = Matrix([[1, -3, 3], [3, -5, 3], [6, -6, 4]]) print(\"Matrix : {} \".format(M)) # Use sympy.diagonalize() method P, D = M.diagonalize() print(\"Diagonal of a matrix : {}\".format(D))", "e": 1080, "s": 854, "text": null }, { "code": null, "e": 1088, "s": 1080, "text": "Output:" }, { "code": null, "e": 1208, "s": 1088, "text": "Matrix : Matrix([[1, -3, 3], [3, -5, 3], [6, -6, 4]])Diagonal of a matrix : Matrix([[-2, 0, 0], [0, -2, 0], [0, 0, 4]])" }, { "code": null, "e": 1230, "s": 1208, "text": "Python matrix-program" }, { "code": null, "e": 1236, "s": 1230, "text": "SymPy" }, { "code": null, "e": 1243, "s": 1236, "text": "Python" }, { "code": null, "e": 1341, "s": 1243, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1359, "s": 1341, "text": "Python Dictionary" }, { "code": null, "e": 1401, "s": 1359, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1423, "s": 1401, "text": "Enumerate() in Python" }, { "code": null, "e": 1458, "s": 1423, "text": "Read a file line by line in Python" }, { "code": null, "e": 1484, "s": 1458, "text": "Python String | replace()" }, { "code": null, "e": 1516, "s": 1484, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1545, "s": 1516, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1575, "s": 1545, "text": "Iterate over a list in Python" }, { "code": null, "e": 1602, "s": 1575, "text": "Python Classes and Objects" } ]
Find the sum of the series 1+11+111+1111+..... upto n terms
25 May, 2022 Here we are going to find the sum of the series 1 + 11 + 111 + 1111 +.....upto N terms (where N is given).Example : Input : 3 Output : 1 + 11 + 111 +.... Total sum is : 123 Input : 4 Output : 1 + 11 + 111 + 1111 +..... Total sum is : 1234 Input : 7 Output : 1 + 11 + 111 + 1111 + 11111 + 111111 + 1111111 +..... Total sum is : 1234567 Here we see that when value of N is 3, series last upto 1 + 11 + 111 i.e, three term and it’s sum is 123.Program for finding sum of above series : C++ C Java Python C# PHP Javascript // C++ program to find the sum of// the series 1+11+111+1111+....#include <bits/stdc++.h>using namespace std; // Function for finding summationint summation(int n){ int sum = 0, j = 1; for (int i = 1; i <= n; i++) { sum = sum + j; // Appending a 1 at the end j = (j * 10) + 1; } return sum;} // Driver Codeint main(){ int n = 5; cout << " " << summation(n); return 0;} // This code is contributed by shivanisinghss2110 // C program to find the sum of// the series 1+11+111+1111+....#include <stdio.h> // Function for finding summationint summation(int n){ int sum = 0, j = 1; for (int i = 1; i <= n; i++) { sum = sum + j; // Appending a 1 at the end j = (j * 10) + 1; } return sum;} // Driver Codeint main(){ int n = 5; printf("%d", summation(n)); return 0;} // Java program to find the sum of// the series 1+11+111+1111+....import java.io.*; class GFG{ // Function for finding summation static int summation(int n) { int sum = 0, j = 1; for (int i = 1; i <= n; i++) { sum = sum + j; j = (j * 10) + 1; } return sum; } // Driver Code public static void main(String args[]) { int n = 5; System.out.println(summation(n)); }} // This code is contributed// by Nikita Tiwari # Python program to get the summation# of following seriesdef summation(n): sum = 0 j = 1 for i in range(1, n + 1): sum = sum + j j = (j * 10) + 1 return sum # Driver Coden = 5print(summation(n)) // C# program to find the sum of// the series 1+11+111+1111+....using System; class GFG{ // Function for finding summation static int summation(int n) { int sum = 0, j = 1; for (int i = 1; i <= n; i++) { sum = sum + j; j = (j * 10) + 1; } return sum; } // Driver Code public static void Main() { int n = 5; Console.WriteLine(summation(n)); }} // This code is contributed by vt_m <?php// PHP program to find the sum of// the series 1+11+111+1111+.... // Function for finding summationfunction summation($n){ $sum = 0; $j = 1; for ($i = 1; $i <= $n; $i++) { $sum = $sum + $j; // Appending a 1 at the end $j = ($j * 10) + 1; } return $sum;} // Driver Code$n = 5;echo summation($n); // This code is contributed by ajit?> <script> // Javascript program to find the sum of// the series 1+11+111+1111+.... // Function for finding summation function summation( n) { let sum = 0, j = 1; for ( let i = 1; i <= n; i++) { sum = sum + j; // Appending a 1 at the end j = (j * 10) + 1; } return sum; } // Driver Code let n = 5; document.write(summation(n)); // This code contributed by Princi Singh </script> Output : 12345 Time Complexity: O(n), where n represents the given integer.Auxiliary Space: O(1), no extra space is required, so it is a constant. Another method: Let given a series S = 1 + 11 + 111 + 1111 + . . . + upto nth term. Using formula to find sum of series. Below is the implementation of above approach. C++ Java Python3 C# PHP Javascript // C++ program to find the sum of// the series 1+11+111+1111+....#include <bits/stdc++.h> // Function for finding summationint summation(int n){ int sum; sum = (pow(10, n + 1) - 10 - (9 * n)) / 81; return sum;} // Driver Codeint main(){ int n = 5; printf("%d", summation(n)); return 0;} // java program to find the sum of// the series 1+11+111+1111+....import java.io.*; class GFG { // Function for finding summation static int summation(int n) { int sum; sum = (int)(Math.pow(10, n + 1) - 10 - (9 * n)) / 81; return sum; } // Driver Code public static void main (String[] args) { int n = 5; System.out.println(summation(n)); }} // This code is contributed by anuj_67. # Python3 program to# find the sum of# the series 1+11+111+1111+....import math # Function for# finding summationdef summation(n): return int((pow(10, n + 1) - 10 - (9 * n)) / 81); # Driver Codeprint(summation(5)); # This code is contributed# by mits. // C# program to find the sum of// the series 1+11+111+1111+....using System; class GFG { // Function for finding summation static int summation(int n) { int sum; sum = (int)(Math.Pow(10, n + 1) - 10 - (9 * n)) / 81; return sum; } // Driver Code public static void Main () { int n = 5; Console.WriteLine(summation(n)); }} // This code is contributed by anuj_67. <?php//PHP program to find the sum of// the series 1+11+111+1111+.... // Function for finding summationfunction summation($n){ $sum; $sum = (pow(10, $n + 1) - 10 - (9 * $n)) / 81; return $sum;} // Driver Code$n = 5;echo summation($n); // This code is contributed by aj_36?> <script>// javascript program to find the sum of// the series 1+11+111+1111+.... // Function for finding summationfunction summation( n){ let sum; sum = (Math.pow(10, n + 1) - 10 - (9 * n)) / 81; return sum;} // Driver Codelet n = 5; document.write(summation(n)) ; // This code is contributed by aashish1995 </script> Output : 12345 Time Complexity: O(logn), where n represents the given integer.Auxiliary Space: O(1), no extra space is required, so it is a constant. surya2106 jit_t vt_m Mithun Kumar shivanisinghss2110 aashish1995 princi singh samim2000 series Mathematical Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n25 May, 2022" }, { "code": null, "e": 170, "s": 52, "text": "Here we are going to find the sum of the series 1 + 11 + 111 + 1111 +.....upto N terms (where N is given).Example : " }, { "code": null, "e": 403, "s": 170, "text": "Input : 3\nOutput : 1 + 11 + 111 +....\nTotal sum is : 123\n\nInput : 4\nOutput : 1 + 11 + 111 + 1111 +..... \nTotal sum is : 1234\n\nInput : 7\nOutput : 1 + 11 + 111 + 1111 + 11111 + \n 111111 + 1111111 +..... \nTotal sum is : 1234567" }, { "code": null, "e": 554, "s": 405, "text": "Here we see that when value of N is 3, series last upto 1 + 11 + 111 i.e, three term and it’s sum is 123.Program for finding sum of above series : " }, { "code": null, "e": 558, "s": 554, "text": "C++" }, { "code": null, "e": 560, "s": 558, "text": "C" }, { "code": null, "e": 565, "s": 560, "text": "Java" }, { "code": null, "e": 572, "s": 565, "text": "Python" }, { "code": null, "e": 575, "s": 572, "text": "C#" }, { "code": null, "e": 579, "s": 575, "text": "PHP" }, { "code": null, "e": 590, "s": 579, "text": "Javascript" }, { "code": "// C++ program to find the sum of// the series 1+11+111+1111+....#include <bits/stdc++.h>using namespace std; // Function for finding summationint summation(int n){ int sum = 0, j = 1; for (int i = 1; i <= n; i++) { sum = sum + j; // Appending a 1 at the end j = (j * 10) + 1; } return sum;} // Driver Codeint main(){ int n = 5; cout << \" \" << summation(n); return 0;} // This code is contributed by shivanisinghss2110", "e": 1054, "s": 590, "text": null }, { "code": "// C program to find the sum of// the series 1+11+111+1111+....#include <stdio.h> // Function for finding summationint summation(int n){ int sum = 0, j = 1; for (int i = 1; i <= n; i++) { sum = sum + j; // Appending a 1 at the end j = (j * 10) + 1; } return sum;} // Driver Codeint main(){ int n = 5; printf(\"%d\", summation(n)); return 0;}", "e": 1438, "s": 1054, "text": null }, { "code": "// Java program to find the sum of// the series 1+11+111+1111+....import java.io.*; class GFG{ // Function for finding summation static int summation(int n) { int sum = 0, j = 1; for (int i = 1; i <= n; i++) { sum = sum + j; j = (j * 10) + 1; } return sum; } // Driver Code public static void main(String args[]) { int n = 5; System.out.println(summation(n)); }} // This code is contributed// by Nikita Tiwari", "e": 1946, "s": 1438, "text": null }, { "code": "# Python program to get the summation# of following seriesdef summation(n): sum = 0 j = 1 for i in range(1, n + 1): sum = sum + j j = (j * 10) + 1 return sum # Driver Coden = 5print(summation(n))", "e": 2190, "s": 1946, "text": null }, { "code": "// C# program to find the sum of// the series 1+11+111+1111+....using System; class GFG{ // Function for finding summation static int summation(int n) { int sum = 0, j = 1; for (int i = 1; i <= n; i++) { sum = sum + j; j = (j * 10) + 1; } return sum; } // Driver Code public static void Main() { int n = 5; Console.WriteLine(summation(n)); }} // This code is contributed by vt_m", "e": 2667, "s": 2190, "text": null }, { "code": "<?php// PHP program to find the sum of// the series 1+11+111+1111+.... // Function for finding summationfunction summation($n){ $sum = 0; $j = 1; for ($i = 1; $i <= $n; $i++) { $sum = $sum + $j; // Appending a 1 at the end $j = ($j * 10) + 1; } return $sum;} // Driver Code$n = 5;echo summation($n); // This code is contributed by ajit?>", "e": 3043, "s": 2667, "text": null }, { "code": "<script> // Javascript program to find the sum of// the series 1+11+111+1111+.... // Function for finding summation function summation( n) { let sum = 0, j = 1; for ( let i = 1; i <= n; i++) { sum = sum + j; // Appending a 1 at the end j = (j * 10) + 1; } return sum; } // Driver Code let n = 5; document.write(summation(n)); // This code contributed by Princi Singh </script>", "e": 3537, "s": 3043, "text": null }, { "code": null, "e": 3547, "s": 3537, "text": "Output : " }, { "code": null, "e": 3553, "s": 3547, "text": "12345" }, { "code": null, "e": 3685, "s": 3553, "text": "Time Complexity: O(n), where n represents the given integer.Auxiliary Space: O(1), no extra space is required, so it is a constant." }, { "code": null, "e": 3807, "s": 3685, "text": "Another method: Let given a series S = 1 + 11 + 111 + 1111 + . . . + upto nth term. Using formula to find sum of series. " }, { "code": null, "e": 3857, "s": 3809, "text": "Below is the implementation of above approach. " }, { "code": null, "e": 3861, "s": 3857, "text": "C++" }, { "code": null, "e": 3866, "s": 3861, "text": "Java" }, { "code": null, "e": 3874, "s": 3866, "text": "Python3" }, { "code": null, "e": 3877, "s": 3874, "text": "C#" }, { "code": null, "e": 3881, "s": 3877, "text": "PHP" }, { "code": null, "e": 3892, "s": 3881, "text": "Javascript" }, { "code": "// C++ program to find the sum of// the series 1+11+111+1111+....#include <bits/stdc++.h> // Function for finding summationint summation(int n){ int sum; sum = (pow(10, n + 1) - 10 - (9 * n)) / 81; return sum;} // Driver Codeint main(){ int n = 5; printf(\"%d\", summation(n)); return 0;}", "e": 4213, "s": 3892, "text": null }, { "code": "// java program to find the sum of// the series 1+11+111+1111+....import java.io.*; class GFG { // Function for finding summation static int summation(int n) { int sum; sum = (int)(Math.pow(10, n + 1) - 10 - (9 * n)) / 81; return sum; } // Driver Code public static void main (String[] args) { int n = 5; System.out.println(summation(n)); }} // This code is contributed by anuj_67.", "e": 4685, "s": 4213, "text": null }, { "code": "# Python3 program to# find the sum of# the series 1+11+111+1111+....import math # Function for# finding summationdef summation(n): return int((pow(10, n + 1) - 10 - (9 * n)) / 81); # Driver Codeprint(summation(5)); # This code is contributed# by mits.", "e": 4959, "s": 4685, "text": null }, { "code": "// C# program to find the sum of// the series 1+11+111+1111+....using System; class GFG { // Function for finding summation static int summation(int n) { int sum; sum = (int)(Math.Pow(10, n + 1) - 10 - (9 * n)) / 81; return sum; } // Driver Code public static void Main () { int n = 5; Console.WriteLine(summation(n)); }} // This code is contributed by anuj_67.", "e": 5411, "s": 4959, "text": null }, { "code": "<?php//PHP program to find the sum of// the series 1+11+111+1111+.... // Function for finding summationfunction summation($n){ $sum; $sum = (pow(10, $n + 1) - 10 - (9 * $n)) / 81; return $sum;} // Driver Code$n = 5;echo summation($n); // This code is contributed by aj_36?>", "e": 5711, "s": 5411, "text": null }, { "code": "<script>// javascript program to find the sum of// the series 1+11+111+1111+.... // Function for finding summationfunction summation( n){ let sum; sum = (Math.pow(10, n + 1) - 10 - (9 * n)) / 81; return sum;} // Driver Codelet n = 5; document.write(summation(n)) ; // This code is contributed by aashish1995 </script>", "e": 6059, "s": 5711, "text": null }, { "code": null, "e": 6070, "s": 6059, "text": "Output : " }, { "code": null, "e": 6076, "s": 6070, "text": "12345" }, { "code": null, "e": 6211, "s": 6076, "text": "Time Complexity: O(logn), where n represents the given integer.Auxiliary Space: O(1), no extra space is required, so it is a constant." }, { "code": null, "e": 6221, "s": 6211, "text": "surya2106" }, { "code": null, "e": 6227, "s": 6221, "text": "jit_t" }, { "code": null, "e": 6232, "s": 6227, "text": "vt_m" }, { "code": null, "e": 6245, "s": 6232, "text": "Mithun Kumar" }, { "code": null, "e": 6264, "s": 6245, "text": "shivanisinghss2110" }, { "code": null, "e": 6276, "s": 6264, "text": "aashish1995" }, { "code": null, "e": 6289, "s": 6276, "text": "princi singh" }, { "code": null, "e": 6299, "s": 6289, "text": "samim2000" }, { "code": null, "e": 6306, "s": 6299, "text": "series" }, { "code": null, "e": 6319, "s": 6306, "text": "Mathematical" }, { "code": null, "e": 6332, "s": 6319, "text": "Mathematical" }, { "code": null, "e": 6339, "s": 6332, "text": "series" } ]
Python | Decimal quantize() method
09 Sep, 2019 Decimal#quantize() : quantize() is a Decimal class method which returns a value equal to first decimal value (rounded) having the exponent of second decimal value. Syntax: Decimal.quantize() Parameter: Decimal values Return: a value equal to first decimal value (rounded) having the exponent of second decimal value. Code #1 : Example for quantize() method # Python Program explaining # quantize() method # loading decimal libraryfrom decimal import * # Initializing a decimal valuea = Decimal(-1) b = Decimal('0.142857') # printing Decimal valuesprint ("Decimal value a : ", a)print ("Decimal value b : ", b) # Using Decimal.quantize() methodprint ("\n\nDecimal a with quantize() method : ", a.quantize(b)) print ("Decimal b with quantize() method : ", b.quantize(b)) Output : Decimal value a : -1 Decimal value b : 0.142857 Decimal a with quantize() method : -1.000000 Decimal b with quantize() method : 0.142857 Code #2 : Example for quantize() method # Python Program explaining # quantize() method # loading decimal libraryfrom decimal import * # Initializing a decimal valuea = Decimal('-3.14') b = Decimal('321e + 5') # printing Decimal valuesprint ("Decimal value a : ", a)print ("Decimal value b : ", b) # Using Decimal.quantize() methodprint ("\n\nDecimal a with quantize() method : ", a.quantize(b)) print ("Decimal b with quantize() method : ", b.quantize(b)) Output : Decimal value a : -3.14 Decimal value b : 3.21E+7 Decimal a with quantize() method : -0E+5 Decimal b with quantize() method : 3.21E+7 Python-Functions Python 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, 2019" }, { "code": null, "e": 192, "s": 28, "text": "Decimal#quantize() : quantize() is a Decimal class method which returns a value equal to first decimal value (rounded) having the exponent of second decimal value." }, { "code": null, "e": 219, "s": 192, "text": "Syntax: Decimal.quantize()" }, { "code": null, "e": 245, "s": 219, "text": "Parameter: Decimal values" }, { "code": null, "e": 345, "s": 245, "text": "Return: a value equal to first decimal value (rounded) having the exponent of second decimal value." }, { "code": null, "e": 385, "s": 345, "text": "Code #1 : Example for quantize() method" }, { "code": "# Python Program explaining # quantize() method # loading decimal libraryfrom decimal import * # Initializing a decimal valuea = Decimal(-1) b = Decimal('0.142857') # printing Decimal valuesprint (\"Decimal value a : \", a)print (\"Decimal value b : \", b) # Using Decimal.quantize() methodprint (\"\\n\\nDecimal a with quantize() method : \", a.quantize(b)) print (\"Decimal b with quantize() method : \", b.quantize(b))", "e": 807, "s": 385, "text": null }, { "code": null, "e": 816, "s": 807, "text": "Output :" }, { "code": null, "e": 961, "s": 816, "text": "Decimal value a : -1\nDecimal value b : 0.142857\n\n\nDecimal a with quantize() method : -1.000000\nDecimal b with quantize() method : 0.142857\n\n" }, { "code": null, "e": 1001, "s": 961, "text": "Code #2 : Example for quantize() method" }, { "code": "# Python Program explaining # quantize() method # loading decimal libraryfrom decimal import * # Initializing a decimal valuea = Decimal('-3.14') b = Decimal('321e + 5') # printing Decimal valuesprint (\"Decimal value a : \", a)print (\"Decimal value b : \", b) # Using Decimal.quantize() methodprint (\"\\n\\nDecimal a with quantize() method : \", a.quantize(b)) print (\"Decimal b with quantize() method : \", b.quantize(b))", "e": 1430, "s": 1001, "text": null }, { "code": null, "e": 1439, "s": 1430, "text": "Output :" }, { "code": null, "e": 1581, "s": 1439, "text": "Decimal value a : -3.14\nDecimal value b : 3.21E+7\n\n\nDecimal a with quantize() method : -0E+5\nDecimal b with quantize() method : 3.21E+7\n\n" }, { "code": null, "e": 1598, "s": 1581, "text": "Python-Functions" }, { "code": null, "e": 1605, "s": 1598, "text": "Python" } ]
Iterate List in Java using Loops
21 Jun, 2021 In this article, we are going to see how to iterate through a List. In Java, a List is an interface of the Collection framework. List can be of various types such as ArrayList, Stack, LinkedList, and Vector. There are various ways to iterate through a java List but here we will only be discussing our traversal using loops only. So, there were standard three traversals available so do three methods do exists but with the introduction of java 8 and streams other methods do arises out. So, all the four methods are discussed below as follows: Methods: For loop MethodWhile MethodFor-each loop MethodFor-each loop of java 8 For loop Method While Method For-each loop Method For-each loop of java 8 Implementation: Method 1: Using a for loop For Loop is the most common flow control loop. For loop uses a variable to iterate through the list. Example Java // Java Program to Iterate List in java// using for loop// Importing all input output classesimport java.io.*;// Importing all utility classes from// java.util packageimport java.util.*; // Classclass GFG { // main driver method public static void main(String[] args) { // Creating an ArrayList object // Declaring object of Integer type // Custom entries in array List<Integer> my_list = Arrays.asList(10, 20, 30, 40, 50); // Display message System.out.print("Iterating over ArrayList: "); // Iteration over ArrayList // using the for loop for (int i = 0; i < my_list.size(); i++) // Print and display the all elements // in List object System.out.print(my_list.get(i) + " "); // new line System.out.println(); // No, creating a vector of size N // Custom entry for N = 5 // Custom Integer entries List<Integer> v = new Vector<Integer>(5); v.add(10); v.add(20); v.add(30); v.add(40); v.add(50); // Display message System.out.print("Iterating over Vector: "); // iterating over vector using for loop for (int i = 0; i < v.size(); i++) // Print and display vector elements System.out.print(v.get(i) + " "); // New Line System.out.println(); // Creating a stack containing Integer elements List<Integer> s = new Stack<Integer>(); // Adding integer elements // Custom input s.add(10); s.add(20); s.add(30); s.add(40); s.add(50); // Display message System.out.print("Iterating over Stack: "); // For loop o iterate over elements in stack for (int i = 0; i < v.size(); i++) // Print and display all stack elements System.out.print(s.get(i) + " "); }} Iterating over ArrayList: 10 20 30 40 50 Iterating over Vector: 10 20 30 40 50 Iterating over Stack: 10 20 30 40 50 Method 2: Using While loop Java while loop similar to For loop is a control flow statement that allows code to run repeatedly until a desired condition is met. Example Java // Java Program to iterate over List// using while loop // Importing all input output classesimport java.io.*;// Importing all utility classes from// java.util packageimport java.util.*; // Classclass GFG { // Main driver method public static void main(String[] args) { // Creating an object of List // Declaring object of Integer type // Custom Integer entries List<Integer> my_list = Arrays.asList(10, 20, 30, 40, 50); // Display message System.out.print("Iterating over ArrayList: "); // Initially loop variable is initialized // with zero int i = 0; // Iterating over List via while loop // using size() method while (i < my_list.size()) { // Print and display all elements // of an ArrayList System.out.print(my_list.get(i) + " "); // Incrementing the counter by unity safter // one iteration i++; } i = 0; // New Line System.out.println(); // Creating a Vector of size N // Custom value for N = 5 List<Integer> v = new Vector<Integer>(5); // Adding 5 elements to the above List object // for vector // Custom entries v.add(10); v.add(20); v.add(30); v.add(40); v.add(50); // Display message System.out.print("Iterating over Vector: "); // Iterating over Vector via while loop // using the size() method while (i < v.size()) { // Print and display all elements of vector System.out.print(v.get(i) + " "); // Increment the counter variable i++; } // Counter variable is initially // initialized with zero i = 0; // New Line System.out.println(); // Creating a Stack by creating another // list object of Integer type // Declaring object of Integer type List<Integer> s = new Stack<Integer>(); // Adding elements to the above stack // Custom entries s.add(10); s.add(20); s.add(30); s.add(40); s.add(50); // Display message System.out.print("Iterating over Stack: "); // Iterating over stack via while loop // using size method() while (i < v.size()) { // Print and display all elements // of the above stack/ obj created System.out.print(s.get(i) + " "); // Increment the counter by unity i++; } }} Iterating over ArrayList: 10 20 30 40 50 Iterating over Vector: 10 20 30 40 50 Iterating over Stack: 10 20 30 40 50 Method 3: Using for each loop Syntax: for (type temp : list_name) { statements using temp; } Example Java /*package whatever //do not write package name here */ import java.io.*;import java.util.*;class GFG { public static void main(String[] args) { // creating Arraylist List<Integer> my_list = Arrays.asList(10, 20, 30, 40, 50); System.out.print("Iterating over ArrayList: "); // For Each Loop for iterating ArrayList for (Integer i :my_list) System.out.print(i + " "); System.out.println(); // creating Vector of size 5 List<Integer> v = new Vector<Integer>(5); v.add(10); v.add(20); v.add(30); v.add(40); v.add(50); System.out.print("Iterating over Vector: "); // For Each Loop for iterating Vector for (Integer i : v) System.out.print(i + " "); System.out.println(); // creating Stack List<Integer> s = new Stack<Integer>(); s.add(10); s.add(20); s.add(30); s.add(40); s.add(50); System.out.print("Iterating over Stack: "); // For Each Loop for iterating Stack for (Integer i : s) System.out.print(i + " "); }} Iterating over ArrayList: 10 20 30 40 50 Iterating over Vector: 10 20 30 40 50 Iterating over Stack: 10 20 30 40 50 Method 4: Using for each loop of Java 8 This method takes a functional interface as a parameter therefore lambda expression can be passed as an argument. Syntax: void forEach(Consumer<? super T> action) Example Java // Importing all input output classesimport java.io.*;// Importing all classes from// java,util packageimport java.util.*; // Classclass GFG { // Main driver method public static void main(String[] args) { // Creating an Arraylist by creating object // of List and declaring as Integer type // Custom Integer entries List<Integer> my_list = Arrays.asList(10, 20, 30, 40, 50); // Display message System.out.print("Iterating over ArrayList: "); // Traversing over ArrayList // using for each method Java 8 my_list.forEach( list -> System.out.print(list + " ")); // New line System.out.println(); // creating Vector by creating object of // List and declaring as Integer type // Vector is of size N // N = 5 for illustration purposes List<Integer> v = new Vector<Integer>(5); // Adding elements to the vector // Custom Integer elements v.add(10); v.add(20); v.add(30); v.add(40); v.add(50); // Display message System.out.print("Iterating over Vector: "); // Traversing the above vector elements // using for each method Java 8 v.forEach(vector -> System.out.print(vector + " ")); // New line System.out.println(); // Creating a Stack by creating an object of // List and declaring it as of Integer type List<Integer> s = new Stack<Integer>(); // Adding elements to the above stack created // Custom inputs addition using add() method s.add(10); s.add(20); s.add(30); s.add(40); s.add(50); // Display message System.out.print("Iterating over Stack: "); // Print and display all the elements inside stack // using for each method Java 8 s.forEach(stack -> System.out.print(stack + " ")); }} Iterating over ArrayList: 10 20 30 40 50 Iterating over Vector: 10 20 30 40 50 Iterating over Stack: 10 20 30 40 50 simranarora5sos saurabh1990aror Java-Collections java-list Picked Java Java Programs Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n21 Jun, 2021" }, { "code": null, "e": 599, "s": 54, "text": "In this article, we are going to see how to iterate through a List. In Java, a List is an interface of the Collection framework. List can be of various types such as ArrayList, Stack, LinkedList, and Vector. There are various ways to iterate through a java List but here we will only be discussing our traversal using loops only. So, there were standard three traversals available so do three methods do exists but with the introduction of java 8 and streams other methods do arises out. So, all the four methods are discussed below as follows:" }, { "code": null, "e": 609, "s": 599, "text": "Methods: " }, { "code": null, "e": 680, "s": 609, "text": "For loop MethodWhile MethodFor-each loop MethodFor-each loop of java 8" }, { "code": null, "e": 696, "s": 680, "text": "For loop Method" }, { "code": null, "e": 709, "s": 696, "text": "While Method" }, { "code": null, "e": 730, "s": 709, "text": "For-each loop Method" }, { "code": null, "e": 754, "s": 730, "text": "For-each loop of java 8" }, { "code": null, "e": 770, "s": 754, "text": "Implementation:" }, { "code": null, "e": 797, "s": 770, "text": "Method 1: Using a for loop" }, { "code": null, "e": 900, "s": 797, "text": " For Loop is the most common flow control loop. For loop uses a variable to iterate through the list. " }, { "code": null, "e": 909, "s": 900, "text": "Example " }, { "code": null, "e": 914, "s": 909, "text": "Java" }, { "code": "// Java Program to Iterate List in java// using for loop// Importing all input output classesimport java.io.*;// Importing all utility classes from// java.util packageimport java.util.*; // Classclass GFG { // main driver method public static void main(String[] args) { // Creating an ArrayList object // Declaring object of Integer type // Custom entries in array List<Integer> my_list = Arrays.asList(10, 20, 30, 40, 50); // Display message System.out.print(\"Iterating over ArrayList: \"); // Iteration over ArrayList // using the for loop for (int i = 0; i < my_list.size(); i++) // Print and display the all elements // in List object System.out.print(my_list.get(i) + \" \"); // new line System.out.println(); // No, creating a vector of size N // Custom entry for N = 5 // Custom Integer entries List<Integer> v = new Vector<Integer>(5); v.add(10); v.add(20); v.add(30); v.add(40); v.add(50); // Display message System.out.print(\"Iterating over Vector: \"); // iterating over vector using for loop for (int i = 0; i < v.size(); i++) // Print and display vector elements System.out.print(v.get(i) + \" \"); // New Line System.out.println(); // Creating a stack containing Integer elements List<Integer> s = new Stack<Integer>(); // Adding integer elements // Custom input s.add(10); s.add(20); s.add(30); s.add(40); s.add(50); // Display message System.out.print(\"Iterating over Stack: \"); // For loop o iterate over elements in stack for (int i = 0; i < v.size(); i++) // Print and display all stack elements System.out.print(s.get(i) + \" \"); }}", "e": 2855, "s": 914, "text": null }, { "code": null, "e": 2984, "s": 2858, "text": "Iterating over ArrayList: 10 20 30 40 50 \nIterating over Vector: 10 20 30 40 50 \nIterating over Stack: 10 20 30 40 50 " }, { "code": null, "e": 3013, "s": 2986, "text": "Method 2: Using While loop" }, { "code": null, "e": 3149, "s": 3015, "text": "Java while loop similar to For loop is a control flow statement that allows code to run repeatedly until a desired condition is met. " }, { "code": null, "e": 3160, "s": 3151, "text": "Example " }, { "code": null, "e": 3167, "s": 3162, "text": "Java" }, { "code": "// Java Program to iterate over List// using while loop // Importing all input output classesimport java.io.*;// Importing all utility classes from// java.util packageimport java.util.*; // Classclass GFG { // Main driver method public static void main(String[] args) { // Creating an object of List // Declaring object of Integer type // Custom Integer entries List<Integer> my_list = Arrays.asList(10, 20, 30, 40, 50); // Display message System.out.print(\"Iterating over ArrayList: \"); // Initially loop variable is initialized // with zero int i = 0; // Iterating over List via while loop // using size() method while (i < my_list.size()) { // Print and display all elements // of an ArrayList System.out.print(my_list.get(i) + \" \"); // Incrementing the counter by unity safter // one iteration i++; } i = 0; // New Line System.out.println(); // Creating a Vector of size N // Custom value for N = 5 List<Integer> v = new Vector<Integer>(5); // Adding 5 elements to the above List object // for vector // Custom entries v.add(10); v.add(20); v.add(30); v.add(40); v.add(50); // Display message System.out.print(\"Iterating over Vector: \"); // Iterating over Vector via while loop // using the size() method while (i < v.size()) { // Print and display all elements of vector System.out.print(v.get(i) + \" \"); // Increment the counter variable i++; } // Counter variable is initially // initialized with zero i = 0; // New Line System.out.println(); // Creating a Stack by creating another // list object of Integer type // Declaring object of Integer type List<Integer> s = new Stack<Integer>(); // Adding elements to the above stack // Custom entries s.add(10); s.add(20); s.add(30); s.add(40); s.add(50); // Display message System.out.print(\"Iterating over Stack: \"); // Iterating over stack via while loop // using size method() while (i < v.size()) { // Print and display all elements // of the above stack/ obj created System.out.print(s.get(i) + \" \"); // Increment the counter by unity i++; } }}", "e": 5773, "s": 3167, "text": null }, { "code": null, "e": 5902, "s": 5776, "text": "Iterating over ArrayList: 10 20 30 40 50 \nIterating over Vector: 10 20 30 40 50 \nIterating over Stack: 10 20 30 40 50 " }, { "code": null, "e": 5934, "s": 5904, "text": "Method 3: Using for each loop" }, { "code": null, "e": 5944, "s": 5936, "text": "Syntax:" }, { "code": null, "e": 6007, "s": 5946, "text": "for (type temp : list_name) \n{ \n statements using temp;\n}" }, { "code": null, "e": 6018, "s": 6009, "text": "Example " }, { "code": null, "e": 6025, "s": 6020, "text": "Java" }, { "code": "/*package whatever //do not write package name here */ import java.io.*;import java.util.*;class GFG { public static void main(String[] args) { // creating Arraylist List<Integer> my_list = Arrays.asList(10, 20, 30, 40, 50); System.out.print(\"Iterating over ArrayList: \"); // For Each Loop for iterating ArrayList for (Integer i :my_list) System.out.print(i + \" \"); System.out.println(); // creating Vector of size 5 List<Integer> v = new Vector<Integer>(5); v.add(10); v.add(20); v.add(30); v.add(40); v.add(50); System.out.print(\"Iterating over Vector: \"); // For Each Loop for iterating Vector for (Integer i : v) System.out.print(i + \" \"); System.out.println(); // creating Stack List<Integer> s = new Stack<Integer>(); s.add(10); s.add(20); s.add(30); s.add(40); s.add(50); System.out.print(\"Iterating over Stack: \"); // For Each Loop for iterating Stack for (Integer i : s) System.out.print(i + \" \"); }}", "e": 7207, "s": 6025, "text": null }, { "code": null, "e": 7336, "s": 7210, "text": "Iterating over ArrayList: 10 20 30 40 50 \nIterating over Vector: 10 20 30 40 50 \nIterating over Stack: 10 20 30 40 50 " }, { "code": null, "e": 7378, "s": 7338, "text": "Method 4: Using for each loop of Java 8" }, { "code": null, "e": 7494, "s": 7380, "text": "This method takes a functional interface as a parameter therefore lambda expression can be passed as an argument." }, { "code": null, "e": 7504, "s": 7496, "text": "Syntax:" }, { "code": null, "e": 7547, "s": 7506, "text": "void forEach(Consumer<? super T> action)" }, { "code": null, "e": 7558, "s": 7549, "text": "Example " }, { "code": null, "e": 7565, "s": 7560, "text": "Java" }, { "code": "// Importing all input output classesimport java.io.*;// Importing all classes from// java,util packageimport java.util.*; // Classclass GFG { // Main driver method public static void main(String[] args) { // Creating an Arraylist by creating object // of List and declaring as Integer type // Custom Integer entries List<Integer> my_list = Arrays.asList(10, 20, 30, 40, 50); // Display message System.out.print(\"Iterating over ArrayList: \"); // Traversing over ArrayList // using for each method Java 8 my_list.forEach( list -> System.out.print(list + \" \")); // New line System.out.println(); // creating Vector by creating object of // List and declaring as Integer type // Vector is of size N // N = 5 for illustration purposes List<Integer> v = new Vector<Integer>(5); // Adding elements to the vector // Custom Integer elements v.add(10); v.add(20); v.add(30); v.add(40); v.add(50); // Display message System.out.print(\"Iterating over Vector: \"); // Traversing the above vector elements // using for each method Java 8 v.forEach(vector -> System.out.print(vector + \" \")); // New line System.out.println(); // Creating a Stack by creating an object of // List and declaring it as of Integer type List<Integer> s = new Stack<Integer>(); // Adding elements to the above stack created // Custom inputs addition using add() method s.add(10); s.add(20); s.add(30); s.add(40); s.add(50); // Display message System.out.print(\"Iterating over Stack: \"); // Print and display all the elements inside stack // using for each method Java 8 s.forEach(stack -> System.out.print(stack + \" \")); }}", "e": 9522, "s": 7565, "text": null }, { "code": null, "e": 9651, "s": 9525, "text": "Iterating over ArrayList: 10 20 30 40 50 \nIterating over Vector: 10 20 30 40 50 \nIterating over Stack: 10 20 30 40 50 " }, { "code": null, "e": 9669, "s": 9653, "text": "simranarora5sos" }, { "code": null, "e": 9685, "s": 9669, "text": "saurabh1990aror" }, { "code": null, "e": 9702, "s": 9685, "text": "Java-Collections" }, { "code": null, "e": 9712, "s": 9702, "text": "java-list" }, { "code": null, "e": 9719, "s": 9712, "text": "Picked" }, { "code": null, "e": 9724, "s": 9719, "text": "Java" }, { "code": null, "e": 9738, "s": 9724, "text": "Java Programs" }, { "code": null, "e": 9743, "s": 9738, "text": "Java" }, { "code": null, "e": 9760, "s": 9743, "text": "Java-Collections" } ]
Tiling Problem
24 May, 2022 Given a “2 x n” board and tiles of size “2 x 1”, count the number of ways to tile the given board using the 2 x 1 tiles. A tile can either be placed horizontally i.e., as a 1 x 2 tile or vertically i.e., as 2 x 1 tile. Examples: Input: n = 4 Output: 5 Explanation: 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. For a 2 x 4 board, there are 5 ways All 4 vertical (1 way) All 4 horizontal (1 way) 2 vertical and 2 horizontal (3 ways) Input: n = 3 Output: 3 Explanation: We need 3 tiles to tile the board of size 2 x 3. We can tile the board using following ways Place all 3 tiles vertically. Place 1 tile vertically and remaining 2 tiles horizontally (2 ways) Implementation – Let “count(n)” be the count of ways to place tiles on a “2 x n” grid, we have following two ways to place first tile. 1) If we place first tile vertically, the problem reduces to “count(n-1)” 2) If we place first tile horizontally, we have to place second tile also horizontally. So the problem reduces to “count(n-2)” Therefore, count(n) can be written as below. count(n) = n if n = 1 or n = 2 count(n) = count(n-1) + count(n-2) Here’s the code for the above approach: C++ Java Python3 C# Javascript // C++ program to count the// no. of ways to place 2*1 size// tiles in 2*n size board.#include <iostream>using namespace std; int getNoOfWays(int n){ // Base case if (n <= 2) return n; return getNoOfWays(n - 1) + getNoOfWays(n - 2);} // Driver Functionint main(){ cout << getNoOfWays(4) << endl; cout << getNoOfWays(3); return 0;} /* Java program to count the no of ways to place 2*1 size tiles in 2*n size board. */import java.io.*; class GFG { static int getNoOfWays(int n) { // Base case if (n <= 2) { return n; } return getNoOfWays(n - 1) + getNoOfWays(n - 2); } // Driver Function public static void main(String[] args) { System.out.println(getNoOfWays(4)); System.out.println(getNoOfWays(3)); }} // This code is contributed by ashwinaditya21. # Python3 program to count the# no. of ways to place 2*1 size# tiles in 2*n size board.def getNoOfWays(n): # Base case if n <= 2: return n return getNoOfWays(n - 1) + getNoOfWays(n - 2) # Driver Codeprint(getNoOfWays(4))print(getNoOfWays(3)) # This code is contributed by Kevin Joshi // C# program to implement// the above approachusing System; class GFG{ static int getNoOfWays(int n) { // Base case if (n <= 2) { return n; } return getNoOfWays(n - 1) + getNoOfWays(n - 2); } // Driver Codepublic static void Main(){ Console.WriteLine(getNoOfWays(4)); Console.WriteLine(getNoOfWays(3));}} // This code is contributed by code_hunt. <script>// JavaScript program to count the// no. of ways to place 2*1 size// tiles in 2*n size board. function getNoOfWays(n){ // Base case if (n <= 2) return n; return getNoOfWays(n - 1) + getNoOfWays(n - 2);} // Driver Functiondocument.write(getNoOfWays(4));document.write(getNoOfWays(3)); // This code is contributed by shinjanpatra</script> Output: 5 3 The above recurrence is nothing but Fibonacci Number expression. We can find n’th Fibonacci number in O(Log n) time, see below for all method to find n’th Fibonacci Number. https://youtu.be/NyICqRtePVs https://youtu.be/U9ylW7NsHlI Different methods for n’th Fibonacci Number. Count the number of ways to tile the floor of size n x m using 1 x m size tiles This article is contributed by Saurabh Jain. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above shahbazalam75508 vishalsharma14 kevinjoshi46b wangweixvan shinjanpatra ashwinaditya21 code_hunt Amazon Fibonacci Dynamic Programming Mathematical Amazon Dynamic Programming Mathematical Fibonacci Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Find if there is a path between two vertices in an undirected graph Floyd Warshall Algorithm | DP-16 Matrix Chain Multiplication | DP-8 Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Minimum number of jumps to reach end Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string C++ Data Types Merge two sorted arrays Operators in C / C++
[ { "code": null, "e": 52, "s": 24, "text": "\n24 May, 2022" }, { "code": null, "e": 272, "s": 52, "text": "Given a “2 x n” board and tiles of size “2 x 1”, count the number of ways to tile the given board using the 2 x 1 tiles. A tile can either be placed horizontally i.e., as a 1 x 2 tile or vertically i.e., as 2 x 1 tile. " }, { "code": null, "e": 283, "s": 272, "text": "Examples: " }, { "code": null, "e": 296, "s": 283, "text": "Input: n = 4" }, { "code": null, "e": 306, "s": 296, "text": "Output: 5" }, { "code": null, "e": 319, "s": 306, "text": "Explanation:" }, { "code": null, "e": 328, "s": 319, "text": "Chapters" }, { "code": null, "e": 355, "s": 328, "text": "descriptions off, selected" }, { "code": null, "e": 405, "s": 355, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 428, "s": 405, "text": "captions off, selected" }, { "code": null, "e": 436, "s": 428, "text": "English" }, { "code": null, "e": 460, "s": 436, "text": "This is a modal window." }, { "code": null, "e": 529, "s": 460, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 551, "s": 529, "text": "End of dialog window." }, { "code": null, "e": 587, "s": 551, "text": "For a 2 x 4 board, there are 5 ways" }, { "code": null, "e": 610, "s": 587, "text": "All 4 vertical (1 way)" }, { "code": null, "e": 635, "s": 610, "text": "All 4 horizontal (1 way)" }, { "code": null, "e": 672, "s": 635, "text": "2 vertical and 2 horizontal (3 ways)" }, { "code": null, "e": 685, "s": 672, "text": "Input: n = 3" }, { "code": null, "e": 695, "s": 685, "text": "Output: 3" }, { "code": null, "e": 708, "s": 695, "text": "Explanation:" }, { "code": null, "e": 758, "s": 708, "text": "We need 3 tiles to tile the board of size 2 x 3." }, { "code": null, "e": 801, "s": 758, "text": "We can tile the board using following ways" }, { "code": null, "e": 831, "s": 801, "text": "Place all 3 tiles vertically." }, { "code": null, "e": 899, "s": 831, "text": "Place 1 tile vertically and remaining 2 tiles horizontally (2 ways)" }, { "code": null, "e": 921, "s": 903, "text": "Implementation – " }, { "code": null, "e": 1286, "s": 921, "text": "Let “count(n)” be the count of ways to place tiles on a “2 x n” grid, we have following two ways to place first tile. 1) If we place first tile vertically, the problem reduces to “count(n-1)” 2) If we place first tile horizontally, we have to place second tile also horizontally. So the problem reduces to “count(n-2)” Therefore, count(n) can be written as below. " }, { "code": null, "e": 1358, "s": 1286, "text": " count(n) = n if n = 1 or n = 2\n count(n) = count(n-1) + count(n-2)" }, { "code": null, "e": 1398, "s": 1358, "text": "Here’s the code for the above approach:" }, { "code": null, "e": 1402, "s": 1398, "text": "C++" }, { "code": null, "e": 1407, "s": 1402, "text": "Java" }, { "code": null, "e": 1415, "s": 1407, "text": "Python3" }, { "code": null, "e": 1418, "s": 1415, "text": "C#" }, { "code": null, "e": 1429, "s": 1418, "text": "Javascript" }, { "code": "// C++ program to count the// no. of ways to place 2*1 size// tiles in 2*n size board.#include <iostream>using namespace std; int getNoOfWays(int n){ // Base case if (n <= 2) return n; return getNoOfWays(n - 1) + getNoOfWays(n - 2);} // Driver Functionint main(){ cout << getNoOfWays(4) << endl; cout << getNoOfWays(3); return 0;}", "e": 1784, "s": 1429, "text": null }, { "code": "/* Java program to count the no of ways to place 2*1 size tiles in 2*n size board. */import java.io.*; class GFG { static int getNoOfWays(int n) { // Base case if (n <= 2) { return n; } return getNoOfWays(n - 1) + getNoOfWays(n - 2); } // Driver Function public static void main(String[] args) { System.out.println(getNoOfWays(4)); System.out.println(getNoOfWays(3)); }} // This code is contributed by ashwinaditya21.", "e": 2234, "s": 1784, "text": null }, { "code": "# Python3 program to count the# no. of ways to place 2*1 size# tiles in 2*n size board.def getNoOfWays(n): # Base case if n <= 2: return n return getNoOfWays(n - 1) + getNoOfWays(n - 2) # Driver Codeprint(getNoOfWays(4))print(getNoOfWays(3)) # This code is contributed by Kevin Joshi", "e": 2538, "s": 2234, "text": null }, { "code": "// C# program to implement// the above approachusing System; class GFG{ static int getNoOfWays(int n) { // Base case if (n <= 2) { return n; } return getNoOfWays(n - 1) + getNoOfWays(n - 2); } // Driver Codepublic static void Main(){ Console.WriteLine(getNoOfWays(4)); Console.WriteLine(getNoOfWays(3));}} // This code is contributed by code_hunt.", "e": 2917, "s": 2538, "text": null }, { "code": "<script>// JavaScript program to count the// no. of ways to place 2*1 size// tiles in 2*n size board. function getNoOfWays(n){ // Base case if (n <= 2) return n; return getNoOfWays(n - 1) + getNoOfWays(n - 2);} // Driver Functiondocument.write(getNoOfWays(4));document.write(getNoOfWays(3)); // This code is contributed by shinjanpatra</script>", "e": 3283, "s": 2917, "text": null }, { "code": null, "e": 3291, "s": 3283, "text": "Output:" }, { "code": null, "e": 3295, "s": 3291, "text": "5\n3" }, { "code": null, "e": 3821, "s": 3295, "text": "The above recurrence is nothing but Fibonacci Number expression. We can find n’th Fibonacci number in O(Log n) time, see below for all method to find n’th Fibonacci Number. https://youtu.be/NyICqRtePVs https://youtu.be/U9ylW7NsHlI Different methods for n’th Fibonacci Number. Count the number of ways to tile the floor of size n x m using 1 x m size tiles This article is contributed by Saurabh Jain. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 3838, "s": 3821, "text": "shahbazalam75508" }, { "code": null, "e": 3853, "s": 3838, "text": "vishalsharma14" }, { "code": null, "e": 3867, "s": 3853, "text": "kevinjoshi46b" }, { "code": null, "e": 3879, "s": 3867, "text": "wangweixvan" }, { "code": null, "e": 3892, "s": 3879, "text": "shinjanpatra" }, { "code": null, "e": 3907, "s": 3892, "text": "ashwinaditya21" }, { "code": null, "e": 3917, "s": 3907, "text": "code_hunt" }, { "code": null, "e": 3924, "s": 3917, "text": "Amazon" }, { "code": null, "e": 3934, "s": 3924, "text": "Fibonacci" }, { "code": null, "e": 3954, "s": 3934, "text": "Dynamic Programming" }, { "code": null, "e": 3967, "s": 3954, "text": "Mathematical" }, { "code": null, "e": 3974, "s": 3967, "text": "Amazon" }, { "code": null, "e": 3994, "s": 3974, "text": "Dynamic Programming" }, { "code": null, "e": 4007, "s": 3994, "text": "Mathematical" }, { "code": null, "e": 4017, "s": 4007, "text": "Fibonacci" }, { "code": null, "e": 4115, "s": 4017, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4183, "s": 4115, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 4216, "s": 4183, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 4251, "s": 4216, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 4319, "s": 4251, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 4356, "s": 4319, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 4399, "s": 4356, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 4459, "s": 4399, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 4474, "s": 4459, "text": "C++ Data Types" }, { "code": null, "e": 4498, "s": 4474, "text": "Merge two sorted arrays" } ]
Find pairs with given sum such that elements of pair are in different rows
06 Jul, 2022 Given a matrix of distinct values and a sum. The task is to find all the pairs in a given matrix whose summation is equal to the given sum. Each element of a pair must be from different rows i.e; the pair must not lie in the same row. Examples: Input : mat[4][4] = {{1, 3, 2, 4}, {5, 8, 7, 6}, {9, 10, 13, 11}, {12, 0, 14, 15}} sum = 11 Output: (1, 10), (3, 8), (2, 9), (4, 7), (11, 0) Method 1 (Simple): A simple solution for this problem is to, one by one, take each element of all rows and find pairs starting from the next immediate row in the matrix. The time complexity for this approach will be O(n4). Method 2 (Use Sorting) Sort all the rows in ascending order. The time complexity for this preprocessing will be O(n2 logn). Now we will select each row one by one and find pair elements in the remaining rows after the current row. Take two iterators, left and right. left iterator points left corner of the current i’th row and right iterator points right corner of the next j’th row in which we are going to find a pair of elements. If mat[i][left] + mat[j][right] < sum then left++ i.e; move in i’th row towards the right corner, otherwise right++ i.e; move in j’th row towards the left corner Implementation: C++ Java Python 3 C# Javascript // C++ program to find a pair with given sum such that// every element of pair is in different rows.#include<bits/stdc++.h>using namespace std; const int MAX = 100; // Function to find pair for given sum in matrix// mat[][] --> given matrix// n --> order of matrix// sum --> given sum for which we need to find pairvoid pairSum(int mat[][MAX], int n, int sum){ // First sort all the rows in ascending order for (int i=0; i<n; i++) sort(mat[i], mat[i]+n); // Select i'th row and find pair for element in i'th // row in j'th row whose summation is equal to given sum for (int i=0; i<n-1; i++) { for (int j=i+1; j<n; j++) { int left = 0, right = n-1; while (left<n && right>=0) { if ((mat[i][left] + mat[j][right]) == sum) { cout << "(" << mat[i][left] << ", "<< mat[j][right] << "), "; left++; right--; } else { if ((mat[i][left] + mat[j][right]) < sum) left++; else right--; } } } }} // Driver program to run the caseint main(){ int n = 4, sum = 11; int mat[][MAX] = {{1, 3, 2, 4}, {5, 8, 7, 6}, {9, 10, 13, 11}, {12, 0, 14, 15}}; pairSum(mat, n, sum); return 0;} // Java program to find a pair with// given sum such that every element// of pair is in different rows.import java.util.Arrays;class GFG {static final int MAX = 100; // Function to find pair for given sum in// matrix mat[][] --> given matrix// n --> order of matrix// sum --> given sum for which we need to find pairstatic void pairSum(int mat[][], int n, int sum) { // First sort all the rows in ascending order for (int i = 0; i < n; i++) Arrays.sort(mat[i]); // Select i'th row and find pair for element in i'th // row in j'th row whose summation is equal to given sum for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { int left = 0, right = n - 1; while (left < n && right >= 0) { if ((mat[i][left] + mat[j][right]) == sum) { System.out.print("(" + mat[i][left] + ", " + mat[j][right] + "), "); left++; right--; } else { if ((mat[i][left] + mat[j][right]) < sum) left++; else right--; } } } }} // Driver codepublic static void main(String[] args) { int n = 4, sum = 11; int mat[] [] = {{1 , 3, 2, 4}, {5 , 8, 7, 6}, {9 , 10, 13, 11}, {12, 0, 14, 15}}; pairSum(mat, n, sum);}}// This code is contributed by Anant Agarwal. # Python 3 program to find a pair with# given sum such that every element of# pair is in different rows.MAX = 100 # Function to find pair for given# sum in matrix mat[][] --> given matrix# n --> order of matrix# sum --> given sum for which we# need to find pairdef pairSum(mat, n, sum): # First sort all the rows # in ascending order for i in range(n): mat[i].sort() # Select i'th row and find pair for # element in i'th row in j'th row # whose summation is equal to given sum for i in range(n - 1): for j in range(i + 1, n): left = 0 right = n - 1 while (left < n and right >= 0): if ((mat[i][left] + mat[j][right]) == sum): print( "(", mat[i][left], ", ", mat[j][right], "), ", end = " ") left += 1 right -= 1 else: if ((mat[i][left] + mat[j][right]) < sum): left += 1 else: right -= 1 # Driver Codeif __name__ == "__main__": n = 4 sum = 11 mat = [[1, 3, 2, 4], [5, 8, 7, 6], [9, 10, 13, 11], [12, 0, 14, 15]] pairSum(mat, n, sum) # This code is contributed# by ChitraNayal // C# program to find a pair with// given sum such that every element// of pair is in different rows.using System;using System.Collections.Generic; public class GFG { // Function to find pair for given sum in// matrix mat[][] --> given matrix// n --> order of matrix// sum --> given sum for which we need to find pairstatic void pairSum(int [,]mat, int n, int sum) { // First sort all the rows in ascending order for (int i = 0; i < n; i++) { List<int> l = new List<int>(); for(int j = 0; j<n;j++) { l.Add(mat[i,j]); } l.Sort(); for(int j = 0; j<n;j++) { mat[i,j] = l[j]; } } // Select i'th row and find pair for element in i'th // row in j'th row whose summation is equal to given sum for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { int left = 0, right = n - 1; while (left < n && right >= 0) { if ((mat[i,left] + mat[j,right]) == sum) { Console.Write("(" + mat[i,left] + ", " + mat[j,right] + "), "); left++; right--; } else { if ((mat[i,left] + mat[j,right]) < sum) left++; else right--; } } } }} // Driver codepublic static void Main(string[] args) { int n = 4, sum = 11; int [,]mat = {{1 , 3, 2, 4}, {5 , 8, 7, 6}, {9 , 10, 13, 11}, {12, 0, 14, 15}}; pairSum(mat, n, sum);}} // This code is contributed by rutvik_56. <script> // Javascript program to find a pair with// given sum such that every element// of pair is in different rows. let MAX = 100; // Function to find pair for given sum in// matrix mat[][] --> given matrix// n --> order of matrix// sum --> given sum for which we need to find pairfunction pairSum(mat, n, sum) { // First sort all the rows in ascending order for (let i = 0; i < n; i++) mat[i].sort((a, b) => a - b); // Select i'th row and find pair for element in i'th // row in j'th row whose summation is equal to given sum for (let i = 0; i < n - 1; i++) { for (let j = i + 1; j < n; j++) { let left = 0, right = n - 1; while (left < n && right >= 0) { if ((mat[i][left] + mat[j][right]) == sum) { document.write("(" + mat[i][left] + ", " + mat[j][right] + "), "); left++; right--; } else { if ((mat[i][left] + mat[j][right]) < sum) left++; else right--; } } } }} // Driver program let n = 4, sum = 11; let mat = [[1 , 3, 2, 4], [5 , 8, 7, 6], [9 , 10, 13, 11], [12, 0, 14, 15]]; pairSum(mat, n, sum); </script> (3, 8), (4, 7), (1, 10), (2, 9), (11, 0), Time complexity : O(n2logn + n^3) Auxiliary space : O(1) Method 3 (Hashing) Create an empty hash table and store all elements of the matrix in the hash as keys and their locations as values.Traverse the matrix again to check for every element whether its pair exists in the hash table or not. If it exists, then compare row numbers. If row numbers are not the same, then print the pair. Create an empty hash table and store all elements of the matrix in the hash as keys and their locations as values. Traverse the matrix again to check for every element whether its pair exists in the hash table or not. If it exists, then compare row numbers. If row numbers are not the same, then print the pair. Implementation: CPP Java Python3 C# Javascript // C++ program to find pairs with given sum such// the two elements of pairs are from different rows#include<bits/stdc++.h>using namespace std; const int MAX = 100; // Function to find pair for given sum in matrix// mat[][] --> given matrix// n --> order of matrix// sum --> given sum for which we need to find pairvoid pairSum(int mat[][MAX], int n, int sum){ // Create a hash and store all elements of matrix // as keys, and row as values unordered_map<int, int> hm; // Traverse the matrix to check for every // element whether its pair exists or not. for (int i=0; i<n; i++) { for (int j=0; j<n; j++) { // Look for remaining sum in hash int remSum = sum - mat[i][j]; auto it = hm.find(remSum); // it is an iterator // of unordered_map type // If an element with value equal to remaining sum exists if (it != hm.end()) { // Find row numbers of element with // value equal to remaining sum. int row = hm[remSum]; // If row number of pair is not same as current // row, then print it as part of result. // Second condition is there to make sure that a // pair is printed only once. if (row < i) cout << "(" << mat[i][j] << ", " << remSum << "), "; } hm[mat[i][j]] = i; } }} // Driver programint main(){ int n = 4, sum = 11; int mat[][MAX]= {{1, 3, 2, 4}, {5, 8, 7, 6}, {9, 10, 13, 11}, {12, 0, 14, 15}}; pairSum(mat, n, sum); return 0;} // Java program to find pairs with given sum such// the two elements of pairs are from different rowsimport java.io.*;import java.util.*;class GFG{ static int MAX = 100; // Function to find pair for given sum in matrix // mat[][] --> given matrix // n --> order of matrix // sum --> given sum for which we need to find pair static void pairSum(int mat[][], int n, int sum) { // Create a hash and store all elements of matrix // as keys, and row and column numbers as values Map<Integer,ArrayList<Integer>> hm = new HashMap<Integer, ArrayList<Integer>>(); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { hm.put(mat[i][j], new ArrayList<Integer>(Arrays.asList(i, j)) ); } } // Traverse the matrix again to check for every // element whether its pair exists or not. for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // Look for remaining sum in hash int remSum = sum - mat[i][j]; // If an element with value equal to remaining sum exists if(hm.containsKey(remSum)) { // Find row and column numbers of element with // value equal to remaining sum. ArrayList<Integer> p = hm.get(remSum); int row = p.get(0), col = p.get(1); // If row number of pair is not same as current // row, then print it as part of result. // Second condition is there to make sure that a // pair is printed only once. if (row != i && row > i) { System.out.print("(" + mat[i][j] + "," + mat[row][col] + "), "); } } } } } // Driver code public static void main (String[] args) { int n = 4, sum = 11; int[][] mat = {{1, 3, 2, 4}, {5, 8, 7, 6}, {9, 10, 13, 11}, {12, 0, 14, 15}}; pairSum(mat, n, sum); }} // This code is contributed by avanitrachhadiya2155 # Python3 program to find pairs with given sum such# the two elements of pairs are from different rowsMAX = 100 # Function to find pair for given sum in matrix # mat[][] --> given matrix # n --> order of matrix # sum --> given sum for which we need to find pairdef pairSum(mat, n, sum): # Create a hash and store all elements of matrix # as keys, and row and column numbers as values hm = {} for i in range(n): for j in range(n): hm[mat[i][j]] = [i, j] # Traverse the matrix again to check for every # element whether its pair exists or not. for i in range(n): for j in range(n): # Look for remaining sum in hash remSum = sum - mat[i][j] # If an element with value equal to remaining sum exists if remSum in hm: # Find row and column numbers of element with # value equal to remaining sum. p=hm[remSum] row = p[0] col = p[1] # If row number of pair is not same as current # row, then print it as part of result. # Second condition is there to make sure that a # pair is printed only once. if (row != i and row > i): print("(" , mat[i][j] , "," , mat[row][col] , "), ", end="") # Driver coden = 4sum = 11mat = [[1, 3, 2, 4], [5, 8, 7, 6], [9, 10, 13, 11], [12, 0, 14, 15]]pairSum(mat, n, sum) # This code is contributed by patel2127 // C# program to find pairs with given sum such// the two elements of pairs are from different rowsusing System;using System.Collections.Generic;public class GFG{ // Function to find pair for given sum in matrix // mat[][] --> given matrix // n --> order of matrix // sum --> given sum for which we need to find pair static void pairSum(int[,] mat, int n, int sum) { // Create a hash and store all elements of matrix // as keys, and row and column numbers as values Dictionary<int,List<int>> hm = new Dictionary<int,List<int>>(); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { hm.Add(mat[i,j],new List<int>(){i,j}); } } // Traverse the matrix again to check for every // element whether its pair exists or not. for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // Look for remaining sum in hash int remSum = sum - mat[i,j]; // If an element with value equal to remaining sum exists if(hm.ContainsKey(remSum)) { // Find row and column numbers of element with // value equal to remaining sum. List<int> p = hm[remSum]; int row = p[0], col = p[1]; // If row number of pair is not same as current // row, then print it as part of result. // Second condition is there to make sure that a // pair is printed only once. if (row != i && row > i) { Console.Write("(" + mat[i, j] + "," + mat[row, col] + "), "); } } } } } // Driver code static public void Main (){ int n = 4, sum = 11; int[,] mat = {{1, 3, 2, 4}, {5, 8, 7, 6}, {9, 10, 13, 11}, {12, 0, 14, 15}}; pairSum(mat, n, sum); }} // This code is contributed by rag2127 <script> // JavaScript program to find pairs with given sum such// the two elements of pairs are from different rows let MAX = 100; // Function to find pair for given sum in matrix // mat[][] --> given matrix // n --> order of matrix // sum --> given sum for which we need to find pairfunction pairSum(mat,n,sum){ // Create a hash and store all elements of matrix // as keys, and row and column numbers as values let hm = new Map(); for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { hm.set(mat[i][j], [i, j] ); } } // Traverse the matrix again to check for every // element whether its pair exists or not. for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { // Look for remaining sum in hash let remSum = sum - mat[i][j]; // If an element with value equal to remaining sum exists if(hm.has(remSum)) { // Find row and column numbers of element with // value equal to remaining sum. let p = hm.get(remSum); let row = p[0], col = p[1]; // If row number of pair is not same as current // row, then print it as part of result. // Second condition is there to make sure that a // pair is printed only once. if (row != i && row > i) { document.write("(" + mat[i][j] + "," + mat[row][col] + "), "); } } } }} // Driver codelet n = 4, sum = 11;let mat = [[1, 3, 2, 4], [5, 8, 7, 6], [9, 10, 13, 11], [12, 0, 14, 15]]; pairSum(mat, n, sum); // This code is contributed by ab2127 </script> (8, 3), (7, 4), (9, 2), (10, 1), (0, 11), One important thing is, when we traverse a matrix, a pair may be printed twice. To make sure that a pair is printed only once, we check if the row number of other elements picked from the hash table is more than the row number of the current element. Time Complexity: O(n2) under the assumption that hash table inserts and search operations take O(1) time. This article is contributed by Shashank Mishra ( Gullu ). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. ukasp avanitrachhadiya2155 rag2127 avijitmondal1998 ab2127 patel2127 margin01001 rutvik_56 nishantsingh1308 simmytarika5 hardikkoriintern Hash Matrix Hash Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. What is Hashing | A Complete Tutorial Longest Consecutive Subsequence Sorting a Map by value in C++ STL Find the smallest window in a string containing all characters of another string Most frequent element in an array Print a given matrix in spiral form Matrix Chain Multiplication | DP-8 Program to find largest element in an array Rat in a Maze | Backtracking-2 Sudoku | Backtracking-7
[ { "code": null, "e": 54, "s": 26, "text": "\n06 Jul, 2022" }, { "code": null, "e": 289, "s": 54, "text": "Given a matrix of distinct values and a sum. The task is to find all the pairs in a given matrix whose summation is equal to the given sum. Each element of a pair must be from different rows i.e; the pair must not lie in the same row." }, { "code": null, "e": 301, "s": 289, "text": "Examples: " }, { "code": null, "e": 514, "s": 301, "text": "Input : mat[4][4] = {{1, 3, 2, 4},\n {5, 8, 7, 6},\n {9, 10, 13, 11},\n {12, 0, 14, 15}}\n sum = 11\nOutput: (1, 10), (3, 8), (2, 9), (4, 7), (11, 0) " }, { "code": null, "e": 533, "s": 514, "text": "Method 1 (Simple):" }, { "code": null, "e": 760, "s": 533, "text": "A simple solution for this problem is to, one by one, take each element of all rows and find pairs starting from the next immediate row in the matrix. The time complexity for this approach will be O(n4). Method 2 (Use Sorting)" }, { "code": null, "e": 861, "s": 760, "text": "Sort all the rows in ascending order. The time complexity for this preprocessing will be O(n2 logn)." }, { "code": null, "e": 968, "s": 861, "text": "Now we will select each row one by one and find pair elements in the remaining rows after the current row." }, { "code": null, "e": 1171, "s": 968, "text": "Take two iterators, left and right. left iterator points left corner of the current i’th row and right iterator points right corner of the next j’th row in which we are going to find a pair of elements." }, { "code": null, "e": 1333, "s": 1171, "text": "If mat[i][left] + mat[j][right] < sum then left++ i.e; move in i’th row towards the right corner, otherwise right++ i.e; move in j’th row towards the left corner" }, { "code": null, "e": 1349, "s": 1333, "text": "Implementation:" }, { "code": null, "e": 1353, "s": 1349, "text": "C++" }, { "code": null, "e": 1358, "s": 1353, "text": "Java" }, { "code": null, "e": 1367, "s": 1358, "text": "Python 3" }, { "code": null, "e": 1370, "s": 1367, "text": "C#" }, { "code": null, "e": 1381, "s": 1370, "text": "Javascript" }, { "code": "// C++ program to find a pair with given sum such that// every element of pair is in different rows.#include<bits/stdc++.h>using namespace std; const int MAX = 100; // Function to find pair for given sum in matrix// mat[][] --> given matrix// n --> order of matrix// sum --> given sum for which we need to find pairvoid pairSum(int mat[][MAX], int n, int sum){ // First sort all the rows in ascending order for (int i=0; i<n; i++) sort(mat[i], mat[i]+n); // Select i'th row and find pair for element in i'th // row in j'th row whose summation is equal to given sum for (int i=0; i<n-1; i++) { for (int j=i+1; j<n; j++) { int left = 0, right = n-1; while (left<n && right>=0) { if ((mat[i][left] + mat[j][right]) == sum) { cout << \"(\" << mat[i][left] << \", \"<< mat[j][right] << \"), \"; left++; right--; } else { if ((mat[i][left] + mat[j][right]) < sum) left++; else right--; } } } }} // Driver program to run the caseint main(){ int n = 4, sum = 11; int mat[][MAX] = {{1, 3, 2, 4}, {5, 8, 7, 6}, {9, 10, 13, 11}, {12, 0, 14, 15}}; pairSum(mat, n, sum); return 0;}", "e": 2868, "s": 1381, "text": null }, { "code": "// Java program to find a pair with// given sum such that every element// of pair is in different rows.import java.util.Arrays;class GFG {static final int MAX = 100; // Function to find pair for given sum in// matrix mat[][] --> given matrix// n --> order of matrix// sum --> given sum for which we need to find pairstatic void pairSum(int mat[][], int n, int sum) { // First sort all the rows in ascending order for (int i = 0; i < n; i++) Arrays.sort(mat[i]); // Select i'th row and find pair for element in i'th // row in j'th row whose summation is equal to given sum for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { int left = 0, right = n - 1; while (left < n && right >= 0) { if ((mat[i][left] + mat[j][right]) == sum) { System.out.print(\"(\" + mat[i][left] + \", \" + mat[j][right] + \"), \"); left++; right--; } else { if ((mat[i][left] + mat[j][right]) < sum) left++; else right--; } } } }} // Driver codepublic static void main(String[] args) { int n = 4, sum = 11; int mat[] [] = {{1 , 3, 2, 4}, {5 , 8, 7, 6}, {9 , 10, 13, 11}, {12, 0, 14, 15}}; pairSum(mat, n, sum);}}// This code is contributed by Anant Agarwal.", "e": 4371, "s": 2868, "text": null }, { "code": "# Python 3 program to find a pair with# given sum such that every element of# pair is in different rows.MAX = 100 # Function to find pair for given# sum in matrix mat[][] --> given matrix# n --> order of matrix# sum --> given sum for which we# need to find pairdef pairSum(mat, n, sum): # First sort all the rows # in ascending order for i in range(n): mat[i].sort() # Select i'th row and find pair for # element in i'th row in j'th row # whose summation is equal to given sum for i in range(n - 1): for j in range(i + 1, n): left = 0 right = n - 1 while (left < n and right >= 0): if ((mat[i][left] + mat[j][right]) == sum): print( \"(\", mat[i][left], \", \", mat[j][right], \"), \", end = \" \") left += 1 right -= 1 else: if ((mat[i][left] + mat[j][right]) < sum): left += 1 else: right -= 1 # Driver Codeif __name__ == \"__main__\": n = 4 sum = 11 mat = [[1, 3, 2, 4], [5, 8, 7, 6], [9, 10, 13, 11], [12, 0, 14, 15]] pairSum(mat, n, sum) # This code is contributed# by ChitraNayal", "e": 5740, "s": 4371, "text": null }, { "code": "// C# program to find a pair with// given sum such that every element// of pair is in different rows.using System;using System.Collections.Generic; public class GFG { // Function to find pair for given sum in// matrix mat[][] --> given matrix// n --> order of matrix// sum --> given sum for which we need to find pairstatic void pairSum(int [,]mat, int n, int sum) { // First sort all the rows in ascending order for (int i = 0; i < n; i++) { List<int> l = new List<int>(); for(int j = 0; j<n;j++) { l.Add(mat[i,j]); } l.Sort(); for(int j = 0; j<n;j++) { mat[i,j] = l[j]; } } // Select i'th row and find pair for element in i'th // row in j'th row whose summation is equal to given sum for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { int left = 0, right = n - 1; while (left < n && right >= 0) { if ((mat[i,left] + mat[j,right]) == sum) { Console.Write(\"(\" + mat[i,left] + \", \" + mat[j,right] + \"), \"); left++; right--; } else { if ((mat[i,left] + mat[j,right]) < sum) left++; else right--; } } } }} // Driver codepublic static void Main(string[] args) { int n = 4, sum = 11; int [,]mat = {{1 , 3, 2, 4}, {5 , 8, 7, 6}, {9 , 10, 13, 11}, {12, 0, 14, 15}}; pairSum(mat, n, sum);}} // This code is contributed by rutvik_56.", "e": 7426, "s": 5740, "text": null }, { "code": "<script> // Javascript program to find a pair with// given sum such that every element// of pair is in different rows. let MAX = 100; // Function to find pair for given sum in// matrix mat[][] --> given matrix// n --> order of matrix// sum --> given sum for which we need to find pairfunction pairSum(mat, n, sum) { // First sort all the rows in ascending order for (let i = 0; i < n; i++) mat[i].sort((a, b) => a - b); // Select i'th row and find pair for element in i'th // row in j'th row whose summation is equal to given sum for (let i = 0; i < n - 1; i++) { for (let j = i + 1; j < n; j++) { let left = 0, right = n - 1; while (left < n && right >= 0) { if ((mat[i][left] + mat[j][right]) == sum) { document.write(\"(\" + mat[i][left] + \", \" + mat[j][right] + \"), \"); left++; right--; } else { if ((mat[i][left] + mat[j][right]) < sum) left++; else right--; } } } }} // Driver program let n = 4, sum = 11; let mat = [[1 , 3, 2, 4], [5 , 8, 7, 6], [9 , 10, 13, 11], [12, 0, 14, 15]]; pairSum(mat, n, sum); </script>", "e": 8840, "s": 7426, "text": null }, { "code": null, "e": 8883, "s": 8840, "text": "(3, 8), (4, 7), (1, 10), (2, 9), (11, 0), " }, { "code": null, "e": 8940, "s": 8883, "text": "Time complexity : O(n2logn + n^3) Auxiliary space : O(1)" }, { "code": null, "e": 8961, "s": 8940, "text": "Method 3 (Hashing) " }, { "code": null, "e": 9272, "s": 8961, "text": "Create an empty hash table and store all elements of the matrix in the hash as keys and their locations as values.Traverse the matrix again to check for every element whether its pair exists in the hash table or not. If it exists, then compare row numbers. If row numbers are not the same, then print the pair." }, { "code": null, "e": 9387, "s": 9272, "text": "Create an empty hash table and store all elements of the matrix in the hash as keys and their locations as values." }, { "code": null, "e": 9584, "s": 9387, "text": "Traverse the matrix again to check for every element whether its pair exists in the hash table or not. If it exists, then compare row numbers. If row numbers are not the same, then print the pair." }, { "code": null, "e": 9600, "s": 9584, "text": "Implementation:" }, { "code": null, "e": 9604, "s": 9600, "text": "CPP" }, { "code": null, "e": 9609, "s": 9604, "text": "Java" }, { "code": null, "e": 9617, "s": 9609, "text": "Python3" }, { "code": null, "e": 9620, "s": 9617, "text": "C#" }, { "code": null, "e": 9631, "s": 9620, "text": "Javascript" }, { "code": "// C++ program to find pairs with given sum such// the two elements of pairs are from different rows#include<bits/stdc++.h>using namespace std; const int MAX = 100; // Function to find pair for given sum in matrix// mat[][] --> given matrix// n --> order of matrix// sum --> given sum for which we need to find pairvoid pairSum(int mat[][MAX], int n, int sum){ // Create a hash and store all elements of matrix // as keys, and row as values unordered_map<int, int> hm; // Traverse the matrix to check for every // element whether its pair exists or not. for (int i=0; i<n; i++) { for (int j=0; j<n; j++) { // Look for remaining sum in hash int remSum = sum - mat[i][j]; auto it = hm.find(remSum); // it is an iterator // of unordered_map type // If an element with value equal to remaining sum exists if (it != hm.end()) { // Find row numbers of element with // value equal to remaining sum. int row = hm[remSum]; // If row number of pair is not same as current // row, then print it as part of result. // Second condition is there to make sure that a // pair is printed only once. if (row < i) cout << \"(\" << mat[i][j] << \", \" << remSum << \"), \"; } hm[mat[i][j]] = i; } }} // Driver programint main(){ int n = 4, sum = 11; int mat[][MAX]= {{1, 3, 2, 4}, {5, 8, 7, 6}, {9, 10, 13, 11}, {12, 0, 14, 15}}; pairSum(mat, n, sum); return 0;}", "e": 11378, "s": 9631, "text": null }, { "code": "// Java program to find pairs with given sum such// the two elements of pairs are from different rowsimport java.io.*;import java.util.*;class GFG{ static int MAX = 100; // Function to find pair for given sum in matrix // mat[][] --> given matrix // n --> order of matrix // sum --> given sum for which we need to find pair static void pairSum(int mat[][], int n, int sum) { // Create a hash and store all elements of matrix // as keys, and row and column numbers as values Map<Integer,ArrayList<Integer>> hm = new HashMap<Integer, ArrayList<Integer>>(); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { hm.put(mat[i][j], new ArrayList<Integer>(Arrays.asList(i, j)) ); } } // Traverse the matrix again to check for every // element whether its pair exists or not. for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // Look for remaining sum in hash int remSum = sum - mat[i][j]; // If an element with value equal to remaining sum exists if(hm.containsKey(remSum)) { // Find row and column numbers of element with // value equal to remaining sum. ArrayList<Integer> p = hm.get(remSum); int row = p.get(0), col = p.get(1); // If row number of pair is not same as current // row, then print it as part of result. // Second condition is there to make sure that a // pair is printed only once. if (row != i && row > i) { System.out.print(\"(\" + mat[i][j] + \",\" + mat[row][col] + \"), \"); } } } } } // Driver code public static void main (String[] args) { int n = 4, sum = 11; int[][] mat = {{1, 3, 2, 4}, {5, 8, 7, 6}, {9, 10, 13, 11}, {12, 0, 14, 15}}; pairSum(mat, n, sum); }} // This code is contributed by avanitrachhadiya2155", "e": 13331, "s": 11378, "text": null }, { "code": "# Python3 program to find pairs with given sum such# the two elements of pairs are from different rowsMAX = 100 # Function to find pair for given sum in matrix # mat[][] --> given matrix # n --> order of matrix # sum --> given sum for which we need to find pairdef pairSum(mat, n, sum): # Create a hash and store all elements of matrix # as keys, and row and column numbers as values hm = {} for i in range(n): for j in range(n): hm[mat[i][j]] = [i, j] # Traverse the matrix again to check for every # element whether its pair exists or not. for i in range(n): for j in range(n): # Look for remaining sum in hash remSum = sum - mat[i][j] # If an element with value equal to remaining sum exists if remSum in hm: # Find row and column numbers of element with # value equal to remaining sum. p=hm[remSum] row = p[0] col = p[1] # If row number of pair is not same as current # row, then print it as part of result. # Second condition is there to make sure that a # pair is printed only once. if (row != i and row > i): print(\"(\" , mat[i][j] , \",\" , mat[row][col] , \"), \", end=\"\") # Driver coden = 4sum = 11mat = [[1, 3, 2, 4], [5, 8, 7, 6], [9, 10, 13, 11], [12, 0, 14, 15]]pairSum(mat, n, sum) # This code is contributed by patel2127", "e": 14970, "s": 13331, "text": null }, { "code": "// C# program to find pairs with given sum such// the two elements of pairs are from different rowsusing System;using System.Collections.Generic;public class GFG{ // Function to find pair for given sum in matrix // mat[][] --> given matrix // n --> order of matrix // sum --> given sum for which we need to find pair static void pairSum(int[,] mat, int n, int sum) { // Create a hash and store all elements of matrix // as keys, and row and column numbers as values Dictionary<int,List<int>> hm = new Dictionary<int,List<int>>(); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { hm.Add(mat[i,j],new List<int>(){i,j}); } } // Traverse the matrix again to check for every // element whether its pair exists or not. for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // Look for remaining sum in hash int remSum = sum - mat[i,j]; // If an element with value equal to remaining sum exists if(hm.ContainsKey(remSum)) { // Find row and column numbers of element with // value equal to remaining sum. List<int> p = hm[remSum]; int row = p[0], col = p[1]; // If row number of pair is not same as current // row, then print it as part of result. // Second condition is there to make sure that a // pair is printed only once. if (row != i && row > i) { Console.Write(\"(\" + mat[i, j] + \",\" + mat[row, col] + \"), \"); } } } } } // Driver code static public void Main (){ int n = 4, sum = 11; int[,] mat = {{1, 3, 2, 4}, {5, 8, 7, 6}, {9, 10, 13, 11}, {12, 0, 14, 15}}; pairSum(mat, n, sum); }} // This code is contributed by rag2127", "e": 16816, "s": 14970, "text": null }, { "code": "<script> // JavaScript program to find pairs with given sum such// the two elements of pairs are from different rows let MAX = 100; // Function to find pair for given sum in matrix // mat[][] --> given matrix // n --> order of matrix // sum --> given sum for which we need to find pairfunction pairSum(mat,n,sum){ // Create a hash and store all elements of matrix // as keys, and row and column numbers as values let hm = new Map(); for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { hm.set(mat[i][j], [i, j] ); } } // Traverse the matrix again to check for every // element whether its pair exists or not. for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { // Look for remaining sum in hash let remSum = sum - mat[i][j]; // If an element with value equal to remaining sum exists if(hm.has(remSum)) { // Find row and column numbers of element with // value equal to remaining sum. let p = hm.get(remSum); let row = p[0], col = p[1]; // If row number of pair is not same as current // row, then print it as part of result. // Second condition is there to make sure that a // pair is printed only once. if (row != i && row > i) { document.write(\"(\" + mat[i][j] + \",\" + mat[row][col] + \"), \"); } } } }} // Driver codelet n = 4, sum = 11;let mat = [[1, 3, 2, 4], [5, 8, 7, 6], [9, 10, 13, 11], [12, 0, 14, 15]]; pairSum(mat, n, sum); // This code is contributed by ab2127 </script>", "e": 18520, "s": 16816, "text": null }, { "code": null, "e": 18563, "s": 18520, "text": "(8, 3), (7, 4), (9, 2), (10, 1), (0, 11), " }, { "code": null, "e": 18814, "s": 18563, "text": "One important thing is, when we traverse a matrix, a pair may be printed twice. To make sure that a pair is printed only once, we check if the row number of other elements picked from the hash table is more than the row number of the current element." }, { "code": null, "e": 18920, "s": 18814, "text": "Time Complexity: O(n2) under the assumption that hash table inserts and search operations take O(1) time." }, { "code": null, "e": 19229, "s": 18920, "text": "This article is contributed by Shashank Mishra ( Gullu ). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 19235, "s": 19229, "text": "ukasp" }, { "code": null, "e": 19256, "s": 19235, "text": "avanitrachhadiya2155" }, { "code": null, "e": 19264, "s": 19256, "text": "rag2127" }, { "code": null, "e": 19281, "s": 19264, "text": "avijitmondal1998" }, { "code": null, "e": 19288, "s": 19281, "text": "ab2127" }, { "code": null, "e": 19298, "s": 19288, "text": "patel2127" }, { "code": null, "e": 19310, "s": 19298, "text": "margin01001" }, { "code": null, "e": 19320, "s": 19310, "text": "rutvik_56" }, { "code": null, "e": 19337, "s": 19320, "text": "nishantsingh1308" }, { "code": null, "e": 19350, "s": 19337, "text": "simmytarika5" }, { "code": null, "e": 19367, "s": 19350, "text": "hardikkoriintern" }, { "code": null, "e": 19372, "s": 19367, "text": "Hash" }, { "code": null, "e": 19379, "s": 19372, "text": "Matrix" }, { "code": null, "e": 19384, "s": 19379, "text": "Hash" }, { "code": null, "e": 19391, "s": 19384, "text": "Matrix" }, { "code": null, "e": 19489, "s": 19391, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 19527, "s": 19489, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 19559, "s": 19527, "text": "Longest Consecutive Subsequence" }, { "code": null, "e": 19593, "s": 19559, "text": "Sorting a Map by value in C++ STL" }, { "code": null, "e": 19674, "s": 19593, "text": "Find the smallest window in a string containing all characters of another string" }, { "code": null, "e": 19708, "s": 19674, "text": "Most frequent element in an array" }, { "code": null, "e": 19744, "s": 19708, "text": "Print a given matrix in spiral form" }, { "code": null, "e": 19779, "s": 19744, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 19823, "s": 19779, "text": "Program to find largest element in an array" }, { "code": null, "e": 19854, "s": 19823, "text": "Rat in a Maze | Backtracking-2" } ]
Program to print all palindromes in a given range
23 Jun, 2022 Given a range of numbers, print all palindromes in the given range. For example if the given range is {10, 115}, then output should be {11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111}We can run a loop from min to max and check every number for palindrome. If the number is a palindrome, we can simply print it. Implementation: C++ Java Python3 C# Javascript #include<iostream>using namespace std; // A function to check if n is palindromeint isPalindrome(int n){ // Find reverse of n int rev = 0; for (int i = n; i > 0; i /= 10) rev = rev*10 + i%10; // If n and rev are same, then n is palindrome return (n==rev);} // prints palindrome between min and maxvoid countPal(int min, int max){ for (int i = min; i <= max; i++) if (isPalindrome(i)) cout << i << " ";} // Driver program to test above functionint main(){ countPal(100, 2000); return 0;} // Java Program to print all // palindromes in a given range class GFG{ // A function to check // if n is palindrome static int isPalindrome(int n) { // Find reverse of n int rev = 0; for (int i = n; i > 0; i /= 10) rev = rev * 10 + i % 10; // If n and rev are same, // then n is palindrome return(n == rev) ? 1 : 0; } // prints palindrome between // min and max static void countPal(int min, int max) { for (int i = min; i <= max; i++) if (isPalindrome(i)==1) System.out.print(i + " "); } // Driver Code public static void main(String args[]) { countPal(100, 2000); }} // This code is contributed by Taritra Saha. # Python3 implementation of above idea # A function to check if n is palindromedef isPalindrome(n: int) -> bool: # Find reverse of n rev = 0 i = n while i > 0: rev = rev * 10 + i % 10 i //= 10 # If n and rev are same, # then n is palindrome return (n == rev) # prints palindrome between min and maxdef countPal(minn: int, maxx: int) -> None: for i in range(minn, maxx + 1): if isPalindrome(i): print(i, end = " ") # Driver Codeif __name__ == "__main__": countPal(100, 2000) # This code is contributed by# sanjeev2552 // C# Program to print all // palindromes in a given range using System; class GFG{ // A function to check // if n is palindrome public static int isPalindrome(int n){ // Find reverse of n int rev = 0; for (int i = n; i > 0; i /= 10) { rev = rev * 10 + i % 10; } // If n and rev are same, // then n is palindrome return (n == rev) ? 1 : 0;} // prints palindrome between // min and max public static void countPal(int min, int max){ for (int i = min; i <= max; i++) { if (isPalindrome(i) == 1) { Console.Write(i + " "); } }} // Driver Code public static void Main(string[] args){ countPal(100, 2000);}} // This code is contributed by Shrikant13 <script>// A function to check if n is palindromefunction isPalindrome(n){ // Find reverse of n var rev = 0; for (var i = n; Math.trunc(i) > 0; i /= 10) { rev = ((rev*10) + (Math.trunc(i)%10)); } // If n and rev are same, then n is palindrome return (n==rev);} // prints palindrome between min and maxfunction countPal(min, max){ for (var i = min; i <=max; i++) { if(isPalindrome(i)) document.write(i+" " ); }} // Driver program to test above function countPal(100, 2000);</script> 101 111 121 131 141 151 161 171 181 191 202 212 222 232 242 252 262 272 282 292 303 313 323 333 343 353 363 373 383 393 404 414 424 434 444 454 464 474 484 494 505 515 525 535 545 555 565 575 585 595 606 616 626 636 646 656 666 676 686 696 707 717 727 737 747 757 767 777 787 797 808 818 828 838 848 858 868 878 888 898 909 919 929 939 949 959 969 979 989 999 1001 1111 1221 1331 1441 1551 1661 1771 1881 1991 Time Complexity: Time complexity of function to check if a number N is palindrome or not is O(logN). We are calling this function each time while iterating from min to max. So the time complexity will be O(Dlog(M)). Where, D= max-min M = max Auxiliary Space: O(1) noobhere jit_t shrikanth13 sanjeev2552 akshitsaxenaa09 tusharkhorwal11 hardikkoriintern palindrome Strings Strings palindrome Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Jun, 2022" }, { "code": null, "e": 362, "s": 52, "text": "Given a range of numbers, print all palindromes in the given range. For example if the given range is {10, 115}, then output should be {11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111}We can run a loop from min to max and check every number for palindrome. If the number is a palindrome, we can simply print it. " }, { "code": null, "e": 378, "s": 362, "text": "Implementation:" }, { "code": null, "e": 382, "s": 378, "text": "C++" }, { "code": null, "e": 387, "s": 382, "text": "Java" }, { "code": null, "e": 395, "s": 387, "text": "Python3" }, { "code": null, "e": 398, "s": 395, "text": "C#" }, { "code": null, "e": 409, "s": 398, "text": "Javascript" }, { "code": "#include<iostream>using namespace std; // A function to check if n is palindromeint isPalindrome(int n){ // Find reverse of n int rev = 0; for (int i = n; i > 0; i /= 10) rev = rev*10 + i%10; // If n and rev are same, then n is palindrome return (n==rev);} // prints palindrome between min and maxvoid countPal(int min, int max){ for (int i = min; i <= max; i++) if (isPalindrome(i)) cout << i << \" \";} // Driver program to test above functionint main(){ countPal(100, 2000); return 0;}", "e": 948, "s": 409, "text": null }, { "code": "// Java Program to print all // palindromes in a given range class GFG{ // A function to check // if n is palindrome static int isPalindrome(int n) { // Find reverse of n int rev = 0; for (int i = n; i > 0; i /= 10) rev = rev * 10 + i % 10; // If n and rev are same, // then n is palindrome return(n == rev) ? 1 : 0; } // prints palindrome between // min and max static void countPal(int min, int max) { for (int i = min; i <= max; i++) if (isPalindrome(i)==1) System.out.print(i + \" \"); } // Driver Code public static void main(String args[]) { countPal(100, 2000); }} // This code is contributed by Taritra Saha.", "e": 1743, "s": 948, "text": null }, { "code": "# Python3 implementation of above idea # A function to check if n is palindromedef isPalindrome(n: int) -> bool: # Find reverse of n rev = 0 i = n while i > 0: rev = rev * 10 + i % 10 i //= 10 # If n and rev are same, # then n is palindrome return (n == rev) # prints palindrome between min and maxdef countPal(minn: int, maxx: int) -> None: for i in range(minn, maxx + 1): if isPalindrome(i): print(i, end = \" \") # Driver Codeif __name__ == \"__main__\": countPal(100, 2000) # This code is contributed by# sanjeev2552", "e": 2328, "s": 1743, "text": null }, { "code": "// C# Program to print all // palindromes in a given range using System; class GFG{ // A function to check // if n is palindrome public static int isPalindrome(int n){ // Find reverse of n int rev = 0; for (int i = n; i > 0; i /= 10) { rev = rev * 10 + i % 10; } // If n and rev are same, // then n is palindrome return (n == rev) ? 1 : 0;} // prints palindrome between // min and max public static void countPal(int min, int max){ for (int i = min; i <= max; i++) { if (isPalindrome(i) == 1) { Console.Write(i + \" \"); } }} // Driver Code public static void Main(string[] args){ countPal(100, 2000);}} // This code is contributed by Shrikant13", "e": 3087, "s": 2328, "text": null }, { "code": "<script>// A function to check if n is palindromefunction isPalindrome(n){ // Find reverse of n var rev = 0; for (var i = n; Math.trunc(i) > 0; i /= 10) { rev = ((rev*10) + (Math.trunc(i)%10)); } // If n and rev are same, then n is palindrome return (n==rev);} // prints palindrome between min and maxfunction countPal(min, max){ for (var i = min; i <=max; i++) { if(isPalindrome(i)) document.write(i+\" \" ); }} // Driver program to test above function countPal(100, 2000);</script>", "e": 3655, "s": 3087, "text": null }, { "code": null, "e": 4076, "s": 3655, "text": "101 111 121 131 141 151 161 171 181 191 202 212 222 232 242\n 252 262 272 282 292 303 313 323 333 343 353 363 373 383 393 404 \n 414 424 434 444 454 464 474 484 494 505 515 525 535 545 555 565 \n 575 585 595 606 616 626 636 646 656 666 676 686 696 707 717 727 \n 737 747 757 767 777 787 797 808 818 828 838 848 858 868 878 888\n 898 909 919 929 939 949 959 969 979 989 999 1001 1111 1221 1331 \n 1441 1551 1661 1771 1881 1991 " }, { "code": null, "e": 4093, "s": 4076, "text": "Time Complexity:" }, { "code": null, "e": 4177, "s": 4093, "text": "Time complexity of function to check if a number N is palindrome or not is O(logN)." }, { "code": null, "e": 4249, "s": 4177, "text": "We are calling this function each time while iterating from min to max." }, { "code": null, "e": 4292, "s": 4249, "text": "So the time complexity will be O(Dlog(M))." }, { "code": null, "e": 4299, "s": 4292, "text": "Where," }, { "code": null, "e": 4310, "s": 4299, "text": "D= max-min" }, { "code": null, "e": 4318, "s": 4310, "text": "M = max" }, { "code": null, "e": 4340, "s": 4318, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 4349, "s": 4340, "text": "noobhere" }, { "code": null, "e": 4355, "s": 4349, "text": "jit_t" }, { "code": null, "e": 4367, "s": 4355, "text": "shrikanth13" }, { "code": null, "e": 4379, "s": 4367, "text": "sanjeev2552" }, { "code": null, "e": 4395, "s": 4379, "text": "akshitsaxenaa09" }, { "code": null, "e": 4411, "s": 4395, "text": "tusharkhorwal11" }, { "code": null, "e": 4428, "s": 4411, "text": "hardikkoriintern" }, { "code": null, "e": 4439, "s": 4428, "text": "palindrome" }, { "code": null, "e": 4447, "s": 4439, "text": "Strings" }, { "code": null, "e": 4455, "s": 4447, "text": "Strings" }, { "code": null, "e": 4466, "s": 4455, "text": "palindrome" } ]
Optimal Strategy for a Game | DP-31
08 Jul, 2022 Consider a row of n coins of values v1 . . . vn, where n is even. We play a game against an opponent by alternating turns. In each turn, a player selects either the first or last coin from the row, removes it from the row permanently, and receives the value of the coin. Determine the maximum possible amount of money we can definitely win if we move first.Note: The opponent is as clever as the user. Let us understand the problem with few examples: 5, 3, 7, 10 : The user collects maximum value as 15(10 + 5)8, 15, 3, 7 : The user collects maximum value as 22(7 + 15) 5, 3, 7, 10 : The user collects maximum value as 15(10 + 5) 8, 15, 3, 7 : The user collects maximum value as 22(7 + 15) Does choosing the best at each move gives an optimal solution? No. In the second example, this is how the game can be finished: .......User chooses 8. .......Opponent chooses 15. .......User chooses 7. .......Opponent chooses 3. Total value collected by user is 15(8 + 7).......User chooses 7. .......Opponent chooses 8. .......User chooses 15. .......Opponent chooses 3. Total value collected by user is 22(7 + 15) .......User chooses 8. .......Opponent chooses 15. .......User chooses 7. .......Opponent chooses 3. Total value collected by user is 15(8 + 7) .......User chooses 7. .......Opponent chooses 8. .......User chooses 15. .......Opponent chooses 3. Total value collected by user is 22(7 + 15) So if the user follows the second game state, the maximum value can be collected although the first move is not the best. Approach: As both the players are equally strong, both will try to reduce the possibility of winning of each other. Now let’s see how the opponent can achieve this. There are two choices: The user chooses the ‘ith’ coin with value ‘Vi’: The opponent either chooses (i+1)th coin or jth coin. The opponent intends to choose the coin which leaves the user with minimum value. i.e. The user can collect the value Vi + min(F(i+2, j), F(i+1, j-1) ) where [i+2,j] is the range of array indices available to the user if the opponent chooses Vi+1 and [i+1,j-1] is the range of array indexes available if opponent chooses the jth coin. The user chooses the ‘jth’ coin with value ‘Vj’: The opponent either chooses ‘ith’ coin or ‘(j-1)th’ coin. The opponent intends to choose the coin which leaves the user with minimum value, i.e. the user can collect the value Vj + min(F(i+1, j-1), F(i, j-2) ) where [i,j-2] is the range of array indices available for the user if the opponent picks jth coin and [i+1,j-1] is the range of indices avaiable to the user if the opponent picks up the ith coin. Following is the recursive solution that is based on the above two choices. We take a maximum of two choices. F(i, j) represents the maximum value the user can collect from i'th coin to j'th coin. F(i, j) = Max(Vi + min(F(i+2, j), F(i+1, j-1) ), Vj + min(F(i+1, j-1), F(i, j-2) )) As user wants to maximise the number of coins. Base Cases F(i, j) = Vi If j == i F(i, j) = max(Vi, Vj) If j == i + 1 The recursive top down solution in is shown below C++ Python3 Javascript // C++ code to implement the approach #include <bits/stdc++.h> using namespace std; vector<int> arr;map<vector<int>, int> memo;int n = arr.size(); // recursive top down memoized solutionint solve(int i, int j){ if ((i > j) || (i >= n) || (j < 0)) return 0; vector<int> k{ i, j }; if (memo[k] != 0) return memo[k]; // if the user chooses ith coin, the opponent can choose // from i+1th or jth coin. if he chooses i+1th coin, // user is left with [i+2,j] range. if opp chooses jth // coin, then user is left with [i+1,j-1] range to // choose from. Also opponent tries to choose in such a // way that the user has minimum value left. int option1 = arr[i] + min(solve(i + 2, j), solve(i + 1, j - 1)); // if user chooses jth coin, opponent can choose ith // coin or j-1th coin. if opp chooses ith coin,user can // choose in range [i+1,j-1]. if opp chooses j-1th coin, // user can choose in range [i,j-2]. int option2 = arr[j] + min(solve(i + 1, j - 1), solve(i, j - 2)); // since the user wants to get maximum money memo[k] = max(option1, option2); return memo[k];} int optimalStrategyOfGame(){ memo.clear(); return solve(0, n - 1);} // Driver codeint main(){ arr.push_back(8); arr.push_back(15); arr.push_back(3); arr.push_back(7); n = arr.size(); cout << optimalStrategyOfGame() << endl; arr.clear(); arr.push_back(2); arr.push_back(2); arr.push_back(2); arr.push_back(2); n = arr.size(); cout << optimalStrategyOfGame() << endl; arr.clear(); arr.push_back(20); arr.push_back(30); arr.push_back(2); arr.push_back(2); arr.push_back(2); arr.push_back(10); n = arr.size(); cout << optimalStrategyOfGame() << endl;} // This code is contributed by phasing17 def optimalStrategyOfGame(arr, n): memo = {} # recursive top down memoized solution def solve(i, j): if i > j or i >= n or j < 0: return 0 k = (i, j) if k in memo: return memo[k] # if the user chooses ith coin, the opponent can choose from i+1th or jth coin. # if he chooses i+1th coin, user is left with [i+2,j] range. # if opp chooses jth coin, then user is left with [i+1,j-1] range to choose from. # Also opponent tries to choose # in such a way that the user has minimum value left. option1 = arr[i] + min(solve(i+2, j), solve(i+1, j-1)) # if user chooses jth coin, opponent can choose ith coin or j-1th coin. # if opp chooses ith coin,user can choose in range [i+1,j-1]. # if opp chooses j-1th coin, user can choose in range [i,j-2]. option2 = arr[j] + min(solve(i+1, j-1), solve(i, j-2)) # since the user wants to get maximum money memo[k] = max(option1, option2) return memo[k] return solve(0, n-1) // JavaScript code to implement the approach function optimalStrategyOfGame(arr, n){ let memo = {}; // recursive top down memoized solution function solve(i, j) { if ( (i > j) || (i >= n) || (j < 0)) return 0; let k = (i, j); if (memo.hasOwnProperty(k)) return memo[k]; // if the user chooses ith coin, the opponent can choose from i+1th or jth coin. // if he chooses i+1th coin, user is left with [i+2,j] range. // if opp chooses jth coin, then user is left with [i+1,j-1] range to choose from. // Also opponent tries to choose // in such a way that the user has minimum value left. let option1 = arr[i] + Math.min(solve(i+2, j), solve(i+1, j-1)); // if user chooses jth coin, opponent can choose ith coin or j-1th coin. // if opp chooses ith coin,user can choose in range [i+1,j-1]. // if opp chooses j-1th coin, user can choose in range [i,j-2]. let option2 = arr[j] + Math.min(solve(i+1, j-1), solve(i, j-2)); // since the user wants to get maximum money memo[k] = Math.max(option1, option2); return memo[k]; } return solve(0, n-1);} // Driver codelet arr1 = [ 8, 15, 3, 7 ];let n = arr1.length;console.log(optimalStrategyOfGame(arr1, n)); let arr2 = [ 2, 2, 2, 2 ];n = arr2.length;console.log(optimalStrategyOfGame(arr2, n)); let arr3 = [ 20, 30, 2, 2, 2, 10 ];n = arr3.length;console.log(optimalStrategyOfGame(arr3, n)); // This code is contributed by phasing17 The bottom up approach is shown below. C++ Java Python3 C# PHP Javascript // C++ program to find out// maximum value from a given// sequence of coins#include <bits/stdc++.h>using namespace std; // Returns optimal value possible// that a player can collect from// an array of coins of size n.// Note than n must be evenint optimalStrategyOfGame(int* arr, int n){ // Create a table to store // solutions of subproblems int table[n][n]; // Fill table using above // recursive formula. Note // that the table is filled // in diagonal fashion (similar // to http:// goo.gl/PQqoS), // from diagonal elements to // table[0][n-1] which is the result. for (int gap = 0; gap < n; ++gap) { for (int i = 0, j = gap; j < n; ++i, ++j) { // Here x is value of F(i+2, j), // y is F(i+1, j-1) and // z is F(i, j-2) in above recursive // formula int x = ((i + 2) <= j) ? table[i + 2][j] : 0; int y = ((i + 1) <= (j - 1)) ? table[i + 1][j - 1] : 0; int z = (i <= (j - 2)) ? table[i][j - 2] : 0; table[i][j] = max(arr[i] + min(x, y), arr[j] + min(y, z)); } } return table[0][n - 1];} // Driver program to test above functionint main(){ int arr1[] = { 8, 15, 3, 7 }; int n = sizeof(arr1) / sizeof(arr1[0]); printf("%d\n", optimalStrategyOfGame(arr1, n)); int arr2[] = { 2, 2, 2, 2 }; n = sizeof(arr2) / sizeof(arr2[0]); printf("%d\n", optimalStrategyOfGame(arr2, n)); int arr3[] = { 20, 30, 2, 2, 2, 10 }; n = sizeof(arr3) / sizeof(arr3[0]); printf("%d\n", optimalStrategyOfGame(arr3, n)); return 0;} // Java program to find out maximum// value from a given sequence of coinsimport java.io.*; class GFG { // Returns optimal value possible // that a player can collect from // an array of coins of size n. // Note than n must be even static int optimalStrategyOfGame(int arr[], int n) { // Create a table to store // solutions of subproblems int table[][] = new int[n][n]; int gap, i, j, x, y, z; // Fill table using above recursive formula. // Note that the tableis filled in diagonal // fashion (similar to http:// goo.gl/PQqoS), // from diagonal elements to table[0][n-1] // which is the result. for (gap = 0; gap < n; ++gap) { for (i = 0, j = gap; j < n; ++i, ++j) { // Here x is value of F(i+2, j), // y is F(i+1, j-1) and z is // F(i, j-2) in above recursive formula x = ((i + 2) <= j) ? table[i + 2][j] : 0; y = ((i + 1) <= (j - 1)) ? table[i + 1][j - 1] : 0; z = (i <= (j - 2)) ? table[i][j - 2] : 0; table[i][j] = Math.max(arr[i] + Math.min(x, y), arr[j] + Math.min(y, z)); } } return table[0][n - 1]; } // Driver program public static void main(String[] args) { int arr1[] = { 8, 15, 3, 7 }; int n = arr1.length; System.out.println( "" + optimalStrategyOfGame(arr1, n)); int arr2[] = { 2, 2, 2, 2 }; n = arr2.length; System.out.println( "" + optimalStrategyOfGame(arr2, n)); int arr3[] = { 20, 30, 2, 2, 2, 10 }; n = arr3.length; System.out.println( "" + optimalStrategyOfGame(arr3, n)); }} // This code is contributed by vt_m # Python3 program to find out maximum# value from a given sequence of coins # Returns optimal value possible that# a player can collect from an array# of coins of size n. Note than n# must be even def optimalStrategyOfGame(arr, n): # Create a table to store # solutions of subproblems table = [[0 for i in range(n)] for i in range(n)] # Fill table using above recursive # formula. Note that the table is # filled in diagonal fashion # (similar to http://goo.gl / PQqoS), # from diagonal elements to # table[0][n-1] which is the result. for gap in range(n): for j in range(gap, n): i = j - gap # Here x is value of F(i + 2, j), # y is F(i + 1, j-1) and z is # F(i, j-2) in above recursive # formula x = 0 if((i + 2) <= j): x = table[i + 2][j] y = 0 if((i + 1) <= (j - 1)): y = table[i + 1][j - 1] z = 0 if(i <= (j - 2)): z = table[i][j - 2] table[i][j] = max(arr[i] + min(x, y), arr[j] + min(y, z)) return table[0][n - 1] # Driver Codearr1 = [8, 15, 3, 7]n = len(arr1)print(optimalStrategyOfGame(arr1, n)) arr2 = [2, 2, 2, 2]n = len(arr2)print(optimalStrategyOfGame(arr2, n)) arr3 = [20, 30, 2, 2, 2, 10]n = len(arr3)print(optimalStrategyOfGame(arr3, n)) # This code is contributed# by sahilshelangia // C# program to find out maximum// value from a given sequence of coinsusing System; public class GFG { // Returns optimal value possible that a player // can collect from an array of coins of size n. // Note than n must be even static int optimalStrategyOfGame(int[] arr, int n) { // Create a table to store solutions of subproblems int[, ] table = new int[n, n]; int gap, i, j, x, y, z; // Fill table using above recursive formula. // Note that the tableis filled in diagonal // fashion (similar to http:// goo.gl/PQqoS), // from diagonal elements to table[0][n-1] // which is the result. for (gap = 0; gap < n; ++gap) { for (i = 0, j = gap; j < n; ++i, ++j) { // Here x is value of F(i+2, j), // y is F(i+1, j-1) and z is // F(i, j-2) in above recursive formula x = ((i + 2) <= j) ? table[i + 2, j] : 0; y = ((i + 1) <= (j - 1)) ? table[i + 1, j - 1] : 0; z = (i <= (j - 2)) ? table[i, j - 2] : 0; table[i, j] = Math.Max(arr[i] + Math.Min(x, y), arr[j] + Math.Min(y, z)); } } return table[0, n - 1]; } // Driver program static public void Main() { int[] arr1 = { 8, 15, 3, 7 }; int n = arr1.Length; Console.WriteLine("" + optimalStrategyOfGame(arr1, n)); int[] arr2 = { 2, 2, 2, 2 }; n = arr2.Length; Console.WriteLine("" + optimalStrategyOfGame(arr2, n)); int[] arr3 = { 20, 30, 2, 2, 2, 10 }; n = arr3.Length; Console.WriteLine("" + optimalStrategyOfGame(arr3, n)); }} // This code is contributed by ajit <?php// PHP program to find out maximum value// from a given sequence of coins // Returns optimal value possible that a// player can collect from an array of// coins of size n. Note than n must be evenfunction optimalStrategyOfGame($arr, $n){ // Create a table to store solutions // of subproblems $table = array_fill(0, $n, array_fill(0, $n, 0)); // Fill table using above recursive formula. // Note that the table is filled in diagonal // fashion (similar to http://goo.gl/PQqoS), // from diagonal elements to table[0][n-1] // which is the result. for ($gap = 0; $gap < $n; ++$gap) { for ($i = 0, $j = $gap; $j < $n; ++$i, ++$j) { // Here x is value of F(i+2, j), // y is F(i+1, j-1) and z is F(i, j-2) // in above recursive formula $x = (($i + 2) <= $j) ? $table[$i + 2][$j] : 0; $y = (($i + 1) <= ($j - 1)) ? $table[$i + 1][$j - 1] : 0; $z = ($i <= ($j - 2)) ? $table[$i][$j - 2] : 0; $table[$i][$j] = max($arr[$i] + min($x, $y), $arr[$j] + min($y, $z)); } } return $table[0][$n - 1];} // Driver Code$arr1 = array( 8, 15, 3, 7 );$n = count($arr1);print(optimalStrategyOfGame($arr1, $n) . "\n"); $arr2 = array( 2, 2, 2, 2 );$n = count($arr2);print(optimalStrategyOfGame($arr2, $n) . "\n"); $arr3 = array(20, 30, 2, 2, 2, 10);$n = count($arr3);print(optimalStrategyOfGame($arr3, $n) . "\n"); // This code is contributed by chandan_jnu?> <script> // Javascript program to find out maximum// value from a given sequence of coins // Returns optimal value possible// that a player can collect from// an array of coins of size n.// Note than n must be evenfunction optimalStrategyOfGame(arr, n){ // Create a table to store // solutions of subproblems let table = new Array(n); let gap, i, j, x, y, z; for(let d = 0; d < n; d++) { table[d] = new Array(n); } // Fill table using above recursive formula. // Note that the tableis filled in diagonal // fashion (similar to http:// goo.gl/PQqoS), // from diagonal elements to table[0][n-1] // which is the result. for(gap = 0; gap < n; ++gap) { for(i = 0, j = gap; j < n; ++i, ++j) { // Here x is value of F(i+2, j), // y is F(i+1, j-1) and z is // F(i, j-2) in above recursive formula x = ((i + 2) <= j) ? table[i + 2][j] : 0; y = ((i + 1) <= (j - 1)) ? table[i + 1][j - 1] : 0; z = (i <= (j - 2)) ? table[i][j - 2] : 0; table[i][j] = Math.max( arr[i] + Math.min(x, y), arr[j] + Math.min(y, z)); } } return table[0][n - 1];} // Driver codelet arr1 = [ 8, 15, 3, 7 ];let n = arr1.length;document.write("" + optimalStrategyOfGame(arr1, n) + "</br>"); let arr2 = [ 2, 2, 2, 2 ];n = arr2.length;document.write("" + optimalStrategyOfGame(arr2, n) + "</br>"); let arr3 = [ 20, 30, 2, 2, 2, 10 ];n = arr3.length;document.write("" + optimalStrategyOfGame(arr3, n)); // This code is contributed by divyesh072019 </script> 22 4 42 Complexity Analysis: Time Complexity: O(n2). Use of a nested for loop brings the time complexity to n2. Auxiliary Space: O(n2). As a 2-D table is used for storing states. Note: The above solution can be optimized by using less number of comparisons for every choice. Please refer below. Optimal Strategy for a Game | Set 2 Exercise: Your thoughts on the strategy when the user wishes to only win instead of winning with the maximum value. Like the above problem, the number of coins is even. Can the Greedy approach work quite well and give an optimal solution? Will your answer change if the number of coins is odd? Please see Coin game of two cornersThis article is compiled by Aashish Barnwal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above sahilshelangia jit_t Chandan_Kumar CheshtaKwatra bidibaaz123 divyesh072019 surinderdawra388 danceboyyaya phasing17 Amazon Hike Linkedin Dynamic Programming Game Theory Mathematical Amazon Hike Linkedin Dynamic Programming Mathematical Game Theory Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Subset Sum Problem | DP-25 Longest Palindromic Substring | Set 1 Floyd Warshall Algorithm | DP-16 Coin Change | DP-7 Find if there is a path between two vertices in an undirected graph Minimax Algorithm in Game Theory | Set 1 (Introduction) Minimax Algorithm in Game Theory | Set 3 (Tic-Tac-Toe AI - Finding optimal move) Minimax Algorithm in Game Theory | Set 4 (Alpha-Beta Pruning) Implementation of Tic-Tac-Toe game Combinatorial Game Theory | Set 2 (Game of Nim)
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Jul, 2022" }, { "code": null, "e": 454, "s": 52, "text": "Consider a row of n coins of values v1 . . . vn, where n is even. We play a game against an opponent by alternating turns. In each turn, a player selects either the first or last coin from the row, removes it from the row permanently, and receives the value of the coin. Determine the maximum possible amount of money we can definitely win if we move first.Note: The opponent is as clever as the user." }, { "code": null, "e": 505, "s": 454, "text": "Let us understand the problem with few examples: " }, { "code": null, "e": 624, "s": 505, "text": "5, 3, 7, 10 : The user collects maximum value as 15(10 + 5)8, 15, 3, 7 : The user collects maximum value as 22(7 + 15)" }, { "code": null, "e": 684, "s": 624, "text": "5, 3, 7, 10 : The user collects maximum value as 15(10 + 5)" }, { "code": null, "e": 744, "s": 684, "text": "8, 15, 3, 7 : The user collects maximum value as 22(7 + 15)" }, { "code": null, "e": 872, "s": 744, "text": "Does choosing the best at each move gives an optimal solution? No. In the second example, this is how the game can be finished:" }, { "code": null, "e": 1160, "s": 872, "text": ".......User chooses 8. .......Opponent chooses 15. .......User chooses 7. .......Opponent chooses 3. Total value collected by user is 15(8 + 7).......User chooses 7. .......Opponent chooses 8. .......User chooses 15. .......Opponent chooses 3. Total value collected by user is 22(7 + 15)" }, { "code": null, "e": 1304, "s": 1160, "text": ".......User chooses 8. .......Opponent chooses 15. .......User chooses 7. .......Opponent chooses 3. Total value collected by user is 15(8 + 7)" }, { "code": null, "e": 1449, "s": 1304, "text": ".......User chooses 7. .......Opponent chooses 8. .......User chooses 15. .......Opponent chooses 3. Total value collected by user is 22(7 + 15)" }, { "code": null, "e": 1572, "s": 1449, "text": "So if the user follows the second game state, the maximum value can be collected although the first move is not the best. " }, { "code": null, "e": 1737, "s": 1572, "text": "Approach: As both the players are equally strong, both will try to reduce the possibility of winning of each other. Now let’s see how the opponent can achieve this." }, { "code": null, "e": 1762, "s": 1737, "text": "There are two choices: " }, { "code": null, "e": 2201, "s": 1762, "text": "The user chooses the ‘ith’ coin with value ‘Vi’: The opponent either chooses (i+1)th coin or jth coin. The opponent intends to choose the coin which leaves the user with minimum value. i.e. The user can collect the value Vi + min(F(i+2, j), F(i+1, j-1) ) where [i+2,j] is the range of array indices available to the user if the opponent chooses Vi+1 and [i+1,j-1] is the range of array indexes available if opponent chooses the jth coin. " }, { "code": null, "e": 2657, "s": 2201, "text": "The user chooses the ‘jth’ coin with value ‘Vj’: The opponent either chooses ‘ith’ coin or ‘(j-1)th’ coin. The opponent intends to choose the coin which leaves the user with minimum value, i.e. the user can collect the value Vj + min(F(i+1, j-1), F(i, j-2) ) where [i,j-2] is the range of array indices available for the user if the opponent picks jth coin and [i+1,j-1] is the range of indices avaiable to the user if the opponent picks up the ith coin. " }, { "code": null, "e": 2768, "s": 2657, "text": "Following is the recursive solution that is based on the above two choices. We take a maximum of two choices. " }, { "code": null, "e": 3097, "s": 2768, "text": "F(i, j) represents the maximum value the user\ncan collect from i'th coin to j'th coin.\n\nF(i, j) = Max(Vi + min(F(i+2, j), F(i+1, j-1) ), \n Vj + min(F(i+1, j-1), F(i, j-2) ))\nAs user wants to maximise the number of coins. \n\nBase Cases\n F(i, j) = Vi If j == i\n F(i, j) = max(Vi, Vj) If j == i + 1\n " }, { "code": null, "e": 3147, "s": 3097, "text": "The recursive top down solution in is shown below" }, { "code": null, "e": 3151, "s": 3147, "text": "C++" }, { "code": null, "e": 3159, "s": 3151, "text": "Python3" }, { "code": null, "e": 3170, "s": 3159, "text": "Javascript" }, { "code": "// C++ code to implement the approach #include <bits/stdc++.h> using namespace std; vector<int> arr;map<vector<int>, int> memo;int n = arr.size(); // recursive top down memoized solutionint solve(int i, int j){ if ((i > j) || (i >= n) || (j < 0)) return 0; vector<int> k{ i, j }; if (memo[k] != 0) return memo[k]; // if the user chooses ith coin, the opponent can choose // from i+1th or jth coin. if he chooses i+1th coin, // user is left with [i+2,j] range. if opp chooses jth // coin, then user is left with [i+1,j-1] range to // choose from. Also opponent tries to choose in such a // way that the user has minimum value left. int option1 = arr[i] + min(solve(i + 2, j), solve(i + 1, j - 1)); // if user chooses jth coin, opponent can choose ith // coin or j-1th coin. if opp chooses ith coin,user can // choose in range [i+1,j-1]. if opp chooses j-1th coin, // user can choose in range [i,j-2]. int option2 = arr[j] + min(solve(i + 1, j - 1), solve(i, j - 2)); // since the user wants to get maximum money memo[k] = max(option1, option2); return memo[k];} int optimalStrategyOfGame(){ memo.clear(); return solve(0, n - 1);} // Driver codeint main(){ arr.push_back(8); arr.push_back(15); arr.push_back(3); arr.push_back(7); n = arr.size(); cout << optimalStrategyOfGame() << endl; arr.clear(); arr.push_back(2); arr.push_back(2); arr.push_back(2); arr.push_back(2); n = arr.size(); cout << optimalStrategyOfGame() << endl; arr.clear(); arr.push_back(20); arr.push_back(30); arr.push_back(2); arr.push_back(2); arr.push_back(2); arr.push_back(10); n = arr.size(); cout << optimalStrategyOfGame() << endl;} // This code is contributed by phasing17", "e": 4999, "s": 3170, "text": null }, { "code": "def optimalStrategyOfGame(arr, n): memo = {} # recursive top down memoized solution def solve(i, j): if i > j or i >= n or j < 0: return 0 k = (i, j) if k in memo: return memo[k] # if the user chooses ith coin, the opponent can choose from i+1th or jth coin. # if he chooses i+1th coin, user is left with [i+2,j] range. # if opp chooses jth coin, then user is left with [i+1,j-1] range to choose from. # Also opponent tries to choose # in such a way that the user has minimum value left. option1 = arr[i] + min(solve(i+2, j), solve(i+1, j-1)) # if user chooses jth coin, opponent can choose ith coin or j-1th coin. # if opp chooses ith coin,user can choose in range [i+1,j-1]. # if opp chooses j-1th coin, user can choose in range [i,j-2]. option2 = arr[j] + min(solve(i+1, j-1), solve(i, j-2)) # since the user wants to get maximum money memo[k] = max(option1, option2) return memo[k] return solve(0, n-1)", "e": 6058, "s": 4999, "text": null }, { "code": "// JavaScript code to implement the approach function optimalStrategyOfGame(arr, n){ let memo = {}; // recursive top down memoized solution function solve(i, j) { if ( (i > j) || (i >= n) || (j < 0)) return 0; let k = (i, j); if (memo.hasOwnProperty(k)) return memo[k]; // if the user chooses ith coin, the opponent can choose from i+1th or jth coin. // if he chooses i+1th coin, user is left with [i+2,j] range. // if opp chooses jth coin, then user is left with [i+1,j-1] range to choose from. // Also opponent tries to choose // in such a way that the user has minimum value left. let option1 = arr[i] + Math.min(solve(i+2, j), solve(i+1, j-1)); // if user chooses jth coin, opponent can choose ith coin or j-1th coin. // if opp chooses ith coin,user can choose in range [i+1,j-1]. // if opp chooses j-1th coin, user can choose in range [i,j-2]. let option2 = arr[j] + Math.min(solve(i+1, j-1), solve(i, j-2)); // since the user wants to get maximum money memo[k] = Math.max(option1, option2); return memo[k]; } return solve(0, n-1);} // Driver codelet arr1 = [ 8, 15, 3, 7 ];let n = arr1.length;console.log(optimalStrategyOfGame(arr1, n)); let arr2 = [ 2, 2, 2, 2 ];n = arr2.length;console.log(optimalStrategyOfGame(arr2, n)); let arr3 = [ 20, 30, 2, 2, 2, 10 ];n = arr3.length;console.log(optimalStrategyOfGame(arr3, n)); // This code is contributed by phasing17", "e": 7589, "s": 6058, "text": null }, { "code": null, "e": 7628, "s": 7589, "text": "The bottom up approach is shown below." }, { "code": null, "e": 7632, "s": 7628, "text": "C++" }, { "code": null, "e": 7637, "s": 7632, "text": "Java" }, { "code": null, "e": 7645, "s": 7637, "text": "Python3" }, { "code": null, "e": 7648, "s": 7645, "text": "C#" }, { "code": null, "e": 7652, "s": 7648, "text": "PHP" }, { "code": null, "e": 7663, "s": 7652, "text": "Javascript" }, { "code": "// C++ program to find out// maximum value from a given// sequence of coins#include <bits/stdc++.h>using namespace std; // Returns optimal value possible// that a player can collect from// an array of coins of size n.// Note than n must be evenint optimalStrategyOfGame(int* arr, int n){ // Create a table to store // solutions of subproblems int table[n][n]; // Fill table using above // recursive formula. Note // that the table is filled // in diagonal fashion (similar // to http:// goo.gl/PQqoS), // from diagonal elements to // table[0][n-1] which is the result. for (int gap = 0; gap < n; ++gap) { for (int i = 0, j = gap; j < n; ++i, ++j) { // Here x is value of F(i+2, j), // y is F(i+1, j-1) and // z is F(i, j-2) in above recursive // formula int x = ((i + 2) <= j) ? table[i + 2][j] : 0; int y = ((i + 1) <= (j - 1)) ? table[i + 1][j - 1] : 0; int z = (i <= (j - 2)) ? table[i][j - 2] : 0; table[i][j] = max(arr[i] + min(x, y), arr[j] + min(y, z)); } } return table[0][n - 1];} // Driver program to test above functionint main(){ int arr1[] = { 8, 15, 3, 7 }; int n = sizeof(arr1) / sizeof(arr1[0]); printf(\"%d\\n\", optimalStrategyOfGame(arr1, n)); int arr2[] = { 2, 2, 2, 2 }; n = sizeof(arr2) / sizeof(arr2[0]); printf(\"%d\\n\", optimalStrategyOfGame(arr2, n)); int arr3[] = { 20, 30, 2, 2, 2, 10 }; n = sizeof(arr3) / sizeof(arr3[0]); printf(\"%d\\n\", optimalStrategyOfGame(arr3, n)); return 0;}", "e": 9321, "s": 7663, "text": null }, { "code": "// Java program to find out maximum// value from a given sequence of coinsimport java.io.*; class GFG { // Returns optimal value possible // that a player can collect from // an array of coins of size n. // Note than n must be even static int optimalStrategyOfGame(int arr[], int n) { // Create a table to store // solutions of subproblems int table[][] = new int[n][n]; int gap, i, j, x, y, z; // Fill table using above recursive formula. // Note that the tableis filled in diagonal // fashion (similar to http:// goo.gl/PQqoS), // from diagonal elements to table[0][n-1] // which is the result. for (gap = 0; gap < n; ++gap) { for (i = 0, j = gap; j < n; ++i, ++j) { // Here x is value of F(i+2, j), // y is F(i+1, j-1) and z is // F(i, j-2) in above recursive formula x = ((i + 2) <= j) ? table[i + 2][j] : 0; y = ((i + 1) <= (j - 1)) ? table[i + 1][j - 1] : 0; z = (i <= (j - 2)) ? table[i][j - 2] : 0; table[i][j] = Math.max(arr[i] + Math.min(x, y), arr[j] + Math.min(y, z)); } } return table[0][n - 1]; } // Driver program public static void main(String[] args) { int arr1[] = { 8, 15, 3, 7 }; int n = arr1.length; System.out.println( \"\" + optimalStrategyOfGame(arr1, n)); int arr2[] = { 2, 2, 2, 2 }; n = arr2.length; System.out.println( \"\" + optimalStrategyOfGame(arr2, n)); int arr3[] = { 20, 30, 2, 2, 2, 10 }; n = arr3.length; System.out.println( \"\" + optimalStrategyOfGame(arr3, n)); }} // This code is contributed by vt_m", "e": 11199, "s": 9321, "text": null }, { "code": "# Python3 program to find out maximum# value from a given sequence of coins # Returns optimal value possible that# a player can collect from an array# of coins of size n. Note than n# must be even def optimalStrategyOfGame(arr, n): # Create a table to store # solutions of subproblems table = [[0 for i in range(n)] for i in range(n)] # Fill table using above recursive # formula. Note that the table is # filled in diagonal fashion # (similar to http://goo.gl / PQqoS), # from diagonal elements to # table[0][n-1] which is the result. for gap in range(n): for j in range(gap, n): i = j - gap # Here x is value of F(i + 2, j), # y is F(i + 1, j-1) and z is # F(i, j-2) in above recursive # formula x = 0 if((i + 2) <= j): x = table[i + 2][j] y = 0 if((i + 1) <= (j - 1)): y = table[i + 1][j - 1] z = 0 if(i <= (j - 2)): z = table[i][j - 2] table[i][j] = max(arr[i] + min(x, y), arr[j] + min(y, z)) return table[0][n - 1] # Driver Codearr1 = [8, 15, 3, 7]n = len(arr1)print(optimalStrategyOfGame(arr1, n)) arr2 = [2, 2, 2, 2]n = len(arr2)print(optimalStrategyOfGame(arr2, n)) arr3 = [20, 30, 2, 2, 2, 10]n = len(arr3)print(optimalStrategyOfGame(arr3, n)) # This code is contributed# by sahilshelangia", "e": 12662, "s": 11199, "text": null }, { "code": "// C# program to find out maximum// value from a given sequence of coinsusing System; public class GFG { // Returns optimal value possible that a player // can collect from an array of coins of size n. // Note than n must be even static int optimalStrategyOfGame(int[] arr, int n) { // Create a table to store solutions of subproblems int[, ] table = new int[n, n]; int gap, i, j, x, y, z; // Fill table using above recursive formula. // Note that the tableis filled in diagonal // fashion (similar to http:// goo.gl/PQqoS), // from diagonal elements to table[0][n-1] // which is the result. for (gap = 0; gap < n; ++gap) { for (i = 0, j = gap; j < n; ++i, ++j) { // Here x is value of F(i+2, j), // y is F(i+1, j-1) and z is // F(i, j-2) in above recursive formula x = ((i + 2) <= j) ? table[i + 2, j] : 0; y = ((i + 1) <= (j - 1)) ? table[i + 1, j - 1] : 0; z = (i <= (j - 2)) ? table[i, j - 2] : 0; table[i, j] = Math.Max(arr[i] + Math.Min(x, y), arr[j] + Math.Min(y, z)); } } return table[0, n - 1]; } // Driver program static public void Main() { int[] arr1 = { 8, 15, 3, 7 }; int n = arr1.Length; Console.WriteLine(\"\" + optimalStrategyOfGame(arr1, n)); int[] arr2 = { 2, 2, 2, 2 }; n = arr2.Length; Console.WriteLine(\"\" + optimalStrategyOfGame(arr2, n)); int[] arr3 = { 20, 30, 2, 2, 2, 10 }; n = arr3.Length; Console.WriteLine(\"\" + optimalStrategyOfGame(arr3, n)); }} // This code is contributed by ajit", "e": 14549, "s": 12662, "text": null }, { "code": "<?php// PHP program to find out maximum value// from a given sequence of coins // Returns optimal value possible that a// player can collect from an array of// coins of size n. Note than n must be evenfunction optimalStrategyOfGame($arr, $n){ // Create a table to store solutions // of subproblems $table = array_fill(0, $n, array_fill(0, $n, 0)); // Fill table using above recursive formula. // Note that the table is filled in diagonal // fashion (similar to http://goo.gl/PQqoS), // from diagonal elements to table[0][n-1] // which is the result. for ($gap = 0; $gap < $n; ++$gap) { for ($i = 0, $j = $gap; $j < $n; ++$i, ++$j) { // Here x is value of F(i+2, j), // y is F(i+1, j-1) and z is F(i, j-2) // in above recursive formula $x = (($i + 2) <= $j) ? $table[$i + 2][$j] : 0; $y = (($i + 1) <= ($j - 1)) ? $table[$i + 1][$j - 1] : 0; $z = ($i <= ($j - 2)) ? $table[$i][$j - 2] : 0; $table[$i][$j] = max($arr[$i] + min($x, $y), $arr[$j] + min($y, $z)); } } return $table[0][$n - 1];} // Driver Code$arr1 = array( 8, 15, 3, 7 );$n = count($arr1);print(optimalStrategyOfGame($arr1, $n) . \"\\n\"); $arr2 = array( 2, 2, 2, 2 );$n = count($arr2);print(optimalStrategyOfGame($arr2, $n) . \"\\n\"); $arr3 = array(20, 30, 2, 2, 2, 10);$n = count($arr3);print(optimalStrategyOfGame($arr3, $n) . \"\\n\"); // This code is contributed by chandan_jnu?>", "e": 16114, "s": 14549, "text": null }, { "code": "<script> // Javascript program to find out maximum// value from a given sequence of coins // Returns optimal value possible// that a player can collect from// an array of coins of size n.// Note than n must be evenfunction optimalStrategyOfGame(arr, n){ // Create a table to store // solutions of subproblems let table = new Array(n); let gap, i, j, x, y, z; for(let d = 0; d < n; d++) { table[d] = new Array(n); } // Fill table using above recursive formula. // Note that the tableis filled in diagonal // fashion (similar to http:// goo.gl/PQqoS), // from diagonal elements to table[0][n-1] // which is the result. for(gap = 0; gap < n; ++gap) { for(i = 0, j = gap; j < n; ++i, ++j) { // Here x is value of F(i+2, j), // y is F(i+1, j-1) and z is // F(i, j-2) in above recursive formula x = ((i + 2) <= j) ? table[i + 2][j] : 0; y = ((i + 1) <= (j - 1)) ? table[i + 1][j - 1] : 0; z = (i <= (j - 2)) ? table[i][j - 2] : 0; table[i][j] = Math.max( arr[i] + Math.min(x, y), arr[j] + Math.min(y, z)); } } return table[0][n - 1];} // Driver codelet arr1 = [ 8, 15, 3, 7 ];let n = arr1.length;document.write(\"\" + optimalStrategyOfGame(arr1, n) + \"</br>\"); let arr2 = [ 2, 2, 2, 2 ];n = arr2.length;document.write(\"\" + optimalStrategyOfGame(arr2, n) + \"</br>\"); let arr3 = [ 20, 30, 2, 2, 2, 10 ];n = arr3.length;document.write(\"\" + optimalStrategyOfGame(arr3, n)); // This code is contributed by divyesh072019 </script>", "e": 17780, "s": 16114, "text": null }, { "code": null, "e": 17788, "s": 17780, "text": "22\n4\n42" }, { "code": null, "e": 17810, "s": 17788, "text": "Complexity Analysis: " }, { "code": null, "e": 17893, "s": 17810, "text": "Time Complexity: O(n2). Use of a nested for loop brings the time complexity to n2." }, { "code": null, "e": 17960, "s": 17893, "text": "Auxiliary Space: O(n2). As a 2-D table is used for storing states." }, { "code": null, "e": 18112, "s": 17960, "text": "Note: The above solution can be optimized by using less number of comparisons for every choice. Please refer below. Optimal Strategy for a Game | Set 2" }, { "code": null, "e": 18611, "s": 18112, "text": "Exercise: Your thoughts on the strategy when the user wishes to only win instead of winning with the maximum value. Like the above problem, the number of coins is even. Can the Greedy approach work quite well and give an optimal solution? Will your answer change if the number of coins is odd? Please see Coin game of two cornersThis article is compiled by Aashish Barnwal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 18626, "s": 18611, "text": "sahilshelangia" }, { "code": null, "e": 18632, "s": 18626, "text": "jit_t" }, { "code": null, "e": 18646, "s": 18632, "text": "Chandan_Kumar" }, { "code": null, "e": 18660, "s": 18646, "text": "CheshtaKwatra" }, { "code": null, "e": 18672, "s": 18660, "text": "bidibaaz123" }, { "code": null, "e": 18686, "s": 18672, "text": "divyesh072019" }, { "code": null, "e": 18703, "s": 18686, "text": "surinderdawra388" }, { "code": null, "e": 18716, "s": 18703, "text": "danceboyyaya" }, { "code": null, "e": 18726, "s": 18716, "text": "phasing17" }, { "code": null, "e": 18733, "s": 18726, "text": "Amazon" }, { "code": null, "e": 18738, "s": 18733, "text": "Hike" }, { "code": null, "e": 18747, "s": 18738, "text": "Linkedin" }, { "code": null, "e": 18767, "s": 18747, "text": "Dynamic Programming" }, { "code": null, "e": 18779, "s": 18767, "text": "Game Theory" }, { "code": null, "e": 18792, "s": 18779, "text": "Mathematical" }, { "code": null, "e": 18799, "s": 18792, "text": "Amazon" }, { "code": null, "e": 18804, "s": 18799, "text": "Hike" }, { "code": null, "e": 18813, "s": 18804, "text": "Linkedin" }, { "code": null, "e": 18833, "s": 18813, "text": "Dynamic Programming" }, { "code": null, "e": 18846, "s": 18833, "text": "Mathematical" }, { "code": null, "e": 18858, "s": 18846, "text": "Game Theory" }, { "code": null, "e": 18956, "s": 18858, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 18983, "s": 18956, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 19021, "s": 18983, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 19054, "s": 19021, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 19073, "s": 19054, "text": "Coin Change | DP-7" }, { "code": null, "e": 19141, "s": 19073, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 19197, "s": 19141, "text": "Minimax Algorithm in Game Theory | Set 1 (Introduction)" }, { "code": null, "e": 19278, "s": 19197, "text": "Minimax Algorithm in Game Theory | Set 3 (Tic-Tac-Toe AI - Finding optimal move)" }, { "code": null, "e": 19340, "s": 19278, "text": "Minimax Algorithm in Game Theory | Set 4 (Alpha-Beta Pruning)" }, { "code": null, "e": 19375, "s": 19340, "text": "Implementation of Tic-Tac-Toe game" } ]
Difference between cout and puts() in C++ with Examples
08 Jul, 2020 Standard Output Stream(cout): The C++ cout statement is the instance of the ostream class. It is used to display output on the standard output device which is usually the display screen. The data needed to be displayed on the screen is inserted in the standard output stream (cout) using the insertion operator(<<). For more details prefer to this article. puts(): It can be used for printing a string. It is generally less expensive, and if the string has formatting characters like ‘%’, then printf() would give unexpected results. If string str is a user input string, then use of printf() might cause security issues. For more details prefer to this article. Differences are: Program 1: C++ // C++ program use of puts#include <iostream>#include <stdio.h>using namespace std; // main codeint main(){ puts("Geeksforgeeks"); fflush(stdout); return 0;} Geeksforgeeks Program 2: Below program do not require fflush to flush the output buffer, because cout has it inbuilt. C++ // C++ program use of cout#include <iostream>using namespace std; // main codeint main(){ cout << "Geeksforgeeks" << endl; return 0;} Geeksforgeeks CPP-Functions C++ C++ Programs Difference Between CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Sorting a vector in C++ Polymorphism in C++ Friend class and function in C++ std::string class in C++ Pair in C++ Standard Template Library (STL) Header files in C/C++ and its uses Sorting a Map by value in C++ STL Program to print ASCII Value of a character How to return multiple values from a function in C or C++? Shallow Copy and Deep Copy in C++
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Jul, 2020" }, { "code": null, "e": 385, "s": 28, "text": "Standard Output Stream(cout): The C++ cout statement is the instance of the ostream class. It is used to display output on the standard output device which is usually the display screen. The data needed to be displayed on the screen is inserted in the standard output stream (cout) using the insertion operator(<<). For more details prefer to this article." }, { "code": null, "e": 691, "s": 385, "text": "puts(): It can be used for printing a string. It is generally less expensive, and if the string has formatting characters like ‘%’, then printf() would give unexpected results. If string str is a user input string, then use of printf() might cause security issues. For more details prefer to this article." }, { "code": null, "e": 708, "s": 691, "text": "Differences are:" }, { "code": null, "e": 719, "s": 708, "text": "Program 1:" }, { "code": null, "e": 723, "s": 719, "text": "C++" }, { "code": "// C++ program use of puts#include <iostream>#include <stdio.h>using namespace std; // main codeint main(){ puts(\"Geeksforgeeks\"); fflush(stdout); return 0;}", "e": 891, "s": 723, "text": null }, { "code": null, "e": 906, "s": 891, "text": "Geeksforgeeks\n" }, { "code": null, "e": 1010, "s": 906, "text": "Program 2: Below program do not require fflush to flush the output buffer, because cout has it inbuilt." }, { "code": null, "e": 1014, "s": 1010, "text": "C++" }, { "code": "// C++ program use of cout#include <iostream>using namespace std; // main codeint main(){ cout << \"Geeksforgeeks\" << endl; return 0;}", "e": 1157, "s": 1014, "text": null }, { "code": null, "e": 1172, "s": 1157, "text": "Geeksforgeeks\n" }, { "code": null, "e": 1186, "s": 1172, "text": "CPP-Functions" }, { "code": null, "e": 1190, "s": 1186, "text": "C++" }, { "code": null, "e": 1203, "s": 1190, "text": "C++ Programs" }, { "code": null, "e": 1222, "s": 1203, "text": "Difference Between" }, { "code": null, "e": 1226, "s": 1222, "text": "CPP" }, { "code": null, "e": 1324, "s": 1226, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1348, "s": 1324, "text": "Sorting a vector in C++" }, { "code": null, "e": 1368, "s": 1348, "text": "Polymorphism in C++" }, { "code": null, "e": 1401, "s": 1368, "text": "Friend class and function in C++" }, { "code": null, "e": 1426, "s": 1401, "text": "std::string class in C++" }, { "code": null, "e": 1470, "s": 1426, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 1505, "s": 1470, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 1539, "s": 1505, "text": "Sorting a Map by value in C++ STL" }, { "code": null, "e": 1583, "s": 1539, "text": "Program to print ASCII Value of a character" }, { "code": null, "e": 1642, "s": 1583, "text": "How to return multiple values from a function in C or C++?" } ]
Style Plots using Matplotlib
17 Dec, 2020 Matplotlib is the most popular package or library in Python which is used for data visualization. By using this library we can generate plots and figures, and can easily create raster and vector files without using any other GUIs. With matplotlib, we can style the plots like, an HTML webpage is styled by using CSS styles. We just need to import style package of matplotlib library. There are various built-in styles in style package, and we can also write customized style files and, then, to use those styles all you need to import them and apply on the graphs and plots. In this way, we need not write various lines of code for each plot individually again and again i.e. the code is reusable whenever required. First, we will import the module: from matplotlib import style To list all the available styles: Python3 from matplotlib import style print(plt.style.available) Output: [‘Solarize_Light2’, ‘_classic_test_patch’, ‘bmh’, ‘classic’, ‘dark_background’, ‘fast’, ‘fivethirtyeight’, ‘ggplot’,’grayscale’,’seaborn’,’seaborn-bright’,’seaborn-colorblind’, ‘seaborn-dark’, ‘seaborn-dark-palette’, ‘seaborn-darkgrid’, ‘seaborn-deep’, ‘seaborn-muted’, ‘seaborn-notebook’, ‘seaborn-paper’, ‘seaborn-pastel’, ‘seaborn-poster’,’seaborn-talk’,’seaborn-ticks’,’seaborn-white’,’seaborn-whitegrid’,’tableau-colorblind10′] Above is the list of styles available in package. Syntax: plt.style.use(‘style_name”) Where style_name is the name of the style which we want to use. Approach: Import module. Create data for plot. Use the style want to add in plot. Create a plot. Show the plot. Example 1: Python3 # importing all the necessary packagesimport numpy as npimport matplotlib.pyplot as plt # importing the style packagefrom matplotlib import style # creating an array of data for plotdata = np.random.randn(50) # using the style for the plotplt.style.use('Solarize_Light2') # creating a plotplt.plot(data) # show plotplt.show() Output: Example 2: Python3 # importing all the necessary packagesimport numpy as npimport matplotlib.pyplot as plt # importing the style packagefrom matplotlib import style # creating an array of data for plotdata = np.random.randn(50) # using the style for the plotplt.style.use('dark_background') # creating a plotplt.plot(data) # show plotplt.show() Output: Example 3: Python3 # importing all the necessary packagesimport numpy as npimport matplotlib.pyplot as plt # importing the style packagefrom matplotlib import style # creating an array of data for plotdata = np.random.randn(50) # using the style for the plotplt.style.use('ggplot') # creating plotplt.plot(data, linestyle=":", linewidth=2) # show plotplt.show() Output: Note: If you only want to use a style for a particular plot but don’t want to change the global styling for all the plots, the style package provides a context manager for limiting the area of styling for a particular plot. To style changes for a plot, we can write something like this. Example 4: Python3 # importing all the necessary packagesimport numpy as npimport matplotlib.pyplot as plt # importing the style packagefrom matplotlib import style with plt.style.context('dark_background'): plt.plot(np.sin(np.linspace(0, 2 * np.pi)), 'r-o') plt.show() Output: Picked Python-matplotlib Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Python map() function Adding new column to existing DataFrame in Pandas Python Dictionary How to get column names in Pandas dataframe Different ways to create Pandas Dataframe Taking input in Python Enumerate() in Python Read a file line by line in Python Python String | replace()
[ { "code": null, "e": 52, "s": 24, "text": "\n17 Dec, 2020" }, { "code": null, "e": 437, "s": 52, "text": "Matplotlib is the most popular package or library in Python which is used for data visualization. By using this library we can generate plots and figures, and can easily create raster and vector files without using any other GUIs. With matplotlib, we can style the plots like, an HTML webpage is styled by using CSS styles. We just need to import style package of matplotlib library. " }, { "code": null, "e": 770, "s": 437, "text": "There are various built-in styles in style package, and we can also write customized style files and, then, to use those styles all you need to import them and apply on the graphs and plots. In this way, we need not write various lines of code for each plot individually again and again i.e. the code is reusable whenever required. " }, { "code": null, "e": 804, "s": 770, "text": "First, we will import the module:" }, { "code": null, "e": 833, "s": 804, "text": "from matplotlib import style" }, { "code": null, "e": 867, "s": 833, "text": "To list all the available styles:" }, { "code": null, "e": 875, "s": 867, "text": "Python3" }, { "code": "from matplotlib import style print(plt.style.available)", "e": 932, "s": 875, "text": null }, { "code": null, "e": 940, "s": 932, "text": "Output:" }, { "code": null, "e": 1373, "s": 940, "text": "[‘Solarize_Light2’, ‘_classic_test_patch’, ‘bmh’, ‘classic’, ‘dark_background’, ‘fast’, ‘fivethirtyeight’, ‘ggplot’,’grayscale’,’seaborn’,’seaborn-bright’,’seaborn-colorblind’, ‘seaborn-dark’, ‘seaborn-dark-palette’, ‘seaborn-darkgrid’, ‘seaborn-deep’, ‘seaborn-muted’, ‘seaborn-notebook’, ‘seaborn-paper’, ‘seaborn-pastel’, ‘seaborn-poster’,’seaborn-talk’,’seaborn-ticks’,’seaborn-white’,’seaborn-whitegrid’,’tableau-colorblind10′]" }, { "code": null, "e": 1423, "s": 1373, "text": "Above is the list of styles available in package." }, { "code": null, "e": 1459, "s": 1423, "text": "Syntax: plt.style.use(‘style_name”)" }, { "code": null, "e": 1523, "s": 1459, "text": "Where style_name is the name of the style which we want to use." }, { "code": null, "e": 1533, "s": 1523, "text": "Approach:" }, { "code": null, "e": 1548, "s": 1533, "text": "Import module." }, { "code": null, "e": 1570, "s": 1548, "text": "Create data for plot." }, { "code": null, "e": 1605, "s": 1570, "text": "Use the style want to add in plot." }, { "code": null, "e": 1620, "s": 1605, "text": "Create a plot." }, { "code": null, "e": 1635, "s": 1620, "text": "Show the plot." }, { "code": null, "e": 1646, "s": 1635, "text": "Example 1:" }, { "code": null, "e": 1654, "s": 1646, "text": "Python3" }, { "code": "# importing all the necessary packagesimport numpy as npimport matplotlib.pyplot as plt # importing the style packagefrom matplotlib import style # creating an array of data for plotdata = np.random.randn(50) # using the style for the plotplt.style.use('Solarize_Light2') # creating a plotplt.plot(data) # show plotplt.show()", "e": 1985, "s": 1654, "text": null }, { "code": null, "e": 1993, "s": 1985, "text": "Output:" }, { "code": null, "e": 2004, "s": 1993, "text": "Example 2:" }, { "code": null, "e": 2012, "s": 2004, "text": "Python3" }, { "code": "# importing all the necessary packagesimport numpy as npimport matplotlib.pyplot as plt # importing the style packagefrom matplotlib import style # creating an array of data for plotdata = np.random.randn(50) # using the style for the plotplt.style.use('dark_background') # creating a plotplt.plot(data) # show plotplt.show()", "e": 2343, "s": 2012, "text": null }, { "code": null, "e": 2351, "s": 2343, "text": "Output:" }, { "code": null, "e": 2362, "s": 2351, "text": "Example 3:" }, { "code": null, "e": 2370, "s": 2362, "text": "Python3" }, { "code": "# importing all the necessary packagesimport numpy as npimport matplotlib.pyplot as plt # importing the style packagefrom matplotlib import style # creating an array of data for plotdata = np.random.randn(50) # using the style for the plotplt.style.use('ggplot') # creating plotplt.plot(data, linestyle=\":\", linewidth=2) # show plotplt.show()", "e": 2718, "s": 2370, "text": null }, { "code": null, "e": 2726, "s": 2718, "text": "Output:" }, { "code": null, "e": 3013, "s": 2726, "text": "Note: If you only want to use a style for a particular plot but don’t want to change the global styling for all the plots, the style package provides a context manager for limiting the area of styling for a particular plot. To style changes for a plot, we can write something like this." }, { "code": null, "e": 3024, "s": 3013, "text": "Example 4:" }, { "code": null, "e": 3032, "s": 3024, "text": "Python3" }, { "code": "# importing all the necessary packagesimport numpy as npimport matplotlib.pyplot as plt # importing the style packagefrom matplotlib import style with plt.style.context('dark_background'): plt.plot(np.sin(np.linspace(0, 2 * np.pi)), 'r-o') plt.show()", "e": 3289, "s": 3032, "text": null }, { "code": null, "e": 3297, "s": 3289, "text": "Output:" }, { "code": null, "e": 3304, "s": 3297, "text": "Picked" }, { "code": null, "e": 3322, "s": 3304, "text": "Python-matplotlib" }, { "code": null, "e": 3346, "s": 3322, "text": "Technical Scripter 2020" }, { "code": null, "e": 3353, "s": 3346, "text": "Python" }, { "code": null, "e": 3372, "s": 3353, "text": "Technical Scripter" }, { "code": null, "e": 3470, "s": 3372, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3498, "s": 3470, "text": "Read JSON file using Python" }, { "code": null, "e": 3520, "s": 3498, "text": "Python map() function" }, { "code": null, "e": 3570, "s": 3520, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 3588, "s": 3570, "text": "Python Dictionary" }, { "code": null, "e": 3632, "s": 3588, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 3674, "s": 3632, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3697, "s": 3674, "text": "Taking input in Python" }, { "code": null, "e": 3719, "s": 3697, "text": "Enumerate() in Python" }, { "code": null, "e": 3754, "s": 3719, "text": "Read a file line by line in Python" } ]
Python | Send SMS using Twilio
18 Apr, 2019 As we know Python is a cool scripting language and can be used to write scripts to easify day-to-day task. Also, since python has large community support and lots of module/API available, it makes Python more versatile and popular among users. In this article, we will see how to use Twilio API to send SMS using Python. It will be a very quick and easy guide to doing this very interesting task. Firstly, we need to create an account in Twilio’s official website to get the id and token. This is a paid service, but you will be credited with an initial amount to get you started. Steps to create Twilio account: Head to Twilio’s registration page. Complete the registration by filling in with the required details. From the console(dashboard), copy the ACCOUNT SID and AUTH TOKEN. Install Twilio library using pip. pip install twilio Below is the Python implementation: # importing twiliofrom twilio.rest import Client # Your Account Sid and Auth Token from twilio.com / consoleaccount_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'auth_token = 'your_auth_token' client = Client(account_sid, auth_token) ''' Change the value of 'from' with the number received from Twilio and the value of 'to'with the number in which you want to send message.'''message = client.messages.create( from_='+15017122661', body ='body', to ='+15558675310' ) print(message.sid) In the above code, just replace the values of account_sid and auth_token with the values you receive from Twilio. Also, replace the body with the message which you want to send and bingo! Exercise:Extract emails from your account and forward the subject and receivers mail address as a text message to your mobile phone. You can even filter it by limiting it to forward only important mails. python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n18 Apr, 2019" }, { "code": null, "e": 298, "s": 54, "text": "As we know Python is a cool scripting language and can be used to write scripts to easify day-to-day task. Also, since python has large community support and lots of module/API available, it makes Python more versatile and popular among users." }, { "code": null, "e": 451, "s": 298, "text": "In this article, we will see how to use Twilio API to send SMS using Python. It will be a very quick and easy guide to doing this very interesting task." }, { "code": null, "e": 635, "s": 451, "text": "Firstly, we need to create an account in Twilio’s official website to get the id and token. This is a paid service, but you will be credited with an initial amount to get you started." }, { "code": null, "e": 667, "s": 635, "text": "Steps to create Twilio account:" }, { "code": null, "e": 770, "s": 667, "text": "Head to Twilio’s registration page. Complete the registration by filling in with the required details." }, { "code": null, "e": 836, "s": 770, "text": "From the console(dashboard), copy the ACCOUNT SID and AUTH TOKEN." }, { "code": null, "e": 870, "s": 836, "text": "Install Twilio library using pip." }, { "code": null, "e": 889, "s": 870, "text": "pip install twilio" }, { "code": null, "e": 926, "s": 889, "text": " Below is the Python implementation:" }, { "code": "# importing twiliofrom twilio.rest import Client # Your Account Sid and Auth Token from twilio.com / consoleaccount_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'auth_token = 'your_auth_token' client = Client(account_sid, auth_token) ''' Change the value of 'from' with the number received from Twilio and the value of 'to'with the number in which you want to send message.'''message = client.messages.create( from_='+15017122661', body ='body', to ='+15558675310' ) print(message.sid)", "e": 1524, "s": 926, "text": null }, { "code": null, "e": 1712, "s": 1524, "text": "In the above code, just replace the values of account_sid and auth_token with the values you receive from Twilio. Also, replace the body with the message which you want to send and bingo!" }, { "code": null, "e": 1916, "s": 1712, "text": "Exercise:Extract emails from your account and forward the subject and receivers mail address as a text message to your mobile phone. You can even filter it by limiting it to forward only important mails." }, { "code": null, "e": 1931, "s": 1916, "text": "python-utility" }, { "code": null, "e": 1938, "s": 1931, "text": "Python" } ]
How to download and install Python Latest Version on macOS / Mac OS X
24 Oct, 2019 Python is a widely-used general-purpose, high-level programming language. This article will serve as a complete tutorial on How to download and install Python latest version on macOS / Mac OS X. Like Linux, macOS also comes with Python pre-installed on the system. It might be Python version 2 or some similar outdated version. To update to the latest version, we will use the Homebrew Package manager. It is one of the best and convenient methods to install Python on macOS.To know more about Homebrew Package manager, visit here. Download and install Homebrew Package ManagerIf you don’t have homebrew installed on your system, follow the steps belowOpen the Terminal Application of macOS from Application -> Utilities. Bash terminal will open where you can enter commandsEnter following command in macOS terminal/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" Enter system password if prompted. This will install the Homebrew package Manager on your OS.After you see a message called “Installation Successful”. You are ready to install python version 3 on your macOS. If you don’t have homebrew installed on your system, follow the steps belowOpen the Terminal Application of macOS from Application -> Utilities. Bash terminal will open where you can enter commandsEnter following command in macOS terminal /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" Enter system password if prompted. This will install the Homebrew package Manager on your OS.After you see a message called “Installation Successful”. You are ready to install python version 3 on your macOS. Install Python Latest Version on macOS / macOS XTo install python simple open Terminal app from Application -> Utilitiesand enter following commandbrew install python3After command processing is complete, Python’s version 3 would be installed on your mac.To verify the installation enter following commands in your Terminal apppythonpip3Bingo..!! Python is installed on your computer. You can explore more about python here To install python simple open Terminal app from Application -> Utilitiesand enter following command brew install python3 After command processing is complete, Python’s version 3 would be installed on your mac. To verify the installation enter following commands in your Terminal app python pip3 Bingo..!! Python is installed on your computer. You can explore more about python here python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n24 Oct, 2019" }, { "code": null, "e": 584, "s": 52, "text": "Python is a widely-used general-purpose, high-level programming language. This article will serve as a complete tutorial on How to download and install Python latest version on macOS / Mac OS X. Like Linux, macOS also comes with Python pre-installed on the system. It might be Python version 2 or some similar outdated version. To update to the latest version, we will use the Homebrew Package manager. It is one of the best and convenient methods to install Python on macOS.To know more about Homebrew Package manager, visit here." }, { "code": null, "e": 1174, "s": 584, "text": "Download and install Homebrew Package ManagerIf you don’t have homebrew installed on your system, follow the steps belowOpen the Terminal Application of macOS from Application -> Utilities. Bash terminal will open where you can enter commandsEnter following command in macOS terminal/usr/bin/ruby -e \"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)\"\nEnter system password if prompted. This will install the Homebrew package Manager on your OS.After you see a message called “Installation Successful”. You are ready to install python version 3 on your macOS." }, { "code": null, "e": 1413, "s": 1174, "text": "If you don’t have homebrew installed on your system, follow the steps belowOpen the Terminal Application of macOS from Application -> Utilities. Bash terminal will open where you can enter commandsEnter following command in macOS terminal" }, { "code": null, "e": 1513, "s": 1413, "text": "/usr/bin/ruby -e \"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)\"\n" }, { "code": null, "e": 1721, "s": 1513, "text": "Enter system password if prompted. This will install the Homebrew package Manager on your OS.After you see a message called “Installation Successful”. You are ready to install python version 3 on your macOS." }, { "code": null, "e": 2145, "s": 1721, "text": "Install Python Latest Version on macOS / macOS XTo install python simple open Terminal app from Application -> Utilitiesand enter following commandbrew install python3After command processing is complete, Python’s version 3 would be installed on your mac.To verify the installation enter following commands in your Terminal apppythonpip3Bingo..!! Python is installed on your computer. You can explore more about python here" }, { "code": null, "e": 2245, "s": 2145, "text": "To install python simple open Terminal app from Application -> Utilitiesand enter following command" }, { "code": null, "e": 2266, "s": 2245, "text": "brew install python3" }, { "code": null, "e": 2355, "s": 2266, "text": "After command processing is complete, Python’s version 3 would be installed on your mac." }, { "code": null, "e": 2428, "s": 2355, "text": "To verify the installation enter following commands in your Terminal app" }, { "code": null, "e": 2435, "s": 2428, "text": "python" }, { "code": null, "e": 2440, "s": 2435, "text": "pip3" }, { "code": null, "e": 2527, "s": 2440, "text": "Bingo..!! Python is installed on your computer. You can explore more about python here" }, { "code": null, "e": 2542, "s": 2527, "text": "python-utility" }, { "code": null, "e": 2549, "s": 2542, "text": "Python" } ]
How to find specific words in an array with JavaScript?
To find specific words in an array, you can use includes(). We have the following array − var sentence = ["My Name is John Smith. My Favourite Subject is JavaScript. I live in US. I like Hockey"]; Now, the following is an array having the words we need to search in the above “sentence” array − var keywords = ["John", "AUS", "JavaScript", "Hockey"]; Following is the code − var keywords = ["John", "AUS", "JavaScript", "Hockey"]; var sentence = ["My Name is John Smith. My Favourite Subject is JavaScript. I live in US. I like Hockey"]; const matched = []; for (var index = 0; index < sentence.length; index++) { for (var outerIndex = 0; outerIndex < keywords.length; outerIndex++) { if (sentence[index].includes(keywords[outerIndex])) { matched.push(keywords[outerIndex]); } } } console.log("The matched keywords are=="); console.log(matched); To run the above program, you need to use the following command − node fileName.js. Here, my file name is demo226.js. The output is as follows − PS C:\Users\Amit\JavaScript-code> node demo226.js The matched keywords are== [ 'John', 'JavaScript', 'Hockey' ]
[ { "code": null, "e": 1152, "s": 1062, "text": "To find specific words in an array, you can use includes(). We have the following array −" }, { "code": null, "e": 1259, "s": 1152, "text": "var sentence = [\"My Name is John Smith. My Favourite Subject is JavaScript. I live in US. I like Hockey\"];" }, { "code": null, "e": 1357, "s": 1259, "text": "Now, the following is an array having the words we need to search in the above “sentence” array −" }, { "code": null, "e": 1413, "s": 1357, "text": "var keywords = [\"John\", \"AUS\", \"JavaScript\", \"Hockey\"];" }, { "code": null, "e": 1437, "s": 1413, "text": "Following is the code −" }, { "code": null, "e": 1935, "s": 1437, "text": "var keywords = [\"John\", \"AUS\", \"JavaScript\", \"Hockey\"];\nvar sentence = [\"My Name is John Smith. My Favourite Subject is JavaScript. I live in US. I like Hockey\"];\nconst matched = [];\nfor (var index = 0; index < sentence.length; index++) {\n for (var outerIndex = 0; outerIndex < keywords.length; outerIndex++) {\n if (sentence[index].includes(keywords[outerIndex])) {\n matched.push(keywords[outerIndex]);\n }\n }\n}\nconsole.log(\"The matched keywords are==\");\nconsole.log(matched);" }, { "code": null, "e": 2001, "s": 1935, "text": "To run the above program, you need to use the following command −" }, { "code": null, "e": 2019, "s": 2001, "text": "node fileName.js." }, { "code": null, "e": 2053, "s": 2019, "text": "Here, my file name is demo226.js." }, { "code": null, "e": 2080, "s": 2053, "text": "The output is as follows −" }, { "code": null, "e": 2192, "s": 2080, "text": "PS C:\\Users\\Amit\\JavaScript-code> node demo226.js\nThe matched keywords are==\n[ 'John', 'JavaScript', 'Hockey' ]" } ]
Leaf at same level | Practice | GeeksforGeeks
Given a Binary Tree, check if all leaves are at same level or not. Example 1: Input: 1 / \ 2 3 Output: 1 Explanation: Leaves 2 and 3 are at same level. Example 2: Input: 10 / \ 20 30 / \ 10 15 Output: 0 Explanation: Leaves 10, 15 and 30 are not at same level. Your Task: You dont need to read input or print anything. Complete the function check() which takes root node as input parameter and returns true/false depending on whether all the leaf nodes are at the same level or not. Expected Time Complexity: O(N) Expected Auxiliary Space: O(height of tree) Constraints: 1 ≤ N ≤ 10^3 0 sikandarburnwal140820 hours ago Can anyone explain what is the problem in this code or what optimization it needed because it doesn't pass 8 conditions out of 1033 test cases: bool check(Node *root) { if(root==nullptr) return true; map<int,Node*> mp; queue<pair<Node*,int>> q; q.push({root,0}); while(q.empty()==false) { auto u=q.front(); q.pop(); Node*curr=u.first; int hd=u.second; mp[hd]=curr; if(curr->left!=nullptr) q.push({curr->left,hd+1}); if(curr->right!=nullptr) q.push({curr->right,hd+1}); } int level=-1; for(auto u: mp) { if(u.second->left==nullptr && u.second->right==nullptr) { if(level==-1) { level=u.first; } if(u.first!=level) return false; } } return true; } 0 xzqtor3 days ago why I'm getting TLE, I think it is 0(N). Can anyone help me on this.... class Solution: def check(self, root): li=[] self.helper(root,0,li) return li[-1] def helper(self, root, l, li): if len(li)>1: return if root is None: return if root.left is None and root.right is None: if len(li)==0: li.append(l) else: if li[-1]!=l: li.append(False) self.helper(root.left, l+1, li) self.helper(root.right, l+1,li) 0 tirtha19025685 days ago class Solution { boolean check(Node root) { if(root == null) return true; ArrayList<Integer>list = new ArrayList<>(); Queue<Node>q = new LinkedList<>(); q.add(root); int level = 0; while(!q.isEmpty()){ int n = q.size(); while(n-- >0){ Node curr = q.poll(); if(curr.left == null && curr.right == null){ list.add(level); } if(curr.left != null){ q.add(curr.left); } if(curr.right!=null){ q.add(curr.right); } } // Incrementing level level++; } // check if all the levels are same int temp = list.get(0); for(int i=0;i<list.size();i++){ if(list.get(i) != temp){ return false; } } return true; } } 0 adityakapoorr0561 week ago class Solution{ public: /*You are required to complete this method*/ int height=-1; bool ans; void rec(Node *root,int level) { if(!root||!ans)return ; if(!root->left&&!root->right){ if(height==-1)height=level; else if(height!=level)ans=false; return ; } rec(root->left,level+1); rec(root->right,level+1); } bool check(Node *root) { ans=true; rec(root,0); return ans; //Your code here } }; 0 keshavkjha19992 weeks ago Simple and Easy C++ bool check(Node *root){ //Your code here bool isSameLevel = true; int level = 0; queue<pair<Node*, int>> q; q.push(make_pair(root, 0)); while(!q.empty()){ auto itr = q.front(); q.pop(); Node *currentNode = itr.first; if(level!=0 && itr.second!=level){ return false; } else if(level==0){ if(!currentNode->left&&!currentNode->right){ level = itr.second; } } if(currentNode->left){ q.push(make_pair(currentNode->left, itr.second+1)); } if(currentNode->right){ q.push(make_pair(currentNode->right, itr.second+1)); } } return isSameLevel; } 0 amarrajsmart1972 weeks ago C++ Solution :-Using Recursion. int height(Node *root) { if(!root) { return -1; } return 1+max(height(root->left),height(root->right)); } bool check(Node *root) { //Your code here if(!root) { return 1; } int l=height(root->left); int r=height(root->right); if(l!=-1&&r!=-1) return l==r&&check(root->left)&&check(root->right); else if(l!=-1) return r==-1&&check(root->left); else return l==-1&&check(root->right); } +1 sachinnnnnn2 weeks ago public: /*You are required to complete this method*/ bool check(Node *root) { queue<Node*>q; q.push(root); int res=0; while(!q.empty()){ int cnt=q.size(); for(int i=0;i<cnt;i++){ Node* curr=q.front(); q.pop(); if(curr->left==NULL && curr->right==NULL) res++; if(curr->left) q.push(curr->left); if(curr->right) q.push(curr->right); } if(res==cnt) return true; } return false; } +1 hrithikraina20013 weeks ago Total time taken: 0.3/1.6 C++ SOLUTION bool check(Node *root) { if(root==NULL) { return 0; } int level=0; queue<Node *>q; q.push(root); set<int>x; while(!q.empty()) { int n= q.size(); while(n--) { Node *temp= q.front(); q.pop(); if(temp->left==NULL && temp->right==NULL) { x.insert(level); } if(temp->left) { q.push(temp->left); } if(temp->right) { q.push(temp->right); } } level++; } if(x.size()>1) { return 0; } return 1; //Your code here } +1 himanshu0719cse193 weeks ago void helper(Node root,HashSet<Integer>set,int level) { if(root==null) { return; } if(root.left==null&&root.right==null) { set.add(level); } helper(root.left,set,level+1); helper(root.right,set,level+1); } boolean check(Node root) { HashSet<Integer>set=new HashSet<>(); helper(root,set,0); return set.size()==1?true:false; } 0 ahmadsahil261 month ago // JAVA Solution class Solution{ int level = -1; boolean solve(Node root,int l){ if(root==null) return true; if(root.left==null&&root.right==null) if(level==-1) level = l; else if(level!=l) return false; boolean left = solve(root.left,l+1); if(left==false) return false; boolean right = solve(root.right,l+1); return right; } boolean check(Node root) {// Your code here return solve(root,0); }} We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 305, "s": 238, "text": "Given a Binary Tree, check if all leaves are at same level or not." }, { "code": null, "e": 316, "s": 305, "text": "Example 1:" }, { "code": null, "e": 433, "s": 316, "text": "Input: \n 1\n / \\\n 2 3\n\nOutput: 1\n\nExplanation: \nLeaves 2 and 3 are at same level.\n\n" }, { "code": null, "e": 444, "s": 433, "text": "Example 2:" }, { "code": null, "e": 605, "s": 444, "text": "Input:\n 10\n / \\\n 20 30\n / \\ \n 10 15\n\nOutput: 0\n\nExplanation:\nLeaves 10, 15 and 30 are not at same level." }, { "code": null, "e": 832, "s": 605, "text": "\nYour Task: \nYou dont need to read input or print anything. Complete the function check() which takes root node as input parameter and returns true/false depending on whether all the leaf nodes are at the same level or not.\n " }, { "code": null, "e": 909, "s": 832, "text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(height of tree)\n " }, { "code": null, "e": 935, "s": 909, "text": "Constraints:\n1 ≤ N ≤ 10^3" }, { "code": null, "e": 937, "s": 935, "text": "0" }, { "code": null, "e": 969, "s": 937, "text": "sikandarburnwal140820 hours ago" }, { "code": null, "e": 1113, "s": 969, "text": "Can anyone explain what is the problem in this code or what optimization it needed because it doesn't pass 8 conditions out of 1033 test cases:" }, { "code": null, "e": 1868, "s": 1115, "text": "bool check(Node *root) { if(root==nullptr) return true; map<int,Node*> mp; queue<pair<Node*,int>> q; q.push({root,0}); while(q.empty()==false) { auto u=q.front(); q.pop(); Node*curr=u.first; int hd=u.second; mp[hd]=curr; if(curr->left!=nullptr) q.push({curr->left,hd+1}); if(curr->right!=nullptr) q.push({curr->right,hd+1}); } int level=-1; for(auto u: mp) { if(u.second->left==nullptr && u.second->right==nullptr) { if(level==-1) { level=u.first; } if(u.first!=level) return false; } } return true; }" }, { "code": null, "e": 1870, "s": 1868, "text": "0" }, { "code": null, "e": 1887, "s": 1870, "text": "xzqtor3 days ago" }, { "code": null, "e": 1959, "s": 1887, "text": "why I'm getting TLE, I think it is 0(N). Can anyone help me on this...." }, { "code": null, "e": 2447, "s": 1963, "text": "class Solution: def check(self, root): li=[] self.helper(root,0,li) return li[-1] def helper(self, root, l, li): if len(li)>1: return if root is None: return if root.left is None and root.right is None: if len(li)==0: li.append(l) else: if li[-1]!=l: li.append(False) self.helper(root.left, l+1, li) self.helper(root.right, l+1,li)" }, { "code": null, "e": 2449, "s": 2447, "text": "0" }, { "code": null, "e": 2473, "s": 2449, "text": "tirtha19025685 days ago" }, { "code": null, "e": 3310, "s": 2473, "text": "class Solution\n{\n boolean check(Node root)\n {\n \n if(root == null) return true;\n ArrayList<Integer>list = new ArrayList<>();\n Queue<Node>q = new LinkedList<>();\n q.add(root);\n int level = 0;\n while(!q.isEmpty()){\n int n = q.size();\n \n while(n-- >0){\n Node curr = q.poll();\n \n if(curr.left == null && curr.right == null){\n list.add(level);\n }\n if(curr.left != null){\n q.add(curr.left);\n }\n if(curr.right!=null){\n q.add(curr.right);\n }\n }\n \n // Incrementing level \n level++;\n \n }\n \n // check if all the levels are same\n int temp = list.get(0);\n for(int i=0;i<list.size();i++){\n if(list.get(i) != temp){\n return false;\n }\n }\n \n return true;\n \n }\n}\n" }, { "code": null, "e": 3312, "s": 3310, "text": "0" }, { "code": null, "e": 3339, "s": 3312, "text": "adityakapoorr0561 week ago" }, { "code": null, "e": 3875, "s": 3339, "text": "\nclass Solution{\n public:\n /*You are required to complete this method*/\n int height=-1;\n bool ans;\n void rec(Node *root,int level)\n {\n if(!root||!ans)return ;\n if(!root->left&&!root->right){\n if(height==-1)height=level;\n else if(height!=level)ans=false;\n return ;\n }\n rec(root->left,level+1);\n rec(root->right,level+1);\n }\n bool check(Node *root)\n {\n ans=true;\n rec(root,0);\n return ans;\n //Your code here\n }\n};" }, { "code": null, "e": 3877, "s": 3875, "text": "0" }, { "code": null, "e": 3903, "s": 3877, "text": "keshavkjha19992 weeks ago" }, { "code": null, "e": 3923, "s": 3903, "text": "Simple and Easy C++" }, { "code": null, "e": 4747, "s": 3923, "text": "bool check(Node *root){\n //Your code here\n bool isSameLevel = true;\n int level = 0;\n queue<pair<Node*, int>> q;\n q.push(make_pair(root, 0));\n while(!q.empty()){\n auto itr = q.front();\n q.pop();\n Node *currentNode = itr.first;\n if(level!=0 && itr.second!=level){\n return false;\n } else if(level==0){\n if(!currentNode->left&&!currentNode->right){\n level = itr.second;\n }\n }\n if(currentNode->left){\n q.push(make_pair(currentNode->left, itr.second+1));\n }\n if(currentNode->right){\n q.push(make_pair(currentNode->right, itr.second+1));\n }\n }\n return isSameLevel;\n }" }, { "code": null, "e": 4749, "s": 4747, "text": "0" }, { "code": null, "e": 4776, "s": 4749, "text": "amarrajsmart1972 weeks ago" }, { "code": null, "e": 4809, "s": 4776, "text": " C++ Solution :-Using Recursion." }, { "code": null, "e": 5312, "s": 4809, "text": "int height(Node *root) { if(!root) { return -1; } return 1+max(height(root->left),height(root->right)); } bool check(Node *root) { //Your code here if(!root) { return 1; } int l=height(root->left); int r=height(root->right); if(l!=-1&&r!=-1) return l==r&&check(root->left)&&check(root->right); else if(l!=-1) return r==-1&&check(root->left); else return l==-1&&check(root->right); }" }, { "code": null, "e": 5315, "s": 5312, "text": "+1" }, { "code": null, "e": 5338, "s": 5315, "text": "sachinnnnnn2 weeks ago" }, { "code": null, "e": 5869, "s": 5338, "text": "public: /*You are required to complete this method*/ bool check(Node *root) { queue<Node*>q; q.push(root); int res=0; while(!q.empty()){ int cnt=q.size(); for(int i=0;i<cnt;i++){ Node* curr=q.front(); q.pop(); if(curr->left==NULL && curr->right==NULL) res++; if(curr->left) q.push(curr->left); if(curr->right) q.push(curr->right); } if(res==cnt) return true; } return false; }" }, { "code": null, "e": 5872, "s": 5869, "text": "+1" }, { "code": null, "e": 5900, "s": 5872, "text": "hrithikraina20013 weeks ago" }, { "code": null, "e": 5940, "s": 5900, "text": " Total time taken: 0.3/1.6 C++ SOLUTION" }, { "code": null, "e": 6821, "s": 5940, "text": " bool check(Node *root)\n { \n if(root==NULL)\n {\n return 0;\n }\n int level=0;\n queue<Node *>q;\n \n q.push(root);\n \n set<int>x;\n while(!q.empty())\n {\n int n= q.size();\n while(n--)\n {\n Node *temp= q.front();\n q.pop();\n if(temp->left==NULL && temp->right==NULL)\n {\n x.insert(level);\n }\n if(temp->left)\n {\n q.push(temp->left);\n }\n if(temp->right)\n {\n q.push(temp->right);\n }\n \n }\n level++;\n \n }\n if(x.size()>1)\n {\n return 0;\n }\n \n return 1;" }, { "code": null, "e": 6855, "s": 6830, "text": " //Your code here" }, { "code": null, "e": 6861, "s": 6855, "text": " }" }, { "code": null, "e": 6864, "s": 6861, "text": "+1" }, { "code": null, "e": 6893, "s": 6864, "text": "himanshu0719cse193 weeks ago" }, { "code": null, "e": 7313, "s": 6893, "text": "void helper(Node root,HashSet<Integer>set,int level) { if(root==null) { return; } if(root.left==null&&root.right==null) { set.add(level); } helper(root.left,set,level+1); helper(root.right,set,level+1); } boolean check(Node root) { HashSet<Integer>set=new HashSet<>(); helper(root,set,0); return set.size()==1?true:false; }" }, { "code": null, "e": 7315, "s": 7313, "text": "0" }, { "code": null, "e": 7339, "s": 7315, "text": "ahmadsahil261 month ago" }, { "code": null, "e": 7358, "s": 7341, "text": "// JAVA Solution" }, { "code": null, "e": 7931, "s": 7360, "text": "class Solution{ int level = -1; boolean solve(Node root,int l){ if(root==null) return true; if(root.left==null&&root.right==null) if(level==-1) level = l; else if(level!=l) return false; boolean left = solve(root.left,l+1); if(left==false) return false; boolean right = solve(root.right,l+1); return right; } boolean check(Node root) {// Your code here return solve(root,0); }} " }, { "code": null, "e": 8077, "s": 7931, "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": 8113, "s": 8077, "text": " Login to access your submissions. " }, { "code": null, "e": 8123, "s": 8113, "text": "\nProblem\n" }, { "code": null, "e": 8133, "s": 8123, "text": "\nContest\n" }, { "code": null, "e": 8196, "s": 8133, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 8344, "s": 8196, "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": 8552, "s": 8344, "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": 8658, "s": 8552, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
5 Cross-Validation Techniques You Need To Create Models That People Trust | Towards Data Science
I'll be honest. These days I rarely cross-validate. Maybe it is because of the sheer size of the datasets I've been dealing with. Call me lazy, stupid, or even pretentious blank for writing an article on something I am not even using. No matter what, one thing is for sure — I won't stop preaching the importance of cross-validation until I am blue in the face. What?! Are you confused? That's great — let's get started! Until I start selling the related merchandise, I gotta advertise the main idea. Here it goes. Let's imagine a world where you don't know what a CV procedure is. In that crazy world, you obviously split your data into a single train and test sets. The model learns from the training data, and you test its performance by predicting on the so-called unseen data that is your test set. If you are not satisfied with the score, you tune the heck out of your model using the same sets until GridSearch (or Optuna) cries out "enough!". Here are two of the many ways this process can go horribly wrong: The sets don't represent the whole population well. As an extreme example, out of rows with three categories (a, b, c), all a and b categories may end up in the training set while all cs are hanging out in the test set. Or a numeric variable is split so that values to the left and right of some threshold are not distributed well among the train and sets. Or a situation close to that where the new distributions of the variables in both sets are so different than the originals that the model learns from incorrect information.You leak knowledge about the test set into the model during hyperparameter tuning. After the search is done, the framework spits out the parameters that work best for that specific test set. Since I am using the word specific, you should already start thinking about overfitting. Because that's what happens if you keep testing on the same set repeatedly — the searching framework just gives you the result that makes you happy for that specific test set. The sets don't represent the whole population well. As an extreme example, out of rows with three categories (a, b, c), all a and b categories may end up in the training set while all cs are hanging out in the test set. Or a numeric variable is split so that values to the left and right of some threshold are not distributed well among the train and sets. Or a situation close to that where the new distributions of the variables in both sets are so different than the originals that the model learns from incorrect information. You leak knowledge about the test set into the model during hyperparameter tuning. After the search is done, the framework spits out the parameters that work best for that specific test set. Since I am using the word specific, you should already start thinking about overfitting. Because that's what happens if you keep testing on the same set repeatedly — the searching framework just gives you the result that makes you happy for that specific test set. So, if we get back to the world where CV is loved and extensively used by engineers worldwide, all these problems are solved. Here is the magic of CV, as shown in the Sklearn user guide: The above is an example of a 5-fold cross-validation process, which takes five iterations to finish. A new model is trained on four folds in each iteration and tested on the last holdout fold. This way, a model is trained and tested on all of the data without wasting any. Next, the averaged scores are reported with their standard deviations as a confidence interval. Only then can you truly judge your model's performance with its chosen parameters because the average score you got will represent the model's true potential to effectively learn from the data and predict accurately on unseen samples. Now, let's start discussing the many ways you can perform the CV procedure. The simplest one is KFold as seen in the above image. It is implemented with the same name in Sklearn. Here, we will write a quick function that visualizes the split indices of the CV splitter: Now, let's pass a KFold splitter with seven splits to this function: This is how a vanilla KFold looks like. Another version is shuffling the data before a split is performed. This further minimizes the risk of overfitting by breaking the original order of the samples: As you can see, the indices of the validation samples are chosen in a shuffled manner. Even so, the overall number of samples is still one-seventh of the whole data because we are doing a 7-fold CV. KFold is the most commonly used CV splitter. It is easy to understand and deadly effective. However, depending on the characteristics of your datasets, sometimes you need to be pickier over what CV procedure to use. So, let's discuss the alternatives. Another version of KFold designed explicitly for classification problems is StratifiedKFold. In classification, the target distribution must be preserved even after the data is split into multiple sets. More specifically, a binary target with 30 to 70 class ratios should still hold the same ratios in both the training and test sets. The rule is broken in vanilla KFold because it doesn't care about class ratios or shuffles the data before splitting. As a solution, we use another splitter class in Sklearn — StratifiedKFold: It looks the same as KFold, but now class ratios are preserved across all folds and iterations. Sometimes, the data you have is so limited that you can't even afford to divide it into train and test sets. In that case, you can perform a CV where you set aside only a few rows of data in each iteration. This is known as LeavePOut CV, where p is the parameter you choose to specify the number of rows in each holdout set. The most extreme case is the LeaveOneOut splitter where you only use a single row as a test set, and the number of iterations equals the number of rows in the full data. If building 100 models for a small 100-row dataset seems like it is bordering on crazy, I am right there with you. Even for higher numbers of p, the number of iterations grows exponentially as your dataset size increases. Just imagine how many models will be built when p is five and your data has just 50 rows (hint - use the permutations formula). So, you rarely see this one in practice, but it comes up enough times that Sklearn implements these procedures as separate classes: from sklearn.model_selection import LeaveOneOut, LeavePOut How about we don't do CV at all and just repeat the train/test split process multiple times? Well, that's another way you can flirt with the idea of cross-validation and yet still not do it. By logic, generating multiple train/test sets using different random seeds should resemble a robust CV process if done for enough iterations. That's why there is a splitter that performs this process in Sklearn: The advantage of ShuffleSplit is that you have complete control over the sizes of the train and sets in each fold. The size of the sets doesn't have to be inversely proportionate to the number of splits. However, contrary to other splitters, there is no guarantee that random splits will generate different folds in each iteration. So, use this class with caution. By the way, there is also a stratified version of ShuffleSplit for classification: Finally, we have the special case of time series data where the ordering of samples matters. We can't use any of the traditional CV classes because they would lead to a disaster. There is a high chance you would be training on the future samples and predicting the past ones. To solve this, Sklearn offers yet another splitter — TimeSeriesSplit where it ensures that the above does not happen: Nice and neat! So far, we have been dealing with IID (independent and identically distributed) data. In other words, the process that generated the data does not have a memory of the past samples. However, there are cases where your data is not IID — that some groups of samples are dependent on each other. For example, in the Google Brain Ventilator Pressure competition on Kaggle, the participants should work with non-IID data. The data records thousands of breaths (in, out) that an artificial lung takes and records the air pressure for each breath at some millisecond intervals. As a result, the data contains about 80 rows for each breath taken, making those rows dependent. Here, traditional CV splitters won't work as expected because there is a definite chance that a split might occur "right in the middle of a breath." Here is another example from the Sklearn user guide: Such a grouping of data is domain specific. An example would be when there is medical data collected from multiple patients, with multiple samples taken from each patient. And such data is likely to be dependent on the individual group. In our example, the patient id for each sample will be its group identifier. It also states the solution right after that: In this case we would like to know if a model trained on a particular set of groups generalizes well to the unseen groups. To measure this, we need to ensure that all the samples in the validation fold come from groups that are not represented at all in the paired training fold. Then, Sklearn lists five different classes that can work with grouped data. If you grasped the ideas from the previous sections and understood what non-IID data is, you won't have trouble working with them: GroupKFoldStratifiedGroupKFoldLeaveOneGroupOutLeavePGroupsOutGroupShuffleSplit GroupKFold StratifiedGroupKFold LeaveOneGroupOut LeavePGroupsOut GroupShuffleSplit Each of these splitters has a groups argument where you should pass the column the group ids are stored. This tells the classes how to differentiate between each group. Finally, the dust settles, and we are here. One question I probably left unanswered is, "Should you always use cross-validation?". The answer is a tentative yes. When your dataset is sufficiently large, any random split will probably resemble the original data well in both sets. In that case, a CV is not a strict requirement. However, statisticians and folks much more experienced than me on StackExchange say that you should perform at least 2 or 3-fold cross-validation no matter the data size. You just can never be too cautious.
[ { "code": null, "e": 534, "s": 172, "text": "I'll be honest. These days I rarely cross-validate. Maybe it is because of the sheer size of the datasets I've been dealing with. Call me lazy, stupid, or even pretentious blank for writing an article on something I am not even using. No matter what, one thing is for sure — I won't stop preaching the importance of cross-validation until I am blue in the face." }, { "code": null, "e": 593, "s": 534, "text": "What?! Are you confused? That's great — let's get started!" }, { "code": null, "e": 687, "s": 593, "text": "Until I start selling the related merchandise, I gotta advertise the main idea. Here it goes." }, { "code": null, "e": 1123, "s": 687, "text": "Let's imagine a world where you don't know what a CV procedure is. In that crazy world, you obviously split your data into a single train and test sets. The model learns from the training data, and you test its performance by predicting on the so-called unseen data that is your test set. If you are not satisfied with the score, you tune the heck out of your model using the same sets until GridSearch (or Optuna) cries out \"enough!\"." }, { "code": null, "e": 1189, "s": 1123, "text": "Here are two of the many ways this process can go horribly wrong:" }, { "code": null, "e": 2174, "s": 1189, "text": "The sets don't represent the whole population well. As an extreme example, out of rows with three categories (a, b, c), all a and b categories may end up in the training set while all cs are hanging out in the test set. Or a numeric variable is split so that values to the left and right of some threshold are not distributed well among the train and sets. Or a situation close to that where the new distributions of the variables in both sets are so different than the originals that the model learns from incorrect information.You leak knowledge about the test set into the model during hyperparameter tuning. After the search is done, the framework spits out the parameters that work best for that specific test set. Since I am using the word specific, you should already start thinking about overfitting. Because that's what happens if you keep testing on the same set repeatedly — the searching framework just gives you the result that makes you happy for that specific test set." }, { "code": null, "e": 2704, "s": 2174, "text": "The sets don't represent the whole population well. As an extreme example, out of rows with three categories (a, b, c), all a and b categories may end up in the training set while all cs are hanging out in the test set. Or a numeric variable is split so that values to the left and right of some threshold are not distributed well among the train and sets. Or a situation close to that where the new distributions of the variables in both sets are so different than the originals that the model learns from incorrect information." }, { "code": null, "e": 3160, "s": 2704, "text": "You leak knowledge about the test set into the model during hyperparameter tuning. After the search is done, the framework spits out the parameters that work best for that specific test set. Since I am using the word specific, you should already start thinking about overfitting. Because that's what happens if you keep testing on the same set repeatedly — the searching framework just gives you the result that makes you happy for that specific test set." }, { "code": null, "e": 3347, "s": 3160, "text": "So, if we get back to the world where CV is loved and extensively used by engineers worldwide, all these problems are solved. Here is the magic of CV, as shown in the Sklearn user guide:" }, { "code": null, "e": 3620, "s": 3347, "text": "The above is an example of a 5-fold cross-validation process, which takes five iterations to finish. A new model is trained on four folds in each iteration and tested on the last holdout fold. This way, a model is trained and tested on all of the data without wasting any." }, { "code": null, "e": 3951, "s": 3620, "text": "Next, the averaged scores are reported with their standard deviations as a confidence interval. Only then can you truly judge your model's performance with its chosen parameters because the average score you got will represent the model's true potential to effectively learn from the data and predict accurately on unseen samples." }, { "code": null, "e": 4221, "s": 3951, "text": "Now, let's start discussing the many ways you can perform the CV procedure. The simplest one is KFold as seen in the above image. It is implemented with the same name in Sklearn. Here, we will write a quick function that visualizes the split indices of the CV splitter:" }, { "code": null, "e": 4290, "s": 4221, "text": "Now, let's pass a KFold splitter with seven splits to this function:" }, { "code": null, "e": 4330, "s": 4290, "text": "This is how a vanilla KFold looks like." }, { "code": null, "e": 4491, "s": 4330, "text": "Another version is shuffling the data before a split is performed. This further minimizes the risk of overfitting by breaking the original order of the samples:" }, { "code": null, "e": 4690, "s": 4491, "text": "As you can see, the indices of the validation samples are chosen in a shuffled manner. Even so, the overall number of samples is still one-seventh of the whole data because we are doing a 7-fold CV." }, { "code": null, "e": 4942, "s": 4690, "text": "KFold is the most commonly used CV splitter. It is easy to understand and deadly effective. However, depending on the characteristics of your datasets, sometimes you need to be pickier over what CV procedure to use. So, let's discuss the alternatives." }, { "code": null, "e": 5035, "s": 4942, "text": "Another version of KFold designed explicitly for classification problems is StratifiedKFold." }, { "code": null, "e": 5277, "s": 5035, "text": "In classification, the target distribution must be preserved even after the data is split into multiple sets. More specifically, a binary target with 30 to 70 class ratios should still hold the same ratios in both the training and test sets." }, { "code": null, "e": 5470, "s": 5277, "text": "The rule is broken in vanilla KFold because it doesn't care about class ratios or shuffles the data before splitting. As a solution, we use another splitter class in Sklearn — StratifiedKFold:" }, { "code": null, "e": 5566, "s": 5470, "text": "It looks the same as KFold, but now class ratios are preserved across all folds and iterations." }, { "code": null, "e": 5891, "s": 5566, "text": "Sometimes, the data you have is so limited that you can't even afford to divide it into train and test sets. In that case, you can perform a CV where you set aside only a few rows of data in each iteration. This is known as LeavePOut CV, where p is the parameter you choose to specify the number of rows in each holdout set." }, { "code": null, "e": 6176, "s": 5891, "text": "The most extreme case is the LeaveOneOut splitter where you only use a single row as a test set, and the number of iterations equals the number of rows in the full data. If building 100 models for a small 100-row dataset seems like it is bordering on crazy, I am right there with you." }, { "code": null, "e": 6411, "s": 6176, "text": "Even for higher numbers of p, the number of iterations grows exponentially as your dataset size increases. Just imagine how many models will be built when p is five and your data has just 50 rows (hint - use the permutations formula)." }, { "code": null, "e": 6543, "s": 6411, "text": "So, you rarely see this one in practice, but it comes up enough times that Sklearn implements these procedures as separate classes:" }, { "code": null, "e": 6602, "s": 6543, "text": "from sklearn.model_selection import LeaveOneOut, LeavePOut" }, { "code": null, "e": 6793, "s": 6602, "text": "How about we don't do CV at all and just repeat the train/test split process multiple times? Well, that's another way you can flirt with the idea of cross-validation and yet still not do it." }, { "code": null, "e": 7005, "s": 6793, "text": "By logic, generating multiple train/test sets using different random seeds should resemble a robust CV process if done for enough iterations. That's why there is a splitter that performs this process in Sklearn:" }, { "code": null, "e": 7209, "s": 7005, "text": "The advantage of ShuffleSplit is that you have complete control over the sizes of the train and sets in each fold. The size of the sets doesn't have to be inversely proportionate to the number of splits." }, { "code": null, "e": 7370, "s": 7209, "text": "However, contrary to other splitters, there is no guarantee that random splits will generate different folds in each iteration. So, use this class with caution." }, { "code": null, "e": 7453, "s": 7370, "text": "By the way, there is also a stratified version of ShuffleSplit for classification:" }, { "code": null, "e": 7546, "s": 7453, "text": "Finally, we have the special case of time series data where the ordering of samples matters." }, { "code": null, "e": 7729, "s": 7546, "text": "We can't use any of the traditional CV classes because they would lead to a disaster. There is a high chance you would be training on the future samples and predicting the past ones." }, { "code": null, "e": 7847, "s": 7729, "text": "To solve this, Sklearn offers yet another splitter — TimeSeriesSplit where it ensures that the above does not happen:" }, { "code": null, "e": 7862, "s": 7847, "text": "Nice and neat!" }, { "code": null, "e": 8044, "s": 7862, "text": "So far, we have been dealing with IID (independent and identically distributed) data. In other words, the process that generated the data does not have a memory of the past samples." }, { "code": null, "e": 8279, "s": 8044, "text": "However, there are cases where your data is not IID — that some groups of samples are dependent on each other. For example, in the Google Brain Ventilator Pressure competition on Kaggle, the participants should work with non-IID data." }, { "code": null, "e": 8530, "s": 8279, "text": "The data records thousands of breaths (in, out) that an artificial lung takes and records the air pressure for each breath at some millisecond intervals. As a result, the data contains about 80 rows for each breath taken, making those rows dependent." }, { "code": null, "e": 8732, "s": 8530, "text": "Here, traditional CV splitters won't work as expected because there is a definite chance that a split might occur \"right in the middle of a breath.\" Here is another example from the Sklearn user guide:" }, { "code": null, "e": 9046, "s": 8732, "text": "Such a grouping of data is domain specific. An example would be when there is medical data collected from multiple patients, with multiple samples taken from each patient. And such data is likely to be dependent on the individual group. In our example, the patient id for each sample will be its group identifier." }, { "code": null, "e": 9092, "s": 9046, "text": "It also states the solution right after that:" }, { "code": null, "e": 9372, "s": 9092, "text": "In this case we would like to know if a model trained on a particular set of groups generalizes well to the unseen groups. To measure this, we need to ensure that all the samples in the validation fold come from groups that are not represented at all in the paired training fold." }, { "code": null, "e": 9579, "s": 9372, "text": "Then, Sklearn lists five different classes that can work with grouped data. If you grasped the ideas from the previous sections and understood what non-IID data is, you won't have trouble working with them:" }, { "code": null, "e": 9658, "s": 9579, "text": "GroupKFoldStratifiedGroupKFoldLeaveOneGroupOutLeavePGroupsOutGroupShuffleSplit" }, { "code": null, "e": 9669, "s": 9658, "text": "GroupKFold" }, { "code": null, "e": 9690, "s": 9669, "text": "StratifiedGroupKFold" }, { "code": null, "e": 9707, "s": 9690, "text": "LeaveOneGroupOut" }, { "code": null, "e": 9723, "s": 9707, "text": "LeavePGroupsOut" }, { "code": null, "e": 9741, "s": 9723, "text": "GroupShuffleSplit" }, { "code": null, "e": 9910, "s": 9741, "text": "Each of these splitters has a groups argument where you should pass the column the group ids are stored. This tells the classes how to differentiate between each group." }, { "code": null, "e": 9954, "s": 9910, "text": "Finally, the dust settles, and we are here." }, { "code": null, "e": 10238, "s": 9954, "text": "One question I probably left unanswered is, \"Should you always use cross-validation?\". The answer is a tentative yes. When your dataset is sufficiently large, any random split will probably resemble the original data well in both sets. In that case, a CV is not a strict requirement." } ]
How to remove blank (undefined) elements from JavaScript array - JavaScript
Suppose we have an array of literals like this − const arr = [4, 6, , 45, 3, 345, , 56, 6]; We are required to write a JavaScript function that takes in one such array and remove all the undefined elements from the array in place. We are only required to remove the undefined and empty values and not all the falsy values. Use a for loop to iterate over the array and Array.prototype.splice() to remove undefined elements in place. Following is the code − const arr = [4, 6, , 45, 3, 345, , 56, 6] const eliminateUndefined = arr => { for(let i = 0; i < arr.length; ){ if(typeof arr[i] !== 'undefined'){ i++; continue; }; arr.splice(i, 1); }; }; eliminateUndefined(arr); console.log(arr); This will produce the following output in console − [ 4, 6, 45, 3, 345, 56, 6 ]
[ { "code": null, "e": 1111, "s": 1062, "text": "Suppose we have an array of literals like this −" }, { "code": null, "e": 1154, "s": 1111, "text": "const arr = [4, 6, , 45, 3, 345, , 56, 6];" }, { "code": null, "e": 1385, "s": 1154, "text": "We are required to write a JavaScript function that takes in one such array and remove all the undefined elements from the array in place. We are only required to remove the undefined and empty values and not all the falsy values." }, { "code": null, "e": 1494, "s": 1385, "text": "Use a for loop to iterate over the array and Array.prototype.splice() to remove undefined elements in place." }, { "code": null, "e": 1518, "s": 1494, "text": "Following is the code −" }, { "code": null, "e": 1792, "s": 1518, "text": "const arr = [4, 6, , 45, 3, 345, , 56, 6]\nconst eliminateUndefined = arr => {\n for(let i = 0; i < arr.length; ){\n if(typeof arr[i] !== 'undefined'){\n i++;\n continue;\n };\n arr.splice(i, 1);\n };\n};\neliminateUndefined(arr);\nconsole.log(arr);" }, { "code": null, "e": 1844, "s": 1792, "text": "This will produce the following output in console −" }, { "code": null, "e": 1878, "s": 1844, "text": "[\n 4, 6, 45, 3,\n 345, 56, 6\n]" } ]
C++ Program to Check the Connectivity of Undirected Graph Using DFS
To check connectivity of a graph, we will try to traverse all nodes using any traversal algorithm. After completing the traversal, if there is any node, which is not visited, then the graph is not connected. For the undirected graph, we will select one node and traverse from it. In this case the traversal algorithm is recursive DFS traversal. Input − Adjacency matrix of a graph Output − The Graph is connected. Input − The start node u and the visited node to mark which node is visited. Output: Traverse all connected vertices. Begin mark u as visited for all vertex v, if it is adjacent with u, do if v is not visited, then traverse(v, visited) done End Input − The graph. Output − True if the graph is connected. Begin define visited array for all vertices u in the graph, do make all nodes unvisited traverse(u, visited) if any unvisited node is still remaining, then return false done return true End Live Demo #include<iostream> #define NODE 5 using namespace std; int graph[NODE][NODE] = {{0, 1, 1, 0, 0}, {1, 0, 1, 1, 0}, {1, 1, 0, 1, 1}, {0, 1, 1, 0, 1}, {0, 0, 1, 1, 0}}; void traverse(int u, bool visited[]) { visited[u] = true; //mark v as visited for(int v = 0; v<NODE; v++) { if(graph[u][v]) { if(!visited[v]) traverse(v, visited); } } } bool isConnected() { bool *vis = new bool[NODE]; //for all vertex u as start point, check whether all nodes are visible or not for(int u; u < NODE; u++) { for(int i = 0; i<NODE; i++) vis[i] = false; //initialize as no node is visited traverse(u, vis); for(int i = 0; i<NODE; i++) { if(!vis[i]) //if there is a node, not visited by traversal, graph is not connected return false; } } return true; } int main() { if(isConnected()) cout << "The Graph is connected."; else cout << "The Graph is not connected."; } The Graph is connected.
[ { "code": null, "e": 1270, "s": 1062, "text": "To check connectivity of a graph, we will try to traverse all nodes using any traversal algorithm. After completing the traversal, if there is any node, which is not visited, then the graph is not connected." }, { "code": null, "e": 1342, "s": 1270, "text": "For the undirected graph, we will select one node and traverse from it." }, { "code": null, "e": 1407, "s": 1342, "text": "In this case the traversal algorithm is recursive DFS traversal." }, { "code": null, "e": 1443, "s": 1407, "text": "Input − Adjacency matrix of a graph" }, { "code": null, "e": 1476, "s": 1443, "text": "Output − The Graph is connected." }, { "code": null, "e": 1553, "s": 1476, "text": "Input − The start node u and the visited node to mark which node is visited." }, { "code": null, "e": 1594, "s": 1553, "text": "Output: Traverse all connected vertices." }, { "code": null, "e": 1745, "s": 1594, "text": "Begin\n mark u as visited\n for all vertex v, if it is adjacent with u, do\n if v is not visited, then\n traverse(v, visited)\n done\nEnd" }, { "code": null, "e": 1764, "s": 1745, "text": "Input − The graph." }, { "code": null, "e": 1805, "s": 1764, "text": "Output − True if the graph is connected." }, { "code": null, "e": 2052, "s": 1805, "text": "Begin\n define visited array\n for all vertices u in the graph, do\n make all nodes unvisited\n traverse(u, visited)\n if any unvisited node is still remaining, then\n return false\n done\n return true\nEnd" }, { "code": null, "e": 2063, "s": 2052, "text": " Live Demo" }, { "code": null, "e": 3041, "s": 2063, "text": "#include<iostream>\n#define NODE 5\nusing namespace std;\nint graph[NODE][NODE] = {{0, 1, 1, 0, 0},\n{1, 0, 1, 1, 0},\n{1, 1, 0, 1, 1},\n{0, 1, 1, 0, 1},\n{0, 0, 1, 1, 0}};\nvoid traverse(int u, bool visited[]) {\n visited[u] = true; //mark v as visited\n for(int v = 0; v<NODE; v++) {\n if(graph[u][v]) {\n if(!visited[v])\n traverse(v, visited);\n }\n }\n}\nbool isConnected() {\n bool *vis = new bool[NODE];\n //for all vertex u as start point, check whether all nodes are visible or not\n for(int u; u < NODE; u++) {\n for(int i = 0; i<NODE; i++)\n vis[i] = false; //initialize as no node is visited\n traverse(u, vis);\n for(int i = 0; i<NODE; i++) {\n if(!vis[i]) //if there is a node, not visited by traversal, graph is not connected\n return false;\n }\n }\n return true;\n}\nint main() {\n if(isConnected())\n cout << \"The Graph is connected.\";\n else\n cout << \"The Graph is not connected.\";\n}" }, { "code": null, "e": 3065, "s": 3041, "text": "The Graph is connected." } ]
LCM of factorial and its neighbors - GeeksforGeeks
01 Apr, 2021 Given a number, we need to find LCM of the factorial of the numbers and its neighbors. If the number is N, we need to find LCM of (N-1)!, N! and (N+1)!.Here N is always greater than or equal too 1Examples : Input : N = 5 Output : 720 Explanation Here the given number is 5, its neighbors are 4 and 6. The factorial of these three numbers are 24, 120, and 720.so the LCM of 24, 120, 720 is 720. Input : N = 3 Output : 24 Explanation Here the given number is 3, its Neighbors are 2 and 4.the factorial of these three numbers are 2, 6, and 24. So the LCM of 2, 6 and 24 is 24. Method 1(Simple). We first calculate the factorial of number and and the factorial of its neighbor then find the LCM of these factorials numbers.Method 2(Efficient) We can see that the LCM of (N-1)!, N! and (N+1)! is always (N-1)! * N! * (N+1)! this can be written as (N-1)! * N*(N-1)! * (N+1)*N*(N-1)! so the LCM become (N-1)! * N * (N+1) which is (N+1)!Example N = 5 We need to find the LCM of 4!, 5!and 6! LCM of 4!, 5!and 6! = 4! * 5! * 6! = 4! * 5*4! * 6*5*4! = 6*5*4! = 720 So we can say that LCM of the factorial of three consecutive numbers is always the factorial of the largest number.in this case (N+1)!. C++ Java Python3 C# PHP Javascript // CPP program to calculate the LCM of N!// and its neighbor (N-1)! and (N+1)!#include <bits/stdc++.h>using namespace std; // function to calculate the factorialunsigned int factorial(unsigned int n){ if (n == 0) return 1; return n * factorial(n - 1);} int LCMOfNeighbourFact(int n){ // returning the factorial of the // largest number in the given three // consecutive numbers return factorial(n + 1);} // Driver codeint main(){ int N = 5; cout << LCMOfNeighbourFact(N) << "\n"; return 0;} // Java program to calculate the LCM of N!// and its neighbor (N-1)! and (N+1)!import java.io.*; class GFG { // function to calculate the factorial static int factorial(int n) { if (n == 0) return 1; return n * factorial(n - 1); } static int LCMOfNeighbourFact(int n) { // returning the factorial of the // largest number in the given three // consecutive numbers return factorial(n + 1); } // Driver code public static void main(String args[]) { int N = 5; System.out.println(LCMOfNeighbourFact(N)); }} /*This code is contributed by Nikita Tiwari.*/ # Python3 program to calculate the LCM of N!# and its neighbor (N-1)! and (N+1)! # Function to calculate the factorialdef factorial(n): if (n == 0): return 1 return n * factorial(n - 1) def LCMOfNeighbourFact(n): # returning the factorial of the # largest number in the given three # consecutive numbers return factorial(n + 1) # Driver codeN = 5print(LCMOfNeighbourFact(N)) # This code is contributed by Anant Agarwal. // Program to calculate the LCM// of N! and its neighbor (N-1)!// and (N+1)!using System; class GFG{// function to calculate the factorialstatic int factorial(int n) { if (n == 0) return 1; return n * factorial(n - 1);} static int LCMOfNeighbourFact(int n) { // returning the factorial of the // largest number in the given three // consecutive numbers return factorial(n + 1);} // Driver codepublic static void Main(){ int N = 5; Console.WriteLine(LCMOfNeighbourFact(N));}} // This code is contributed by Anant Agarwal. <?php// PHP program to calculate// the LCM of N! and its neighbor// (N-1)! and (N+1)! // function to calculate// the factorialfunction factorial($n){ if ($n == 0) return 1; return $n * factorial($n - 1);} function LCMOfNeighbourFact($n){ // returning the factorial // of the largest number in // the given three // consecutive numbers return factorial($n + 1);} // Driver code$N = 5;echo(LCMOfNeighbourFact($N)); // This code is contributed by Ajit.?> <script>// javascript program to calculate the LCM of N!// and its neighbor (N-1)! and (N+1)! // function to calculate the factorial function factorial(n) { if (n == 0) return 1; return n * factorial(n - 1); } function LCMOfNeighbourFact(n) { // returning the factorial of the // largest number in the given three // consecutive numbers return factorial(n + 1); } // Driver code var N = 5; document.write(LCMOfNeighbourFact(N)); // This code is contributed by aashish1995</script> 720 jit_t Akanksha_Rai aashish1995 GCD-LCM Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Program to find sum of elements in a given array Modulo Operator (%) in C/C++ with Examples The Knight's tour problem | Backtracking-1 Algorithm to solve Rubik's Cube Merge two sorted arrays Find minimum number of coins that make a given value Operators in C / C++ Prime Numbers Program for factorial of a number Minimum number of jumps to reach end
[ { "code": null, "e": 24437, "s": 24409, "text": "\n01 Apr, 2021" }, { "code": null, "e": 24646, "s": 24437, "text": "Given a number, we need to find LCM of the factorial of the numbers and its neighbors. If the number is N, we need to find LCM of (N-1)!, N! and (N+1)!.Here N is always greater than or equal too 1Examples : " }, { "code": null, "e": 25023, "s": 24646, "text": "Input : N = 5 \nOutput : 720\nExplanation\nHere the given number is 5, its neighbors \nare 4 and 6. The factorial of these three \nnumbers are 24, 120, and 720.so the LCM\nof 24, 120, 720 is 720.\n \nInput : N = 3 \nOutput : 24\nExplanation\nHere the given number is 3, its Neighbors\nare 2 and 4.the factorial of these three \nnumbers are 2, 6, and 24. So the LCM of \n2, 6 and 24 is 24." }, { "code": null, "e": 25643, "s": 25025, "text": "Method 1(Simple). We first calculate the factorial of number and and the factorial of its neighbor then find the LCM of these factorials numbers.Method 2(Efficient) We can see that the LCM of (N-1)!, N! and (N+1)! is always (N-1)! * N! * (N+1)! this can be written as (N-1)! * N*(N-1)! * (N+1)*N*(N-1)! so the LCM become (N-1)! * N * (N+1) which is (N+1)!Example N = 5 We need to find the LCM of 4!, 5!and 6! LCM of 4!, 5!and 6! = 4! * 5! * 6! = 4! * 5*4! * 6*5*4! = 6*5*4! = 720 So we can say that LCM of the factorial of three consecutive numbers is always the factorial of the largest number.in this case (N+1)!. " }, { "code": null, "e": 25647, "s": 25643, "text": "C++" }, { "code": null, "e": 25652, "s": 25647, "text": "Java" }, { "code": null, "e": 25660, "s": 25652, "text": "Python3" }, { "code": null, "e": 25663, "s": 25660, "text": "C#" }, { "code": null, "e": 25667, "s": 25663, "text": "PHP" }, { "code": null, "e": 25678, "s": 25667, "text": "Javascript" }, { "code": "// CPP program to calculate the LCM of N!// and its neighbor (N-1)! and (N+1)!#include <bits/stdc++.h>using namespace std; // function to calculate the factorialunsigned int factorial(unsigned int n){ if (n == 0) return 1; return n * factorial(n - 1);} int LCMOfNeighbourFact(int n){ // returning the factorial of the // largest number in the given three // consecutive numbers return factorial(n + 1);} // Driver codeint main(){ int N = 5; cout << LCMOfNeighbourFact(N) << \"\\n\"; return 0;}", "e": 26203, "s": 25678, "text": null }, { "code": "// Java program to calculate the LCM of N!// and its neighbor (N-1)! and (N+1)!import java.io.*; class GFG { // function to calculate the factorial static int factorial(int n) { if (n == 0) return 1; return n * factorial(n - 1); } static int LCMOfNeighbourFact(int n) { // returning the factorial of the // largest number in the given three // consecutive numbers return factorial(n + 1); } // Driver code public static void main(String args[]) { int N = 5; System.out.println(LCMOfNeighbourFact(N)); }} /*This code is contributed by Nikita Tiwari.*/", "e": 26888, "s": 26203, "text": null }, { "code": "# Python3 program to calculate the LCM of N!# and its neighbor (N-1)! and (N+1)! # Function to calculate the factorialdef factorial(n): if (n == 0): return 1 return n * factorial(n - 1) def LCMOfNeighbourFact(n): # returning the factorial of the # largest number in the given three # consecutive numbers return factorial(n + 1) # Driver codeN = 5print(LCMOfNeighbourFact(N)) # This code is contributed by Anant Agarwal.", "e": 27334, "s": 26888, "text": null }, { "code": "// Program to calculate the LCM// of N! and its neighbor (N-1)!// and (N+1)!using System; class GFG{// function to calculate the factorialstatic int factorial(int n) { if (n == 0) return 1; return n * factorial(n - 1);} static int LCMOfNeighbourFact(int n) { // returning the factorial of the // largest number in the given three // consecutive numbers return factorial(n + 1);} // Driver codepublic static void Main(){ int N = 5; Console.WriteLine(LCMOfNeighbourFact(N));}} // This code is contributed by Anant Agarwal.", "e": 27890, "s": 27334, "text": null }, { "code": "<?php// PHP program to calculate// the LCM of N! and its neighbor// (N-1)! and (N+1)! // function to calculate// the factorialfunction factorial($n){ if ($n == 0) return 1; return $n * factorial($n - 1);} function LCMOfNeighbourFact($n){ // returning the factorial // of the largest number in // the given three // consecutive numbers return factorial($n + 1);} // Driver code$N = 5;echo(LCMOfNeighbourFact($N)); // This code is contributed by Ajit.?>", "e": 28370, "s": 27890, "text": null }, { "code": "<script>// javascript program to calculate the LCM of N!// and its neighbor (N-1)! and (N+1)! // function to calculate the factorial function factorial(n) { if (n == 0) return 1; return n * factorial(n - 1); } function LCMOfNeighbourFact(n) { // returning the factorial of the // largest number in the given three // consecutive numbers return factorial(n + 1); } // Driver code var N = 5; document.write(LCMOfNeighbourFact(N)); // This code is contributed by aashish1995</script>", "e": 28939, "s": 28370, "text": null }, { "code": null, "e": 28943, "s": 28939, "text": "720" }, { "code": null, "e": 28951, "s": 28945, "text": "jit_t" }, { "code": null, "e": 28964, "s": 28951, "text": "Akanksha_Rai" }, { "code": null, "e": 28976, "s": 28964, "text": "aashish1995" }, { "code": null, "e": 28984, "s": 28976, "text": "GCD-LCM" }, { "code": null, "e": 28997, "s": 28984, "text": "Mathematical" }, { "code": null, "e": 29010, "s": 28997, "text": "Mathematical" }, { "code": null, "e": 29108, "s": 29010, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29117, "s": 29108, "text": "Comments" }, { "code": null, "e": 29130, "s": 29117, "text": "Old Comments" }, { "code": null, "e": 29179, "s": 29130, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 29222, "s": 29179, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 29265, "s": 29222, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 29297, "s": 29265, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 29321, "s": 29297, "text": "Merge two sorted arrays" }, { "code": null, "e": 29374, "s": 29321, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 29395, "s": 29374, "text": "Operators in C / C++" }, { "code": null, "e": 29409, "s": 29395, "text": "Prime Numbers" }, { "code": null, "e": 29443, "s": 29409, "text": "Program for factorial of a number" } ]
Political Python. Scraping Congressional documents with... | by Ray Johns | Towards Data Science
The 2020 Democratic candidates for President will face off in debates starting Wednesday. Many of them are current or former members of Congress. All of them are vying to lead the country. As voters, wouldn’t it be extraordinary if we had a record of everything that they had said on the floor of the Senate or the House, over the course of their careers as politicians? And as data scientists, wouldn’t we like to extract their words, analyze them, and use them to make judgments or predictions about these Congresspeople as Presidential candidates? Yes, we can. The Constitution requires Congress to keep a journal of its proceedings. The Government Publishing Office thus prints (and digitally posts) the Congressional Record, which contains the daily official proceedings of the legislature’s two chambers, including: The House section The Senate section Extensions of Remarks (speeches, tributes, testimony, and legislative history) The Daily Digest Although the data live in the public domain, getting them out of the website and into a usable format poses a bit of a challenge. Without access to pricy legal databases, web scraping is the best option for an enterprising member of the public, and Scrapy makes it relatively painless to get a lot of information quickly. Scrapy allows for asynchronous web scraping with python. You can use it to extract data using APIs, integrate it with BeautifulSoup and Selenium, and extend its capabilities in as many ways as a spider web has filaments. Scrapy’s central conceit is copying Django a “don’t repeat yourself” framework, meaning it provides a way to reuse code and easily scale projects up to a larger scope. The component parts of the crawler, such as the items, middlewares, pipelines, and settings, live in separate scripts, and multiple “spiders” that crawl different websites can use them within the same “project”. The spiders themselves, naturally, rely on object-oriented programming (each is of the class “Spider”): The vital components are: The start URLs What you extract from the response, and how What you yield back to the parse function One of Scrapy’s most useful features is the Scrapy shell, which allows you to explore the website you are scraping in real time to test your assumptions. Essentially, you get to try your code out in sandbox mode before you deploy it (and find out it doesn’t work). When you’re working with something as complex as XPath, this addition vastly reduces the time and frustration of drilling down into the structure of a website to extract the content you need. For instance, I needed to fetch partial URLs and text from particular elements within the HTML on the Congress.gov website. The Scrapy shell let me ensure my XPath syntax did not return empty lists before I copied and pasted the resultant syntax into my code. A note on “copy XPath” from DevTools: While you may find it enticing to simply right-click on an HTML element in DevTools and select “Copy XPath” from the menu that appears, do not succumb to temptation. If, like Congress, your site is organized in tables, you’ll fail to retrieve everything you want. In my case, the PDFs I wanted are located in the far right column of the page: Clicking “Copy XPath” gives me the following: //*[@id="browse_expanded_panel_1"]/div/table/tbody/tr[1]/td[6]/a This is just describing a position within a table. Here’s what that returns in the shell: Here’s what my actual XPath expression is: response.xpath('//td/a[@target="_blank"]/@href').extract() And here’s what it returns, for a given page: You must learn to use XPath to select the meaningful content, rather than rely on automatically generated expressions, which — rather like the governmental body in question — often table function in favor of form. Once I had written the spider, it wasted remarkably little time in downloading 25 years’ worth of the Congressional Record to my hard drive. Not too much additional code later, and I had extracted the text with Tika, a python library that processes PDFs. I created a regular expression to split out individual speeches: And tried out some very preliminary sentiment analysis: What’s next for Congress, now that their words are laid bare? Analysis and data mining, Natural(Language Processing)ly. While much ado has been made about Twitter, hardly a covfefe has yet been raised about what Senators and Representatives have said on the floor of Congress, whether because of the difficulty of obtaining the data, the trickiness of training the models, the lack of legal literacy, or all of the above. But with the proper tools and domain knowledge, I hope to provide some valuable insights ahead of the 2020 election season. Originally published at https://www.espritdecorpus.com.
[ { "code": null, "e": 361, "s": 172, "text": "The 2020 Democratic candidates for President will face off in debates starting Wednesday. Many of them are current or former members of Congress. All of them are vying to lead the country." }, { "code": null, "e": 543, "s": 361, "text": "As voters, wouldn’t it be extraordinary if we had a record of everything that they had said on the floor of the Senate or the House, over the course of their careers as politicians?" }, { "code": null, "e": 723, "s": 543, "text": "And as data scientists, wouldn’t we like to extract their words, analyze them, and use them to make judgments or predictions about these Congresspeople as Presidential candidates?" }, { "code": null, "e": 994, "s": 723, "text": "Yes, we can. The Constitution requires Congress to keep a journal of its proceedings. The Government Publishing Office thus prints (and digitally posts) the Congressional Record, which contains the daily official proceedings of the legislature’s two chambers, including:" }, { "code": null, "e": 1012, "s": 994, "text": "The House section" }, { "code": null, "e": 1031, "s": 1012, "text": "The Senate section" }, { "code": null, "e": 1110, "s": 1031, "text": "Extensions of Remarks (speeches, tributes, testimony, and legislative history)" }, { "code": null, "e": 1127, "s": 1110, "text": "The Daily Digest" }, { "code": null, "e": 1449, "s": 1127, "text": "Although the data live in the public domain, getting them out of the website and into a usable format poses a bit of a challenge. Without access to pricy legal databases, web scraping is the best option for an enterprising member of the public, and Scrapy makes it relatively painless to get a lot of information quickly." }, { "code": null, "e": 1670, "s": 1449, "text": "Scrapy allows for asynchronous web scraping with python. You can use it to extract data using APIs, integrate it with BeautifulSoup and Selenium, and extend its capabilities in as many ways as a spider web has filaments." }, { "code": null, "e": 2050, "s": 1670, "text": "Scrapy’s central conceit is copying Django a “don’t repeat yourself” framework, meaning it provides a way to reuse code and easily scale projects up to a larger scope. The component parts of the crawler, such as the items, middlewares, pipelines, and settings, live in separate scripts, and multiple “spiders” that crawl different websites can use them within the same “project”." }, { "code": null, "e": 2154, "s": 2050, "text": "The spiders themselves, naturally, rely on object-oriented programming (each is of the class “Spider”):" }, { "code": null, "e": 2180, "s": 2154, "text": "The vital components are:" }, { "code": null, "e": 2195, "s": 2180, "text": "The start URLs" }, { "code": null, "e": 2239, "s": 2195, "text": "What you extract from the response, and how" }, { "code": null, "e": 2281, "s": 2239, "text": "What you yield back to the parse function" }, { "code": null, "e": 2546, "s": 2281, "text": "One of Scrapy’s most useful features is the Scrapy shell, which allows you to explore the website you are scraping in real time to test your assumptions. Essentially, you get to try your code out in sandbox mode before you deploy it (and find out it doesn’t work)." }, { "code": null, "e": 2998, "s": 2546, "text": "When you’re working with something as complex as XPath, this addition vastly reduces the time and frustration of drilling down into the structure of a website to extract the content you need. For instance, I needed to fetch partial URLs and text from particular elements within the HTML on the Congress.gov website. The Scrapy shell let me ensure my XPath syntax did not return empty lists before I copied and pasted the resultant syntax into my code." }, { "code": null, "e": 3379, "s": 2998, "text": "A note on “copy XPath” from DevTools: While you may find it enticing to simply right-click on an HTML element in DevTools and select “Copy XPath” from the menu that appears, do not succumb to temptation. If, like Congress, your site is organized in tables, you’ll fail to retrieve everything you want. In my case, the PDFs I wanted are located in the far right column of the page:" }, { "code": null, "e": 3425, "s": 3379, "text": "Clicking “Copy XPath” gives me the following:" }, { "code": null, "e": 3490, "s": 3425, "text": "//*[@id=\"browse_expanded_panel_1\"]/div/table/tbody/tr[1]/td[6]/a" }, { "code": null, "e": 3541, "s": 3490, "text": "This is just describing a position within a table." }, { "code": null, "e": 3580, "s": 3541, "text": "Here’s what that returns in the shell:" }, { "code": null, "e": 3623, "s": 3580, "text": "Here’s what my actual XPath expression is:" }, { "code": null, "e": 3682, "s": 3623, "text": "response.xpath('//td/a[@target=\"_blank\"]/@href').extract()" }, { "code": null, "e": 3728, "s": 3682, "text": "And here’s what it returns, for a given page:" }, { "code": null, "e": 3942, "s": 3728, "text": "You must learn to use XPath to select the meaningful content, rather than rely on automatically generated expressions, which — rather like the governmental body in question — often table function in favor of form." }, { "code": null, "e": 4197, "s": 3942, "text": "Once I had written the spider, it wasted remarkably little time in downloading 25 years’ worth of the Congressional Record to my hard drive. Not too much additional code later, and I had extracted the text with Tika, a python library that processes PDFs." }, { "code": null, "e": 4262, "s": 4197, "text": "I created a regular expression to split out individual speeches:" }, { "code": null, "e": 4318, "s": 4262, "text": "And tried out some very preliminary sentiment analysis:" }, { "code": null, "e": 4864, "s": 4318, "text": "What’s next for Congress, now that their words are laid bare? Analysis and data mining, Natural(Language Processing)ly. While much ado has been made about Twitter, hardly a covfefe has yet been raised about what Senators and Representatives have said on the floor of Congress, whether because of the difficulty of obtaining the data, the trickiness of training the models, the lack of legal literacy, or all of the above. But with the proper tools and domain knowledge, I hope to provide some valuable insights ahead of the 2020 election season." } ]
Fraud Detection in Healthcare. Identifying Suspicious Healthcare... | by Nishant Mohan | Towards Data Science
Did you know that in the US, billions are expended in frauds, waste and abuse of prescription drugs. Also, did you know that only 20% of the healthcare providers cause 80% of the costs!? How do I know this, you ask? TLDR: How to identify suspicious and possibly fraudulent healthcare providers? Check out my Tableau Viz and this quick video I made explaining the viz. I’ve worked with a major health insurance provider of the US in the past. Having extensively explored top secret patient claims data (It’s protected by strict laws!) across multiple projects, one thing I realized was that the opioid crisis is real. Even if we keep opioids aside, the sheer volume of fraudulent claims is huge. However, it should be mentioned that what we generally call fraud, is in fact, Fraud, Waste and Abuse (FWA). While Frauds are performed willfully and with malicious intent (duh!), Waste and Abuse do not require intent and knowledge of wrongdoing. Waste is overutilisation of resources, and Abuse refers to provider practices that are inconsistent with sound fiscal, business, or medical practices. Anyway, when the aim is to identify such healthcare providers, we are faced with a problem: There’s just too many of them! It’s like finding a needle in a haystack. More precisely, it’s like finding a faulty needle in a pool of needles. Enter Graph Analysis to the rescue. Using Tableau dashboards, I will show how we can filter the providers and identify suspicious ones. This way, we reduce the size of the search pool, so that finding a faulty needle becomes easy. ;) But where’s the data? The actual patient claim data is protected (called PHI, Protected Health Information) and is not available to the public. But we can make do with a publicly available healthcare data which is aggregated at the provider level, so that it does not identify patients. Centers for Medicare and Medicaid Services provide such data in a Prescriber Summary Table. This data contains aggregated details of the prescription each provider gives, such as opioids, antibiotics, branded drugs, generic ones, and also about the demographics of the providers. I identified some features I think are important when it comes to judging the fraudulent behaviour of prescribers. I applied k-means clustering and used KElbowVisualizer to identify optimum number of clusters as below. from yellowbrick.cluster import KElbowVisualizervisualizer = KElbowVisualizer(KMeans(init='k-means++'), k=(3,11))visualizer.fit(X) # Fit the data to the visualizervisualizer.show() Complete code can be seen in this colab notebook. Using elbow method, I decided that 5 is the optimum number of clusters I tag each prescriber with their cluster number in the dataframe. Check out this Tableau viz that I made. It has three views that tell a story and aid in pinpointing some specific suspicious prescribers. Here’s what the three views show: An overview of overall healthcare provider/prescriber scenario in the US; the charts also act as filters for other charts, so we can see the sickness level of patients of California going to see a dentist in the bottom right bar chart using the two charts above. The second screen explains visually the difference among the clusters; viewer has the option to alter the metrics using a drop-down list of features giving top 3 specialties of each cluster. It can be seen evidently that cluster 4 is indeed suspicious as it has highest costs across categories. Finally, we dive deeper into the cluster 4 to identify outlier providers. We can also select any other cluster for pinpointing at confounding providers. The scatter plot on the right side provides details of the provider on hovering over a circle. The providers/prescribers towards the far right are the ones who incur high costs. When their patient risk score is low, I consider them to be suspicious. In summary, view 1 of the dashboard aims at educating an analyst or viewer of the data and overall healthcare situation in the US. After becoming familiar with the data, in the second view, I wish to visually communicate the differences between the formed clusters and the features used. As such, View 2 can be considered explanatory. The end objective of identifying one or more confounding or outlier prescriber is achieved in View 3. As can be seen in the last chart of the third view, we have an easy way of pinpointing the prescribers who are potentially fraudulent. Here’s a 2-minute video I made explaining the viz: The strength of the presented visualization lies in successfully achieving the main task of identifying suspected prescribers. In the process, the analyst or viewer also gets to appreciate the complexity of data in the field of healthcare, such as costs and patient risk scores. However, the robustness of this method cannot be guaranteed as such. A domain expert is still needed to tell if a prescriber identified as suspicious using the viz is a false positive. For instance, it is possible that a prescriber, thus identified through the visualization, is one that caters only to high cost-incurring patients/cases only. Such a prescriber will be incorrectly identified through the proposed visualization. At the same time, it can be argued that given other features, an analyst or viewer who is adept in the healthcare field would be able to judge if the prescriber is, in fact, a confounder. Connect with me on LinkedIn Check out some of my interesting projects on GitHub
[ { "code": null, "e": 273, "s": 172, "text": "Did you know that in the US, billions are expended in frauds, waste and abuse of prescription drugs." }, { "code": null, "e": 359, "s": 273, "text": "Also, did you know that only 20% of the healthcare providers cause 80% of the costs!?" }, { "code": null, "e": 388, "s": 359, "text": "How do I know this, you ask?" }, { "code": null, "e": 540, "s": 388, "text": "TLDR: How to identify suspicious and possibly fraudulent healthcare providers? Check out my Tableau Viz and this quick video I made explaining the viz." }, { "code": null, "e": 1265, "s": 540, "text": "I’ve worked with a major health insurance provider of the US in the past. Having extensively explored top secret patient claims data (It’s protected by strict laws!) across multiple projects, one thing I realized was that the opioid crisis is real. Even if we keep opioids aside, the sheer volume of fraudulent claims is huge. However, it should be mentioned that what we generally call fraud, is in fact, Fraud, Waste and Abuse (FWA). While Frauds are performed willfully and with malicious intent (duh!), Waste and Abuse do not require intent and knowledge of wrongdoing. Waste is overutilisation of resources, and Abuse refers to provider practices that are inconsistent with sound fiscal, business, or medical practices." }, { "code": null, "e": 1388, "s": 1265, "text": "Anyway, when the aim is to identify such healthcare providers, we are faced with a problem: There’s just too many of them!" }, { "code": null, "e": 1736, "s": 1388, "text": "It’s like finding a needle in a haystack. More precisely, it’s like finding a faulty needle in a pool of needles. Enter Graph Analysis to the rescue. Using Tableau dashboards, I will show how we can filter the providers and identify suspicious ones. This way, we reduce the size of the search pool, so that finding a faulty needle becomes easy. ;)" }, { "code": null, "e": 2303, "s": 1736, "text": "But where’s the data? The actual patient claim data is protected (called PHI, Protected Health Information) and is not available to the public. But we can make do with a publicly available healthcare data which is aggregated at the provider level, so that it does not identify patients. Centers for Medicare and Medicaid Services provide such data in a Prescriber Summary Table. This data contains aggregated details of the prescription each provider gives, such as opioids, antibiotics, branded drugs, generic ones, and also about the demographics of the providers." }, { "code": null, "e": 2418, "s": 2303, "text": "I identified some features I think are important when it comes to judging the fraudulent behaviour of prescribers." }, { "code": null, "e": 2522, "s": 2418, "text": "I applied k-means clustering and used KElbowVisualizer to identify optimum number of clusters as below." }, { "code": null, "e": 2710, "s": 2522, "text": "from yellowbrick.cluster import KElbowVisualizervisualizer = KElbowVisualizer(KMeans(init='k-means++'), k=(3,11))visualizer.fit(X) # Fit the data to the visualizervisualizer.show()" }, { "code": null, "e": 2831, "s": 2710, "text": "Complete code can be seen in this colab notebook. Using elbow method, I decided that 5 is the optimum number of clusters" }, { "code": null, "e": 2897, "s": 2831, "text": "I tag each prescriber with their cluster number in the dataframe." }, { "code": null, "e": 3035, "s": 2897, "text": "Check out this Tableau viz that I made. It has three views that tell a story and aid in pinpointing some specific suspicious prescribers." }, { "code": null, "e": 3069, "s": 3035, "text": "Here’s what the three views show:" }, { "code": null, "e": 3332, "s": 3069, "text": "An overview of overall healthcare provider/prescriber scenario in the US; the charts also act as filters for other charts, so we can see the sickness level of patients of California going to see a dentist in the bottom right bar chart using the two charts above." }, { "code": null, "e": 3627, "s": 3332, "text": "The second screen explains visually the difference among the clusters; viewer has the option to alter the metrics using a drop-down list of features giving top 3 specialties of each cluster. It can be seen evidently that cluster 4 is indeed suspicious as it has highest costs across categories." }, { "code": null, "e": 4030, "s": 3627, "text": "Finally, we dive deeper into the cluster 4 to identify outlier providers. We can also select any other cluster for pinpointing at confounding providers. The scatter plot on the right side provides details of the provider on hovering over a circle. The providers/prescribers towards the far right are the ones who incur high costs. When their patient risk score is low, I consider them to be suspicious." }, { "code": null, "e": 4602, "s": 4030, "text": "In summary, view 1 of the dashboard aims at educating an analyst or viewer of the data and overall healthcare situation in the US. After becoming familiar with the data, in the second view, I wish to visually communicate the differences between the formed clusters and the features used. As such, View 2 can be considered explanatory. The end objective of identifying one or more confounding or outlier prescriber is achieved in View 3. As can be seen in the last chart of the third view, we have an easy way of pinpointing the prescribers who are potentially fraudulent." }, { "code": null, "e": 4653, "s": 4602, "text": "Here’s a 2-minute video I made explaining the viz:" }, { "code": null, "e": 5001, "s": 4653, "text": "The strength of the presented visualization lies in successfully achieving the main task of identifying suspected prescribers. In the process, the analyst or viewer also gets to appreciate the complexity of data in the field of healthcare, such as costs and patient risk scores. However, the robustness of this method cannot be guaranteed as such." }, { "code": null, "e": 5117, "s": 5001, "text": "A domain expert is still needed to tell if a prescriber identified as suspicious using the viz is a false positive." }, { "code": null, "e": 5549, "s": 5117, "text": "For instance, it is possible that a prescriber, thus identified through the visualization, is one that caters only to high cost-incurring patients/cases only. Such a prescriber will be incorrectly identified through the proposed visualization. At the same time, it can be argued that given other features, an analyst or viewer who is adept in the healthcare field would be able to judge if the prescriber is, in fact, a confounder." }, { "code": null, "e": 5577, "s": 5549, "text": "Connect with me on LinkedIn" } ]
How to Insert Records and Do Conditional Delete for DynamoDB Using Python and Boto3 Library | by billydharmawan | Towards Data Science
It is very common to have many junk or dummy records in our DynamoDB table for testing purposes. It may be an application we are developing or even just a function. It can also be some records that our existing application generates but, actually, they have no values. Regardless of what it is, we end up creating many records in our database. Every now and then, we want to clean up our database tables, so only valuable and meaningful records are stored. For example, we did a load testing to test the user account creation API in our application. This obviously resulted in many records in the table, which are just “test” records. All these “test” records have the characteristics of the email starting with testing and last name starting with TEST. You know, whatever. 😆 These records, obviously, can be removed from the table once we finish our load testing. In this tutorial, you will learn how to use Python to insert items and conditionally delete items from your DynamoDB table, which you do not want to keep anymore, for whatever reasons it may be. We are going to use the official AWS SDK library for Python, which is known as Boto3. I am not going to do a detailed walkthrough on this but will show you quickly how to do it via virtualenv. First things first, you need to install virtualenv via pip3 if you haven’t already. It is as simple as: $ ~/demo > pip3 install virtualenv Then, create a directory where you want to put your project file (or in this case, the Python script). $ ~/demo > mkdir batch-ops-dynamodb Go to the directory and create the virtual environment in there. $ ~/demo > cd ./batch-ops-dynamodb$ ~/demo/batch-ops-dynamodb > virtualenv ./venvUsing base prefix '/Library/Frameworks/Python.framework/Versions/3.8'New python executable in /Users/billyde/demo/batch-ops-dynamodb/venv/bin/python3.8Also creating executable in /Users/billyde/demo/batch-ops-dynamodb/venv/bin/pythonInstalling setuptools, pip, wheel...done. Lastly, we want to active the virtual environment. Just a quick reminder, a virtual environment is really useful as it isolates your development from the rest of your machine. Think of it like a container, where all the dependencies are provided within the virtual environment and accessible only from within the environment. $ ~/demo/batch-ops-dynamodb > source ./venv/bin/activate$ ~/demo/batch-ops-dynamodb (venv) > Notice the (venv). This indicates that you are in the virtual environment. You may not see that, though, depending on your terminal’s settings. So, as an alternative, here’s why you can validate whether your virtual environment is active or not. $ ~/demo/batch-ops-dynamodb (venv) > which python/Users/billyde/demo/batch-ops-dynamodb/venv/bin/python$ ~/demo/batch-ops-dynamodb (venv) > which pip/Users/billyde/demo/batch-ops-dynamodb/venv/bin/pip You can see that the Python and pip executables are the one from our virtual environment. All is good. 🙂 The only dependency for this tutorial is the Boto3 library. So, let’s go ahead and install it within our virtual environment. $ ~/demo/batch-ops-dynamodb (venv) > pip install boto3Collecting boto3 Downloading boto3-1.11.7-py2.py3-none-any.whl (128 kB) |████████████████████████████████| 128 kB 1.0 MB/sCollecting botocore<1.15.0,>=1.14.7 Downloading botocore-1.14.7-py2.py3-none-any.whl (5.9 MB) |████████████████████████████████| 5.9 MB 462 kB/sCollecting s3transfer<0.4.0,>=0.3.0 Downloading s3transfer-0.3.1-py2.py3-none-any.whl (69 kB) |████████████████████████████████| 69 kB 2.1 MB/sCollecting jmespath<1.0.0,>=0.7.1 Using cached jmespath-0.9.4-py2.py3-none-any.whl (24 kB)Collecting urllib3<1.26,>=1.20 Downloading urllib3-1.25.8-py2.py3-none-any.whl (125 kB) |████████████████████████████████| 125 kB 5.3 MB/sCollecting python-dateutil<3.0.0,>=2.1 Using cached python_dateutil-2.8.1-py2.py3-none-any.whl (227 kB)Collecting docutils<0.16,>=0.10 Using cached docutils-0.15.2-py3-none-any.whl (547 kB)Collecting six>=1.5 Downloading six-1.14.0-py2.py3-none-any.whl (10 kB)Installing collected packages: urllib3, six, python-dateutil, docutils, jmespath, botocore, s3transfer, boto3Successfully installed boto3-1.11.7 botocore-1.14.7 docutils-0.15.2 jmespath-0.9.4 python-dateutil-2.8.1 s3transfer-0.3.1 six-1.14.0 urllib3-1.25.8 Once you have completed the pre-requisites, we’re ready to do the fun stuff, which is writing the actual script that will do the batch delete of our junk records. To help us see how the script works, we will spin up a local DynamoDB instance in a Docker container. You can follow this tutorial to achieve this. Essentially, what you need to do is spin up the DynamoDB Docker and create the table demo-customer-info as written in the tutorial. Let’s create dummy records so we can see how the batch operation works. To do this, we are going to write a Python script that calls the DynamoDB PutItem operation in a loop. Create a new Python file in batch-ops-dynamo and name it insert_dummy_records.py. ~/demo/batch-ops-dynamodb ❯ touch insert_dummy_records.py As mentioned in the Introduction section earlier, our dummy records will have the following traits: last name begins with TEST email address begins with testing Our script will have the following components: insert_dummy_record: a function that does the PutItem operation for loop: a loop that will call insert_dummy_record function 10 times to insert dummy records. We also leverage random.randint method to generate some random integers to be added to our dummy records’ attributes, which are: customerId lastName emailAddress Our script looks good! Now, it’s time for us to run it from the command line, using the Python executable from our virtual environment. ~/demo/batch-ops-dynamodb ❯ python3 insert_dummy_records.pyInserting record number 1 with customerId 769Inserting record number 2 with customerId 885Inserting record number 3 with customerId 873Inserting record number 4 with customerId 827Inserting record number 5 with customerId 231Inserting record number 6 with customerId 199Inserting record number 7 with customerId 272Inserting record number 8 with customerId 268Inserting record number 9 with customerId 729Inserting record number 10 with customerId 289 Ok. The script seems to work as expected. Hooray! 😄 Let’s validate by calling the scan operation on our local DynamoDB demo-customer-info table to check the records. ~/demo/batch-ops-dynamodb ❯ aws dynamodb scan --endpoint-url http://localhost:8042 --table-name demo-customer-info{ "Items": [ { "customerId": { "S": "199" }, "lastName": { "S": "TEST199" }, "emailAddress": { "S": "testing199@dummy.com" } }, { "customerId": { "S": "769" }, "lastName": { "S": "TEST769" }, "emailAddress": { "S": "testing769@dummy.com" } },... truncated... truncated... truncated { "customerId": { "S": "827" }, "lastName": { "S": "TEST827" }, "emailAddress": { "S": "testing827@dummy.com" } } ], "Count": 10, "ScannedCount": 10, "ConsumedCapacity": null} Perfect! We have some dummy records in our table now. We’ll quickly insert 2 records that are “real” to the table. To do this, we are just going to write another Python script that takes command line argument as its input. Let’s name the file insert_real_record.py. ~/demo/batch-ops-dynamodb ❯ touch insert_real_record.py The content of the file will be as follows. Let’s go ahead and insert 2 records to the table. ~/demo/batch-ops-dynamodb ❯ python insert_real_record.py 11111 jones sam.jones@something.comInserting record with customerId 11111~/demo/batch-ops-dynamodb ❯ python insert_real_record.py 22222 smith jack.smith@somedomain.comInserting record with customerId 22222 Finally, we are going to write the script that deletes records that meet some specified conditions from our table. Again, as a reminder, we want to remove the dummy records we inserted. The filter that we need to apply is last name begins with TEST and email address begins with testing. How the script works: do a scan operation on the table with the given filter expression retrieve just the customerId attribute from all records, which meet our filter expression, as this is all we need to do the DeleteItem operation. Remember, customerId is the partition key of the table. in a for loop, for each customerId returned by our scan operation, do the DeleteItem operation. Go ahead and run this script from the command line. ~/demo/batch-ops-dynamodb ❯ python delete_records_conditionally.pyGetting customer ids to delete============['199', '769', '873', '268', '289', '231', '272', '885', '729', '827']Deleting customer 199Deleting customer 769Deleting customer 873Deleting customer 268Deleting customer 289Deleting customer 231Deleting customer 272Deleting customer 885Deleting customer 729Deleting customer 827 Great! The script works as intended. Now, let’s check the remaining records in our table. ~/demo/batch-ops-dynamodb ❯ aws dynamodb scan --endpoint-url http://localhost:8042 --table-name demo-customer-info{ "Items": [ { "customerId": { "S": "22222" }, "lastName": { "S": "smith" }, "emailAddress": { "S": "jack.smith@somedomain.com" } }, { "customerId": { "S": "11111" }, "lastName": { "S": "jones" }, "emailAddress": { "S": "sam.jones@something.com" } } ], "Count": 2, "ScannedCount": 2, "ConsumedCapacity": null} There are only 2 records remaining, which are the “real” records we inserted. We can be certain now that our delete_records_conditionally.py script does what it is intended for. Awesome stuff. 👍 Let’s take a look at a few things from the delete_records_conditionally.py script we just wrote. Notice that we have a deserializer and we use it to get the customerId. The reason is because, the scan operation actually returns something like this. # scan operation response{'Items': [{'customerId': {'S': '300'}}, {'customerId': {'S': '794'}}, {'customerId': {'S': '266'}}, {'customerId': {'S': '281'}}, {'customerId': {'S': '223'}}, {'customerId': {'S': '660'}}, {'customerId': {'S': '384'}}, {'customerId': {'S': '673'}}, {'customerId': {'S': '378'}}, {'customerId': {'S': '426'}}], 'Count': 10, 'ScannedCount': 12, 'ResponseMetadata': {'RequestId': 'eb18e221-d825-4f28-b142-ff616d0ca323', 'HTTPStatusCode': 200, 'HTTPHeaders': {'content-type': 'application/x-amz-json-1.0', 'x-amz-crc32': '2155737492', 'x-amzn-requestid': 'eb18e221-d825-4f28-b142-ff616d0ca323', 'content-length': '310', 'server': 'Jetty(8.1.12.v20130726)'}, 'RetryAttempts': 0}} Since we are only interested in the value of customerId, we need to deserialise the DynamoDB item using the TypeDeserializer that is provided by the Boto3 library. Another component worth mentioning is the Select and ProjectionExpression, which are parameters of the scan function. These 2 parameters work hand-in-hand. We set the value of Select to SPECIFIC_ATTRIBUTES and according to the official Boto3 documentation, this will return only the attributes listed in AttributesToGet. AttributesToGet has been marked as a legacy parameter and AWS advises us to use ProjectionExpression, instead. From the official Boto3 documentation: “If you use the ProjectionExpression parameter, then the value for Select can only be SPECIFIC_ATTRIBUTES . Any other value for Select will return an error.” These 2 parameters are basically saying that the scan operation should only return the customerId attribute, which is what we need. Lastly, we use the begins_with() function that is provided by AWS. This function takes an attribute name and the prefix to check against the value of the attribute specified. By this point, you will have learnt how to do insert and delete DynamoDB records with Python and Boto3. You can certainly adjust and modify the script to suit your needs. For instance, the filter expression used in this tutorial is relatively simple, you can add more complex conditions, if need be. Anyways, I hope this tutorial has given you a basic understanding of how to do DynamoDB operation using Python. So, go ahead and be creative, taking this script and enhance it to do more advanced stuff. Happy hacking! 🙂 Note: here’s the Github repo.
[ { "code": null, "e": 516, "s": 172, "text": "It is very common to have many junk or dummy records in our DynamoDB table for testing purposes. It may be an application we are developing or even just a function. It can also be some records that our existing application generates but, actually, they have no values. Regardless of what it is, we end up creating many records in our database." }, { "code": null, "e": 1037, "s": 516, "text": "Every now and then, we want to clean up our database tables, so only valuable and meaningful records are stored. For example, we did a load testing to test the user account creation API in our application. This obviously resulted in many records in the table, which are just “test” records. All these “test” records have the characteristics of the email starting with testing and last name starting with TEST. You know, whatever. 😆 These records, obviously, can be removed from the table once we finish our load testing." }, { "code": null, "e": 1318, "s": 1037, "text": "In this tutorial, you will learn how to use Python to insert items and conditionally delete items from your DynamoDB table, which you do not want to keep anymore, for whatever reasons it may be. We are going to use the official AWS SDK library for Python, which is known as Boto3." }, { "code": null, "e": 1425, "s": 1318, "text": "I am not going to do a detailed walkthrough on this but will show you quickly how to do it via virtualenv." }, { "code": null, "e": 1529, "s": 1425, "text": "First things first, you need to install virtualenv via pip3 if you haven’t already. It is as simple as:" }, { "code": null, "e": 1564, "s": 1529, "text": "$ ~/demo > pip3 install virtualenv" }, { "code": null, "e": 1667, "s": 1564, "text": "Then, create a directory where you want to put your project file (or in this case, the Python script)." }, { "code": null, "e": 1703, "s": 1667, "text": "$ ~/demo > mkdir batch-ops-dynamodb" }, { "code": null, "e": 1768, "s": 1703, "text": "Go to the directory and create the virtual environment in there." }, { "code": null, "e": 2124, "s": 1768, "text": "$ ~/demo > cd ./batch-ops-dynamodb$ ~/demo/batch-ops-dynamodb > virtualenv ./venvUsing base prefix '/Library/Frameworks/Python.framework/Versions/3.8'New python executable in /Users/billyde/demo/batch-ops-dynamodb/venv/bin/python3.8Also creating executable in /Users/billyde/demo/batch-ops-dynamodb/venv/bin/pythonInstalling setuptools, pip, wheel...done." }, { "code": null, "e": 2450, "s": 2124, "text": "Lastly, we want to active the virtual environment. Just a quick reminder, a virtual environment is really useful as it isolates your development from the rest of your machine. Think of it like a container, where all the dependencies are provided within the virtual environment and accessible only from within the environment." }, { "code": null, "e": 2543, "s": 2450, "text": "$ ~/demo/batch-ops-dynamodb > source ./venv/bin/activate$ ~/demo/batch-ops-dynamodb (venv) >" }, { "code": null, "e": 2789, "s": 2543, "text": "Notice the (venv). This indicates that you are in the virtual environment. You may not see that, though, depending on your terminal’s settings. So, as an alternative, here’s why you can validate whether your virtual environment is active or not." }, { "code": null, "e": 2990, "s": 2789, "text": "$ ~/demo/batch-ops-dynamodb (venv) > which python/Users/billyde/demo/batch-ops-dynamodb/venv/bin/python$ ~/demo/batch-ops-dynamodb (venv) > which pip/Users/billyde/demo/batch-ops-dynamodb/venv/bin/pip" }, { "code": null, "e": 3095, "s": 2990, "text": "You can see that the Python and pip executables are the one from our virtual environment. All is good. 🙂" }, { "code": null, "e": 3221, "s": 3095, "text": "The only dependency for this tutorial is the Boto3 library. So, let’s go ahead and install it within our virtual environment." }, { "code": null, "e": 4453, "s": 3221, "text": "$ ~/demo/batch-ops-dynamodb (venv) > pip install boto3Collecting boto3 Downloading boto3-1.11.7-py2.py3-none-any.whl (128 kB) |████████████████████████████████| 128 kB 1.0 MB/sCollecting botocore<1.15.0,>=1.14.7 Downloading botocore-1.14.7-py2.py3-none-any.whl (5.9 MB) |████████████████████████████████| 5.9 MB 462 kB/sCollecting s3transfer<0.4.0,>=0.3.0 Downloading s3transfer-0.3.1-py2.py3-none-any.whl (69 kB) |████████████████████████████████| 69 kB 2.1 MB/sCollecting jmespath<1.0.0,>=0.7.1 Using cached jmespath-0.9.4-py2.py3-none-any.whl (24 kB)Collecting urllib3<1.26,>=1.20 Downloading urllib3-1.25.8-py2.py3-none-any.whl (125 kB) |████████████████████████████████| 125 kB 5.3 MB/sCollecting python-dateutil<3.0.0,>=2.1 Using cached python_dateutil-2.8.1-py2.py3-none-any.whl (227 kB)Collecting docutils<0.16,>=0.10 Using cached docutils-0.15.2-py3-none-any.whl (547 kB)Collecting six>=1.5 Downloading six-1.14.0-py2.py3-none-any.whl (10 kB)Installing collected packages: urllib3, six, python-dateutil, docutils, jmespath, botocore, s3transfer, boto3Successfully installed boto3-1.11.7 botocore-1.14.7 docutils-0.15.2 jmespath-0.9.4 python-dateutil-2.8.1 s3transfer-0.3.1 six-1.14.0 urllib3-1.25.8" }, { "code": null, "e": 4616, "s": 4453, "text": "Once you have completed the pre-requisites, we’re ready to do the fun stuff, which is writing the actual script that will do the batch delete of our junk records." }, { "code": null, "e": 4764, "s": 4616, "text": "To help us see how the script works, we will spin up a local DynamoDB instance in a Docker container. You can follow this tutorial to achieve this." }, { "code": null, "e": 4896, "s": 4764, "text": "Essentially, what you need to do is spin up the DynamoDB Docker and create the table demo-customer-info as written in the tutorial." }, { "code": null, "e": 5153, "s": 4896, "text": "Let’s create dummy records so we can see how the batch operation works. To do this, we are going to write a Python script that calls the DynamoDB PutItem operation in a loop. Create a new Python file in batch-ops-dynamo and name it insert_dummy_records.py." }, { "code": null, "e": 5211, "s": 5153, "text": "~/demo/batch-ops-dynamodb ❯ touch insert_dummy_records.py" }, { "code": null, "e": 5311, "s": 5211, "text": "As mentioned in the Introduction section earlier, our dummy records will have the following traits:" }, { "code": null, "e": 5338, "s": 5311, "text": "last name begins with TEST" }, { "code": null, "e": 5372, "s": 5338, "text": "email address begins with testing" }, { "code": null, "e": 5419, "s": 5372, "text": "Our script will have the following components:" }, { "code": null, "e": 5483, "s": 5419, "text": "insert_dummy_record: a function that does the PutItem operation" }, { "code": null, "e": 5578, "s": 5483, "text": "for loop: a loop that will call insert_dummy_record function 10 times to insert dummy records." }, { "code": null, "e": 5707, "s": 5578, "text": "We also leverage random.randint method to generate some random integers to be added to our dummy records’ attributes, which are:" }, { "code": null, "e": 5718, "s": 5707, "text": "customerId" }, { "code": null, "e": 5727, "s": 5718, "text": "lastName" }, { "code": null, "e": 5740, "s": 5727, "text": "emailAddress" }, { "code": null, "e": 5876, "s": 5740, "text": "Our script looks good! Now, it’s time for us to run it from the command line, using the Python executable from our virtual environment." }, { "code": null, "e": 6387, "s": 5876, "text": "~/demo/batch-ops-dynamodb ❯ python3 insert_dummy_records.pyInserting record number 1 with customerId 769Inserting record number 2 with customerId 885Inserting record number 3 with customerId 873Inserting record number 4 with customerId 827Inserting record number 5 with customerId 231Inserting record number 6 with customerId 199Inserting record number 7 with customerId 272Inserting record number 8 with customerId 268Inserting record number 9 with customerId 729Inserting record number 10 with customerId 289" }, { "code": null, "e": 6439, "s": 6387, "text": "Ok. The script seems to work as expected. Hooray! 😄" }, { "code": null, "e": 6553, "s": 6439, "text": "Let’s validate by calling the scan operation on our local DynamoDB demo-customer-info table to check the records." }, { "code": null, "e": 7515, "s": 6553, "text": "~/demo/batch-ops-dynamodb ❯ aws dynamodb scan --endpoint-url http://localhost:8042 --table-name demo-customer-info{ \"Items\": [ { \"customerId\": { \"S\": \"199\" }, \"lastName\": { \"S\": \"TEST199\" }, \"emailAddress\": { \"S\": \"testing199@dummy.com\" } }, { \"customerId\": { \"S\": \"769\" }, \"lastName\": { \"S\": \"TEST769\" }, \"emailAddress\": { \"S\": \"testing769@dummy.com\" } },... truncated... truncated... truncated { \"customerId\": { \"S\": \"827\" }, \"lastName\": { \"S\": \"TEST827\" }, \"emailAddress\": { \"S\": \"testing827@dummy.com\" } } ], \"Count\": 10, \"ScannedCount\": 10, \"ConsumedCapacity\": null}" }, { "code": null, "e": 7569, "s": 7515, "text": "Perfect! We have some dummy records in our table now." }, { "code": null, "e": 7781, "s": 7569, "text": "We’ll quickly insert 2 records that are “real” to the table. To do this, we are just going to write another Python script that takes command line argument as its input. Let’s name the file insert_real_record.py." }, { "code": null, "e": 7837, "s": 7781, "text": "~/demo/batch-ops-dynamodb ❯ touch insert_real_record.py" }, { "code": null, "e": 7881, "s": 7837, "text": "The content of the file will be as follows." }, { "code": null, "e": 7931, "s": 7881, "text": "Let’s go ahead and insert 2 records to the table." }, { "code": null, "e": 8194, "s": 7931, "text": "~/demo/batch-ops-dynamodb ❯ python insert_real_record.py 11111 jones sam.jones@something.comInserting record with customerId 11111~/demo/batch-ops-dynamodb ❯ python insert_real_record.py 22222 smith jack.smith@somedomain.comInserting record with customerId 22222" }, { "code": null, "e": 8309, "s": 8194, "text": "Finally, we are going to write the script that deletes records that meet some specified conditions from our table." }, { "code": null, "e": 8482, "s": 8309, "text": "Again, as a reminder, we want to remove the dummy records we inserted. The filter that we need to apply is last name begins with TEST and email address begins with testing." }, { "code": null, "e": 8504, "s": 8482, "text": "How the script works:" }, { "code": null, "e": 8570, "s": 8504, "text": "do a scan operation on the table with the given filter expression" }, { "code": null, "e": 8772, "s": 8570, "text": "retrieve just the customerId attribute from all records, which meet our filter expression, as this is all we need to do the DeleteItem operation. Remember, customerId is the partition key of the table." }, { "code": null, "e": 8868, "s": 8772, "text": "in a for loop, for each customerId returned by our scan operation, do the DeleteItem operation." }, { "code": null, "e": 8920, "s": 8868, "text": "Go ahead and run this script from the command line." }, { "code": null, "e": 9309, "s": 8920, "text": "~/demo/batch-ops-dynamodb ❯ python delete_records_conditionally.pyGetting customer ids to delete============['199', '769', '873', '268', '289', '231', '272', '885', '729', '827']Deleting customer 199Deleting customer 769Deleting customer 873Deleting customer 268Deleting customer 289Deleting customer 231Deleting customer 272Deleting customer 885Deleting customer 729Deleting customer 827" }, { "code": null, "e": 9399, "s": 9309, "text": "Great! The script works as intended. Now, let’s check the remaining records in our table." }, { "code": null, "e": 10088, "s": 9399, "text": "~/demo/batch-ops-dynamodb ❯ aws dynamodb scan --endpoint-url http://localhost:8042 --table-name demo-customer-info{ \"Items\": [ { \"customerId\": { \"S\": \"22222\" }, \"lastName\": { \"S\": \"smith\" }, \"emailAddress\": { \"S\": \"jack.smith@somedomain.com\" } }, { \"customerId\": { \"S\": \"11111\" }, \"lastName\": { \"S\": \"jones\" }, \"emailAddress\": { \"S\": \"sam.jones@something.com\" } } ], \"Count\": 2, \"ScannedCount\": 2, \"ConsumedCapacity\": null}" }, { "code": null, "e": 10266, "s": 10088, "text": "There are only 2 records remaining, which are the “real” records we inserted. We can be certain now that our delete_records_conditionally.py script does what it is intended for." }, { "code": null, "e": 10283, "s": 10266, "text": "Awesome stuff. 👍" }, { "code": null, "e": 10380, "s": 10283, "text": "Let’s take a look at a few things from the delete_records_conditionally.py script we just wrote." }, { "code": null, "e": 10532, "s": 10380, "text": "Notice that we have a deserializer and we use it to get the customerId. The reason is because, the scan operation actually returns something like this." }, { "code": null, "e": 11234, "s": 10532, "text": "# scan operation response{'Items': [{'customerId': {'S': '300'}}, {'customerId': {'S': '794'}}, {'customerId': {'S': '266'}}, {'customerId': {'S': '281'}}, {'customerId': {'S': '223'}}, {'customerId': {'S': '660'}}, {'customerId': {'S': '384'}}, {'customerId': {'S': '673'}}, {'customerId': {'S': '378'}}, {'customerId': {'S': '426'}}], 'Count': 10, 'ScannedCount': 12, 'ResponseMetadata': {'RequestId': 'eb18e221-d825-4f28-b142-ff616d0ca323', 'HTTPStatusCode': 200, 'HTTPHeaders': {'content-type': 'application/x-amz-json-1.0', 'x-amz-crc32': '2155737492', 'x-amzn-requestid': 'eb18e221-d825-4f28-b142-ff616d0ca323', 'content-length': '310', 'server': 'Jetty(8.1.12.v20130726)'}, 'RetryAttempts': 0}}" }, { "code": null, "e": 11398, "s": 11234, "text": "Since we are only interested in the value of customerId, we need to deserialise the DynamoDB item using the TypeDeserializer that is provided by the Boto3 library." }, { "code": null, "e": 11830, "s": 11398, "text": "Another component worth mentioning is the Select and ProjectionExpression, which are parameters of the scan function. These 2 parameters work hand-in-hand. We set the value of Select to SPECIFIC_ATTRIBUTES and according to the official Boto3 documentation, this will return only the attributes listed in AttributesToGet. AttributesToGet has been marked as a legacy parameter and AWS advises us to use ProjectionExpression, instead." }, { "code": null, "e": 11869, "s": 11830, "text": "From the official Boto3 documentation:" }, { "code": null, "e": 12027, "s": 11869, "text": "“If you use the ProjectionExpression parameter, then the value for Select can only be SPECIFIC_ATTRIBUTES . Any other value for Select will return an error.”" }, { "code": null, "e": 12159, "s": 12027, "text": "These 2 parameters are basically saying that the scan operation should only return the customerId attribute, which is what we need." }, { "code": null, "e": 12334, "s": 12159, "text": "Lastly, we use the begins_with() function that is provided by AWS. This function takes an attribute name and the prefix to check against the value of the attribute specified." }, { "code": null, "e": 12634, "s": 12334, "text": "By this point, you will have learnt how to do insert and delete DynamoDB records with Python and Boto3. You can certainly adjust and modify the script to suit your needs. For instance, the filter expression used in this tutorial is relatively simple, you can add more complex conditions, if need be." }, { "code": null, "e": 12854, "s": 12634, "text": "Anyways, I hope this tutorial has given you a basic understanding of how to do DynamoDB operation using Python. So, go ahead and be creative, taking this script and enhance it to do more advanced stuff. Happy hacking! 🙂" } ]
How to Display Data from CSV file using PHP ? - GeeksforGeeks
14 Dec, 2020 We have given the data in CSV file format and the task is to display the CSV file data into the web browser using PHP. To display the data from CSV file to web browser, we will use fgetcsv() function. Comma Separated Value (CSV) is a text file containing data contents. It is a comma-separated value file with .csv extension, which allows data to be saved in a tabular format. fgetcsv() Function: The fgetcsv() function is used to parse a line from an open file, checking for CSV fields. Execution Steps: Open XAMPP server and start apache service Open notepad and type the PHP code and save it as code.php Store the CSV file in the same folder. Like xampp/htdocs/gfg/a.csv Go to browser and type http://localhost/gfg/code.php. Filename: code.php PHP <!DOCTYPE html><html> <body> <center> <h1>DISPLAY DATA PRESENT IN CSV</h1> <h3>Student data</h3> <?php echo "<html><body><center><table>\n\n"; // Open a file $file = fopen("a.csv", "r"); // Fetching data from csv file row by row while (($data = fgetcsv($file)) !== false) { // HTML tag for placing in row format echo "<tr>"; foreach ($data as $i) { echo "<td>" . htmlspecialchars($i) . "</td>"; } echo "</tr> \n"; } // Closing the file fclose($file); echo "\n</table></center></body></html>"; ?> </center></body> </html> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-Misc PHP-Misc HTML PHP PHP Programs Web Technologies Web technologies Questions HTML PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to update Node.js and NPM to next version ? Types of CSS (Cascading Style Sheet) How to Insert Form Data into Database using PHP ? CSS to put icon inside an input element in a form REST API (Introduction) How to Insert Form Data into Database using PHP ? How to execute PHP code using command line ? How to pop an alert message box using PHP ? How to convert array to string in PHP ? How to Upload Image into Database and Display it using PHP ?
[ { "code": null, "e": 24616, "s": 24588, "text": "\n14 Dec, 2020" }, { "code": null, "e": 24817, "s": 24616, "text": "We have given the data in CSV file format and the task is to display the CSV file data into the web browser using PHP. To display the data from CSV file to web browser, we will use fgetcsv() function." }, { "code": null, "e": 24993, "s": 24817, "text": "Comma Separated Value (CSV) is a text file containing data contents. It is a comma-separated value file with .csv extension, which allows data to be saved in a tabular format." }, { "code": null, "e": 25104, "s": 24993, "text": "fgetcsv() Function: The fgetcsv() function is used to parse a line from an open file, checking for CSV fields." }, { "code": null, "e": 25121, "s": 25104, "text": "Execution Steps:" }, { "code": null, "e": 25164, "s": 25121, "text": "Open XAMPP server and start apache service" }, { "code": null, "e": 25223, "s": 25164, "text": "Open notepad and type the PHP code and save it as code.php" }, { "code": null, "e": 25290, "s": 25223, "text": "Store the CSV file in the same folder. Like xampp/htdocs/gfg/a.csv" }, { "code": null, "e": 25345, "s": 25290, "text": "Go to browser and type http://localhost/gfg/code.php. " }, { "code": null, "e": 25366, "s": 25347, "text": "Filename: code.php" }, { "code": null, "e": 25370, "s": 25366, "text": "PHP" }, { "code": "<!DOCTYPE html><html> <body> <center> <h1>DISPLAY DATA PRESENT IN CSV</h1> <h3>Student data</h3> <?php echo \"<html><body><center><table>\\n\\n\"; // Open a file $file = fopen(\"a.csv\", \"r\"); // Fetching data from csv file row by row while (($data = fgetcsv($file)) !== false) { // HTML tag for placing in row format echo \"<tr>\"; foreach ($data as $i) { echo \"<td>\" . htmlspecialchars($i) . \"</td>\"; } echo \"</tr> \\n\"; } // Closing the file fclose($file); echo \"\\n</table></center></body></html>\"; ?> </center></body> </html>", "e": 26092, "s": 25370, "text": null }, { "code": null, "e": 26100, "s": 26092, "text": "Output:" }, { "code": null, "e": 26237, "s": 26100, "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": 26247, "s": 26237, "text": "HTML-Misc" }, { "code": null, "e": 26256, "s": 26247, "text": "PHP-Misc" }, { "code": null, "e": 26261, "s": 26256, "text": "HTML" }, { "code": null, "e": 26265, "s": 26261, "text": "PHP" }, { "code": null, "e": 26278, "s": 26265, "text": "PHP Programs" }, { "code": null, "e": 26295, "s": 26278, "text": "Web Technologies" }, { "code": null, "e": 26322, "s": 26295, "text": "Web technologies Questions" }, { "code": null, "e": 26327, "s": 26322, "text": "HTML" }, { "code": null, "e": 26331, "s": 26327, "text": "PHP" }, { "code": null, "e": 26429, "s": 26331, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26438, "s": 26429, "text": "Comments" }, { "code": null, "e": 26451, "s": 26438, "text": "Old Comments" }, { "code": null, "e": 26499, "s": 26451, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 26536, "s": 26499, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 26586, "s": 26536, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 26636, "s": 26586, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 26660, "s": 26636, "text": "REST API (Introduction)" }, { "code": null, "e": 26710, "s": 26660, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 26755, "s": 26710, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 26799, "s": 26755, "text": "How to pop an alert message box using PHP ?" }, { "code": null, "e": 26839, "s": 26799, "text": "How to convert array to string in PHP ?" } ]
Encryption of Transposition Cipher
In the previous chapter, we have learnt about Transposition Cipher. In this chapter, let us discuss its encryption. The main usage of pyperclip plugin in Python programming language is to perform cross platform module for copying and pasting text to the clipboard. You can install python pyperclip module using the command as shown pip install pyperclip If the requirement already exists in the system, you can see the following output − The python code for encrypting transposition cipher in which pyperclip is the main module is as shown below − import pyperclip def main(): myMessage = 'Transposition Cipher' myKey = 10 ciphertext = encryptMessage(myKey, myMessage) print("Cipher Text is") print(ciphertext + '|') pyperclip.copy(ciphertext) def encryptMessage(key, message): ciphertext = [''] * key for col in range(key): position = col while position < len(message): ciphertext[col] += message[position] position += key return ''.join(ciphertext) #Cipher text if __name__ == '__main__': main() The program code for encrypting transposition cipher in which pyperclip is the main module gives the following output − The function main() calls the encryptMessage() which includes the procedure for splitting the characters using len function and iterating them in a columnar format. The function main() calls the encryptMessage() which includes the procedure for splitting the characters using len function and iterating them in a columnar format. The main function is initialized at the end to get the appropriate output. The main function is initialized at the end to get the appropriate output. 10 Lectures 2 hours Total Seminars 10 Lectures 2 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2408, "s": 2292, "text": "In the previous chapter, we have learnt about Transposition Cipher. In this chapter, let us discuss its encryption." }, { "code": null, "e": 2624, "s": 2408, "text": "The main usage of pyperclip plugin in Python programming language is to perform cross platform module for copying and pasting text to the clipboard. You can install python pyperclip module using the command as shown" }, { "code": null, "e": 2647, "s": 2624, "text": "pip install pyperclip\n" }, { "code": null, "e": 2731, "s": 2647, "text": "If the requirement already exists in the system, you can see the following output −" }, { "code": null, "e": 2841, "s": 2731, "text": "The python code for encrypting transposition cipher in which pyperclip is the main module is as shown below −" }, { "code": null, "e": 3357, "s": 2841, "text": "import pyperclip\ndef main():\n myMessage = 'Transposition Cipher'\n myKey = 10\n ciphertext = encryptMessage(myKey, myMessage)\n \n print(\"Cipher Text is\")\n print(ciphertext + '|')\n pyperclip.copy(ciphertext)\n\ndef encryptMessage(key, message):\n ciphertext = [''] * key\n \n for col in range(key):\n position = col\n while position < len(message):\n ciphertext[col] += message[position]\n\t\t\tposition += key\n return ''.join(ciphertext) #Cipher text\nif __name__ == '__main__':\n main()" }, { "code": null, "e": 3477, "s": 3357, "text": "The program code for encrypting transposition cipher in which pyperclip is the main module gives the following output −" }, { "code": null, "e": 3642, "s": 3477, "text": "The function main() calls the encryptMessage() which includes the procedure for splitting the characters using len function and iterating them in a columnar format." }, { "code": null, "e": 3807, "s": 3642, "text": "The function main() calls the encryptMessage() which includes the procedure for splitting the characters using len function and iterating them in a columnar format." }, { "code": null, "e": 3882, "s": 3807, "text": "The main function is initialized at the end to get the appropriate output." }, { "code": null, "e": 3957, "s": 3882, "text": "The main function is initialized at the end to get the appropriate output." }, { "code": null, "e": 3990, "s": 3957, "text": "\n 10 Lectures \n 2 hours \n" }, { "code": null, "e": 4006, "s": 3990, "text": " Total Seminars" }, { "code": null, "e": 4039, "s": 4006, "text": "\n 10 Lectures \n 2 hours \n" }, { "code": null, "e": 4062, "s": 4039, "text": " Stone River ELearning" }, { "code": null, "e": 4069, "s": 4062, "text": " Print" }, { "code": null, "e": 4080, "s": 4069, "text": " Add Notes" } ]
Stack.GetEnumerator Method in C#
04 Feb, 2019 This method returns an IEnumerator that iterates through the Stack. And it comes under the System.Collections namespace. Syntax: public virtual System.Collections.IEnumerator GetEnumerator (); Below programs illustrate the use of above-discussed method: Example 1: // C# program to illustrate the// Stack.GetEnumerator Methodusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Stack Stack myStack = new Stack(); // Inserting the elements into the Stack myStack.Push("Geeks"); myStack.Push("Geeks Classes"); myStack.Push("Noida"); myStack.Push("Data Structures"); myStack.Push("GeeksforGeeks"); // To get an Enumerator // for the Stack IEnumerator enumerator = myStack.GetEnumerator(); // If MoveNext passes the end of the // collection, the enumerator is positioned // after the last element in the Stack // and MoveNext returns false. while (enumerator.MoveNext()) { Console.WriteLine(enumerator.Current); } }} GeeksforGeeks Data Structures Noida Geeks Classes Geeks Example 2: // C# code to illustrate the// Stack.GetEnumerator Methodusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Stack Stack myStack = new Stack(); // Inserting the elements into the Stack myStack.Push(2); myStack.Push(3); myStack.Push(4); myStack.Push(5); myStack.Push(6); // To get an Enumerator // for the Stack IEnumerator enumerator = myStack.GetEnumerator(); // If MoveNext passes the end of the // collection, the enumerator is positioned // after the last element in the Stack // and MoveNext returns false. while (enumerator.MoveNext()) { Console.WriteLine(enumerator.Current); } }} 6 5 4 3 2 Note: The foreach statement of the C# language hides the complexity of the enumerators. Therefore, using foreach is recommended, instead of directly manipulating the enumerator. Enumerators can be used to read the data in the collection, but they cannot be used to modify the underlying collection. Current returns the same object until either MoveNext or Reset is called. MoveNext sets Current to the next element. An enumerator remains valid as long as the collection remains unchanged. If changes are made to the collection, such as adding, modifying, or deleting elements, the enumerator is irrecoverably invalidated and its behavior is undefined. This method is an O(1) operation. Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.stack.getenumerator?view=netframework-4.7.2 CSharp-Collections-Namespace CSharp-Collections-Stack CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Feb, 2019" }, { "code": null, "e": 149, "s": 28, "text": "This method returns an IEnumerator that iterates through the Stack. And it comes under the System.Collections namespace." }, { "code": null, "e": 157, "s": 149, "text": "Syntax:" }, { "code": null, "e": 221, "s": 157, "text": "public virtual System.Collections.IEnumerator GetEnumerator ();" }, { "code": null, "e": 282, "s": 221, "text": "Below programs illustrate the use of above-discussed method:" }, { "code": null, "e": 293, "s": 282, "text": "Example 1:" }, { "code": "// C# program to illustrate the// Stack.GetEnumerator Methodusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Stack Stack myStack = new Stack(); // Inserting the elements into the Stack myStack.Push(\"Geeks\"); myStack.Push(\"Geeks Classes\"); myStack.Push(\"Noida\"); myStack.Push(\"Data Structures\"); myStack.Push(\"GeeksforGeeks\"); // To get an Enumerator // for the Stack IEnumerator enumerator = myStack.GetEnumerator(); // If MoveNext passes the end of the // collection, the enumerator is positioned // after the last element in the Stack // and MoveNext returns false. while (enumerator.MoveNext()) { Console.WriteLine(enumerator.Current); } }}", "e": 1151, "s": 293, "text": null }, { "code": null, "e": 1208, "s": 1151, "text": "GeeksforGeeks\nData Structures\nNoida\nGeeks Classes\nGeeks\n" }, { "code": null, "e": 1219, "s": 1208, "text": "Example 2:" }, { "code": "// C# code to illustrate the// Stack.GetEnumerator Methodusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Stack Stack myStack = new Stack(); // Inserting the elements into the Stack myStack.Push(2); myStack.Push(3); myStack.Push(4); myStack.Push(5); myStack.Push(6); // To get an Enumerator // for the Stack IEnumerator enumerator = myStack.GetEnumerator(); // If MoveNext passes the end of the // collection, the enumerator is positioned // after the last element in the Stack // and MoveNext returns false. while (enumerator.MoveNext()) { Console.WriteLine(enumerator.Current); } }}", "e": 2018, "s": 1219, "text": null }, { "code": null, "e": 2029, "s": 2018, "text": "6\n5\n4\n3\n2\n" }, { "code": null, "e": 2035, "s": 2029, "text": "Note:" }, { "code": null, "e": 2207, "s": 2035, "text": "The foreach statement of the C# language hides the complexity of the enumerators. Therefore, using foreach is recommended, instead of directly manipulating the enumerator." }, { "code": null, "e": 2328, "s": 2207, "text": "Enumerators can be used to read the data in the collection, but they cannot be used to modify the underlying collection." }, { "code": null, "e": 2445, "s": 2328, "text": "Current returns the same object until either MoveNext or Reset is called. MoveNext sets Current to the next element." }, { "code": null, "e": 2681, "s": 2445, "text": "An enumerator remains valid as long as the collection remains unchanged. If changes are made to the collection, such as adding, modifying, or deleting elements, the enumerator is irrecoverably invalidated and its behavior is undefined." }, { "code": null, "e": 2715, "s": 2681, "text": "This method is an O(1) operation." }, { "code": null, "e": 2726, "s": 2715, "text": "Reference:" }, { "code": null, "e": 2833, "s": 2726, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.stack.getenumerator?view=netframework-4.7.2" }, { "code": null, "e": 2862, "s": 2833, "text": "CSharp-Collections-Namespace" }, { "code": null, "e": 2887, "s": 2862, "text": "CSharp-Collections-Stack" }, { "code": null, "e": 2901, "s": 2887, "text": "CSharp-method" }, { "code": null, "e": 2904, "s": 2901, "text": "C#" } ]
Explain Event-Driven Programming in Node.js
19 Oct, 2021 Event-Driven Programming in Node.js: Node.js makes extensive use of events which is one of the reasons behind its speed when compared to other similar technologies. Once we start a Node.js server, it initializes the variables and functions and then listens for the occurrence of an event. Event-driven programming is used to synchronize the occurrence of multiple events and to make the program as simple as possible. The basic components of an Event-Driven Program are: A callback function ( called an event handler) is called when an event is triggered. An event loop that listens for event triggers and calls the corresponding event handler for that event. A function that listens for the triggering of an event is said to be an ‘Observer’. It gets triggered when an event occurs. Node.js provides a range of events that are already in-built. These ‘events’ can be accessed via the ‘events’ module and the EventEmitter class. Most of the in-built modules of Node.js inherit from the EventEmitter class EventEmitter: The EventEmitter is a Node module that allows objects to communicate with one another. The core of Node’s asynchronous event-driven architecture is EventEmitter. Many of Node’s built-in modules inherit from EventEmitter. The idea is simple – emitter objects send out named events, which trigger listeners that have already been registered. Hence, an emitter object has two key characteristics: Emitting name events: The signal that something has happened is called emitting an event. A status change in the emitting object is often the cause of this condition. Registering and unregistering listener functions: It refers to the binding and unbinding of the callback functions with their corresponding events. Event-Driven Programming Principles: A suite of functions for handling the events. These can be either blocking or non-blocking, depending on the implementation. Binding registered functions to events. When a registered event is received, an event loop polls for new events and calls the matching event handler(s). Implementation: Filename: app.js Javascript // Import the 'events' moduleconst events = require('events'); // Instantiate an EventEmitter objectconst eventEmitter = new events.EventEmitter(); // Handler associated with the eventconst connectHandler = function connected() { console.log('Connection established.'); // Trigger the corresponding event eventEmitter.emit('data_received');} // Binds the event with handlereventEmitter.on('connection', connectHandler); // Binds the data receivedeventEmitter.on( 'data_received', function () { console.log('Data Transfer Successful.'); }); // Trigger the connection eventeventEmitter.emit('connection'); console.log("Finish"); The above code snippet binds the handler named ‘connectHandler’ with the event ‘connection’’. The callback function is triggered when the event is emitted. Run the app.js file using the following command: node app.js Output: Connection established. Data Transfer Successful. Finish Advantages of Event-Driven Programming: Flexibility: It is easier to alter sections of code as and when required. Suitability for graphical interfaces: It allows the user to select tools (like radio buttons etc.) directly from the toolbar Programming simplicity: It supports predictive coding, which improves the programmer’s coding experience. Easy to find natural dividing lines: Natural dividing lines for unit testing infrastructure are easy to come by. A good way to model systems: Useful method for modeling systems that must be asynchronous and reactive. Allows for more interactive programs: It enables more interactive programming. Event-driven programming is used in almost all recent GUI apps. Using hardware interrupts: It can be accomplished via hardware interrupts, lowering the computer’s power consumption. Allows sensors and other hardware: It makes it simple for sensors and other hardware to communicate with software. Disadvantages of Event-Driven Programming: Complex: Simple programs become unnecessarily complex. Less logical and obvious: The flow of the program is usually less logical and more obvious Difficult to find error: Debugging an event-driven program is difficult Confusing: Too many forms in a program might be confusing and/or frustrating for the programmer. Tight coupling: The event schema will be tightly coupled with the consumers of the schema. Blocking: Complex blocking of operations. Relation between Event-Driven Programming and Object-Oriented Programming: We can combine Object-oriented Programming (OOP) and Event-driven programming (EDP) and use them together in the same code snippet. When OOP is used with EDP: All OOP fundamentals (encapsulation, inheritance, and polymorphism) are preserved. Objects get the ability to post-event notifications and subscribe to event notifications from other objects. How to distinguish between OOP with and without EDP: The control flow between objects is the distinction between OOP with and without EDP. On a method call in OOP without EDP, control flows from one object to another. The primary function of an object is to call the methods of other objects. However, on event notification, control in OOP with EDP moves from one object to another. Object subscribes to notifications from other objects, waits for notifications from those objects, performs work based on the notification, and then publishes its own notifications. NodeJS-Questions Picked TrueGeek-2021 Node.js TrueGeek Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n19 Oct, 2021" }, { "code": null, "e": 342, "s": 53, "text": "Event-Driven Programming in Node.js: Node.js makes extensive use of events which is one of the reasons behind its speed when compared to other similar technologies. Once we start a Node.js server, it initializes the variables and functions and then listens for the occurrence of an event." }, { "code": null, "e": 524, "s": 342, "text": "Event-driven programming is used to synchronize the occurrence of multiple events and to make the program as simple as possible. The basic components of an Event-Driven Program are:" }, { "code": null, "e": 609, "s": 524, "text": "A callback function ( called an event handler) is called when an event is triggered." }, { "code": null, "e": 713, "s": 609, "text": "An event loop that listens for event triggers and calls the corresponding event handler for that event." }, { "code": null, "e": 1058, "s": 713, "text": "A function that listens for the triggering of an event is said to be an ‘Observer’. It gets triggered when an event occurs. Node.js provides a range of events that are already in-built. These ‘events’ can be accessed via the ‘events’ module and the EventEmitter class. Most of the in-built modules of Node.js inherit from the EventEmitter class" }, { "code": null, "e": 1293, "s": 1058, "text": "EventEmitter: The EventEmitter is a Node module that allows objects to communicate with one another. The core of Node’s asynchronous event-driven architecture is EventEmitter. Many of Node’s built-in modules inherit from EventEmitter." }, { "code": null, "e": 1466, "s": 1293, "text": "The idea is simple – emitter objects send out named events, which trigger listeners that have already been registered. Hence, an emitter object has two key characteristics:" }, { "code": null, "e": 1633, "s": 1466, "text": "Emitting name events: The signal that something has happened is called emitting an event. A status change in the emitting object is often the cause of this condition." }, { "code": null, "e": 1781, "s": 1633, "text": "Registering and unregistering listener functions: It refers to the binding and unbinding of the callback functions with their corresponding events." }, { "code": null, "e": 1818, "s": 1781, "text": "Event-Driven Programming Principles:" }, { "code": null, "e": 1943, "s": 1818, "text": "A suite of functions for handling the events. These can be either blocking or non-blocking, depending on the implementation." }, { "code": null, "e": 1983, "s": 1943, "text": "Binding registered functions to events." }, { "code": null, "e": 2096, "s": 1983, "text": "When a registered event is received, an event loop polls for new events and calls the matching event handler(s)." }, { "code": null, "e": 2130, "s": 2096, "text": "Implementation: Filename: app.js" }, { "code": null, "e": 2141, "s": 2130, "text": "Javascript" }, { "code": "// Import the 'events' moduleconst events = require('events'); // Instantiate an EventEmitter objectconst eventEmitter = new events.EventEmitter(); // Handler associated with the eventconst connectHandler = function connected() { console.log('Connection established.'); // Trigger the corresponding event eventEmitter.emit('data_received');} // Binds the event with handlereventEmitter.on('connection', connectHandler); // Binds the data receivedeventEmitter.on( 'data_received', function () { console.log('Data Transfer Successful.'); }); // Trigger the connection eventeventEmitter.emit('connection'); console.log(\"Finish\");", "e": 2798, "s": 2141, "text": null }, { "code": null, "e": 2954, "s": 2798, "text": "The above code snippet binds the handler named ‘connectHandler’ with the event ‘connection’’. The callback function is triggered when the event is emitted." }, { "code": null, "e": 3003, "s": 2954, "text": "Run the app.js file using the following command:" }, { "code": null, "e": 3015, "s": 3003, "text": "node app.js" }, { "code": null, "e": 3025, "s": 3015, "text": "Output: " }, { "code": null, "e": 3082, "s": 3025, "text": "Connection established.\nData Transfer Successful.\nFinish" }, { "code": null, "e": 3122, "s": 3082, "text": "Advantages of Event-Driven Programming:" }, { "code": null, "e": 3196, "s": 3122, "text": "Flexibility: It is easier to alter sections of code as and when required." }, { "code": null, "e": 3321, "s": 3196, "text": "Suitability for graphical interfaces: It allows the user to select tools (like radio buttons etc.) directly from the toolbar" }, { "code": null, "e": 3427, "s": 3321, "text": "Programming simplicity: It supports predictive coding, which improves the programmer’s coding experience." }, { "code": null, "e": 3540, "s": 3427, "text": "Easy to find natural dividing lines: Natural dividing lines for unit testing infrastructure are easy to come by." }, { "code": null, "e": 3644, "s": 3540, "text": "A good way to model systems: Useful method for modeling systems that must be asynchronous and reactive." }, { "code": null, "e": 3787, "s": 3644, "text": "Allows for more interactive programs: It enables more interactive programming. Event-driven programming is used in almost all recent GUI apps." }, { "code": null, "e": 3905, "s": 3787, "text": "Using hardware interrupts: It can be accomplished via hardware interrupts, lowering the computer’s power consumption." }, { "code": null, "e": 4020, "s": 3905, "text": "Allows sensors and other hardware: It makes it simple for sensors and other hardware to communicate with software." }, { "code": null, "e": 4063, "s": 4020, "text": "Disadvantages of Event-Driven Programming:" }, { "code": null, "e": 4118, "s": 4063, "text": "Complex: Simple programs become unnecessarily complex." }, { "code": null, "e": 4209, "s": 4118, "text": "Less logical and obvious: The flow of the program is usually less logical and more obvious" }, { "code": null, "e": 4281, "s": 4209, "text": "Difficult to find error: Debugging an event-driven program is difficult" }, { "code": null, "e": 4378, "s": 4281, "text": "Confusing: Too many forms in a program might be confusing and/or frustrating for the programmer." }, { "code": null, "e": 4469, "s": 4378, "text": "Tight coupling: The event schema will be tightly coupled with the consumers of the schema." }, { "code": null, "e": 4511, "s": 4469, "text": "Blocking: Complex blocking of operations." }, { "code": null, "e": 4718, "s": 4511, "text": "Relation between Event-Driven Programming and Object-Oriented Programming: We can combine Object-oriented Programming (OOP) and Event-driven programming (EDP) and use them together in the same code snippet." }, { "code": null, "e": 4747, "s": 4718, "text": "When OOP is used with EDP: " }, { "code": null, "e": 4830, "s": 4747, "text": "All OOP fundamentals (encapsulation, inheritance, and polymorphism) are preserved." }, { "code": null, "e": 4939, "s": 4830, "text": "Objects get the ability to post-event notifications and subscribe to event notifications from other objects." }, { "code": null, "e": 5232, "s": 4939, "text": "How to distinguish between OOP with and without EDP: The control flow between objects is the distinction between OOP with and without EDP. On a method call in OOP without EDP, control flows from one object to another. The primary function of an object is to call the methods of other objects." }, { "code": null, "e": 5504, "s": 5232, "text": "However, on event notification, control in OOP with EDP moves from one object to another. Object subscribes to notifications from other objects, waits for notifications from those objects, performs work based on the notification, and then publishes its own notifications." }, { "code": null, "e": 5521, "s": 5504, "text": "NodeJS-Questions" }, { "code": null, "e": 5528, "s": 5521, "text": "Picked" }, { "code": null, "e": 5542, "s": 5528, "text": "TrueGeek-2021" }, { "code": null, "e": 5550, "s": 5542, "text": "Node.js" }, { "code": null, "e": 5559, "s": 5550, "text": "TrueGeek" }, { "code": null, "e": 5576, "s": 5559, "text": "Web Technologies" } ]
Working Storage Section in COBOL
22 Sep, 2021 Cobol is a high-level language, which has its own compiler. The COBOL compiler translates the COBOL program into an object program, which is finally executed. To execute the COBOL program without any error, these divisions must be written in the order in which they are specified below: In this division, we write the details about the program like author name, date of execution, date of writing the code, etc. Syntax: IDENTIFICATION DIVISION. PROGRAM-ID. Entry [AUTHOR. Entry]. [INSTALLATION Entry]. [DATE-WRITTEN. Entry]. [DATA-COMPILED. Entry]. [SECURITY. Entry. [REMARKS. Entry.] In this division, we write the details about the computer environment in which the program has been written and executed. Syntax: ENVIRONMENT DIVISION. CONFIGURATION SECTION. SOURCE-COMPUTER. Source-computer-entry. OBJECT-COMPUTER. Object-computer-entry. [SPECIAL NAMES. Special-computer-entry.] INPUT-OUTPUT SECTION. FILE CONTROL. File-control-entry. [I-O CONTROL. Input-output-control-entry]. In this division, we declare the variables, their data type, size, usage type, etc. which are to be used in the program. It is the most important division in the COBOL program structure. Syntax: DATA DIVISION. FILE SECTION. File-section-entry. WORKING-STORAGE SECTION. Variables. LINKAGE SECTION.[Linkage-section-entry]. REPORT SECTION. In this division, the executable COBOL statements, i.e. the main program code is written. It must contain at least one statement. To stop the execution of the program we write STOP (in case of calling program) or EXIT (in case of called program). Syntax: PROCEDURE DIVISION[USING DATA-NAME1[,DATA-NAME2,...]]. WORKING-STORAGE SECTION is declared under the DATA DIVISION in COBOL structure. It must be declared with the heading WORKING-STORAGE SECTION with a separator period(.). It is one of the most important sections in Cobol programming because we declare all the variables and file structures, their types, size, etc in this section. The variables declared in the section can be assigned values at the time of declaration as well as during the flow of the program. We use level 77 to declare elementary variables and level 01 to 49 for grouped variables. In this section, we also define the record description entries which are not part of the record but are used to write records into the file. The memory is allocated to all the variables and file structures declared in WORKING-STORAGE SECTION at the time of execution of the program and is deallocated as soon as the program ends. The variables declared within this section can only be used inside the program and not outside the program. Syntax: DATA DIVISION. WORKING-STORAGE SECTION. Record-description-entries. Variable-description-entries. Example: Cobol IDENTIFICATION DIVISION.PROGRAM-ID. HELLOWORD.ENVIRONMENT DIVISION.DATA DIVISION. WORKING-STORAGE SECTION. 77 VARIABLE1 PIC 99. 77 VARIABLE2 PIC A. 01 GROUPEDATA. 02 GROUPVAR1 PIC 99. 02 GROUPVAR2 PIC A(5).PROCEDURE DIVISION.DISPLAY "WELCOME To GEEKSFORGEEKS".STOP RUN. Output: WELCOME To GEEKSFORGEEKS Explanation: In the above-given example code, we have shown the declaration of variables in the WORKING-STORAGE SECTION. VARIABLE1 and VARIABLE2 are the Elementary data with integer data type and character data type respectively and GROUPEDATA is the Grouped data with level 01 and 02. Grouped data are used to declare structures like arrays. Now observe clearly, we have written WORKING-STORAGE SECTION with a separator period, under DATA DIVISION. Blogathon-2021 COBOL-Basics Picked Blogathon COBOL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Sep, 2021" }, { "code": null, "e": 188, "s": 28, "text": "Cobol is a high-level language, which has its own compiler. The COBOL compiler translates the COBOL program into an object program, which is finally executed. " }, { "code": null, "e": 316, "s": 188, "text": "To execute the COBOL program without any error, these divisions must be written in the order in which they are specified below:" }, { "code": null, "e": 442, "s": 316, "text": " In this division, we write the details about the program like author name, date of execution, date of writing the code, etc." }, { "code": null, "e": 450, "s": 442, "text": "Syntax:" }, { "code": null, "e": 615, "s": 450, "text": "IDENTIFICATION DIVISION.\nPROGRAM-ID. Entry\n[AUTHOR. Entry].\n[INSTALLATION Entry].\n[DATE-WRITTEN. Entry].\n[DATA-COMPILED. Entry].\n[SECURITY. Entry.\n[REMARKS. Entry.]" }, { "code": null, "e": 738, "s": 615, "text": " In this division, we write the details about the computer environment in which the program has been written and executed." }, { "code": null, "e": 746, "s": 738, "text": "Syntax:" }, { "code": null, "e": 1011, "s": 746, "text": "ENVIRONMENT DIVISION.\nCONFIGURATION SECTION.\nSOURCE-COMPUTER. Source-computer-entry.\nOBJECT-COMPUTER. Object-computer-entry.\n[SPECIAL NAMES. Special-computer-entry.]\nINPUT-OUTPUT SECTION.\nFILE CONTROL. File-control-entry.\n[I-O CONTROL. Input-output-control-entry]." }, { "code": null, "e": 1198, "s": 1011, "text": "In this division, we declare the variables, their data type, size, usage type, etc. which are to be used in the program. It is the most important division in the COBOL program structure." }, { "code": null, "e": 1206, "s": 1198, "text": "Syntax:" }, { "code": null, "e": 1348, "s": 1206, "text": "DATA DIVISION.\nFILE SECTION. File-section-entry.\nWORKING-STORAGE SECTION. Variables.\nLINKAGE SECTION.[Linkage-section-entry].\nREPORT SECTION." }, { "code": null, "e": 1595, "s": 1348, "text": "In this division, the executable COBOL statements, i.e. the main program code is written. It must contain at least one statement. To stop the execution of the program we write STOP (in case of calling program) or EXIT (in case of called program)." }, { "code": null, "e": 1603, "s": 1595, "text": "Syntax:" }, { "code": null, "e": 1659, "s": 1603, "text": "PROCEDURE DIVISION[USING DATA-NAME1[,DATA-NAME2,...]]. " }, { "code": null, "e": 1739, "s": 1659, "text": "WORKING-STORAGE SECTION is declared under the DATA DIVISION in COBOL structure." }, { "code": null, "e": 1828, "s": 1739, "text": "It must be declared with the heading WORKING-STORAGE SECTION with a separator period(.)." }, { "code": null, "e": 1988, "s": 1828, "text": "It is one of the most important sections in Cobol programming because we declare all the variables and file structures, their types, size, etc in this section." }, { "code": null, "e": 2119, "s": 1988, "text": "The variables declared in the section can be assigned values at the time of declaration as well as during the flow of the program." }, { "code": null, "e": 2209, "s": 2119, "text": "We use level 77 to declare elementary variables and level 01 to 49 for grouped variables." }, { "code": null, "e": 2350, "s": 2209, "text": "In this section, we also define the record description entries which are not part of the record but are used to write records into the file." }, { "code": null, "e": 2539, "s": 2350, "text": "The memory is allocated to all the variables and file structures declared in WORKING-STORAGE SECTION at the time of execution of the program and is deallocated as soon as the program ends." }, { "code": null, "e": 2647, "s": 2539, "text": "The variables declared within this section can only be used inside the program and not outside the program." }, { "code": null, "e": 2655, "s": 2647, "text": "Syntax:" }, { "code": null, "e": 2753, "s": 2655, "text": "DATA DIVISION.\nWORKING-STORAGE SECTION.\nRecord-description-entries.\nVariable-description-entries." }, { "code": null, "e": 2762, "s": 2753, "text": "Example:" }, { "code": null, "e": 2768, "s": 2762, "text": "Cobol" }, { "code": "IDENTIFICATION DIVISION.PROGRAM-ID. HELLOWORD.ENVIRONMENT DIVISION.DATA DIVISION. WORKING-STORAGE SECTION. 77 VARIABLE1 PIC 99. 77 VARIABLE2 PIC A. 01 GROUPEDATA. 02 GROUPVAR1 PIC 99. 02 GROUPVAR2 PIC A(5).PROCEDURE DIVISION.DISPLAY \"WELCOME To GEEKSFORGEEKS\".STOP RUN.", "e": 3076, "s": 2768, "text": null }, { "code": null, "e": 3084, "s": 3076, "text": "Output:" }, { "code": null, "e": 3109, "s": 3084, "text": "WELCOME To GEEKSFORGEEKS" }, { "code": null, "e": 3122, "s": 3109, "text": "Explanation:" }, { "code": null, "e": 3560, "s": 3122, "text": "In the above-given example code, we have shown the declaration of variables in the WORKING-STORAGE SECTION. VARIABLE1 and VARIABLE2 are the Elementary data with integer data type and character data type respectively and GROUPEDATA is the Grouped data with level 01 and 02. Grouped data are used to declare structures like arrays. Now observe clearly, we have written WORKING-STORAGE SECTION with a separator period, under DATA DIVISION. " }, { "code": null, "e": 3575, "s": 3560, "text": "Blogathon-2021" }, { "code": null, "e": 3588, "s": 3575, "text": "COBOL-Basics" }, { "code": null, "e": 3595, "s": 3588, "text": "Picked" }, { "code": null, "e": 3605, "s": 3595, "text": "Blogathon" }, { "code": null, "e": 3611, "s": 3605, "text": "COBOL" } ]
How to Pass Arguments to Tkinter Button Command?
11 Aug, 2021 Tkinter is the standard GUI library for Python. Tkinter is the Python interface to the Tk GUI toolkit shipped with Python. It provides a robust and platform independent windowing toolkit, that is available to Python programmers using this package. Python when combined with Tkinter provides a fast and easy way to create GUI applications. Tkinter provides a powerful object-oriented interface to the Tk GUI toolkit. Import tkinter package. Create a root window. Give the root window a title(using title()) and dimension(using geometry()). Create a button using (Button()). Use mainloop() to call the endless loop of the window. These steps remain same for both methods, only thing that has to be changed is how to apply these two methods. Method 1: Using lambda function Python3 # importing tkinterimport tkinter as tk # defining function def func(args): print(args) # create root windowroot = tk.Tk() # root window title and dimensionroot.title("Welcome to GeekForGeeks")root.geometry("380x400") # creating buttonbtn = tk.Button(root, text="Press", command=lambda: func("See this worked!"))btn.pack() # running the main looproot.mainloop() Output: using lambda Method 2: Using partial Python3 # importing necessary librariesfrom functools import partialimport tkinter as tk # defining function def function_name(func): print(func) # creating root windowroot = tk.Tk() # root window title and dimensionroot.title("Welcome to GeekForGeeks")root.geometry("380x400") # creating buttonbtn = tk.Button(root, text="Click Me", command=partial( function_name, "Thanks, Geeks for Geeks !!!"))btn.pack() # running the main looproot.mainloop() Output: using partial adnanirshad158 Python-tkinter Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n11 Aug, 2021" }, { "code": null, "e": 468, "s": 52, "text": "Tkinter is the standard GUI library for Python. Tkinter is the Python interface to the Tk GUI toolkit shipped with Python. It provides a robust and platform independent windowing toolkit, that is available to Python programmers using this package. Python when combined with Tkinter provides a fast and easy way to create GUI applications. Tkinter provides a powerful object-oriented interface to the Tk GUI toolkit." }, { "code": null, "e": 492, "s": 468, "text": "Import tkinter package." }, { "code": null, "e": 591, "s": 492, "text": "Create a root window. Give the root window a title(using title()) and dimension(using geometry())." }, { "code": null, "e": 625, "s": 591, "text": "Create a button using (Button())." }, { "code": null, "e": 680, "s": 625, "text": "Use mainloop() to call the endless loop of the window." }, { "code": null, "e": 791, "s": 680, "text": "These steps remain same for both methods, only thing that has to be changed is how to apply these two methods." }, { "code": null, "e": 823, "s": 791, "text": "Method 1: Using lambda function" }, { "code": null, "e": 831, "s": 823, "text": "Python3" }, { "code": "# importing tkinterimport tkinter as tk # defining function def func(args): print(args) # create root windowroot = tk.Tk() # root window title and dimensionroot.title(\"Welcome to GeekForGeeks\")root.geometry(\"380x400\") # creating buttonbtn = tk.Button(root, text=\"Press\", command=lambda: func(\"See this worked!\"))btn.pack() # running the main looproot.mainloop()", "e": 1198, "s": 831, "text": null }, { "code": null, "e": 1206, "s": 1198, "text": "Output:" }, { "code": null, "e": 1219, "s": 1206, "text": "using lambda" }, { "code": null, "e": 1244, "s": 1219, "text": "Method 2: Using partial " }, { "code": null, "e": 1252, "s": 1244, "text": "Python3" }, { "code": "# importing necessary librariesfrom functools import partialimport tkinter as tk # defining function def function_name(func): print(func) # creating root windowroot = tk.Tk() # root window title and dimensionroot.title(\"Welcome to GeekForGeeks\")root.geometry(\"380x400\") # creating buttonbtn = tk.Button(root, text=\"Click Me\", command=partial( function_name, \"Thanks, Geeks for Geeks !!!\"))btn.pack() # running the main looproot.mainloop()", "e": 1699, "s": 1252, "text": null }, { "code": null, "e": 1707, "s": 1699, "text": "Output:" }, { "code": null, "e": 1721, "s": 1707, "text": "using partial" }, { "code": null, "e": 1736, "s": 1721, "text": "adnanirshad158" }, { "code": null, "e": 1751, "s": 1736, "text": "Python-tkinter" }, { "code": null, "e": 1775, "s": 1751, "text": "Technical Scripter 2020" }, { "code": null, "e": 1782, "s": 1775, "text": "Python" }, { "code": null, "e": 1801, "s": 1782, "text": "Technical Scripter" } ]
Hamiltonian Path ( Using Dynamic Programming )
31 May, 2021 Given an adjacency matrix adj[][] of an undirected graph consisting of N vertices, the task is to find whether the graph contains a Hamiltonian Path or not. If found to be true, then print “Yes”. Otherwise, print “No”. A Hamiltonian path is defined as the path in a directed or undirected graph which visits each and every vertex of the graph exactly once. Examples: Input: adj[][] = {{0, 1, 1, 1, 0}, {1, 0, 1, 0, 1}, {1, 1, 0, 1, 1}, {1, 0, 1, 0, 0}}Output: YesExplanation:There exists a Hamiltonian Path for the given graph as shown in the image below: Input: adj[][] = {{0, 1, 0, 0}, {1, 0, 1, 1}, {0, 1, 0, 0}, {0, 1, 0, 0}}Output: No Naive Approach: The simplest approach to solve the given problem is to generate all the possible permutations of N vertices. For each permutation, check if it is a valid Hamiltonian path by checking if there is an edge between adjacent vertices or not. If found to be true, then print “Yes”. Otherwise, print “No”. Time Complexity: O(N * N!)Auxiliary Space: O(1) Efficient Approach: The above approach can be optimized by using Dynamic Programming and Bit Masking which is based on the following observations: The idea is such that for every subset S of vertices, check whether there is a hamiltonian path in the subset S that ends at vertex v where v € S. If v has a neighbor u, where u € S – {v}, therefore, there exists a Hamiltonian path that ends at vertex u. The problem can be solved by generalizing the subset of vertices and the ending vertex of the Hamiltonian path. Follow the steps below to solve the problem: Initialize a boolean matrix dp[][] in dimension N*2N where dp[j ][i] represents whether there exists a path in the subset or not represented by the mask i that visits each and every vertex in i once and ends at vertex j. For the base case, update dp[i][1 << i] = true, for i in range [0, N – 1] Iterate over the range [1, 2N – 1] using the variable i and perform the following steps:All the vertices with bits set in mask i, are included in the subset.Iterate over the range [1, N] using the variable j that will represent the end vertex of the hamiltonian path of current subset mask i and perform the following steps:If the value of i and 2j is true, then iterate over the range [1, N] using the variable k and if the value of dp[k][i^2j] is true, then mark dp[j][i] is true and break out of the loop.Otherwise, continue to the next iteration. All the vertices with bits set in mask i, are included in the subset. Iterate over the range [1, N] using the variable j that will represent the end vertex of the hamiltonian path of current subset mask i and perform the following steps:If the value of i and 2j is true, then iterate over the range [1, N] using the variable k and if the value of dp[k][i^2j] is true, then mark dp[j][i] is true and break out of the loop.Otherwise, continue to the next iteration. If the value of i and 2j is true, then iterate over the range [1, N] using the variable k and if the value of dp[k][i^2j] is true, then mark dp[j][i] is true and break out of the loop. Otherwise, continue to the next iteration. Iterate over the range using the variable i and if the value of dp[i][2N – 1] is true, then there exists a hamiltonian path ending at vertex i. Therefore, print “Yes”. Otherwise, print “No”. 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;const int N = 5; // Function to check whether there// exists a Hamiltonian Path or notbool Hamiltonian_path( vector<vector<int> >& adj, int N){ int dp[N][(1 << N)]; // Initialize the table memset(dp, 0, sizeof dp); // Set all dp[i][(1 << i)] to // true for (int i = 0; i < N; i++) dp[i][(1 << i)] = true; // Iterate over each subset // of nodes for (int i = 0; i < (1 << N); i++) { for (int j = 0; j < N; j++) { // If the jth nodes is included // in the current subset if (i & (1 << j)) { // Find K, neighbour of j // also present in the // current subset for (int k = 0; k < N; k++) { if (i & (1 << k) && adj[k][j] && j != k && dp[k][i ^ (1 << j)]) { // Update dp[j][i] // to true dp[j][i] = true; break; } } } } } // Traverse the vertices for (int i = 0; i < N; i++) { // Hamiltonian Path exists if (dp[i][(1 << N) - 1]) return true; } // Otherwise, return false return false;} // Driver Codeint main(){ // Input vector<vector<int> > adj = { { 0, 1, 1, 1, 0 }, { 1, 0, 1, 0, 1 }, { 1, 1, 0, 1, 1 }, { 1, 0, 1, 0, 0 } }; int N = adj.size(); // Function Call if (Hamiltonian_path(adj, N)) cout << "YES"; else cout << "NO"; return 0;} // Java program for the above approachimport java.io.*;import java.lang.*;import java.util.*; class GFG{ // Function to check whether there// exists a Hamiltonian Path or notstatic boolean Hamiltonian_path(int adj[][], int N){ boolean dp[][] = new boolean[N][(1 << N)]; // Set all dp[i][(1 << i)] to // true for(int i = 0; i < N; i++) dp[i][(1 << i)] = true; // Iterate over each subset // of nodes for(int i = 0; i < (1 << N); i++) { for(int j = 0; j < N; j++) { // If the jth nodes is included // in the current subset if ((i & (1 << j)) != 0) { // Find K, neighbour of j // also present in the // current subset for(int k = 0; k < N; k++) { if ((i & (1 << k)) != 0 && adj[k][j] == 1 && j != k && dp[k][i ^ (1 << j)]) { // Update dp[j][i] // to true dp[j][i] = true; break; } } } } } // Traverse the vertices for(int i = 0; i < N; i++) { // Hamiltonian Path exists if (dp[i][(1 << N) - 1]) return true; } // Otherwise, return false return false;} // Driver Codepublic static void main(String[] args){ int adj[][] = { { 0, 1, 1, 1, 0 }, { 1, 0, 1, 0, 1 }, { 1, 1, 0, 1, 1 }, { 1, 0, 1, 0, 0 } }; int N = adj.length; // Function Call if (Hamiltonian_path(adj, N)) System.out.println("YES"); else System.out.println("NO");}} // This code is contributed by Kingash # Python3 program for the above approach # Function to check whether there# exists a Hamiltonian Path or notdef Hamiltonian_path(adj, N): dp = [[False for i in range(1 << N)] for j in range(N)] # Set all dp[i][(1 << i)] to # true for i in range(N): dp[i][1 << i] = True # Iterate over each subset # of nodes for i in range(1 << N): for j in range(N): # If the jth nodes is included # in the current subset if ((i & (1 << j)) != 0): # Find K, neighbour of j # also present in the # current subset for k in range(N): if ((i & (1 << k)) != 0 and adj[k][j] == 1 and j != k and dp[k][i ^ (1 << j)]): # Update dp[j][i] # to true dp[j][i] = True break # Traverse the vertices for i in range(N): # Hamiltonian Path exists if (dp[i][(1 << N) - 1]): return True # Otherwise, return false return False # Driver Codeadj = [ [ 0, 1, 1, 1, 0 ] , [ 1, 0, 1, 0, 1 ], [ 1, 1, 0, 1, 1 ], [ 1, 0, 1, 0, 0 ] ] N = len(adj) if (Hamiltonian_path(adj, N)): print("YES")else: print("NO") # This code is contributed by maheshwaripiyush9 // C# program for the above approachusing System; class GFG{ // Function to check whether there// exists a Hamiltonian Path or notstatic bool Hamiltonian_path(int[,] adj, int N){ bool[,] dp = new bool[N, (1 << N)]; // Set all dp[i][(1 << i)] to // true for(int i = 0; i < N; i++) dp[i, (1 << i)] = true; // Iterate over each subset // of nodes for(int i = 0; i < (1 << N); i++) { for(int j = 0; j < N; j++) { // If the jth nodes is included // in the current subset if ((i & (1 << j)) != 0) { // Find K, neighbour of j // also present in the // current subset for(int k = 0; k < N; k++) { if ((i & (1 << k)) != 0 && adj[k, j] == 1 && j != k && dp[k, i ^ (1 << j)]) { // Update dp[j][i] // to true dp[j, i] = true; break; } } } } } // Traverse the vertices for(int i = 0; i < N; i++) { // Hamiltonian Path exists if (dp[i, (1 << N) - 1]) return true; } // Otherwise, return false return false;} // Driver Codepublic static void Main(String[] args){ int[,] adj = { { 0, 1, 1, 1, 0 }, { 1, 0, 1, 0, 1 }, { 1, 1, 0, 1, 1 }, { 1, 0, 1, 0, 0 } }; int N = adj.GetLength(0); // Function Call if (Hamiltonian_path(adj, N)) Console.WriteLine("YES"); else Console.WriteLine("NO");}} // This code is contributed by ukasp <script> // Javascript program for the above approachvar N = 5; // Function to check whether there// exists a Hamiltonian Path or notfunction Hamiltonian_path( adj, N){ var dp = Array.from(Array(N), ()=> Array(1 << N).fill(0)); // Set all dp[i][(1 << i)] to // true for (var i = 0; i < N; i++) dp[i][(1 << i)] = true; // Iterate over each subset // of nodes for (var i = 0; i < (1 << N); i++) { for (var j = 0; j < N; j++) { // If the jth nodes is included // in the current subset if (i & (1 << j)) { // Find K, neighbour of j // also present in the // current subset for (var k = 0; k < N; k++) { if (i & (1 << k) && adj[k][j] && j != k && dp[k][i ^ (1 << j)]) { // Update dp[j][i] // to true dp[j][i] = true; break; } } } } } // Traverse the vertices for (var i = 0; i < N; i++) { // Hamiltonian Path exists if (dp[i][(1 << N) - 1]) return true; } // Otherwise, return false return false;} // Driver Code// Inputvar adj = [ [ 0, 1, 1, 1, 0 ], [ 1, 0, 1, 0, 1 ], [ 1, 1, 0, 1, 1 ], [ 1, 0, 1, 0, 0 ] ];var N = adj.length;// Function Callif (Hamiltonian_path(adj, N)) document.write( "YES");else document.write( "NO"); </script> YES Time Complexity: O(N * 2N)Auxiliary Space: O(N * 2N) Kingash maheswaripiyush9 ukasp rrrtnx subset Bit Magic Dynamic Programming Graph Matrix Dynamic Programming Bit Magic Matrix subset Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n31 May, 2021" }, { "code": null, "e": 273, "s": 54, "text": "Given an adjacency matrix adj[][] of an undirected graph consisting of N vertices, the task is to find whether the graph contains a Hamiltonian Path or not. If found to be true, then print “Yes”. Otherwise, print “No”." }, { "code": null, "e": 411, "s": 273, "text": "A Hamiltonian path is defined as the path in a directed or undirected graph which visits each and every vertex of the graph exactly once." }, { "code": null, "e": 421, "s": 411, "text": "Examples:" }, { "code": null, "e": 610, "s": 421, "text": "Input: adj[][] = {{0, 1, 1, 1, 0}, {1, 0, 1, 0, 1}, {1, 1, 0, 1, 1}, {1, 0, 1, 0, 0}}Output: YesExplanation:There exists a Hamiltonian Path for the given graph as shown in the image below:" }, { "code": null, "e": 694, "s": 610, "text": "Input: adj[][] = {{0, 1, 0, 0}, {1, 0, 1, 1}, {0, 1, 0, 0}, {0, 1, 0, 0}}Output: No" }, { "code": null, "e": 1009, "s": 694, "text": "Naive Approach: The simplest approach to solve the given problem is to generate all the possible permutations of N vertices. For each permutation, check if it is a valid Hamiltonian path by checking if there is an edge between adjacent vertices or not. If found to be true, then print “Yes”. Otherwise, print “No”." }, { "code": null, "e": 1057, "s": 1009, "text": "Time Complexity: O(N * N!)Auxiliary Space: O(1)" }, { "code": null, "e": 1204, "s": 1057, "text": "Efficient Approach: The above approach can be optimized by using Dynamic Programming and Bit Masking which is based on the following observations:" }, { "code": null, "e": 1351, "s": 1204, "text": "The idea is such that for every subset S of vertices, check whether there is a hamiltonian path in the subset S that ends at vertex v where v € S." }, { "code": null, "e": 1459, "s": 1351, "text": "If v has a neighbor u, where u € S – {v}, therefore, there exists a Hamiltonian path that ends at vertex u." }, { "code": null, "e": 1571, "s": 1459, "text": "The problem can be solved by generalizing the subset of vertices and the ending vertex of the Hamiltonian path." }, { "code": null, "e": 1616, "s": 1571, "text": "Follow the steps below to solve the problem:" }, { "code": null, "e": 1837, "s": 1616, "text": "Initialize a boolean matrix dp[][] in dimension N*2N where dp[j ][i] represents whether there exists a path in the subset or not represented by the mask i that visits each and every vertex in i once and ends at vertex j." }, { "code": null, "e": 1911, "s": 1837, "text": "For the base case, update dp[i][1 << i] = true, for i in range [0, N – 1]" }, { "code": null, "e": 2462, "s": 1911, "text": "Iterate over the range [1, 2N – 1] using the variable i and perform the following steps:All the vertices with bits set in mask i, are included in the subset.Iterate over the range [1, N] using the variable j that will represent the end vertex of the hamiltonian path of current subset mask i and perform the following steps:If the value of i and 2j is true, then iterate over the range [1, N] using the variable k and if the value of dp[k][i^2j] is true, then mark dp[j][i] is true and break out of the loop.Otherwise, continue to the next iteration." }, { "code": null, "e": 2532, "s": 2462, "text": "All the vertices with bits set in mask i, are included in the subset." }, { "code": null, "e": 2926, "s": 2532, "text": "Iterate over the range [1, N] using the variable j that will represent the end vertex of the hamiltonian path of current subset mask i and perform the following steps:If the value of i and 2j is true, then iterate over the range [1, N] using the variable k and if the value of dp[k][i^2j] is true, then mark dp[j][i] is true and break out of the loop.Otherwise, continue to the next iteration." }, { "code": null, "e": 3111, "s": 2926, "text": "If the value of i and 2j is true, then iterate over the range [1, N] using the variable k and if the value of dp[k][i^2j] is true, then mark dp[j][i] is true and break out of the loop." }, { "code": null, "e": 3154, "s": 3111, "text": "Otherwise, continue to the next iteration." }, { "code": null, "e": 3345, "s": 3154, "text": "Iterate over the range using the variable i and if the value of dp[i][2N – 1] is true, then there exists a hamiltonian path ending at vertex i. Therefore, print “Yes”. Otherwise, print “No”." }, { "code": null, "e": 3396, "s": 3345, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 3400, "s": 3396, "text": "C++" }, { "code": null, "e": 3405, "s": 3400, "text": "Java" }, { "code": null, "e": 3413, "s": 3405, "text": "Python3" }, { "code": null, "e": 3416, "s": 3413, "text": "C#" }, { "code": null, "e": 3427, "s": 3416, "text": "Javascript" }, { "code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std;const int N = 5; // Function to check whether there// exists a Hamiltonian Path or notbool Hamiltonian_path( vector<vector<int> >& adj, int N){ int dp[N][(1 << N)]; // Initialize the table memset(dp, 0, sizeof dp); // Set all dp[i][(1 << i)] to // true for (int i = 0; i < N; i++) dp[i][(1 << i)] = true; // Iterate over each subset // of nodes for (int i = 0; i < (1 << N); i++) { for (int j = 0; j < N; j++) { // If the jth nodes is included // in the current subset if (i & (1 << j)) { // Find K, neighbour of j // also present in the // current subset for (int k = 0; k < N; k++) { if (i & (1 << k) && adj[k][j] && j != k && dp[k][i ^ (1 << j)]) { // Update dp[j][i] // to true dp[j][i] = true; break; } } } } } // Traverse the vertices for (int i = 0; i < N; i++) { // Hamiltonian Path exists if (dp[i][(1 << N) - 1]) return true; } // Otherwise, return false return false;} // Driver Codeint main(){ // Input vector<vector<int> > adj = { { 0, 1, 1, 1, 0 }, { 1, 0, 1, 0, 1 }, { 1, 1, 0, 1, 1 }, { 1, 0, 1, 0, 0 } }; int N = adj.size(); // Function Call if (Hamiltonian_path(adj, N)) cout << \"YES\"; else cout << \"NO\"; return 0;}", "e": 5200, "s": 3427, "text": null }, { "code": "// Java program for the above approachimport java.io.*;import java.lang.*;import java.util.*; class GFG{ // Function to check whether there// exists a Hamiltonian Path or notstatic boolean Hamiltonian_path(int adj[][], int N){ boolean dp[][] = new boolean[N][(1 << N)]; // Set all dp[i][(1 << i)] to // true for(int i = 0; i < N; i++) dp[i][(1 << i)] = true; // Iterate over each subset // of nodes for(int i = 0; i < (1 << N); i++) { for(int j = 0; j < N; j++) { // If the jth nodes is included // in the current subset if ((i & (1 << j)) != 0) { // Find K, neighbour of j // also present in the // current subset for(int k = 0; k < N; k++) { if ((i & (1 << k)) != 0 && adj[k][j] == 1 && j != k && dp[k][i ^ (1 << j)]) { // Update dp[j][i] // to true dp[j][i] = true; break; } } } } } // Traverse the vertices for(int i = 0; i < N; i++) { // Hamiltonian Path exists if (dp[i][(1 << N) - 1]) return true; } // Otherwise, return false return false;} // Driver Codepublic static void main(String[] args){ int adj[][] = { { 0, 1, 1, 1, 0 }, { 1, 0, 1, 0, 1 }, { 1, 1, 0, 1, 1 }, { 1, 0, 1, 0, 0 } }; int N = adj.length; // Function Call if (Hamiltonian_path(adj, N)) System.out.println(\"YES\"); else System.out.println(\"NO\");}} // This code is contributed by Kingash", "e": 7065, "s": 5200, "text": null }, { "code": "# Python3 program for the above approach # Function to check whether there# exists a Hamiltonian Path or notdef Hamiltonian_path(adj, N): dp = [[False for i in range(1 << N)] for j in range(N)] # Set all dp[i][(1 << i)] to # true for i in range(N): dp[i][1 << i] = True # Iterate over each subset # of nodes for i in range(1 << N): for j in range(N): # If the jth nodes is included # in the current subset if ((i & (1 << j)) != 0): # Find K, neighbour of j # also present in the # current subset for k in range(N): if ((i & (1 << k)) != 0 and adj[k][j] == 1 and j != k and dp[k][i ^ (1 << j)]): # Update dp[j][i] # to true dp[j][i] = True break # Traverse the vertices for i in range(N): # Hamiltonian Path exists if (dp[i][(1 << N) - 1]): return True # Otherwise, return false return False # Driver Codeadj = [ [ 0, 1, 1, 1, 0 ] , [ 1, 0, 1, 0, 1 ], [ 1, 1, 0, 1, 1 ], [ 1, 0, 1, 0, 0 ] ] N = len(adj) if (Hamiltonian_path(adj, N)): print(\"YES\")else: print(\"NO\") # This code is contributed by maheshwaripiyush9", "e": 8526, "s": 7065, "text": null }, { "code": "// C# program for the above approachusing System; class GFG{ // Function to check whether there// exists a Hamiltonian Path or notstatic bool Hamiltonian_path(int[,] adj, int N){ bool[,] dp = new bool[N, (1 << N)]; // Set all dp[i][(1 << i)] to // true for(int i = 0; i < N; i++) dp[i, (1 << i)] = true; // Iterate over each subset // of nodes for(int i = 0; i < (1 << N); i++) { for(int j = 0; j < N; j++) { // If the jth nodes is included // in the current subset if ((i & (1 << j)) != 0) { // Find K, neighbour of j // also present in the // current subset for(int k = 0; k < N; k++) { if ((i & (1 << k)) != 0 && adj[k, j] == 1 && j != k && dp[k, i ^ (1 << j)]) { // Update dp[j][i] // to true dp[j, i] = true; break; } } } } } // Traverse the vertices for(int i = 0; i < N; i++) { // Hamiltonian Path exists if (dp[i, (1 << N) - 1]) return true; } // Otherwise, return false return false;} // Driver Codepublic static void Main(String[] args){ int[,] adj = { { 0, 1, 1, 1, 0 }, { 1, 0, 1, 0, 1 }, { 1, 1, 0, 1, 1 }, { 1, 0, 1, 0, 0 } }; int N = adj.GetLength(0); // Function Call if (Hamiltonian_path(adj, N)) Console.WriteLine(\"YES\"); else Console.WriteLine(\"NO\");}} // This code is contributed by ukasp", "e": 10322, "s": 8526, "text": null }, { "code": "<script> // Javascript program for the above approachvar N = 5; // Function to check whether there// exists a Hamiltonian Path or notfunction Hamiltonian_path( adj, N){ var dp = Array.from(Array(N), ()=> Array(1 << N).fill(0)); // Set all dp[i][(1 << i)] to // true for (var i = 0; i < N; i++) dp[i][(1 << i)] = true; // Iterate over each subset // of nodes for (var i = 0; i < (1 << N); i++) { for (var j = 0; j < N; j++) { // If the jth nodes is included // in the current subset if (i & (1 << j)) { // Find K, neighbour of j // also present in the // current subset for (var k = 0; k < N; k++) { if (i & (1 << k) && adj[k][j] && j != k && dp[k][i ^ (1 << j)]) { // Update dp[j][i] // to true dp[j][i] = true; break; } } } } } // Traverse the vertices for (var i = 0; i < N; i++) { // Hamiltonian Path exists if (dp[i][(1 << N) - 1]) return true; } // Otherwise, return false return false;} // Driver Code// Inputvar adj = [ [ 0, 1, 1, 1, 0 ], [ 1, 0, 1, 0, 1 ], [ 1, 1, 0, 1, 1 ], [ 1, 0, 1, 0, 0 ] ];var N = adj.length;// Function Callif (Hamiltonian_path(adj, N)) document.write( \"YES\");else document.write( \"NO\"); </script>", "e": 11957, "s": 10322, "text": null }, { "code": null, "e": 11961, "s": 11957, "text": "YES" }, { "code": null, "e": 12016, "s": 11963, "text": "Time Complexity: O(N * 2N)Auxiliary Space: O(N * 2N)" }, { "code": null, "e": 12024, "s": 12016, "text": "Kingash" }, { "code": null, "e": 12041, "s": 12024, "text": "maheswaripiyush9" }, { "code": null, "e": 12047, "s": 12041, "text": "ukasp" }, { "code": null, "e": 12054, "s": 12047, "text": "rrrtnx" }, { "code": null, "e": 12061, "s": 12054, "text": "subset" }, { "code": null, "e": 12071, "s": 12061, "text": "Bit Magic" }, { "code": null, "e": 12091, "s": 12071, "text": "Dynamic Programming" }, { "code": null, "e": 12097, "s": 12091, "text": "Graph" }, { "code": null, "e": 12104, "s": 12097, "text": "Matrix" }, { "code": null, "e": 12124, "s": 12104, "text": "Dynamic Programming" }, { "code": null, "e": 12134, "s": 12124, "text": "Bit Magic" }, { "code": null, "e": 12141, "s": 12134, "text": "Matrix" }, { "code": null, "e": 12148, "s": 12141, "text": "subset" }, { "code": null, "e": 12154, "s": 12148, "text": "Graph" } ]
ES6 | Loops
31 Oct, 2019 Loops are the way to do the same task again and again in a cyclic way. A loop represents a set of instructions that must be repeated. In a loop’s context, a repetition is termed as an iteration. The following figure illustrates the classification of loops: Definite: There are three types of Definite loops in ES6. Each of them described below with the example: for( ; ; ) The for loop executes the code block for a specified number of times.Syntax:for( Initialization; Terminate Condition; Increment/Decrement )The Initialization can be also be known as count value as this variable keeps track of the counting till the terminator. Increment/Decrement the variable to a certain value of steps. Terminate condition determines the indefinite or definite category, because if the terminator statement is valid then the loop gets terminated at a definite time, else it goes for infinity loops and will be an indefinite loop. Syntax: for( Initialization; Terminate Condition; Increment/Decrement ) The Initialization can be also be known as count value as this variable keeps track of the counting till the terminator. Increment/Decrement the variable to a certain value of steps. Terminate condition determines the indefinite or definite category, because if the terminator statement is valid then the loop gets terminated at a definite time, else it goes for infinity loops and will be an indefinite loop. for...in The for...in loop is used to loop through an object’s properties.Syntax:for(variable_name in object) { . . . } In each iteration, one property from the object is assigned to the variable_name and this loop continues till the end of the object properties. It certainly ends its iteration for sure so, it comes under definite loop. Syntax: for(variable_name in object) { . . . } In each iteration, one property from the object is assigned to the variable_name and this loop continues till the end of the object properties. It certainly ends its iteration for sure so, it comes under definite loop. for...of The for...of loop is used to execute the loop block to iterates the iterable instead of object literals.Syntax:for(variable_name of object) { . . . } In each iteration, one property from the iterable(array, string, etc) is assigned to the variable_name and this loop continues till the end of the iterates, it certainly ends its iteration for sure so, it comes under definite loop. Syntax: for(variable_name of object) { . . . } In each iteration, one property from the iterable(array, string, etc) is assigned to the variable_name and this loop continues till the end of the iterates, it certainly ends its iteration for sure so, it comes under definite loop. Example: This example illustrates all the three loops described above.<script>function geeks() { var obj = {Geeks:1, on:2, one:3}; document.write("for(;;)<br>") for( var i = 0 ; i <= 10; i+=2) { document.write(i+" ") } document.write("<br>for...of<br>") // If 'of' is replaced by 'in' it throws an error // as 'in' and literal are not compatible for (var i of ['hello', "Geeks", 3000]) { document.write(i+" ") } // If 'in' is replaced by 'of' it throws an error // as 'of' and objects are not compatible document.write("<br>for...in<br>") for (var i in obj) { document.write(obj[i]+" "); }}geeks();</script> <script>function geeks() { var obj = {Geeks:1, on:2, one:3}; document.write("for(;;)<br>") for( var i = 0 ; i <= 10; i+=2) { document.write(i+" ") } document.write("<br>for...of<br>") // If 'of' is replaced by 'in' it throws an error // as 'in' and literal are not compatible for (var i of ['hello', "Geeks", 3000]) { document.write(i+" ") } // If 'in' is replaced by 'of' it throws an error // as 'of' and objects are not compatible document.write("<br>for...in<br>") for (var i in obj) { document.write(obj[i]+" "); }}geeks();</script> Output:for(;;) 0 2 4 6 8 10 for...of hello Geeks 3000 for...in 1 2 3 for(;;) 0 2 4 6 8 10 for...of hello Geeks 3000 for...in 1 2 3 Indefinite: There are two types of Indefinite loops in ES6. Each of them described below with the example: While loop: This loop comes under the indefinite loop, where it may go to the undeterminate or infinity stage. This loop is of two types.The while loop executes the instructions each time the condition specified, evaluates to true.Syntax:while (terminator condition) { . . . } while (terminator condition) { . . . } do...while: The do...while loop is similar to the while loop except that the do...while loop doesn’t evaluate the condition for the first time the loop executes. It executes the loop at least once irrespective of the terminator condition.Syntax:do { . . . } while (terminator condition); do { . . . } while (terminator condition); Example This example illustrates all the three loops described above.<script>function geeks() { var i = 1; document.write("while<br>"); while(i <= 10) { document.write(i+" "); i += 2 } document.write("<br>do...while<br>"); var j = 11; do { // Prints j even though it is not satisfying // the condition because the condition is // not checked yet document.write(j + " "); j += 2; } while(j <= 10); // ; is necessary}geeks();</script> <script>function geeks() { var i = 1; document.write("while<br>"); while(i <= 10) { document.write(i+" "); i += 2 } document.write("<br>do...while<br>"); var j = 11; do { // Prints j even though it is not satisfying // the condition because the condition is // not checked yet document.write(j + " "); j += 2; } while(j <= 10); // ; is necessary}geeks();</script> Output:while 1 3 5 7 9 do...while 11 while 1 3 5 7 9 do...while 11 Loop Control Statements: To interrupt the execution of the flow or to control the flow of execution we use Loop Control Statements. Example: <script>function geeks() { var i = 1; document.write("break<br>"); while(i <= 10) { document.write(i + " "); if(i == 3) { document.write("break executed as i==3 is" + " true and breaks the loop."); break; } i += 1; } var j = 0; document.write("<br>continue<br>"); while(j <= 10) { j += 1; if(j == 4) { document.write("<br>continue executed as i==3" + " is true and skips the remaining loop " + "for that iteration<br>"); continue; } if(j == 8) return; document.write(j + " "); }}geeks();document.write("<br>returned to main as j==8 is true.<br>");</script> Output: break 1 2 3 break executed as i==3 is true and breaks the loop. continue 1 2 3 continue executed as i==3 is true and and skips the remaining loop for that iteration 5 6 7 returned to main as j==8 is true. Used Labels to Control the Flow: A label is simply an identifier followed by a colon (:) that is applied to a statement or a block of code. A label can be used with a break and continue to control the flow more precisely, but label use is not widely used as it leads to time-complexity issues and gets more complicated with more inner loops. Example: <script>function geeks() { outerloop: for (var i = 0; i <=3; i++) { document.write("Outerloop: " + i); innerloop: for (var j = 0; j<=3; j++) { // Quit the innermost loop if (i == 1 && j>1){ document.write("<br>innerloop skips the" + "rest of the loop as i == 1 && j>1" + " outerloop still in execution") continue innerloop; } // Do the same thing if (i == 2) { document.write(" outerloop breaks as i==2 <br>") break outerloop; // Quit the outer loop } document.write("<br>Innerloop: " + j); } document.write("<br>") }}geeks();</script> Output: Outerloop: 0 Innerloop: 0 Innerloop: 1 Innerloop: 2 Innerloop: 3 Outerloop: 1 Innerloop: 0 Innerloop: 1 innerloop skips the rest of the loop as i == 1 && j>1 outerloop still in execution innerloop skips the rest of the loop as i == 1 && j>1 outerloop still in execution Outerloop: 2 outerloop breaks as i==2 In simple words, we name the loops using a label and whenever according to the execution we can get hold of break and continue of a specific loop anywhere. ES6 Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n31 Oct, 2019" }, { "code": null, "e": 223, "s": 28, "text": "Loops are the way to do the same task again and again in a cyclic way. A loop represents a set of instructions that must be repeated. In a loop’s context, a repetition is termed as an iteration." }, { "code": null, "e": 285, "s": 223, "text": "The following figure illustrates the classification of loops:" }, { "code": null, "e": 390, "s": 285, "text": "Definite: There are three types of Definite loops in ES6. Each of them described below with the example:" }, { "code": null, "e": 950, "s": 390, "text": "for( ; ; ) The for loop executes the code block for a specified number of times.Syntax:for( Initialization; Terminate Condition; Increment/Decrement )The Initialization can be also be known as count value as this variable keeps track of the counting till the terminator. Increment/Decrement the variable to a certain value of steps. Terminate condition determines the indefinite or definite category, because if the terminator statement is valid then the loop gets terminated at a definite time, else it goes for infinity loops and will be an indefinite loop." }, { "code": null, "e": 958, "s": 950, "text": "Syntax:" }, { "code": null, "e": 1022, "s": 958, "text": "for( Initialization; Terminate Condition; Increment/Decrement )" }, { "code": null, "e": 1432, "s": 1022, "text": "The Initialization can be also be known as count value as this variable keeps track of the counting till the terminator. Increment/Decrement the variable to a certain value of steps. Terminate condition determines the indefinite or definite category, because if the terminator statement is valid then the loop gets terminated at a definite time, else it goes for infinity loops and will be an indefinite loop." }, { "code": null, "e": 1778, "s": 1432, "text": "for...in The for...in loop is used to loop through an object’s properties.Syntax:for(variable_name in object) { \n . . . \n}\nIn each iteration, one property from the object is assigned to the variable_name and this loop continues till the end of the object properties. It certainly ends its iteration for sure so, it comes under definite loop." }, { "code": null, "e": 1786, "s": 1778, "text": "Syntax:" }, { "code": null, "e": 1833, "s": 1786, "text": "for(variable_name in object) { \n . . . \n}\n" }, { "code": null, "e": 2052, "s": 1833, "text": "In each iteration, one property from the object is assigned to the variable_name and this loop continues till the end of the object properties. It certainly ends its iteration for sure so, it comes under definite loop." }, { "code": null, "e": 2449, "s": 2052, "text": "for...of The for...of loop is used to execute the loop block to iterates the iterable instead of object literals.Syntax:for(variable_name of object) { \n . . .\n}\nIn each iteration, one property from the iterable(array, string, etc) is assigned to the variable_name and this loop continues till the end of the iterates, it certainly ends its iteration for sure so, it comes under definite loop." }, { "code": null, "e": 2457, "s": 2449, "text": "Syntax:" }, { "code": null, "e": 2503, "s": 2457, "text": "for(variable_name of object) { \n . . .\n}\n" }, { "code": null, "e": 2735, "s": 2503, "text": "In each iteration, one property from the iterable(array, string, etc) is assigned to the variable_name and this loop continues till the end of the iterates, it certainly ends its iteration for sure so, it comes under definite loop." }, { "code": null, "e": 3421, "s": 2735, "text": "Example: This example illustrates all the three loops described above.<script>function geeks() { var obj = {Geeks:1, on:2, one:3}; document.write(\"for(;;)<br>\") for( var i = 0 ; i <= 10; i+=2) { document.write(i+\" \") } document.write(\"<br>for...of<br>\") // If 'of' is replaced by 'in' it throws an error // as 'in' and literal are not compatible for (var i of ['hello', \"Geeks\", 3000]) { document.write(i+\" \") } // If 'in' is replaced by 'of' it throws an error // as 'of' and objects are not compatible document.write(\"<br>for...in<br>\") for (var i in obj) { document.write(obj[i]+\" \"); }}geeks();</script>" }, { "code": "<script>function geeks() { var obj = {Geeks:1, on:2, one:3}; document.write(\"for(;;)<br>\") for( var i = 0 ; i <= 10; i+=2) { document.write(i+\" \") } document.write(\"<br>for...of<br>\") // If 'of' is replaced by 'in' it throws an error // as 'in' and literal are not compatible for (var i of ['hello', \"Geeks\", 3000]) { document.write(i+\" \") } // If 'in' is replaced by 'of' it throws an error // as 'of' and objects are not compatible document.write(\"<br>for...in<br>\") for (var i in obj) { document.write(obj[i]+\" \"); }}geeks();</script>", "e": 4037, "s": 3421, "text": null }, { "code": null, "e": 4107, "s": 4037, "text": "Output:for(;;)\n0 2 4 6 8 10\nfor...of\nhello Geeks 3000\nfor...in\n1 2 3\n" }, { "code": null, "e": 4170, "s": 4107, "text": "for(;;)\n0 2 4 6 8 10\nfor...of\nhello Geeks 3000\nfor...in\n1 2 3\n" }, { "code": null, "e": 4277, "s": 4170, "text": "Indefinite: There are two types of Indefinite loops in ES6. Each of them described below with the example:" }, { "code": null, "e": 4561, "s": 4277, "text": "While loop: This loop comes under the indefinite loop, where it may go to the undeterminate or infinity stage. This loop is of two types.The while loop executes the instructions each time the condition specified, evaluates to true.Syntax:while (terminator condition) { \n . . .\n} " }, { "code": null, "e": 4607, "s": 4561, "text": "while (terminator condition) { \n . . .\n} " }, { "code": null, "e": 4905, "s": 4607, "text": "do...while: The do...while loop is similar to the while loop except that the do...while loop doesn’t evaluate the condition for the first time the loop executes. It executes the loop at least once irrespective of the terminator condition.Syntax:do { \n . . .\n} \nwhile (terminator condition); \n" }, { "code": null, "e": 4958, "s": 4905, "text": "do { \n . . .\n} \nwhile (terminator condition); \n" }, { "code": null, "e": 5467, "s": 4958, "text": "Example This example illustrates all the three loops described above.<script>function geeks() { var i = 1; document.write(\"while<br>\"); while(i <= 10) { document.write(i+\" \"); i += 2 } document.write(\"<br>do...while<br>\"); var j = 11; do { // Prints j even though it is not satisfying // the condition because the condition is // not checked yet document.write(j + \" \"); j += 2; } while(j <= 10); // ; is necessary}geeks();</script>" }, { "code": "<script>function geeks() { var i = 1; document.write(\"while<br>\"); while(i <= 10) { document.write(i+\" \"); i += 2 } document.write(\"<br>do...while<br>\"); var j = 11; do { // Prints j even though it is not satisfying // the condition because the condition is // not checked yet document.write(j + \" \"); j += 2; } while(j <= 10); // ; is necessary}geeks();</script>", "e": 5907, "s": 5467, "text": null }, { "code": null, "e": 5945, "s": 5907, "text": "Output:while\n1 3 5 7 9\ndo...while\n11\n" }, { "code": null, "e": 5976, "s": 5945, "text": "while\n1 3 5 7 9\ndo...while\n11\n" }, { "code": null, "e": 6108, "s": 5976, "text": "Loop Control Statements: To interrupt the execution of the flow or to control the flow of execution we use Loop Control Statements." }, { "code": null, "e": 6117, "s": 6108, "text": "Example:" }, { "code": "<script>function geeks() { var i = 1; document.write(\"break<br>\"); while(i <= 10) { document.write(i + \" \"); if(i == 3) { document.write(\"break executed as i==3 is\" + \" true and breaks the loop.\"); break; } i += 1; } var j = 0; document.write(\"<br>continue<br>\"); while(j <= 10) { j += 1; if(j == 4) { document.write(\"<br>continue executed as i==3\" + \" is true and skips the remaining loop \" + \"for that iteration<br>\"); continue; } if(j == 8) return; document.write(j + \" \"); }}geeks();document.write(\"<br>returned to main as j==8 is true.<br>\");</script> ", "e": 6885, "s": 6117, "text": null }, { "code": null, "e": 6893, "s": 6885, "text": "Output:" }, { "code": null, "e": 7099, "s": 6893, "text": "break\n1 2 3 break executed as i==3 is true and breaks the loop.\ncontinue\n1 2 3\ncontinue executed as i==3 is true and and skips the remaining\nloop for that iteration\n5 6 7\nreturned to main as j==8 is true.\n" }, { "code": null, "e": 7441, "s": 7099, "text": "Used Labels to Control the Flow: A label is simply an identifier followed by a colon (:) that is applied to a statement or a block of code. A label can be used with a break and continue to control the flow more precisely, but label use is not widely used as it leads to time-complexity issues and gets more complicated with more inner loops." }, { "code": null, "e": 7450, "s": 7441, "text": "Example:" }, { "code": "<script>function geeks() { outerloop: for (var i = 0; i <=3; i++) { document.write(\"Outerloop: \" + i); innerloop: for (var j = 0; j<=3; j++) { // Quit the innermost loop if (i == 1 && j>1){ document.write(\"<br>innerloop skips the\" + \"rest of the loop as i == 1 && j>1\" + \" outerloop still in execution\") continue innerloop; } // Do the same thing if (i == 2) { document.write(\" outerloop breaks as i==2 <br>\") break outerloop; // Quit the outer loop } document.write(\"<br>Innerloop: \" + j); } document.write(\"<br>\") }}geeks();</script> ", "e": 8273, "s": 7450, "text": null }, { "code": null, "e": 8281, "s": 8273, "text": "Output:" }, { "code": null, "e": 8590, "s": 8281, "text": "Outerloop: 0\nInnerloop: 0\nInnerloop: 1\nInnerloop: 2\nInnerloop: 3\nOuterloop: 1\nInnerloop: 0\nInnerloop: 1\ninnerloop skips the rest of the loop as i == 1 && j>1 outerloop still in execution\ninnerloop skips the rest of the loop as i == 1 && j>1 outerloop still in execution\nOuterloop: 2 outerloop breaks as i==2\n" }, { "code": null, "e": 8746, "s": 8590, "text": "In simple words, we name the loops using a label and whenever according to the execution we can get hold of break and continue of a specific loop anywhere." }, { "code": null, "e": 8750, "s": 8746, "text": "ES6" }, { "code": null, "e": 8757, "s": 8750, "text": "Picked" }, { "code": null, "e": 8768, "s": 8757, "text": "JavaScript" }, { "code": null, "e": 8785, "s": 8768, "text": "Web Technologies" }, { "code": null, "e": 8812, "s": 8785, "text": "Web technologies Questions" } ]
What is the aria-labelledby attribute ?
09 Jul, 2020 The aria-labelledby attribute is an inherent attribute in hypertext markup language that’s wont to produce relationships between objects and there labels. Once any component containing each the attribute aria-labelledby and aria-label attribute the browsers high priority are going to be aria-labelledby with none doubt. This aria-labelledby attribute may be used with any typical hypertext markup language kind element. It is not restricted to components however aria-label attribute we must always watch out whereas victimization aria-label because it doesn’t work with all HTML elements. Syntax: <element aria-labelledby =""> Content </element> Parameters: A space-separated list of all the element IDs. Following are some of the list of all the popular usage of aria-labelledby attribute: Multiple Labels: Here each element is a field with both labels, the individual labels, and the group labels.Example:<!DOCTYPE html> <html> <head> <style> body { text-align: center; } h1 { color: green; } </style> </head> <body> <h1>GeeksforGeeks</h1> <div id="myBillingId"><h4>Billing of the Course</h4></div> <br> <div> <div id="myNameId">Student_ID: <input type="text" aria-labelledby="myBillingId myNameId" /> </div> </div> <div> <div id="myCourseId">Course: <input type="text" aria-labelledby="myBillingId myCourseId" /> </div> </div> </body> </html>Output: Example: <!DOCTYPE html> <html> <head> <style> body { text-align: center; } h1 { color: green; } </style> </head> <body> <h1>GeeksforGeeks</h1> <div id="myBillingId"><h4>Billing of the Course</h4></div> <br> <div> <div id="myNameId">Student_ID: <input type="text" aria-labelledby="myBillingId myNameId" /> </div> </div> <div> <div id="myCourseId">Course: <input type="text" aria-labelledby="myBillingId myCourseId" /> </div> </div> </body> </html> Output: Associating Headings With Regions: In this example, the header element is linked with the group head div, which makes the relation between the group head and the header element.Example:<!DOCTYPE html> <html> <head> <style> body { text-align: center; } h1 { color: green; } </style> </head> <body> <div role="main" aria-labelledby="geeks"> <h1>GeeksforGeeks</h1> <h4 id="geeks">A Computer Science Portal for Geeks</h4> The articles are reviewed by reviewers and then published. </div> </body> </html>Output: Example: <!DOCTYPE html> <html> <head> <style> body { text-align: center; } h1 { color: green; } </style> </head> <body> <div role="main" aria-labelledby="geeks"> <h1>GeeksforGeeks</h1> <h4 id="geeks">A Computer Science Portal for Geeks</h4> The articles are reviewed by reviewers and then published. </div> </body> </html> Output: Radio Groups: In this example, the radio group of a button is in relation to the container head.Example:<!DOCTYPE html> <html> <head> <style> body { text-align: center; } h1 { color: green; } </style> </head> <body> <h1>GeeksforGeeks</h1> <div id="radio_label">My radio labels</div> <ul role="radiogroup" aria-labelledby="radio_label"> <li role="radio"> <input type="radio">Geeks</li> <li role="radio"> <input type="radio">For</li> <li role="radio"> <input type="radio">Geeks</li> </ul> </body> </html>Output: Example: <!DOCTYPE html> <html> <head> <style> body { text-align: center; } h1 { color: green; } </style> </head> <body> <h1>GeeksforGeeks</h1> <div id="radio_label">My radio labels</div> <ul role="radiogroup" aria-labelledby="radio_label"> <li role="radio"> <input type="radio">Geeks</li> <li role="radio"> <input type="radio">For</li> <li role="radio"> <input type="radio">Geeks</li> </ul> </body> </html> Output: Dialog Label: In this example relation established between dialog and the header element.Example:<div role="dialog" aria-labelledby="dialogheader"> <dialog id="dialogheader">Choose a File</dialog> A Computer Science Portal </div> Output: Example: <div role="dialog" aria-labelledby="dialogheader"> <dialog id="dialogheader">Choose a File</dialog> A Computer Science Portal </div> Output: Inline Definition: In the example below, the definition of a term that is described in the natural flow of the narrative is associated with the term itself using the aria-labelledby attribute.Example:<p> The articles are reviewed by reviewers and then <dfn id="placebo">placebo</dfn>, published. <span role="definition" aria-labelledby="placebo"> The reviewers basically check for correctness and basic plagiarism. </span> </p>Output: Example: <p> The articles are reviewed by reviewers and then <dfn id="placebo">placebo</dfn>, published. <span role="definition" aria-labelledby="placebo"> The reviewers basically check for correctness and basic plagiarism. </span> </p> Output: Definition Lists: In the example below, the definitions in a formal definition list are associated with the terms they define using the aria-labelledby attribute.Example:<dl> <dt id="Geeks">Geeks</dt> <dd role="definition" aria-labelledby="Geeks"> The articles are reviewed by reviewers and then published. </dd> <dd role="definition" aria-labelledby="Geeks"> The reviewers basically check for correctness and basic plagiarism. </dd> <dt id="GFG">GfG</dt> <dd role="definition" aria-labelledby="GFG"> The articles are reviewed by reviewers and then published. </dd> <dd role="definition" aria-labelledby="GFG"> The reviewers basically check for correctness and basic plagiarism. </dd> </dl>Output: Example: <dl> <dt id="Geeks">Geeks</dt> <dd role="definition" aria-labelledby="Geeks"> The articles are reviewed by reviewers and then published. </dd> <dd role="definition" aria-labelledby="Geeks"> The reviewers basically check for correctness and basic plagiarism. </dd> <dt id="GFG">GfG</dt> <dd role="definition" aria-labelledby="GFG"> The articles are reviewed by reviewers and then published. </dd> <dd role="definition" aria-labelledby="GFG"> The reviewers basically check for correctness and basic plagiarism. </dd> </dl> Output: Menus: In the example below, a popup menu is associated with its label using the aria-labelledby attributeExample:<div role="menubar"> <div role="menuitem" aria-haspopup="true" id="fileMenu">File</div> <div role="menu" aria-labelledby="fileMenu"> <div role="menuitem">GeeksforGeeks</div> <div role="menuitem">Courses</div> </div> </div> Output: Example: <div role="menubar"> <div role="menuitem" aria-haspopup="true" id="fileMenu">File</div> <div role="menu" aria-labelledby="fileMenu"> <div role="menuitem">GeeksforGeeks</div> <div role="menuitem">Courses</div> </div> </div> Output: Akanksha_Rai HTML-Attributes Picked HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Jul, 2020" }, { "code": null, "e": 619, "s": 28, "text": "The aria-labelledby attribute is an inherent attribute in hypertext markup language that’s wont to produce relationships between objects and there labels. Once any component containing each the attribute aria-labelledby and aria-label attribute the browsers high priority are going to be aria-labelledby with none doubt. This aria-labelledby attribute may be used with any typical hypertext markup language kind element. It is not restricted to components however aria-label attribute we must always watch out whereas victimization aria-label because it doesn’t work with all HTML elements." }, { "code": null, "e": 627, "s": 619, "text": "Syntax:" }, { "code": null, "e": 676, "s": 627, "text": "<element aria-labelledby =\"\"> Content </element>" }, { "code": null, "e": 735, "s": 676, "text": "Parameters: A space-separated list of all the element IDs." }, { "code": null, "e": 821, "s": 735, "text": "Following are some of the list of all the popular usage of aria-labelledby attribute:" }, { "code": null, "e": 1577, "s": 821, "text": "Multiple Labels: Here each element is a field with both labels, the individual labels, and the group labels.Example:<!DOCTYPE html> <html> <head> <style> body { text-align: center; } h1 { color: green; } </style> </head> <body> <h1>GeeksforGeeks</h1> <div id=\"myBillingId\"><h4>Billing of the Course</h4></div> <br> <div> <div id=\"myNameId\">Student_ID: <input type=\"text\" aria-labelledby=\"myBillingId myNameId\" /> </div> </div> <div> <div id=\"myCourseId\">Course: <input type=\"text\" aria-labelledby=\"myBillingId myCourseId\" /> </div> </div> </body> </html>Output:" }, { "code": null, "e": 1586, "s": 1577, "text": "Example:" }, { "code": "<!DOCTYPE html> <html> <head> <style> body { text-align: center; } h1 { color: green; } </style> </head> <body> <h1>GeeksforGeeks</h1> <div id=\"myBillingId\"><h4>Billing of the Course</h4></div> <br> <div> <div id=\"myNameId\">Student_ID: <input type=\"text\" aria-labelledby=\"myBillingId myNameId\" /> </div> </div> <div> <div id=\"myCourseId\">Course: <input type=\"text\" aria-labelledby=\"myBillingId myCourseId\" /> </div> </div> </body> </html>", "e": 2219, "s": 1586, "text": null }, { "code": null, "e": 2227, "s": 2219, "text": "Output:" }, { "code": null, "e": 2846, "s": 2227, "text": "Associating Headings With Regions: In this example, the header element is linked with the group head div, which makes the relation between the group head and the header element.Example:<!DOCTYPE html> <html> <head> <style> body { text-align: center; } h1 { color: green; } </style> </head> <body> <div role=\"main\" aria-labelledby=\"geeks\"> <h1>GeeksforGeeks</h1> <h4 id=\"geeks\">A Computer Science Portal for Geeks</h4> The articles are reviewed by reviewers and then published. </div> </body> </html>Output:" }, { "code": null, "e": 2855, "s": 2846, "text": "Example:" }, { "code": "<!DOCTYPE html> <html> <head> <style> body { text-align: center; } h1 { color: green; } </style> </head> <body> <div role=\"main\" aria-labelledby=\"geeks\"> <h1>GeeksforGeeks</h1> <h4 id=\"geeks\">A Computer Science Portal for Geeks</h4> The articles are reviewed by reviewers and then published. </div> </body> </html>", "e": 3282, "s": 2855, "text": null }, { "code": null, "e": 3290, "s": 3282, "text": "Output:" }, { "code": null, "e": 3956, "s": 3290, "text": "Radio Groups: In this example, the radio group of a button is in relation to the container head.Example:<!DOCTYPE html> <html> <head> <style> body { text-align: center; } h1 { color: green; } </style> </head> <body> <h1>GeeksforGeeks</h1> <div id=\"radio_label\">My radio labels</div> <ul role=\"radiogroup\" aria-labelledby=\"radio_label\"> <li role=\"radio\"> <input type=\"radio\">Geeks</li> <li role=\"radio\"> <input type=\"radio\">For</li> <li role=\"radio\"> <input type=\"radio\">Geeks</li> </ul> </body> </html>Output:" }, { "code": null, "e": 3965, "s": 3956, "text": "Example:" }, { "code": "<!DOCTYPE html> <html> <head> <style> body { text-align: center; } h1 { color: green; } </style> </head> <body> <h1>GeeksforGeeks</h1> <div id=\"radio_label\">My radio labels</div> <ul role=\"radiogroup\" aria-labelledby=\"radio_label\"> <li role=\"radio\"> <input type=\"radio\">Geeks</li> <li role=\"radio\"> <input type=\"radio\">For</li> <li role=\"radio\"> <input type=\"radio\">Geeks</li> </ul> </body> </html>", "e": 4520, "s": 3965, "text": null }, { "code": null, "e": 4528, "s": 4520, "text": "Output:" }, { "code": null, "e": 4774, "s": 4528, "text": "Dialog Label: In this example relation established between dialog and the header element.Example:<div role=\"dialog\" aria-labelledby=\"dialogheader\"> <dialog id=\"dialogheader\">Choose a File</dialog> A Computer Science Portal </div> Output:" }, { "code": null, "e": 4783, "s": 4774, "text": "Example:" }, { "code": "<div role=\"dialog\" aria-labelledby=\"dialogheader\"> <dialog id=\"dialogheader\">Choose a File</dialog> A Computer Science Portal </div> ", "e": 4925, "s": 4783, "text": null }, { "code": null, "e": 4933, "s": 4925, "text": "Output:" }, { "code": null, "e": 5403, "s": 4933, "text": "Inline Definition: In the example below, the definition of a term that is described in the natural flow of the narrative is associated with the term itself using the aria-labelledby attribute.Example:<p> The articles are reviewed by reviewers and then <dfn id=\"placebo\">placebo</dfn>, published. <span role=\"definition\" aria-labelledby=\"placebo\"> The reviewers basically check for correctness and basic plagiarism. </span> </p>Output:" }, { "code": null, "e": 5412, "s": 5403, "text": "Example:" }, { "code": "<p> The articles are reviewed by reviewers and then <dfn id=\"placebo\">placebo</dfn>, published. <span role=\"definition\" aria-labelledby=\"placebo\"> The reviewers basically check for correctness and basic plagiarism. </span> </p>", "e": 5675, "s": 5412, "text": null }, { "code": null, "e": 5683, "s": 5675, "text": "Output:" }, { "code": null, "e": 6493, "s": 5683, "text": "Definition Lists: In the example below, the definitions in a formal definition list are associated with the terms they define using the aria-labelledby attribute.Example:<dl> <dt id=\"Geeks\">Geeks</dt> <dd role=\"definition\" aria-labelledby=\"Geeks\"> The articles are reviewed by reviewers and then published. </dd> <dd role=\"definition\" aria-labelledby=\"Geeks\"> The reviewers basically check for correctness and basic plagiarism. </dd> <dt id=\"GFG\">GfG</dt> <dd role=\"definition\" aria-labelledby=\"GFG\"> The articles are reviewed by reviewers and then published. </dd> <dd role=\"definition\" aria-labelledby=\"GFG\"> The reviewers basically check for correctness and basic plagiarism. </dd> </dl>Output:" }, { "code": null, "e": 6502, "s": 6493, "text": "Example:" }, { "code": "<dl> <dt id=\"Geeks\">Geeks</dt> <dd role=\"definition\" aria-labelledby=\"Geeks\"> The articles are reviewed by reviewers and then published. </dd> <dd role=\"definition\" aria-labelledby=\"Geeks\"> The reviewers basically check for correctness and basic plagiarism. </dd> <dt id=\"GFG\">GfG</dt> <dd role=\"definition\" aria-labelledby=\"GFG\"> The articles are reviewed by reviewers and then published. </dd> <dd role=\"definition\" aria-labelledby=\"GFG\"> The reviewers basically check for correctness and basic plagiarism. </dd> </dl>", "e": 7135, "s": 6502, "text": null }, { "code": null, "e": 7143, "s": 7135, "text": "Output:" }, { "code": null, "e": 7516, "s": 7143, "text": "Menus: In the example below, a popup menu is associated with its label using the aria-labelledby attributeExample:<div role=\"menubar\"> <div role=\"menuitem\" aria-haspopup=\"true\" id=\"fileMenu\">File</div> <div role=\"menu\" aria-labelledby=\"fileMenu\"> <div role=\"menuitem\">GeeksforGeeks</div> <div role=\"menuitem\">Courses</div> </div> </div> Output:" }, { "code": null, "e": 7525, "s": 7516, "text": "Example:" }, { "code": "<div role=\"menubar\"> <div role=\"menuitem\" aria-haspopup=\"true\" id=\"fileMenu\">File</div> <div role=\"menu\" aria-labelledby=\"fileMenu\"> <div role=\"menuitem\">GeeksforGeeks</div> <div role=\"menuitem\">Courses</div> </div> </div> ", "e": 7777, "s": 7525, "text": null }, { "code": null, "e": 7785, "s": 7777, "text": "Output:" }, { "code": null, "e": 7798, "s": 7785, "text": "Akanksha_Rai" }, { "code": null, "e": 7814, "s": 7798, "text": "HTML-Attributes" }, { "code": null, "e": 7821, "s": 7814, "text": "Picked" }, { "code": null, "e": 7826, "s": 7821, "text": "HTML" }, { "code": null, "e": 7843, "s": 7826, "text": "Web Technologies" }, { "code": null, "e": 7848, "s": 7843, "text": "HTML" } ]
How to use User model in Django?
04 Jan, 2021 The Django’s built-in authentication system is great. For the most part we can use it out-of-the-box, saving a lot of development and testing effort. It fits most of the use cases and is very safe. But sometimes we need to do some fine adjustment so to fit our Web application. Commonly we want to store a few more data related to our User but the next question might be that how should a Django developer reference a User? The official Django docs list three separate ways: User AUTH_USER_MODEL get_user_model() Explanation: Illustration of how to reference user model by an example. Consider a project named mysite having an app name blog. Refer to the following article to check how to create a project and an app in Django. How to Create Basic Project using MVT in Django ? How to Create an App in Django? Method 1 – User model Directly : Inside the models.py add the following code: Python3 from django.db import modelsfrom django.contrib.auth.models import User# Create your models here.class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=50) content= models.TextField() def __str__(self): return self.title Register this model by adding the following code inside the admin.py. from django.contrib import admin from .models import Post # Register your models here. admin.site.register(Post) Some kinds of projects may have authentication requirements for which Django’s built-in User model is not always appropriate. For instance, on some sites it makes more sense to use an email address as your identification token instead of a username. Django allows you to override the default user model by providing a value for the AUTH_USER_MODEL setting that references a custom model. Method 2 – AUTH_USER_MODEL : AUTH_USER_MODEL is the recommended approach when referring to a user model in a models.py file. For this you need to create custom User Model by either subclassing AbstractUser or AbstractBaseUser. AbstractUser: Use this option if you are happy with the existing fields on the User model and just want to remove the username field. AbstractBaseUser: Use this option if you want to start from scratch by creating your own, completely new User model. Refer Below Article for Creating Custom User model: Creating Custom User Model If you’ve already created a custom user model say CustomUser in an app called users , you’d reference it in your settings.py file as follows: #settings.py AUTH_USER_MODEL = 'users.CustomUser' Then in blog models.py add the following code: Python3 # blog/models.pyfrom django.conf import settingsfrom django.db import models class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) title = models.CharField(max_length=50) content = models.TextField() Register this model by adding the following code inside the admin.py. from django.contrib import admin from .models import Post # Register your models here. admin.site.register(Post) Method 3 – get_user_model() : If you reference User directly (for example, by referring to it in a foreign key), your code will not work in projects where the AUTH_USER_MODEL setting has been changed to a different user model. The other way to reference the user model is via get_user_model which returns the currently active user model: either a custom user model specificed in AUTH_USER_MODEL or else the default built-in User. Inside the models.py add the following code: Python3 from django.db import modelsfrom django.contrib.auth import get_user_modelUser=get_user_model()# Create your models here.class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=50) content= models.TextField() def __str__(self): return self.title Register this model by adding the following code inside the admin.py. from django.contrib import admin from .models import Post # Register your models here. admin.site.register(Post) Output – Creating instances with author as user Python Django Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n04 Jan, 2021" }, { "code": null, "e": 530, "s": 54, "text": "The Django’s built-in authentication system is great. For the most part we can use it out-of-the-box, saving a lot of development and testing effort. It fits most of the use cases and is very safe. But sometimes we need to do some fine adjustment so to fit our Web application. Commonly we want to store a few more data related to our User but the next question might be that how should a Django developer reference a User? The official Django docs list three separate ways:" }, { "code": null, "e": 535, "s": 530, "text": "User" }, { "code": null, "e": 551, "s": 535, "text": "AUTH_USER_MODEL" }, { "code": null, "e": 568, "s": 551, "text": "get_user_model()" }, { "code": null, "e": 581, "s": 568, "text": "Explanation:" }, { "code": null, "e": 698, "s": 581, "text": "Illustration of how to reference user model by an example. Consider a project named mysite having an app name blog." }, { "code": null, "e": 785, "s": 698, "text": "Refer to the following article to check how to create a project and an app in Django. " }, { "code": null, "e": 839, "s": 785, "text": "How to Create Basic Project using MVT in Django ? " }, { "code": null, "e": 871, "s": 839, "text": "How to Create an App in Django?" }, { "code": null, "e": 905, "s": 871, "text": "Method 1 – User model Directly : " }, { "code": null, "e": 950, "s": 905, "text": "Inside the models.py add the following code:" }, { "code": null, "e": 958, "s": 950, "text": "Python3" }, { "code": "from django.db import modelsfrom django.contrib.auth.models import User# Create your models here.class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=50) content= models.TextField() def __str__(self): return self.title", "e": 1264, "s": 958, "text": null }, { "code": null, "e": 1334, "s": 1264, "text": "Register this model by adding the following code inside the admin.py." }, { "code": null, "e": 1448, "s": 1334, "text": "from django.contrib import admin\nfrom .models import Post\n\n# Register your models here.\nadmin.site.register(Post)" }, { "code": null, "e": 1698, "s": 1448, "text": "Some kinds of projects may have authentication requirements for which Django’s built-in User model is not always appropriate. For instance, on some sites it makes more sense to use an email address as your identification token instead of a username." }, { "code": null, "e": 1836, "s": 1698, "text": "Django allows you to override the default user model by providing a value for the AUTH_USER_MODEL setting that references a custom model." }, { "code": null, "e": 1865, "s": 1836, "text": "Method 2 – AUTH_USER_MODEL :" }, { "code": null, "e": 1961, "s": 1865, "text": "AUTH_USER_MODEL is the recommended approach when referring to a user model in a models.py file." }, { "code": null, "e": 2063, "s": 1961, "text": "For this you need to create custom User Model by either subclassing AbstractUser or AbstractBaseUser." }, { "code": null, "e": 2197, "s": 2063, "text": "AbstractUser: Use this option if you are happy with the existing fields on the User model and just want to remove the username field." }, { "code": null, "e": 2314, "s": 2197, "text": "AbstractBaseUser: Use this option if you want to start from scratch by creating your own, completely new User model." }, { "code": null, "e": 2367, "s": 2314, "text": "Refer Below Article for Creating Custom User model: " }, { "code": null, "e": 2394, "s": 2367, "text": "Creating Custom User Model" }, { "code": null, "e": 2536, "s": 2394, "text": "If you’ve already created a custom user model say CustomUser in an app called users , you’d reference it in your settings.py file as follows:" }, { "code": null, "e": 2587, "s": 2536, "text": "#settings.py\n\nAUTH_USER_MODEL = 'users.CustomUser'" }, { "code": null, "e": 2634, "s": 2587, "text": "Then in blog models.py add the following code:" }, { "code": null, "e": 2642, "s": 2634, "text": "Python3" }, { "code": "# blog/models.pyfrom django.conf import settingsfrom django.db import models class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) title = models.CharField(max_length=50) content = models.TextField()", "e": 2902, "s": 2642, "text": null }, { "code": null, "e": 2972, "s": 2902, "text": "Register this model by adding the following code inside the admin.py." }, { "code": null, "e": 3086, "s": 2972, "text": "from django.contrib import admin\nfrom .models import Post\n\n# Register your models here.\nadmin.site.register(Post)" }, { "code": null, "e": 3116, "s": 3086, "text": "Method 3 – get_user_model() :" }, { "code": null, "e": 3313, "s": 3116, "text": "If you reference User directly (for example, by referring to it in a foreign key), your code will not work in projects where the AUTH_USER_MODEL setting has been changed to a different user model." }, { "code": null, "e": 3516, "s": 3313, "text": "The other way to reference the user model is via get_user_model which returns the currently active user model: either a custom user model specificed in AUTH_USER_MODEL or else the default built-in User." }, { "code": null, "e": 3561, "s": 3516, "text": "Inside the models.py add the following code:" }, { "code": null, "e": 3569, "s": 3561, "text": "Python3" }, { "code": "from django.db import modelsfrom django.contrib.auth import get_user_modelUser=get_user_model()# Create your models here.class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=50) content= models.TextField() def __str__(self): return self.title", "e": 3899, "s": 3569, "text": null }, { "code": null, "e": 3969, "s": 3899, "text": "Register this model by adding the following code inside the admin.py." }, { "code": null, "e": 4083, "s": 3969, "text": "from django.contrib import admin\nfrom .models import Post\n\n# Register your models here.\nadmin.site.register(Post)" }, { "code": null, "e": 4093, "s": 4083, "text": "Output – " }, { "code": null, "e": 4132, "s": 4093, "text": "Creating instances with author as user" }, { "code": null, "e": 4146, "s": 4132, "text": "Python Django" }, { "code": null, "e": 4153, "s": 4146, "text": "Python" } ]
Java Program to Convert OutputStream to String
09 Dec, 2021 OutputStream is an abstract class that is available in the java.io package. As it is an abstract class in order to use its functionality we can use its subclasses. Some subclasses are FileOutputStream, ByteArrayOutputStream, ObjectOutputStream etc. And a String is nothing but a sequence of characters, use double quotes to represent it. The java.io.ByteArrayOutputStream.toString() method converts the stream using the character set. Approach 1: Create an object of ByteArrayoutputStream.Create a String variable and initialize it.Use the write method to copy the contents of the string to the object of ByteArrayoutputStream.Print it. Create an object of ByteArrayoutputStream. Create a String variable and initialize it. Use the write method to copy the contents of the string to the object of ByteArrayoutputStream. Print it. Example: Input : String = "Hello World" Output: Hello World Below is the implementation of the above approach: Java // Java program to demonstrate conversion// from outputStream to string import java.io.*; class GFG { // we know that main will throw // IOException so we are ducking it public static void main(String[] args) throws IOException { // declaring ByteArrayOutputStream ByteArrayOutputStream stream = new ByteArrayOutputStream(); // Initializing string String st = "Hello Geek!"; // writing the specified byte to the output stream stream.write(st.getBytes()); // converting stream to byte array // and typecasting into string String finalString = new String(stream.toByteArray()); // printing the final string System.out.println(finalString); }} Hello Geek! Approach 2: Create a byte array and store ASCII value of the characters.Create an object of ByteArrayoutputStream.Use write method to copy the content from the byte array to the object.Print it. Create a byte array and store ASCII value of the characters. Create an object of ByteArrayoutputStream. Use write method to copy the content from the byte array to the object. Print it. Example: Input : array = [71, 69, 69, 75] Output: GEEK Below is the implementation of the above approach: Java // Java program to demonstrate conversion// from outputStream to string import java.io.*; class GFG { public static void main(String[] args) throws IOException { // Initializing empty string // and byte array String str = ""; byte[] bs = { 71, 69, 69, 75, 83, 70, 79, 82, 71, 69, 69, 75, 83 }; // create new ByteArrayOutputStream ByteArrayOutputStream stream = new ByteArrayOutputStream(); // write byte array to the output stream stream.write(bs); // converts buffers using default character set // toString is a method for casting into String type str = stream.toString(); // print System.out.println(str); }} GEEKSFORGEEKS simranarora5sos Java-String-Programs Picked Technical Scripter 2020 Java Java Programs Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Dec, 2021" }, { "code": null, "e": 463, "s": 28, "text": "OutputStream is an abstract class that is available in the java.io package. As it is an abstract class in order to use its functionality we can use its subclasses. Some subclasses are FileOutputStream, ByteArrayOutputStream, ObjectOutputStream etc. And a String is nothing but a sequence of characters, use double quotes to represent it. The java.io.ByteArrayOutputStream.toString() method converts the stream using the character set." }, { "code": null, "e": 475, "s": 463, "text": "Approach 1:" }, { "code": null, "e": 665, "s": 475, "text": "Create an object of ByteArrayoutputStream.Create a String variable and initialize it.Use the write method to copy the contents of the string to the object of ByteArrayoutputStream.Print it." }, { "code": null, "e": 708, "s": 665, "text": "Create an object of ByteArrayoutputStream." }, { "code": null, "e": 752, "s": 708, "text": "Create a String variable and initialize it." }, { "code": null, "e": 848, "s": 752, "text": "Use the write method to copy the contents of the string to the object of ByteArrayoutputStream." }, { "code": null, "e": 858, "s": 848, "text": "Print it." }, { "code": null, "e": 867, "s": 858, "text": "Example:" }, { "code": null, "e": 918, "s": 867, "text": "Input : String = \"Hello World\"\nOutput: Hello World" }, { "code": null, "e": 969, "s": 918, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 974, "s": 969, "text": "Java" }, { "code": "// Java program to demonstrate conversion// from outputStream to string import java.io.*; class GFG { // we know that main will throw // IOException so we are ducking it public static void main(String[] args) throws IOException { // declaring ByteArrayOutputStream ByteArrayOutputStream stream = new ByteArrayOutputStream(); // Initializing string String st = \"Hello Geek!\"; // writing the specified byte to the output stream stream.write(st.getBytes()); // converting stream to byte array // and typecasting into string String finalString = new String(stream.toByteArray()); // printing the final string System.out.println(finalString); }}", "e": 1742, "s": 974, "text": null }, { "code": null, "e": 1754, "s": 1742, "text": "Hello Geek!" }, { "code": null, "e": 1766, "s": 1754, "text": "Approach 2:" }, { "code": null, "e": 1949, "s": 1766, "text": "Create a byte array and store ASCII value of the characters.Create an object of ByteArrayoutputStream.Use write method to copy the content from the byte array to the object.Print it." }, { "code": null, "e": 2010, "s": 1949, "text": "Create a byte array and store ASCII value of the characters." }, { "code": null, "e": 2053, "s": 2010, "text": "Create an object of ByteArrayoutputStream." }, { "code": null, "e": 2125, "s": 2053, "text": "Use write method to copy the content from the byte array to the object." }, { "code": null, "e": 2135, "s": 2125, "text": "Print it." }, { "code": null, "e": 2144, "s": 2135, "text": "Example:" }, { "code": null, "e": 2191, "s": 2144, "text": "Input : array = [71, 69, 69, 75]\nOutput: GEEK " }, { "code": null, "e": 2242, "s": 2191, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 2247, "s": 2242, "text": "Java" }, { "code": "// Java program to demonstrate conversion// from outputStream to string import java.io.*; class GFG { public static void main(String[] args) throws IOException { // Initializing empty string // and byte array String str = \"\"; byte[] bs = { 71, 69, 69, 75, 83, 70, 79, 82, 71, 69, 69, 75, 83 }; // create new ByteArrayOutputStream ByteArrayOutputStream stream = new ByteArrayOutputStream(); // write byte array to the output stream stream.write(bs); // converts buffers using default character set // toString is a method for casting into String type str = stream.toString(); // print System.out.println(str); }}", "e": 3003, "s": 2247, "text": null }, { "code": null, "e": 3017, "s": 3003, "text": "GEEKSFORGEEKS" }, { "code": null, "e": 3033, "s": 3017, "text": "simranarora5sos" }, { "code": null, "e": 3054, "s": 3033, "text": "Java-String-Programs" }, { "code": null, "e": 3061, "s": 3054, "text": "Picked" }, { "code": null, "e": 3085, "s": 3061, "text": "Technical Scripter 2020" }, { "code": null, "e": 3090, "s": 3085, "text": "Java" }, { "code": null, "e": 3104, "s": 3090, "text": "Java Programs" }, { "code": null, "e": 3123, "s": 3104, "text": "Technical Scripter" }, { "code": null, "e": 3128, "s": 3123, "text": "Java" } ]
numpy.indices() function – Python
11 Jun, 2020 numpy.indices() function return an array representing the indices of a grid. Compute an array where the subarrays contain index values 0, 1, ... varying only along the corresponding axis. Syntax : numpy.indices(dimensions, dtype, sparse = False) Parameters :dimensions : [sequence of ints] The shape of the grid.dtype: [dtype, optional] Data type of the result.sparse: [boolean, optional] Return a sparse representation of the grid instead of a dense representation. Default is False. Return : [ndarray or tuple of ndarrays]If sparse is False:Returns one array of grid indices, grid.shape = (len(dimensions), ) + tuple(dimensions). If sparse is True:Returns a tuple of arrays, with grid[i].shape = (1, ..., 1, dimensions[i], 1, ..., 1) with dimensions[i] in the ith place Code #1 : # Python program explaining# numpy.indices() function # importing numpy as geek import numpy as geek gfg = geek.indices((2, 3)) print (gfg) Output : [[[0 0 0] [1 1 1]] [[0 1 2] [0 1 2]]] Code #2 : # Python program explaining# numpy.indices() function # importing numpy as geek import numpy as geek grid = geek.indices((2, 3))gfg = grid[1] print (gfg) Output : [[0 1 2] [0 1 2]] Python numpy-ndarray Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Jun, 2020" }, { "code": null, "e": 216, "s": 28, "text": "numpy.indices() function return an array representing the indices of a grid. Compute an array where the subarrays contain index values 0, 1, ... varying only along the corresponding axis." }, { "code": null, "e": 274, "s": 216, "text": "Syntax : numpy.indices(dimensions, dtype, sparse = False)" }, { "code": null, "e": 513, "s": 274, "text": "Parameters :dimensions : [sequence of ints] The shape of the grid.dtype: [dtype, optional] Data type of the result.sparse: [boolean, optional] Return a sparse representation of the grid instead of a dense representation. Default is False." }, { "code": null, "e": 660, "s": 513, "text": "Return : [ndarray or tuple of ndarrays]If sparse is False:Returns one array of grid indices, grid.shape = (len(dimensions), ) + tuple(dimensions)." }, { "code": null, "e": 800, "s": 660, "text": "If sparse is True:Returns a tuple of arrays, with grid[i].shape = (1, ..., 1, dimensions[i], 1, ..., 1) with dimensions[i] in the ith place" }, { "code": null, "e": 810, "s": 800, "text": "Code #1 :" }, { "code": "# Python program explaining# numpy.indices() function # importing numpy as geek import numpy as geek gfg = geek.indices((2, 3)) print (gfg)", "e": 960, "s": 810, "text": null }, { "code": null, "e": 969, "s": 960, "text": "Output :" }, { "code": null, "e": 1014, "s": 969, "text": "[[[0 0 0]\n [1 1 1]]\n\n [[0 1 2]\n [0 1 2]]]\n" }, { "code": null, "e": 1025, "s": 1014, "text": " Code #2 :" }, { "code": "# Python program explaining# numpy.indices() function # importing numpy as geek import numpy as geek grid = geek.indices((2, 3))gfg = grid[1] print (gfg)", "e": 1189, "s": 1025, "text": null }, { "code": null, "e": 1198, "s": 1189, "text": "Output :" }, { "code": null, "e": 1218, "s": 1198, "text": "[[0 1 2]\n [0 1 2]]\n" }, { "code": null, "e": 1239, "s": 1218, "text": "Python numpy-ndarray" }, { "code": null, "e": 1252, "s": 1239, "text": "Python-numpy" }, { "code": null, "e": 1259, "s": 1252, "text": "Python" } ]