title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Uncertainty via 3D Bayesian Deep Learning | Towards Data Science
PAPER: https://arxiv.org/abs/1910.10793 CODE: https://github.com/sandialabs/bcnn Key Takeaways: · Measuring uncertainty is not possible in a regular deep neural network, but it is extremely important for interpretability and validation · Bayesian neural networks learn probability distributions rather than point estimates, allowing them to measure uncertainty · We designed the first-ever successful Bayesian convolutional neural network (BCNN) architecture for 3D segmentation · Our BCNN beats the current state-of-the-art neural network in uncertainty quantification while achieving equal or better segmentation accuracy · Our academic paper and full open-source code implementation are available online Consider this scenario: a certain aircraft manufacturing company produces safety-critical engine parts for commercial aircraft. Since the engine parts must be guaranteed to work, the company validates each of them in a painstaking, months-long process wherein they take a 3D CT scan of the part, annotate the hundreds of millions of voxels by hand, and use the annotated scan to analyze the part for defects. This is not time- or cost-effective, so the company hires a team of data scientists to design a deep neural network which automatically validates the parts using state-of-the-art volumetric segmentation techniques. The neural network is seemingly successful, but one day a part verified by the neural network inexplicably fails during usage, causing engine failure in the aircraft and leading to hundreds of fatalities and billions of dollars lost for the company. So what went wrong? Well, deep neural networks are well-known for making accurate predictions, but one of their greatest weaknesses is that they lack the capacity for measuring uncertainty within their predictions. Thus, the deep learning system had no capacity to distinguish between a part that was 100% certified, and a part that just barely made the cut. One may think that the value of the sigmoid output is usable as a measure of uncertainty, but this is not true because these values are dependent on the inferred sample being “close” to the training distribution. If one infers on a sample far from the training distribution (i.e., a part with a defect in it), the sigmoid output cannot be used as a proxy for model uncertainty3. In other words, deep neural networks perform best when the test set is “similar” to the training set; in other words, there may be examples in the test set which the neural network is unsure about because there were no similar training examples. But because there is no “I don’t know” output available, defective parts can end up verified by the deep learning system and moved to production. This example illustrates the critical importance of uncertainty quantification in deep neural networks, the research and development of which has skyrocketed in the last five years. Recent techniques cast neural networks, usually pointwise estimators, as probabilistic or Bayesian models. The two most common neural network architectures for this purpose are Monte Carlo dropout networks3 (MCDNs) and Bayesian convolutional neural networks1 (BCNNs). MCDNs use dropout layers to approximate deep Gaussian processes, and while easy to implement, their statistical soundness has been called into question9. BCNNs use variational inference to learn the posterior distribution of the weights given the dataset and are much more difficult to implement but give greatly improved uncertainty results. It has been postulated that Bayesian neural networks for large problems, including in the 3D image segmentation space, are infeasible due to prohibitive computational costs3. Here, we refute that claim and present the first-ever successful implementation of a 3D BCNN for uncertainty quantification in volumetric segmentation, detail how it works, and explain some sections of the open-source codebase. In particular, this novel neural network architecture provides improved uncertainty quantification as compared to MCDNs while achieving equal or better segmentation accuracy. Through experimentation on CT scans of battery electrode and laser-welded metals, we show that the uncertainty maps generated by the BCNN capture continuity and visual gradients, making them interpretable as confidence intervals for segmentation. While most neural networks learn pointwise estimates of their weights, the more rigorous view is that these estimates do not fully encapsulate the uncertainty inherent in the values of the weights. Instead, in a BCNN, the weights are each implicitly described as (multivariate) probability distributions. Describing the weights of the neural networks as probability distributions has several consequences. First, it makes the neural network nondeterministic; every time we compute a forward pass, we must sample from each weight distribution to obtain a point estimate which can be used for inference. Repeated applications of this sampling technique, called Monte Carlo sampling, will result in different predictions which can then be analyzed for uncertainty. Second, it changes the backpropagation algorithm since we cannot backpropagate through a sampling operation (it has no gradient). In a later section, we will discuss how to fix this problem using the Bayes by Backprop algorithm. Finally, it makes the neural network much more difficult to reliably train, especially in 3D, and susceptible to vanishing/exploding gradients. We use a clever normalization technique called group normalization to solve this problem, also detailed in a later section. How exactly do we get distributions over the weights? Well, in a perfect world, we could use Bayes’ Rule to calculate them precisely. To do this, we would begin with a prior distribution over the weights; this is our “initial guess” of what a weight distribution would look like. It is denoted p(w) and is generally a standard normal distribution. Then, we would use our data to calculate the posterior distributions of the weights given the dataset, denoted p(w|D). This is equivalent to finding a w that maximizes the likelihood of the dataset given those weights, denoted p(D|w), and we can perform this calculation via Bayes’ Rule: However, due to the extreme overparameterization found in neural networks, the integral in the denominator is generally intractable. So, we need to learn the posterior distribution rather than calculate it exactly. Previous work by Hinton and Van Camp5 and Graves4 proposed variational learning (also called variational inference) as a method to approximate the posterior distribution. Variational learning finds the parameters θ of the distribution p(w|θ), called the variational distribution, via the minimization of the variational free energy cost function F, often called the expected lower bound (ELBO). The variational free energy consists of the sum of the Kullback-Leibler (KL) divergence, which measures the distance between the prior and variational distributions, and the negative log-likelihood, which measures the goodness-of-fit of the model. Blundell et al.1 explains the variational free energy loss function as a tradeoff between satisfying the simplicity prior (represented by the KL term) and satisfying the complexity of the dataset (represented by the NLL term): The longer we train the neural network, the closer we will get to minimizing this cost function, and the closer our variational distribution will get to the true posterior distribution. In practice, the KL term has a regularizing effect on the output of the neural network, preventing the learned distribution from overfitting at the cost of a lower NLL term in the training set. This loss function is amenable to mini-batch optimization by scaling the cost for mini-batch i as follows, essentially spreading out the KL divergence penalty across the entire dataset1: If a Bayesian neural network is implemented in TensorFlow Probability, the below is a valid Python implementation of the variational free energy loss (note that binary cross-entropy is just negated NLL): from tensorflow.keras.losses import binary_crossentropydef vfe_loss(model, dataset_size, batch_size, alpha=1): """Defines variational free energy loss. Sum of KL divergence and binary cross-entropy.""" # KL Divergence should be applied once per epoch only. kl = sum(model.losses) / (dataset_size / batch_size) def loss(y_true, y_pred): bce = binary_crossentropy(y_true, y_pred) return alpha * kl + (1. / alpha) * bce return loss Challenges in Bayesian Learning Variational Bayesian learning is generally considered more statistically sound than, for example, approximate Bayesian inference via dropout layers9. However, this comes at the cost of several computational challenges. First, a random variable sampled from a distribution has no gradient, so Bayesian neural networks seem incompatible with backpropagation. However, Kingma et al.6 showed that it is possible to reparametrize the random variable as a deterministic variable for computation. As an example, let a weight w be sampled from a normal distribution with mean μ and variance σ2. Then, a valid reparameterization is w=μ+σε where ε is an auxiliary noise variable sampled from a standard normal distribution. Now, instead of a sampling operation, we have an affine combination, which is easily utilized in backpropagation. More complex calculations are needed to efficiently scale this computation; see Kingma’s paper for more. This is often called the local reparameterization trick. Next, Bayesian learning was previously considered computationally infeasible due to the massive number of weight updates necessary if trained using an ensemble method. To solve this, Blundell et al.1 designed the Bayes by Backprop algorithm. Previous work focused on training stochastic hidden units, but there are easily two orders of magnitude more weights than hidden units, and Bayes by Backprop was the first algorithm to effectively train probabilistic weights in a neural network. Bayes by Backprop works by using the gradients calculated in backpropagation to “scale and shift” the variational parameters of the posterior, thus updating the posterior with minimal additional computation. Since 3D training volumes can be quite large, our batch size is constrained by the amount of available GPU memory, resulting in a batch size too small for batch normalization to accurately compute batch statistics. Thus, we use a technique proposed by Wu and He12 called group normalization, which normalizes groups of channels and is shown to have accurate performance independent of batch size. Proper normalization was observed to be a critical factor in the convergence of our model since it helps avoid vanishing/exploding gradients; by tuning the number of groups used in the group normalization layers, we found that the BCNN converged most reliably when using 4 groups. Finally, one challenge associated with probabilistic weights is that all examples in a mini-batch typically have similarly sampled weights, limiting the variance reduction effect of large mini-batches. One side effect of the local reparameterization trick6 mentioned above is that it greatly reduces the variance of stochastically sampled weights by transforming global weight uncertainty into independent local noise across examples in the mini-batch. In a similar vein, Wen et al.11 proposed the Flipout estimator, which empirically achieves ideal variance reduction by sampling weights pseudo-independently for each example. An important difference is that local reparametrization works only for fully connected networks, while Flipout can be used effectively in fully-connected, convolutional, and recurrent networks. Our 3D BCNN architecture draws from the image segmentation literature by utilizing the common encoder-decoder setup seen in V-Net7 and 3D U-Net2 , deep neural networks originally used for 3D segmentation of human prostates and frog kidneys, respectively. In this architecture, the encoder half (left) of the network compresses the input into a latent space while the decoder half (right) decompresses the latent representation of the input into a segmentation map. The encoder half of the BCNN uses typical 3D convolutions to maximize information transfer between the original volume and the latent space, but the decoder half of the network uses 3D Bayesian convolutional layers. Each of these is initialized with a standard normal prior and employs the aforementioned Flipout estimator11 to approximate the distribution during forward passes. Note the skip connections in yellow, which assist in feature-forwarding throughout the network. Our implementation draws from the Bayesian Layers library10 included in TensorFlow Probability, which keeps track of losses representing the KL divergence of the layer’s posterior distribution with respect to its prior and makes computing the variational free energy loss simple. An implementation of this BCNN architecture is available at https://github.com/sandialabs/bcnn/blob/master/bayesian_vnet.py. Using a BCNN in practice brings with it a few peculiarities that can be difficult to effectively implement. First, it is currently impossible to save the architecture and weights of a model that combines, say, Keras layers and Bayesian layers. Instead, one must save the weights only and then load them into an instantiated architecture. This gets worse when the models are designated as multi-GPU, which is virtually necessary when working with many 3D datasets. When a multi-GPU model is saved as weights only, it is difficult to re-load the model because the neural network architecture expects single-GPU weights to be imported. A clever solution is to re-save the multi-GPU weights as single-GPU by extracting the weights of the second-to-last layer in the multi-GPU model. The below code provides an example: from tensorflow.keras.utils import multi_gpu_model# Assumes the BCNN architecture is defined in the model file.from model import bcnndef load_model(input_shape, weights_path, num_gpus): """Loads model from .h5 file. If model is saved as multi-gpu, re-saves it as single-gpu.""" # Loads model as multi-gpu, if possible. try: model = bcnn(input_shape) model = multi_gpu_model(model, gpus=num_gpus) # Converts .h5 file to single-gpu. model.load_weights(weights_path) model = model.layers[-2] model.save_weights(weights_path) except ValueError as e: pass # Loads single-gpu model. model = bcnn(input_shape) model.load_weights(weights_path) # Converts to multi-gpu model if applicable. if num_gpus > 1: model = multi_gpu_model(model, gpus=num_gpus) return model In addition, 3D dataset management can become overwhelming very quickly. Many CT and MRI scans can be of dimension 1000 x 1000 x 1000 or even larger, which is infeasible to perform inference on all at once. Instead, a “chunking” technique is required, which separates the large volume into overlapping chunks for feeding into the BCNN. The neural network is then trained on the chunks and predicts on chunks of the same size, which can be reconstructed to obtain a fully-inferred complete volume by reversing the chunking process. The chunking process involves passing a sliding rectangular prism “window” across the original volume at a certain ratio of overlap, called the “step size”. We have to be careful to avoid off-by-one errors, and we also need to save the coordinates of each chunk to use during reconstruction. The output of the algorithm is an enormous 5D numpy array which contains all of the chunks in the dataset. Furthermore, there is a Keras bug that causes an error whenever the last batch in an epoch is not divisible across all GPUs; avoiding this bug requires truncating the end of the array. An implementation of this algorithm is in the “chunks” method here: https://github.com/sandialabs/bcnn/blob/master/dataset.py. Recall that BCNNs are nondeterministic, so when predicting on a chunk multiple times, one will obtain many different (and possibly very wrong) predictions. In order to obtain an accurate prediction as well as uncertainty maps, we must predict many times on each chunk to obtain a distribution of sigmoid values. This is called Monte Carlo sampling. This process is heavily customizable, but here we represent the segmentation as the average of all sigmoid values (casting to 0 and 1 for binary segmentations), and the uncertainty map as the difference between the 20th and 80th percentiles. Critically, the chunking reconstruction process can lead to heavy artifacts in the output segmentation volumes. This is because the neural network does not have enough spatial context to predict effectively on the edges of every chunk; instead, we discard a certain percentage around each chunk (about 5%) to ensure that we only keep justified predictions. An implementation of this algorithm is in the “predict” method here: https://github.com/sandialabs/bcnn/blob/master/test.py. The BCNN is the new state-of-the-art in uncertainty quantification for volumetric segmentation; in particular, we validated the BCNN using CT scans of graphite electrodes for lithium-ion batteries and laser-welded metal joints. The BCNN provides greatly improved uncertainty maps as compared to the previously superior MCDN while achieving an equal or better segmentation accuracy. See below for a sample image from our paper which highlights the continuity and visual gradients of the BCNN uncertainty map, while the MCDN generates an uninterpretable pointwise uncertainty map. Furthermore, we employ the PAvPU metric8, a recent measure designed to validate uncertainty results, and find that the BCNN consistently and vastly outperforms the MCDN at encoding the relationship between uncertainty and accuracy. See our paper at https://arxiv.org/pdf/1910.10793.pdf for an in-depth analysis and validation of the BCNN and its advantages over the MCDN, and feel free to utilize and fork the open-source codebase at https://github.com/sandialabs/bcnn. While our novel contribution is in the 3D space, we also provide a 2D implementation for typical image segmentation. [1] Charles Blundell, Julien Cornebise, Koray Kavukcuoglu, and Daan Wierstra. Weight uncertainty in neural networks. In Proceedings of the 32nd International Conference on Machine Learning, 2015. https://arxiv.org/abs/1505.05424 [2] Ozgun Cicek, Ahmed Abdulkadir, Soeren S. Lienkamp, Thomas Brox, and Olaf Ronneberger. 3d u-net: Learning dense volumetric segmentation from sparse annotation. In Proceedings of the 19th International Conference on Medical Image Computing and Computer-Assisted Intervention, 2016. https://arxiv.org/abs/1606.06650 [3] Yarin Gal and Zoubin Ghahramani. Dropout as a bayesian approximation: Representing model uncertainty in deep learning. In Proceedings of the 33rd International Conference on Machine Learning, 2016. https://arxiv.org/abs/1506.02142 [4] Alex Graves. Practical variational inference for neural networks. In Proceedings of the 24th Conference on Advances in Neural Information Processing Systems, 2011. https://papers.nips.cc/paper/4329-practical-variational-inference-for-neural-networks [5] Geoffrey E. Hinton and Drew Van Camp. Keeping neural networks simple by minimizing the description length of the weights. In Proceedings of the 16th Conference on Learning Theory, 1993. https://www.cs.toronto.edu/~hinton/absps/colt93.html [6] Diederik P. Kingma, Tim Salimans, and Max Welling. Variational Dropout and the Local Reparameterization Trick. In Proceedings of the 28th Conference on Advances in Neural Information Processing Systems, 2015. https://arxiv.org/abs/1506.02557 [7] Fausto Milletari, Nassir Navab, and Seyed-Ahmad Ahmadi. V-net: Fully convolutional neural networks for volumetric medical image segmentation. In Proceedings of the 4th International Conference on 3D Vision, 2016. https://arxiv.org/abs/1606.04797 [8] Jishnu Mukhoti and Yarin Gal. Evaluating bayesian deep learning methods for semantic segmentation. arXiv preprint 1811.12709, 2019. https://arxiv.org/abs/1811.12709 [9] Ian Osband. Risk versus uncertainty in deep learning: Bayes, bootstrap and the dangers of dropout. In Proceedings of the 29th Conference on Advances in Neural Information Processing Systems: Workshop on Bayesian Deep Learning, 2016. https://pdfs.semanticscholar.org/dde4/b95be20a160253a6cc9ecd75492a13d60c10.pdf [10] Dustin Tran, Michael W. Dusenberry, Mark van der Wilk, and Danijar Hafner. Bayesian layers: A module for neural network uncertainty. 2019. https://arxiv.org/abs/1812.03973 [11] Yeming Wen, Paul Vicol, Jimmy Ba, Dustin Train, and Roger Grosse. Flipout: Efficient pseudo-independent weight perturbations on mini-batches. In Proceedings of the 6th International Conference on Learning Representations, 2018. https://arxiv.org/abs/1803.04386 [12] Yuxin Wu and Kaiming He. Group normalization. In Proceedings of the 2018 European Conference on Computer Vision, 2018. https://arxiv.org/abs/1803.08494 This work was produced during the author’s internship at Sandia National Laboratories. Sandia National Laboratories is a multimission laboratory managed and operated by National Technology & Engineering Solutions of Sandia, LLC, a wholly owned subsidiary of Honeywell International Inc., for the U.S. Department of Energy’s National Nuclear Security Administration under contract DE-NA0003525. SAND2020–1419 S.
[ { "code": null, "e": 86, "s": 46, "text": "PAPER: https://arxiv.org/abs/1910.10793" }, { "code": null, "e": 127, "s": 86, "text": "CODE: https://github.com/sandialabs/bcnn" }, { "code": null, "e": 142, "s": 127, "text": "Key Takeaways:" }, { "code": null, "e": 282, "s": 142, "text": "· Measuring uncertainty is not possible in a regular deep neural network, but it is extremely important for interpretability and validation" }, { "code": null, "e": 407, "s": 282, "text": "· Bayesian neural networks learn probability distributions rather than point estimates, allowing them to measure uncertainty" }, { "code": null, "e": 525, "s": 407, "text": "· We designed the first-ever successful Bayesian convolutional neural network (BCNN) architecture for 3D segmentation" }, { "code": null, "e": 670, "s": 525, "text": "· Our BCNN beats the current state-of-the-art neural network in uncertainty quantification while achieving equal or better segmentation accuracy" }, { "code": null, "e": 753, "s": 670, "text": "· Our academic paper and full open-source code implementation are available online" }, { "code": null, "e": 1162, "s": 753, "text": "Consider this scenario: a certain aircraft manufacturing company produces safety-critical engine parts for commercial aircraft. Since the engine parts must be guaranteed to work, the company validates each of them in a painstaking, months-long process wherein they take a 3D CT scan of the part, annotate the hundreds of millions of voxels by hand, and use the annotated scan to analyze the part for defects." }, { "code": null, "e": 1627, "s": 1162, "text": "This is not time- or cost-effective, so the company hires a team of data scientists to design a deep neural network which automatically validates the parts using state-of-the-art volumetric segmentation techniques. The neural network is seemingly successful, but one day a part verified by the neural network inexplicably fails during usage, causing engine failure in the aircraft and leading to hundreds of fatalities and billions of dollars lost for the company." }, { "code": null, "e": 1986, "s": 1627, "text": "So what went wrong? Well, deep neural networks are well-known for making accurate predictions, but one of their greatest weaknesses is that they lack the capacity for measuring uncertainty within their predictions. Thus, the deep learning system had no capacity to distinguish between a part that was 100% certified, and a part that just barely made the cut." }, { "code": null, "e": 2365, "s": 1986, "text": "One may think that the value of the sigmoid output is usable as a measure of uncertainty, but this is not true because these values are dependent on the inferred sample being “close” to the training distribution. If one infers on a sample far from the training distribution (i.e., a part with a defect in it), the sigmoid output cannot be used as a proxy for model uncertainty3." }, { "code": null, "e": 2757, "s": 2365, "text": "In other words, deep neural networks perform best when the test set is “similar” to the training set; in other words, there may be examples in the test set which the neural network is unsure about because there were no similar training examples. But because there is no “I don’t know” output available, defective parts can end up verified by the deep learning system and moved to production." }, { "code": null, "e": 3207, "s": 2757, "text": "This example illustrates the critical importance of uncertainty quantification in deep neural networks, the research and development of which has skyrocketed in the last five years. Recent techniques cast neural networks, usually pointwise estimators, as probabilistic or Bayesian models. The two most common neural network architectures for this purpose are Monte Carlo dropout networks3 (MCDNs) and Bayesian convolutional neural networks1 (BCNNs)." }, { "code": null, "e": 3550, "s": 3207, "text": "MCDNs use dropout layers to approximate deep Gaussian processes, and while easy to implement, their statistical soundness has been called into question9. BCNNs use variational inference to learn the posterior distribution of the weights given the dataset and are much more difficult to implement but give greatly improved uncertainty results." }, { "code": null, "e": 3953, "s": 3550, "text": "It has been postulated that Bayesian neural networks for large problems, including in the 3D image segmentation space, are infeasible due to prohibitive computational costs3. Here, we refute that claim and present the first-ever successful implementation of a 3D BCNN for uncertainty quantification in volumetric segmentation, detail how it works, and explain some sections of the open-source codebase." }, { "code": null, "e": 4375, "s": 3953, "text": "In particular, this novel neural network architecture provides improved uncertainty quantification as compared to MCDNs while achieving equal or better segmentation accuracy. Through experimentation on CT scans of battery electrode and laser-welded metals, we show that the uncertainty maps generated by the BCNN capture continuity and visual gradients, making them interpretable as confidence intervals for segmentation." }, { "code": null, "e": 4680, "s": 4375, "text": "While most neural networks learn pointwise estimates of their weights, the more rigorous view is that these estimates do not fully encapsulate the uncertainty inherent in the values of the weights. Instead, in a BCNN, the weights are each implicitly described as (multivariate) probability distributions." }, { "code": null, "e": 5634, "s": 4680, "text": "Describing the weights of the neural networks as probability distributions has several consequences. First, it makes the neural network nondeterministic; every time we compute a forward pass, we must sample from each weight distribution to obtain a point estimate which can be used for inference. Repeated applications of this sampling technique, called Monte Carlo sampling, will result in different predictions which can then be analyzed for uncertainty. Second, it changes the backpropagation algorithm since we cannot backpropagate through a sampling operation (it has no gradient). In a later section, we will discuss how to fix this problem using the Bayes by Backprop algorithm. Finally, it makes the neural network much more difficult to reliably train, especially in 3D, and susceptible to vanishing/exploding gradients. We use a clever normalization technique called group normalization to solve this problem, also detailed in a later section." }, { "code": null, "e": 6270, "s": 5634, "text": "How exactly do we get distributions over the weights? Well, in a perfect world, we could use Bayes’ Rule to calculate them precisely. To do this, we would begin with a prior distribution over the weights; this is our “initial guess” of what a weight distribution would look like. It is denoted p(w) and is generally a standard normal distribution. Then, we would use our data to calculate the posterior distributions of the weights given the dataset, denoted p(w|D). This is equivalent to finding a w that maximizes the likelihood of the dataset given those weights, denoted p(D|w), and we can perform this calculation via Bayes’ Rule:" }, { "code": null, "e": 6880, "s": 6270, "text": "However, due to the extreme overparameterization found in neural networks, the integral in the denominator is generally intractable. So, we need to learn the posterior distribution rather than calculate it exactly. Previous work by Hinton and Van Camp5 and Graves4 proposed variational learning (also called variational inference) as a method to approximate the posterior distribution. Variational learning finds the parameters θ of the distribution p(w|θ), called the variational distribution, via the minimization of the variational free energy cost function F, often called the expected lower bound (ELBO)." }, { "code": null, "e": 7355, "s": 6880, "text": "The variational free energy consists of the sum of the Kullback-Leibler (KL) divergence, which measures the distance between the prior and variational distributions, and the negative log-likelihood, which measures the goodness-of-fit of the model. Blundell et al.1 explains the variational free energy loss function as a tradeoff between satisfying the simplicity prior (represented by the KL term) and satisfying the complexity of the dataset (represented by the NLL term):" }, { "code": null, "e": 7735, "s": 7355, "text": "The longer we train the neural network, the closer we will get to minimizing this cost function, and the closer our variational distribution will get to the true posterior distribution. In practice, the KL term has a regularizing effect on the output of the neural network, preventing the learned distribution from overfitting at the cost of a lower NLL term in the training set." }, { "code": null, "e": 7922, "s": 7735, "text": "This loss function is amenable to mini-batch optimization by scaling the cost for mini-batch i as follows, essentially spreading out the KL divergence penalty across the entire dataset1:" }, { "code": null, "e": 8126, "s": 7922, "text": "If a Bayesian neural network is implemented in TensorFlow Probability, the below is a valid Python implementation of the variational free energy loss (note that binary cross-entropy is just negated NLL):" }, { "code": null, "e": 8592, "s": 8126, "text": "from tensorflow.keras.losses import binary_crossentropydef vfe_loss(model, dataset_size, batch_size, alpha=1): \"\"\"Defines variational free energy loss. Sum of KL divergence and binary cross-entropy.\"\"\" # KL Divergence should be applied once per epoch only. kl = sum(model.losses) / (dataset_size / batch_size) def loss(y_true, y_pred): bce = binary_crossentropy(y_true, y_pred) return alpha * kl + (1. / alpha) * bce return loss" }, { "code": null, "e": 8624, "s": 8592, "text": "Challenges in Bayesian Learning" }, { "code": null, "e": 8843, "s": 8624, "text": "Variational Bayesian learning is generally considered more statistically sound than, for example, approximate Bayesian inference via dropout layers9. However, this comes at the cost of several computational challenges." }, { "code": null, "e": 9614, "s": 8843, "text": "First, a random variable sampled from a distribution has no gradient, so Bayesian neural networks seem incompatible with backpropagation. However, Kingma et al.6 showed that it is possible to reparametrize the random variable as a deterministic variable for computation. As an example, let a weight w be sampled from a normal distribution with mean μ and variance σ2. Then, a valid reparameterization is w=μ+σε where ε is an auxiliary noise variable sampled from a standard normal distribution. Now, instead of a sampling operation, we have an affine combination, which is easily utilized in backpropagation. More complex calculations are needed to efficiently scale this computation; see Kingma’s paper for more. This is often called the local reparameterization trick." }, { "code": null, "e": 10310, "s": 9614, "text": "Next, Bayesian learning was previously considered computationally infeasible due to the massive number of weight updates necessary if trained using an ensemble method. To solve this, Blundell et al.1 designed the Bayes by Backprop algorithm. Previous work focused on training stochastic hidden units, but there are easily two orders of magnitude more weights than hidden units, and Bayes by Backprop was the first algorithm to effectively train probabilistic weights in a neural network. Bayes by Backprop works by using the gradients calculated in backpropagation to “scale and shift” the variational parameters of the posterior, thus updating the posterior with minimal additional computation." }, { "code": null, "e": 10988, "s": 10310, "text": "Since 3D training volumes can be quite large, our batch size is constrained by the amount of available GPU memory, resulting in a batch size too small for batch normalization to accurately compute batch statistics. Thus, we use a technique proposed by Wu and He12 called group normalization, which normalizes groups of channels and is shown to have accurate performance independent of batch size. Proper normalization was observed to be a critical factor in the convergence of our model since it helps avoid vanishing/exploding gradients; by tuning the number of groups used in the group normalization layers, we found that the BCNN converged most reliably when using 4 groups." }, { "code": null, "e": 11810, "s": 10988, "text": "Finally, one challenge associated with probabilistic weights is that all examples in a mini-batch typically have similarly sampled weights, limiting the variance reduction effect of large mini-batches. One side effect of the local reparameterization trick6 mentioned above is that it greatly reduces the variance of stochastically sampled weights by transforming global weight uncertainty into independent local noise across examples in the mini-batch. In a similar vein, Wen et al.11 proposed the Flipout estimator, which empirically achieves ideal variance reduction by sampling weights pseudo-independently for each example. An important difference is that local reparametrization works only for fully connected networks, while Flipout can be used effectively in fully-connected, convolutional, and recurrent networks." }, { "code": null, "e": 12275, "s": 11810, "text": "Our 3D BCNN architecture draws from the image segmentation literature by utilizing the common encoder-decoder setup seen in V-Net7 and 3D U-Net2 , deep neural networks originally used for 3D segmentation of human prostates and frog kidneys, respectively. In this architecture, the encoder half (left) of the network compresses the input into a latent space while the decoder half (right) decompresses the latent representation of the input into a segmentation map." }, { "code": null, "e": 13031, "s": 12275, "text": "The encoder half of the BCNN uses typical 3D convolutions to maximize information transfer between the original volume and the latent space, but the decoder half of the network uses 3D Bayesian convolutional layers. Each of these is initialized with a standard normal prior and employs the aforementioned Flipout estimator11 to approximate the distribution during forward passes. Note the skip connections in yellow, which assist in feature-forwarding throughout the network. Our implementation draws from the Bayesian Layers library10 included in TensorFlow Probability, which keeps track of losses representing the KL divergence of the layer’s posterior distribution with respect to its prior and makes computing the variational free energy loss simple." }, { "code": null, "e": 13156, "s": 13031, "text": "An implementation of this BCNN architecture is available at https://github.com/sandialabs/bcnn/blob/master/bayesian_vnet.py." }, { "code": null, "e": 13971, "s": 13156, "text": "Using a BCNN in practice brings with it a few peculiarities that can be difficult to effectively implement. First, it is currently impossible to save the architecture and weights of a model that combines, say, Keras layers and Bayesian layers. Instead, one must save the weights only and then load them into an instantiated architecture. This gets worse when the models are designated as multi-GPU, which is virtually necessary when working with many 3D datasets. When a multi-GPU model is saved as weights only, it is difficult to re-load the model because the neural network architecture expects single-GPU weights to be imported. A clever solution is to re-save the multi-GPU weights as single-GPU by extracting the weights of the second-to-last layer in the multi-GPU model. The below code provides an example:" }, { "code": null, "e": 14820, "s": 13971, "text": "from tensorflow.keras.utils import multi_gpu_model# Assumes the BCNN architecture is defined in the model file.from model import bcnndef load_model(input_shape, weights_path, num_gpus): \"\"\"Loads model from .h5 file. If model is saved as multi-gpu, re-saves it as single-gpu.\"\"\" # Loads model as multi-gpu, if possible. try: model = bcnn(input_shape) model = multi_gpu_model(model, gpus=num_gpus) # Converts .h5 file to single-gpu. model.load_weights(weights_path) model = model.layers[-2] model.save_weights(weights_path) except ValueError as e: pass # Loads single-gpu model. model = bcnn(input_shape) model.load_weights(weights_path) # Converts to multi-gpu model if applicable. if num_gpus > 1: model = multi_gpu_model(model, gpus=num_gpus) return model" }, { "code": null, "e": 15351, "s": 14820, "text": "In addition, 3D dataset management can become overwhelming very quickly. Many CT and MRI scans can be of dimension 1000 x 1000 x 1000 or even larger, which is infeasible to perform inference on all at once. Instead, a “chunking” technique is required, which separates the large volume into overlapping chunks for feeding into the BCNN. The neural network is then trained on the chunks and predicts on chunks of the same size, which can be reconstructed to obtain a fully-inferred complete volume by reversing the chunking process." }, { "code": null, "e": 15935, "s": 15351, "text": "The chunking process involves passing a sliding rectangular prism “window” across the original volume at a certain ratio of overlap, called the “step size”. We have to be careful to avoid off-by-one errors, and we also need to save the coordinates of each chunk to use during reconstruction. The output of the algorithm is an enormous 5D numpy array which contains all of the chunks in the dataset. Furthermore, there is a Keras bug that causes an error whenever the last batch in an epoch is not divisible across all GPUs; avoiding this bug requires truncating the end of the array." }, { "code": null, "e": 16062, "s": 15935, "text": "An implementation of this algorithm is in the “chunks” method here: https://github.com/sandialabs/bcnn/blob/master/dataset.py." }, { "code": null, "e": 16653, "s": 16062, "text": "Recall that BCNNs are nondeterministic, so when predicting on a chunk multiple times, one will obtain many different (and possibly very wrong) predictions. In order to obtain an accurate prediction as well as uncertainty maps, we must predict many times on each chunk to obtain a distribution of sigmoid values. This is called Monte Carlo sampling. This process is heavily customizable, but here we represent the segmentation as the average of all sigmoid values (casting to 0 and 1 for binary segmentations), and the uncertainty map as the difference between the 20th and 80th percentiles." }, { "code": null, "e": 17010, "s": 16653, "text": "Critically, the chunking reconstruction process can lead to heavy artifacts in the output segmentation volumes. This is because the neural network does not have enough spatial context to predict effectively on the edges of every chunk; instead, we discard a certain percentage around each chunk (about 5%) to ensure that we only keep justified predictions." }, { "code": null, "e": 17135, "s": 17010, "text": "An implementation of this algorithm is in the “predict” method here: https://github.com/sandialabs/bcnn/blob/master/test.py." }, { "code": null, "e": 17714, "s": 17135, "text": "The BCNN is the new state-of-the-art in uncertainty quantification for volumetric segmentation; in particular, we validated the BCNN using CT scans of graphite electrodes for lithium-ion batteries and laser-welded metal joints. The BCNN provides greatly improved uncertainty maps as compared to the previously superior MCDN while achieving an equal or better segmentation accuracy. See below for a sample image from our paper which highlights the continuity and visual gradients of the BCNN uncertainty map, while the MCDN generates an uninterpretable pointwise uncertainty map." }, { "code": null, "e": 18301, "s": 17714, "text": "Furthermore, we employ the PAvPU metric8, a recent measure designed to validate uncertainty results, and find that the BCNN consistently and vastly outperforms the MCDN at encoding the relationship between uncertainty and accuracy. See our paper at https://arxiv.org/pdf/1910.10793.pdf for an in-depth analysis and validation of the BCNN and its advantages over the MCDN, and feel free to utilize and fork the open-source codebase at https://github.com/sandialabs/bcnn. While our novel contribution is in the 3D space, we also provide a 2D implementation for typical image segmentation." }, { "code": null, "e": 18530, "s": 18301, "text": "[1] Charles Blundell, Julien Cornebise, Koray Kavukcuoglu, and Daan Wierstra. Weight uncertainty in neural networks. In Proceedings of the 32nd International Conference on Machine Learning, 2015. https://arxiv.org/abs/1505.05424" }, { "code": null, "e": 18847, "s": 18530, "text": "[2] Ozgun Cicek, Ahmed Abdulkadir, Soeren S. Lienkamp, Thomas Brox, and Olaf Ronneberger. 3d u-net: Learning dense volumetric segmentation from sparse annotation. In Proceedings of the 19th International Conference on Medical Image Computing and Computer-Assisted Intervention, 2016. https://arxiv.org/abs/1606.06650" }, { "code": null, "e": 19082, "s": 18847, "text": "[3] Yarin Gal and Zoubin Ghahramani. Dropout as a bayesian approximation: Representing model uncertainty in deep learning. In Proceedings of the 33rd International Conference on Machine Learning, 2016. https://arxiv.org/abs/1506.02142" }, { "code": null, "e": 19336, "s": 19082, "text": "[4] Alex Graves. Practical variational inference for neural networks. In Proceedings of the 24th Conference on Advances in Neural Information Processing Systems, 2011. https://papers.nips.cc/paper/4329-practical-variational-inference-for-neural-networks" }, { "code": null, "e": 19579, "s": 19336, "text": "[5] Geoffrey E. Hinton and Drew Van Camp. Keeping neural networks simple by minimizing the description length of the weights. In Proceedings of the 16th Conference on Learning Theory, 1993. https://www.cs.toronto.edu/~hinton/absps/colt93.html" }, { "code": null, "e": 19825, "s": 19579, "text": "[6] Diederik P. Kingma, Tim Salimans, and Max Welling. Variational Dropout and the Local Reparameterization Trick. In Proceedings of the 28th Conference on Advances in Neural Information Processing Systems, 2015. https://arxiv.org/abs/1506.02557" }, { "code": null, "e": 20075, "s": 19825, "text": "[7] Fausto Milletari, Nassir Navab, and Seyed-Ahmad Ahmadi. V-net: Fully convolutional neural networks for volumetric medical image segmentation. In Proceedings of the 4th International Conference on 3D Vision, 2016. https://arxiv.org/abs/1606.04797" }, { "code": null, "e": 20244, "s": 20075, "text": "[8] Jishnu Mukhoti and Yarin Gal. Evaluating bayesian deep learning methods for semantic segmentation. arXiv preprint 1811.12709, 2019. https://arxiv.org/abs/1811.12709" }, { "code": null, "e": 20560, "s": 20244, "text": "[9] Ian Osband. Risk versus uncertainty in deep learning: Bayes, bootstrap and the dangers of dropout. In Proceedings of the 29th Conference on Advances in Neural Information Processing Systems: Workshop on Bayesian Deep Learning, 2016. https://pdfs.semanticscholar.org/dde4/b95be20a160253a6cc9ecd75492a13d60c10.pdf" }, { "code": null, "e": 20737, "s": 20560, "text": "[10] Dustin Tran, Michael W. Dusenberry, Mark van der Wilk, and Danijar Hafner. Bayesian layers: A module for neural network uncertainty. 2019. https://arxiv.org/abs/1812.03973" }, { "code": null, "e": 21003, "s": 20737, "text": "[11] Yeming Wen, Paul Vicol, Jimmy Ba, Dustin Train, and Roger Grosse. Flipout: Efficient pseudo-independent weight perturbations on mini-batches. In Proceedings of the 6th International Conference on Learning Representations, 2018. https://arxiv.org/abs/1803.04386" }, { "code": null, "e": 21160, "s": 21003, "text": "[12] Yuxin Wu and Kaiming He. Group normalization. In Proceedings of the 2018 European Conference on Computer Vision, 2018. https://arxiv.org/abs/1803.08494" } ]
Step by step bar-charts using Plotly Express | by Alejandra Vlerick | Towards Data Science
As an aspiring data scientist, I love playing around with datasets and unraveling the story hidden behind the rows and columns. One of the first things I do is to visualise the data with bar charts. This allows me to get acquainted with the information and formulate a game plan for future analysis. If you’re not already a member, get your Medium Membership here! I decided to find a nice and simple dataset that would allow me to focus on the plotting and not on the cleaning. I found the “Married at first sight” dataset to fit my needs because it has a healthy mix of numerical and categorical data. This TV show has become a quarantine guilty pleasure. On this series, two people are randomly matched and they can decide to get married or not after vacationing for three weeks in a dream location. The dataset can be found here. The first step is to import all the libraries I will be using. Plotly is a is a library for creating static, animated, and interactive visualisations in Python. Plotly Express is a new high-level Python visualisation library part of Plotly v.4, that allows to plot complex charts using simple syntax. Once the libraries have been imported, I load my file using the read_csv() function and convert it to a pandas dataframe. import pandas as pdimport plotly.express as pxfrom plotly.subplots import make_subplotsdf = pd.read_csv("Data/mafs.csv") There are two things I do as soon as I have my pandas dataframe. Firstly, I look at the header names and the variable types stored in each column. print(df.info()) This tells me that there are 17 columns in my dataset, some store ‘Object’ types, which I like to think of as strings and also ‘int64’ which is simply and integer stored with 64 bits. Secondly, I look at the first row of my dataframe. print(df.iloc[0]) By changing the index [0] to any integer I could also find the information of any row. This tells me that in this TV show, the contestant Jamie Otis-Hehner was 27 years old at the time of the competition and a nurse in profession. More importantly, this contestant decided to get married in the TV show, and is still married today. Lucky gal! My first instinct was to plot the number of people that agreed to get married versus those that preferred remaining single. This information is found on the ‘Decision’ column where values are ‘Yes’ or ‘No’. df1 = df.groupby(["Decision"]).count().reset_index()fig = px.bar(df1, y=df.groupby(["Decision"]).size(), x="Decision", color='Decision')fig.show() Using the groupby() function I was able to shuffle the rows in my dataset such that they were organised by Decision outcome. The only thing left to do was to select the x-axis and y-axis that yielded the desired information. It is clear from the graph that 70% of the contestants decide to get married after three weeks, which is a surprisingly high success rate. Maybe this is why there have been 10 seasons of the show! The second thing I wanted to do is to see if the location influences the number of successful couples. For this, I plotted location on the x-axis and the number of ‘Yes’ and ‘No’ answers on the y-axis. df2 = df.groupby(['Location','Decision']).size().reset_index(name='Decision_qt')df2_yes = df2[df2['Decision']=='Yes']df2_yes.set_index('Location', inplace=True)fig = px.bar(df2, x="Location", y="Decision_qt", color='Decision', barmode='stack')fig.show() Again, using the groupby() function I group my rows by Location first and then Decision, essentially creating a group, within a group. I also create an additional column called Decision_qt, which holds the number of ‘Yes’ and ‘No’ answers per location. Other than Chicago and Dallas (where ALL the contestants decided to get married!) we can see that the location influences lightly the success rate of the couples. At this point I would add that we are only looking at around 6 to 12 people per location, a bigger sample size would yield more reliable information... Now, the next thing I want to look into is the number of people that divorced after getting married on the show. In order to plot this ratio, I need to follow three simple steps. I create a dataframe ‘df_married’ that groups the rows by location and status. I also create an additional column ‘Maried_qt’ with the total number of married people in each row. Finally, I modify this dataset such that only the rows of married participants remain. df_married = df.groupby(['Location','Status']).size().reset_index(name='Married_qt')df_married = df_married[df_married['Status']=='Married'] Now I want to count the total number of participants per location. This is achieved again by using the groupby() function and summing the rows in each group using the size() function. df3 = df.groupby(['Location']).size().reset_index(name='Participants_qt') In order to perform the division we first have to set the index of our two dataframes to be the Location (the ratio is taken between couples that married and divorced in the same city). The result of the division is saved in a column named ‘ratio_Married’ # Divisiondf_married.set_index('Location', inplace=True)df3.set_index('Location', inplace=True)df3['ratio_Married'] = (df_married['Married_qt'] / df3['Participants_qt'])# Plottingdf_married.reset_index(inplace = True)df3.reset_index(inplace = True)fig = px.bar(df3, x='Location', y='ratio_Married', color='Location', barmode='stack')# fig.show() For the plotting, the corresponding Location and Ratio columns of the dataframe are selected in x-axis and y-axis respectively from dataframe df3. This plot is less optimistic than the previous two. More than 50% of the couples that agreed to get married get divorced subsequently. In Atlanta and South Florida, not a single contestant is still married to his/her counterpart... This took me a little while to figure out, which is why I’m super excited to share! Creating subplots can be extremely useful when trying to compare and contrast plots, or bar charts. Underlying relationships can be easily visualised when things are put side by side. In order to make a figure with multiple subplots, the first step is to specify the number of subplots and their location. In my case, I chose to have my figures on the same row but different columns (side by side). The type “xy” indicates the coordinate system (could also be polar for example). subfig = make_subplots(rows=1, cols=2, specs=[[{"type": "xy"}, {"type": "xy"}]]) Now we create two sub-plots, specify their axis and values. This is the same as the Yes vs No bar chart at the beginning of the article. It is important to note that plotly express only supports series. This means that I need to convert the information I want to plot into a series from the pandas dataframe using the pd.Series() function. df4 = df.groupby(["Decision"]).size().reset_index(name='Total_YesNo')y1=pd.Series(df4['Total_YesNo'])subfig.add_bar(row=1, col=1, y=y1, x=["Yes", "No"]) In the second figure I plot the ratio of Yes vs No answers per location. The x and y-axis values are transformed into series and this is passed onto the subfigure for plotting. df5 = df.groupby(['Location']).size().reset_index(name='Participants_qt')x2=pd.Series(df5['Location'])y2=pd.Series(df3['ratio_YesNo'])subfig.add_bar( row=1, col=2, x=x2, y=y2)subfig.show() All the code can be found in the Married.py file on Github here! If you like my work, I’d greatly appreciate if you followed me Medium here. If you have any questions, suggestions or ideas on how to improve, please leave a comment below or get in touch through LinkedIn here.
[ { "code": null, "e": 472, "s": 172, "text": "As an aspiring data scientist, I love playing around with datasets and unraveling the story hidden behind the rows and columns. One of the first things I do is to visualise the data with bar charts. This allows me to get acquainted with the information and formulate a game plan for future analysis." }, { "code": null, "e": 537, "s": 472, "text": "If you’re not already a member, get your Medium Membership here!" }, { "code": null, "e": 1006, "s": 537, "text": "I decided to find a nice and simple dataset that would allow me to focus on the plotting and not on the cleaning. I found the “Married at first sight” dataset to fit my needs because it has a healthy mix of numerical and categorical data. This TV show has become a quarantine guilty pleasure. On this series, two people are randomly matched and they can decide to get married or not after vacationing for three weeks in a dream location. The dataset can be found here." }, { "code": null, "e": 1307, "s": 1006, "text": "The first step is to import all the libraries I will be using. Plotly is a is a library for creating static, animated, and interactive visualisations in Python. Plotly Express is a new high-level Python visualisation library part of Plotly v.4, that allows to plot complex charts using simple syntax." }, { "code": null, "e": 1429, "s": 1307, "text": "Once the libraries have been imported, I load my file using the read_csv() function and convert it to a pandas dataframe." }, { "code": null, "e": 1550, "s": 1429, "text": "import pandas as pdimport plotly.express as pxfrom plotly.subplots import make_subplotsdf = pd.read_csv(\"Data/mafs.csv\")" }, { "code": null, "e": 1697, "s": 1550, "text": "There are two things I do as soon as I have my pandas dataframe. Firstly, I look at the header names and the variable types stored in each column." }, { "code": null, "e": 1714, "s": 1697, "text": "print(df.info())" }, { "code": null, "e": 1898, "s": 1714, "text": "This tells me that there are 17 columns in my dataset, some store ‘Object’ types, which I like to think of as strings and also ‘int64’ which is simply and integer stored with 64 bits." }, { "code": null, "e": 1949, "s": 1898, "text": "Secondly, I look at the first row of my dataframe." }, { "code": null, "e": 1967, "s": 1949, "text": "print(df.iloc[0])" }, { "code": null, "e": 2054, "s": 1967, "text": "By changing the index [0] to any integer I could also find the information of any row." }, { "code": null, "e": 2310, "s": 2054, "text": "This tells me that in this TV show, the contestant Jamie Otis-Hehner was 27 years old at the time of the competition and a nurse in profession. More importantly, this contestant decided to get married in the TV show, and is still married today. Lucky gal!" }, { "code": null, "e": 2517, "s": 2310, "text": "My first instinct was to plot the number of people that agreed to get married versus those that preferred remaining single. This information is found on the ‘Decision’ column where values are ‘Yes’ or ‘No’." }, { "code": null, "e": 2700, "s": 2517, "text": "df1 = df.groupby([\"Decision\"]).count().reset_index()fig = px.bar(df1, y=df.groupby([\"Decision\"]).size(), x=\"Decision\", color='Decision')fig.show()" }, { "code": null, "e": 2925, "s": 2700, "text": "Using the groupby() function I was able to shuffle the rows in my dataset such that they were organised by Decision outcome. The only thing left to do was to select the x-axis and y-axis that yielded the desired information." }, { "code": null, "e": 3122, "s": 2925, "text": "It is clear from the graph that 70% of the contestants decide to get married after three weeks, which is a surprisingly high success rate. Maybe this is why there have been 10 seasons of the show!" }, { "code": null, "e": 3324, "s": 3122, "text": "The second thing I wanted to do is to see if the location influences the number of successful couples. For this, I plotted location on the x-axis and the number of ‘Yes’ and ‘No’ answers on the y-axis." }, { "code": null, "e": 3626, "s": 3324, "text": "df2 = df.groupby(['Location','Decision']).size().reset_index(name='Decision_qt')df2_yes = df2[df2['Decision']=='Yes']df2_yes.set_index('Location', inplace=True)fig = px.bar(df2, x=\"Location\", y=\"Decision_qt\", color='Decision', barmode='stack')fig.show()" }, { "code": null, "e": 3879, "s": 3626, "text": "Again, using the groupby() function I group my rows by Location first and then Decision, essentially creating a group, within a group. I also create an additional column called Decision_qt, which holds the number of ‘Yes’ and ‘No’ answers per location." }, { "code": null, "e": 4194, "s": 3879, "text": "Other than Chicago and Dallas (where ALL the contestants decided to get married!) we can see that the location influences lightly the success rate of the couples. At this point I would add that we are only looking at around 6 to 12 people per location, a bigger sample size would yield more reliable information..." }, { "code": null, "e": 4373, "s": 4194, "text": "Now, the next thing I want to look into is the number of people that divorced after getting married on the show. In order to plot this ratio, I need to follow three simple steps." }, { "code": null, "e": 4639, "s": 4373, "text": "I create a dataframe ‘df_married’ that groups the rows by location and status. I also create an additional column ‘Maried_qt’ with the total number of married people in each row. Finally, I modify this dataset such that only the rows of married participants remain." }, { "code": null, "e": 4780, "s": 4639, "text": "df_married = df.groupby(['Location','Status']).size().reset_index(name='Married_qt')df_married = df_married[df_married['Status']=='Married']" }, { "code": null, "e": 4964, "s": 4780, "text": "Now I want to count the total number of participants per location. This is achieved again by using the groupby() function and summing the rows in each group using the size() function." }, { "code": null, "e": 5038, "s": 4964, "text": "df3 = df.groupby(['Location']).size().reset_index(name='Participants_qt')" }, { "code": null, "e": 5294, "s": 5038, "text": "In order to perform the division we first have to set the index of our two dataframes to be the Location (the ratio is taken between couples that married and divorced in the same city). The result of the division is saved in a column named ‘ratio_Married’" }, { "code": null, "e": 5688, "s": 5294, "text": "# Divisiondf_married.set_index('Location', inplace=True)df3.set_index('Location', inplace=True)df3['ratio_Married'] = (df_married['Married_qt'] / df3['Participants_qt'])# Plottingdf_married.reset_index(inplace = True)df3.reset_index(inplace = True)fig = px.bar(df3, x='Location', y='ratio_Married', color='Location', barmode='stack')# fig.show()" }, { "code": null, "e": 5835, "s": 5688, "text": "For the plotting, the corresponding Location and Ratio columns of the dataframe are selected in x-axis and y-axis respectively from dataframe df3." }, { "code": null, "e": 6067, "s": 5835, "text": "This plot is less optimistic than the previous two. More than 50% of the couples that agreed to get married get divorced subsequently. In Atlanta and South Florida, not a single contestant is still married to his/her counterpart..." }, { "code": null, "e": 6335, "s": 6067, "text": "This took me a little while to figure out, which is why I’m super excited to share! Creating subplots can be extremely useful when trying to compare and contrast plots, or bar charts. Underlying relationships can be easily visualised when things are put side by side." }, { "code": null, "e": 6631, "s": 6335, "text": "In order to make a figure with multiple subplots, the first step is to specify the number of subplots and their location. In my case, I chose to have my figures on the same row but different columns (side by side). The type “xy” indicates the coordinate system (could also be polar for example)." }, { "code": null, "e": 6731, "s": 6631, "text": "subfig = make_subplots(rows=1, cols=2, specs=[[{\"type\": \"xy\"}, {\"type\": \"xy\"}]])" }, { "code": null, "e": 6791, "s": 6731, "text": "Now we create two sub-plots, specify their axis and values." }, { "code": null, "e": 7071, "s": 6791, "text": "This is the same as the Yes vs No bar chart at the beginning of the article. It is important to note that plotly express only supports series. This means that I need to convert the information I want to plot into a series from the pandas dataframe using the pd.Series() function." }, { "code": null, "e": 7248, "s": 7071, "text": "df4 = df.groupby([\"Decision\"]).size().reset_index(name='Total_YesNo')y1=pd.Series(df4['Total_YesNo'])subfig.add_bar(row=1, col=1, y=y1, x=[\"Yes\", \"No\"])" }, { "code": null, "e": 7425, "s": 7248, "text": "In the second figure I plot the ratio of Yes vs No answers per location. The x and y-axis values are transformed into series and this is passed onto the subfigure for plotting." }, { "code": null, "e": 7644, "s": 7425, "text": "df5 = df.groupby(['Location']).size().reset_index(name='Participants_qt')x2=pd.Series(df5['Location'])y2=pd.Series(df3['ratio_YesNo'])subfig.add_bar( row=1, col=2, x=x2, y=y2)subfig.show()" }, { "code": null, "e": 7709, "s": 7644, "text": "All the code can be found in the Married.py file on Github here!" }, { "code": null, "e": 7785, "s": 7709, "text": "If you like my work, I’d greatly appreciate if you followed me Medium here." } ]
ChoiceField - Django Forms - GeeksforGeeks
13 Feb, 2020 ChoiceField in Django Forms is a string field, for selecting a particular choice out of a list of available choices. It is used to implement State, Countries etc. like fields for which information is already defined and user has to choose one. It is used for taking text inputs from the user. The default widget for this input is Select.It Normalizes to: A string. ChoiceField has one extra required argument : choices :Either an iterable of 2-tuples to use as choices for this field, or a callable that returns such an iterable. This argument accepts the same formats as the choices argument to a model field. Syntax field_name = forms.ChoiceField(**options) Illustration of ChoiceField using an Example. Consider a project named geeksforgeeks having an app named geeks. Refer to the following articles to check how to create a project and an app in Django. How to Create a Basic Project using MVT in Django? How to Create an App in Django ? Enter the following code into forms.py file of geeks app. from django import forms # iterableGEEKS_CHOICES =( ("1", "One"), ("2", "Two"), ("3", "Three"), ("4", "Four"), ("5", "Five"),) # creating a form class GeeksForm(forms.Form): geeks_field = forms.ChoiceField(choices = GEEKS_CHOICES) Add the geeks app to INSTALLED_APPS # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'geeks',] Now to render this form into a view we need a view and a URL mapped to that URL. Let’s create a view first in views.py of geeks app, from django.shortcuts import renderfrom .forms import GeeksForm # Create your views here.def home_view(request): context = {} context['form'] = GeeksForm() return render( request, "home.html", context) Here we are importing that particular form from forms.py and creating an object of it in the view so that it can be rendered in a template.Now, to initiate a Django form you need to create home.html where one would be designing the stuff as they like. Let’s create a form in home.html. <form method = "GET"> {{ form }} <input type = "submit" value = "Submit"></form> Finally, a URL to map to this view in urls.py from django.urls import path # importing views from views..pyfrom .views import home_view urlpatterns = [ path('', home_view ),] Let’s run the server and check what has actually happened, Run Python manage.py runserver Thus, an geeks_field ChoiceField is created by replacing “_” with ” “. It is a field to input choices of strings. ChoiceField is used for input of small-sized strings in the database. One can input state, country, city, etc. Till now we have discussed how to implement ChoiceField but how to use it in the view for performing the logical part. To perform some logic we would need to get the value entered into field into a python string instance.In views.py, from django.shortcuts import renderfrom .forms import GeeksForm # Create your views here.def home_view(request): context ={} form = GeeksForm() context['form']= form if request.GET: temp = request.GET['geeks_field'] print(temp) return render(request, "home.html", context) Now let’s try entering data into the field. Now this data can be fetched using corresponding request dictionary. If method is GET, data would be available in request.GET and if post, request.POST correspondingly. In above example we have the value in temp which we can use for any purpose. Core Field arguments are the arguments given to each field for applying some constraint or imparting a particular characteristic to a particular Field. For example, adding an argument required = False to ChoiceField will enable it to be left blank by the user. Each Field class constructor takes at least these arguments. Some Field classes take additional, field-specific arguments, but the following should always be accepted: NaveenArora Django-forms Python Django Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists Python program to convert a list to string Reading and Writing to text files in Python
[ { "code": null, "e": 24598, "s": 24570, "text": "\n13 Feb, 2020" }, { "code": null, "e": 24963, "s": 24598, "text": "ChoiceField in Django Forms is a string field, for selecting a particular choice out of a list of available choices. It is used to implement State, Countries etc. like fields for which information is already defined and user has to choose one. It is used for taking text inputs from the user. The default widget for this input is Select.It Normalizes to: A string." }, { "code": null, "e": 25009, "s": 24963, "text": "ChoiceField has one extra required argument :" }, { "code": null, "e": 25209, "s": 25009, "text": "choices :Either an iterable of 2-tuples to use as choices for this field, or a callable that returns such an iterable. This argument accepts the same formats as the choices argument to a model field." }, { "code": null, "e": 25216, "s": 25209, "text": "Syntax" }, { "code": null, "e": 25258, "s": 25216, "text": "field_name = forms.ChoiceField(**options)" }, { "code": null, "e": 25370, "s": 25258, "text": "Illustration of ChoiceField using an Example. Consider a project named geeksforgeeks having an app named geeks." }, { "code": null, "e": 25457, "s": 25370, "text": "Refer to the following articles to check how to create a project and an app in Django." }, { "code": null, "e": 25508, "s": 25457, "text": "How to Create a Basic Project using MVT in Django?" }, { "code": null, "e": 25541, "s": 25508, "text": "How to Create an App in Django ?" }, { "code": null, "e": 25599, "s": 25541, "text": "Enter the following code into forms.py file of geeks app." }, { "code": "from django import forms # iterableGEEKS_CHOICES =( (\"1\", \"One\"), (\"2\", \"Two\"), (\"3\", \"Three\"), (\"4\", \"Four\"), (\"5\", \"Five\"),) # creating a form class GeeksForm(forms.Form): geeks_field = forms.ChoiceField(choices = GEEKS_CHOICES)", "e": 25850, "s": 25599, "text": null }, { "code": null, "e": 25886, "s": 25850, "text": "Add the geeks app to INSTALLED_APPS" }, { "code": "# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'geeks',]", "e": 26124, "s": 25886, "text": null }, { "code": null, "e": 26257, "s": 26124, "text": "Now to render this form into a view we need a view and a URL mapped to that URL. Let’s create a view first in views.py of geeks app," }, { "code": "from django.shortcuts import renderfrom .forms import GeeksForm # Create your views here.def home_view(request): context = {} context['form'] = GeeksForm() return render( request, \"home.html\", context)", "e": 26469, "s": 26257, "text": null }, { "code": null, "e": 26755, "s": 26469, "text": "Here we are importing that particular form from forms.py and creating an object of it in the view so that it can be rendered in a template.Now, to initiate a Django form you need to create home.html where one would be designing the stuff as they like. Let’s create a form in home.html." }, { "code": "<form method = \"GET\"> {{ form }} <input type = \"submit\" value = \"Submit\"></form>", "e": 26842, "s": 26755, "text": null }, { "code": null, "e": 26888, "s": 26842, "text": "Finally, a URL to map to this view in urls.py" }, { "code": "from django.urls import path # importing views from views..pyfrom .views import home_view urlpatterns = [ path('', home_view ),]", "e": 27022, "s": 26888, "text": null }, { "code": null, "e": 27085, "s": 27022, "text": "Let’s run the server and check what has actually happened, Run" }, { "code": null, "e": 27112, "s": 27085, "text": "Python manage.py runserver" }, { "code": null, "e": 27226, "s": 27112, "text": "Thus, an geeks_field ChoiceField is created by replacing “_” with ” “. It is a field to input choices of strings." }, { "code": null, "e": 27571, "s": 27226, "text": "ChoiceField is used for input of small-sized strings in the database. One can input state, country, city, etc. Till now we have discussed how to implement ChoiceField but how to use it in the view for performing the logical part. To perform some logic we would need to get the value entered into field into a python string instance.In views.py," }, { "code": "from django.shortcuts import renderfrom .forms import GeeksForm # Create your views here.def home_view(request): context ={} form = GeeksForm() context['form']= form if request.GET: temp = request.GET['geeks_field'] print(temp) return render(request, \"home.html\", context)", "e": 27874, "s": 27571, "text": null }, { "code": null, "e": 27918, "s": 27874, "text": "Now let’s try entering data into the field." }, { "code": null, "e": 28164, "s": 27918, "text": "Now this data can be fetched using corresponding request dictionary. If method is GET, data would be available in request.GET and if post, request.POST correspondingly. In above example we have the value in temp which we can use for any purpose." }, { "code": null, "e": 28593, "s": 28164, "text": "Core Field arguments are the arguments given to each field for applying some constraint or imparting a particular characteristic to a particular Field. For example, adding an argument required = False to ChoiceField will enable it to be left blank by the user. Each Field class constructor takes at least these arguments. Some Field classes take additional, field-specific arguments, but the following should always be accepted:" }, { "code": null, "e": 28605, "s": 28593, "text": "NaveenArora" }, { "code": null, "e": 28618, "s": 28605, "text": "Django-forms" }, { "code": null, "e": 28632, "s": 28618, "text": "Python Django" }, { "code": null, "e": 28639, "s": 28632, "text": "Python" }, { "code": null, "e": 28737, "s": 28639, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28755, "s": 28737, "text": "Python Dictionary" }, { "code": null, "e": 28790, "s": 28755, "text": "Read a file line by line in Python" }, { "code": null, "e": 28812, "s": 28790, "text": "Enumerate() in Python" }, { "code": null, "e": 28844, "s": 28812, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28874, "s": 28844, "text": "Iterate over a list in Python" }, { "code": null, "e": 28916, "s": 28874, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28942, "s": 28916, "text": "Python String | replace()" }, { "code": null, "e": 28979, "s": 28942, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 29022, "s": 28979, "text": "Python program to convert a list to string" } ]
How to count the total number of lines in the file in PowerShell?
To count the total number of lines in the file in PowerShell, you first need to retrieve the content of the item using Get-Content cmdlet and need to use method Length() to retrieve the total number of lines. An example is shown below. (Get-Content D:\Temp\PowerShellcommands.csv).Length PS C:\WINDOWS\system32> (Get-Content D:\Temp\PowerShellcommands.csv).Length 5727
[ { "code": null, "e": 1298, "s": 1062, "text": "To count the total number of lines in the file in PowerShell, you first need to retrieve the content of the item using Get-Content cmdlet and need to use method Length() to retrieve the total number of lines. An example is shown below." }, { "code": null, "e": 1350, "s": 1298, "text": "(Get-Content D:\\Temp\\PowerShellcommands.csv).Length" }, { "code": null, "e": 1431, "s": 1350, "text": "PS C:\\WINDOWS\\system32> (Get-Content D:\\Temp\\PowerShellcommands.csv).Length\n5727" } ]
C# Program to Convert Decimal to Binary
Let’ s say you have set the decimal to be − decVal = 34; Console.WriteLine("Decimal: {0}", decVal); Use the ToString() method for the values you get as a binary number for the decimal value − while (decVal >= 1) { val = decVal / 2; a += (decVal % 2).ToString(); decVal = val; } Now set a new empty variable to display the binary number using a loop − string binValue = ""; You can try to run the following code to convert decimal to binary in C#. Live Demo using System; using System.Collections.Generic; using System.Text; namespace Demo { class MyApplication { static void Main(string[] args) { int decVal; int val; string a = ""; decVal = 34; Console.WriteLine("Decimal: {0}", decVal); while (decVal >= 1) { val = decVal / 2; a += (decVal % 2).ToString(); decVal = val; } string binValue = ""; for (int i = a.Length - 1; i >= 0; i--) { binValue = binValue + a[i]; } Console.WriteLine("Binary: {0}", binValue); Console.Read(); } } } Decimal: 34 Binary: 100010
[ { "code": null, "e": 1106, "s": 1062, "text": "Let’ s say you have set the decimal to be −" }, { "code": null, "e": 1162, "s": 1106, "text": "decVal = 34;\nConsole.WriteLine(\"Decimal: {0}\", decVal);" }, { "code": null, "e": 1254, "s": 1162, "text": "Use the ToString() method for the values you get as a binary number for the decimal value −" }, { "code": null, "e": 1349, "s": 1254, "text": "while (decVal >= 1) {\n val = decVal / 2;\n a += (decVal % 2).ToString();\n decVal = val;\n}" }, { "code": null, "e": 1422, "s": 1349, "text": "Now set a new empty variable to display the binary number using a loop −" }, { "code": null, "e": 1444, "s": 1422, "text": "string binValue = \"\";" }, { "code": null, "e": 1518, "s": 1444, "text": "You can try to run the following code to convert decimal to binary in C#." }, { "code": null, "e": 1528, "s": 1518, "text": "Live Demo" }, { "code": null, "e": 2180, "s": 1528, "text": "using System;\nusing System.Collections.Generic;\nusing System.Text;\nnamespace Demo {\n class MyApplication {\n static void Main(string[] args) {\n int decVal;\n int val;\n string a = \"\";\n decVal = 34;\n Console.WriteLine(\"Decimal: {0}\", decVal);\n while (decVal >= 1) {\n val = decVal / 2;\n a += (decVal % 2).ToString();\n decVal = val;\n }\n string binValue = \"\";\n for (int i = a.Length - 1; i >= 0; i--) {\n binValue = binValue + a[i];\n }\n Console.WriteLine(\"Binary: {0}\", binValue);\n Console.Read();\n }\n }\n}" }, { "code": null, "e": 2207, "s": 2180, "text": "Decimal: 34\nBinary: 100010" } ]
How to Calculate the Average using Arrays in Golang? - GeeksforGeeks
13 Sep, 2021 Given an array of n elements, your task is to find out the average of the array.Approach: Accept the size of the array. Accept the elements of the array. Store the sum of the elements using for loop. Calculate Average = (sum/size of array) Print the average. Example: Input: n = 4 array = 1, 2, 3, 4 Output : sum = 10 average = 2.5 C // Golang program to Calculate the Average using Arrayspackage main import "fmt" func main() { // declaring an array of values array := []int{1, 2, 3, 4} // size of the array n := 4 // declaring a variable // to store the sum sum := 0 // traversing through the // array using for loop for i := 0; i < n; i++ { // adding the values of // array to the variable sum sum += (array[i]) } // declaring a variable // avg to find the average avg := (float64(sum)) / (float64(n)) // typecast all values to float // to get the correct result fmt.Println("Sum = ", sum, "\nAverage = ", avg)} Output Sum = 10 Average = 2.5 Here, n is the size of the array and sum is to store the sum of all the values of the array. Using a for loop we find the sum of the elements of the array. After calculating the sum, we must convert the data types of the sum and size of the array to float, so that we don’t lose any decimal values.To know more approaches you can go through the article Program for the average of an array (Iterative and Recursive) akshaysingh98088 Golang-Arrays Golang-Program Picked Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Time Formatting in Golang strings.Replace() Function in Golang With Examples fmt.Sprintf() Function in Golang With Examples How to Split a String in Golang? Golang Maps Arrays in Go Slices in Golang How to compare times in Golang? How to Trim a String in Golang? Inheritance in GoLang
[ { "code": null, "e": 24472, "s": 24444, "text": "\n13 Sep, 2021" }, { "code": null, "e": 24563, "s": 24472, "text": "Given an array of n elements, your task is to find out the average of the array.Approach: " }, { "code": null, "e": 24593, "s": 24563, "text": "Accept the size of the array." }, { "code": null, "e": 24627, "s": 24593, "text": "Accept the elements of the array." }, { "code": null, "e": 24673, "s": 24627, "text": "Store the sum of the elements using for loop." }, { "code": null, "e": 24713, "s": 24673, "text": "Calculate Average = (sum/size of array)" }, { "code": null, "e": 24732, "s": 24713, "text": "Print the average." }, { "code": null, "e": 24742, "s": 24732, "text": "Example: " }, { "code": null, "e": 24809, "s": 24742, "text": "Input:\n\nn = 4\narray = 1, 2, 3, 4\n\nOutput :\n\nsum = 10\naverage = 2.5" }, { "code": null, "e": 24813, "s": 24811, "text": "C" }, { "code": "// Golang program to Calculate the Average using Arrayspackage main import \"fmt\" func main() { // declaring an array of values array := []int{1, 2, 3, 4} // size of the array n := 4 // declaring a variable // to store the sum sum := 0 // traversing through the // array using for loop for i := 0; i < n; i++ { // adding the values of // array to the variable sum sum += (array[i]) } // declaring a variable // avg to find the average avg := (float64(sum)) / (float64(n)) // typecast all values to float // to get the correct result fmt.Println(\"Sum = \", sum, \"\\nAverage = \", avg)}", "e": 25490, "s": 24813, "text": null }, { "code": null, "e": 25498, "s": 25490, "text": "Output " }, { "code": null, "e": 25524, "s": 25498, "text": "Sum = 10 \nAverage = 2.5" }, { "code": null, "e": 25939, "s": 25524, "text": "Here, n is the size of the array and sum is to store the sum of all the values of the array. Using a for loop we find the sum of the elements of the array. After calculating the sum, we must convert the data types of the sum and size of the array to float, so that we don’t lose any decimal values.To know more approaches you can go through the article Program for the average of an array (Iterative and Recursive)" }, { "code": null, "e": 25956, "s": 25939, "text": "akshaysingh98088" }, { "code": null, "e": 25970, "s": 25956, "text": "Golang-Arrays" }, { "code": null, "e": 25985, "s": 25970, "text": "Golang-Program" }, { "code": null, "e": 25992, "s": 25985, "text": "Picked" }, { "code": null, "e": 26004, "s": 25992, "text": "Go Language" }, { "code": null, "e": 26102, "s": 26004, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26128, "s": 26102, "text": "Time Formatting in Golang" }, { "code": null, "e": 26179, "s": 26128, "text": "strings.Replace() Function in Golang With Examples" }, { "code": null, "e": 26226, "s": 26179, "text": "fmt.Sprintf() Function in Golang With Examples" }, { "code": null, "e": 26259, "s": 26226, "text": "How to Split a String in Golang?" }, { "code": null, "e": 26271, "s": 26259, "text": "Golang Maps" }, { "code": null, "e": 26284, "s": 26271, "text": "Arrays in Go" }, { "code": null, "e": 26301, "s": 26284, "text": "Slices in Golang" }, { "code": null, "e": 26333, "s": 26301, "text": "How to compare times in Golang?" }, { "code": null, "e": 26365, "s": 26333, "text": "How to Trim a String in Golang?" } ]
Same characters in two strings | Practice | GeeksforGeeks
Given two strings A and B of equal length, find how many times the corresponding position in the two strings hold exactly the same character. The comparison should not be case sensitive. Example 1: Input: A = choice B = chancE Output: 4 Explanation: characters at position 0, 1, 4 and 5 are same in the two strings A and B. Example 2: Input: A = Geek B = gang Output: 1 Explanation: charactera at position 0 is the same in the two strings A and B. Your Task: You dont need to read input or print anything. Complete the function sameChar() which takes the two strings A and B as input parameters and returns the count of the characters that are same in A and B. Expected Time Complexity: O(N) where N is the length of strings A and B. Expected Auxiliary Space: O(1) Constraints: 1<= A.length(), B.length() <= 104 0 mehtay0374 days ago Python Solution: class Solution: def sameChar(self, A, B): # code here a=A.lower() b=B.lower() count=0 for i in range(len(a)): if(a[i]==b[i]): count+=1 return count 0 debasishtewary51 week ago EASY SOLUTION int sameChar(String A, String B) { // code here int c=0;for(int i=0;i<A.length();i++){ if((int)A.charAt(i)==(int)B.charAt(i)||(int)A.charAt(i)==(int)B.charAt(i)+32||(int)A.charAt(i)+32==(int)B.charAt(i)){ c++; }} return c; +1 badgujarsachin835 months ago int sameChar(string A, string B) { int count=0; for(int i=0;i<A.size();i++){ if(tolower(A[i])==tolower(B[i])){ count++; } } return count; } 0 Imran Wahid7 months ago Imran Wahid Easy C++ solution class Solution{ public: int sameChar(string A, string B) { int count=0; for(int i=0;i<a.length();i++) <br=""/> { if(A[i]>='A' && A[i]<='Z') { A[i]+=32; } if(B[i]>='A' && B[i]<='Z') { B[i]+=32; } if(A[i]==B[i]) { count++; } } return count; }}; 0 Priyam Saxena10 months ago Priyam Saxena class Solution { int sameChar(String A, String B) { int c=0; A = A.toLowerCase(); B = B.toLowerCase(); for(int i=0;i<a.length();i++) {="" if(a.charat(i)="=B.charAt(i))" {="" c++;="" }="" }="" return="" c;="" }="" }=""> 0 Annanya Mathur1 year ago Annanya Mathur #include<bits stdc++.h="">using namespace std;int main() {int t;cin>>t;while(t--){ string a,b; cin>>a>>b; int c=0; for(int i=0;i<a.size();i++) {="" if(isupper(a[i]))="" a[i]="tolower(a[i]);" if(isupper(b[i]))="" b[i]="tolower(b[i]);" if(a[i]="=b[i])" c++;="" }="" cout<<c<<endl;="" }="" return="" 0;="" }=""> 0 Aman Vishwakarma1 year ago Aman Vishwakarma int main() { int t; cin>>t; while(t!=0) { int count=0; string s1,s2; cin>>s1; cin>>s2; for(int i=0;i<s1.length();i++) {="" if(s1[i]="=s2[i]" ||="" s1[i]="=(char)(s2[i]+32)" ||="" s1[i]="=(char)(s2[i]-32))" count++;="" }="" cout<<count="" <<"\n";="" t--;="" }="" return="" 0;="" }=""> 0 Siddharth Katiyar1 year ago Siddharth Katiyar #include<bits stdc++.h="">using namespace std;int main(){ int t; cin >> t; while(t--){ string s1; string s2; cin >> s1; cin >> s2; transform(s1.begin(), s1.end(), s1.begin(), ::tolower); transform(s2.begin(), s2.end(), s2.begin(), ::tolower); int i = 0, j = 0, count = 0; while (s1.length() && j < s2.length()) { if (s1[i] == s2[j]) count++; i++;j++; } cout << count << endl; } return 0;} 0 shivendu1 year ago shivendu #include<bits stdc++.h=""> using namespace std;int cpostion(string S1,string S2){int count=0;int i=0;int j=0; transform(S1.begin(), S1.end(), S1.begin(), ::toupper); transform(S2.begin(), S2.end(), S2.begin(), ::toupper); while( i<s1.length() &&="" j<s2.length())="" {="" if(s1[i]="=" s2[j])="" {="" count++;="" }="" i++;="" j++;="" }="" return="" count;="" }="" int="" main()="" {="" int="" t;="" cin="">>t;while(t--){ string s1; string s2; cin>>s1; cin>>s2; cout<<cpostion(s1,s2)<<endl; }="" }=""> 0 pratyush shekhar1 year ago pratyush shekhar t=int(input())for i in range(t): s1=input() s2=input() s1=s1.lower() s2=s2.lower() count=0 for i in range(len(s1)): if(s1[i]==s2[i]): count=count+1 print(count) 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": 426, "s": 238, "text": "Given two strings A and B of equal length, find how many times the corresponding position in the two strings hold exactly the same character. The comparison should not be case sensitive. " }, { "code": null, "e": 437, "s": 426, "text": "Example 1:" }, { "code": null, "e": 564, "s": 437, "text": "Input:\nA = choice \nB = chancE\nOutput: 4\nExplanation: characters at position 0, 1, 4 and 5\nare same in the two strings A and B." }, { "code": null, "e": 575, "s": 564, "text": "Example 2:" }, { "code": null, "e": 689, "s": 575, "text": "Input:\nA = Geek \nB = gang\nOutput: 1\nExplanation: charactera at position 0 is the\nsame in the two strings A and B." }, { "code": null, "e": 905, "s": 689, "text": "\nYour Task: \nYou dont need to read input or print anything. Complete the function sameChar() which takes the two strings A and B as input parameters and returns the count of the characters that are same in A and B." }, { "code": null, "e": 1011, "s": 905, "text": "\nExpected Time Complexity: O(N) where N is the length of strings A and B.\nExpected Auxiliary Space: O(1) " }, { "code": null, "e": 1059, "s": 1011, "text": "\nConstraints:\n1<= A.length(), B.length() <= 104" }, { "code": null, "e": 1063, "s": 1061, "text": "0" }, { "code": null, "e": 1083, "s": 1063, "text": "mehtay0374 days ago" }, { "code": null, "e": 1100, "s": 1083, "text": "Python Solution:" }, { "code": null, "e": 1116, "s": 1100, "text": "class Solution:" }, { "code": null, "e": 1320, "s": 1116, "text": " def sameChar(self, A, B): # code here a=A.lower() b=B.lower() count=0 for i in range(len(a)): if(a[i]==b[i]): count+=1 return count " }, { "code": null, "e": 1322, "s": 1320, "text": "0" }, { "code": null, "e": 1348, "s": 1322, "text": "debasishtewary51 week ago" }, { "code": null, "e": 1363, "s": 1348, "text": " EASY SOLUTION" }, { "code": null, "e": 1616, "s": 1363, "text": "int sameChar(String A, String B) { // code here int c=0;for(int i=0;i<A.length();i++){ if((int)A.charAt(i)==(int)B.charAt(i)||(int)A.charAt(i)==(int)B.charAt(i)+32||(int)A.charAt(i)+32==(int)B.charAt(i)){ c++; }} return c;" }, { "code": null, "e": 1619, "s": 1616, "text": "+1" }, { "code": null, "e": 1648, "s": 1619, "text": "badgujarsachin835 months ago" }, { "code": null, "e": 1869, "s": 1648, "text": "int sameChar(string A, string B)\n { \n int count=0;\n for(int i=0;i<A.size();i++){\n if(tolower(A[i])==tolower(B[i])){\n count++;\n }\n }\n return count;\n }" }, { "code": null, "e": 1871, "s": 1869, "text": "0" }, { "code": null, "e": 1895, "s": 1871, "text": "Imran Wahid7 months ago" }, { "code": null, "e": 1907, "s": 1895, "text": "Imran Wahid" }, { "code": null, "e": 1925, "s": 1907, "text": "Easy C++ solution" }, { "code": null, "e": 2359, "s": 1925, "text": "class Solution{ public: int sameChar(string A, string B) { int count=0; for(int i=0;i<a.length();i++) <br=\"\"/> { if(A[i]>='A' && A[i]<='Z') { A[i]+=32; } if(B[i]>='A' && B[i]<='Z') { B[i]+=32; } if(A[i]==B[i]) { count++; } } return count; }};" }, { "code": null, "e": 2361, "s": 2359, "text": "0" }, { "code": null, "e": 2388, "s": 2361, "text": "Priyam Saxena10 months ago" }, { "code": null, "e": 2402, "s": 2388, "text": "Priyam Saxena" }, { "code": null, "e": 2657, "s": 2402, "text": "class Solution { int sameChar(String A, String B) { int c=0; A = A.toLowerCase(); B = B.toLowerCase(); for(int i=0;i<a.length();i++) {=\"\" if(a.charat(i)=\"=B.charAt(i))\" {=\"\" c++;=\"\" }=\"\" }=\"\" return=\"\" c;=\"\" }=\"\" }=\"\">" }, { "code": null, "e": 2659, "s": 2657, "text": "0" }, { "code": null, "e": 2684, "s": 2659, "text": "Annanya Mathur1 year ago" }, { "code": null, "e": 2699, "s": 2684, "text": "Annanya Mathur" }, { "code": null, "e": 3020, "s": 2699, "text": "#include<bits stdc++.h=\"\">using namespace std;int main() {int t;cin>>t;while(t--){ string a,b; cin>>a>>b; int c=0; for(int i=0;i<a.size();i++) {=\"\" if(isupper(a[i]))=\"\" a[i]=\"tolower(a[i]);\" if(isupper(b[i]))=\"\" b[i]=\"tolower(b[i]);\" if(a[i]=\"=b[i])\" c++;=\"\" }=\"\" cout<<c<<endl;=\"\" }=\"\" return=\"\" 0;=\"\" }=\"\">" }, { "code": null, "e": 3022, "s": 3020, "text": "0" }, { "code": null, "e": 3049, "s": 3022, "text": "Aman Vishwakarma1 year ago" }, { "code": null, "e": 3066, "s": 3049, "text": "Aman Vishwakarma" }, { "code": null, "e": 3397, "s": 3066, "text": "int main() { int t; cin>>t; while(t!=0) { int count=0; string s1,s2; cin>>s1; cin>>s2; for(int i=0;i<s1.length();i++) {=\"\" if(s1[i]=\"=s2[i]\" ||=\"\" s1[i]=\"=(char)(s2[i]+32)\" ||=\"\" s1[i]=\"=(char)(s2[i]-32))\" count++;=\"\" }=\"\" cout<<count=\"\" <<\"\\n\";=\"\" t--;=\"\" }=\"\" return=\"\" 0;=\"\" }=\"\">" }, { "code": null, "e": 3399, "s": 3397, "text": "0" }, { "code": null, "e": 3427, "s": 3399, "text": "Siddharth Katiyar1 year ago" }, { "code": null, "e": 3445, "s": 3427, "text": "Siddharth Katiyar" }, { "code": null, "e": 3966, "s": 3445, "text": "#include<bits stdc++.h=\"\">using namespace std;int main(){ int t; cin >> t; while(t--){ string s1; string s2; cin >> s1; cin >> s2; transform(s1.begin(), s1.end(), s1.begin(), ::tolower); transform(s2.begin(), s2.end(), s2.begin(), ::tolower); int i = 0, j = 0, count = 0; while (s1.length() && j < s2.length()) { if (s1[i] == s2[j]) count++; i++;j++; } cout << count << endl; } return 0;}" }, { "code": null, "e": 3968, "s": 3966, "text": "0" }, { "code": null, "e": 3987, "s": 3968, "text": "shivendu1 year ago" }, { "code": null, "e": 3996, "s": 3987, "text": "shivendu" }, { "code": null, "e": 4528, "s": 3996, "text": "#include<bits stdc++.h=\"\"> using namespace std;int cpostion(string S1,string S2){int count=0;int i=0;int j=0; transform(S1.begin(), S1.end(), S1.begin(), ::toupper); transform(S2.begin(), S2.end(), S2.begin(), ::toupper); while( i<s1.length() &&=\"\" j<s2.length())=\"\" {=\"\" if(s1[i]=\"=\" s2[j])=\"\" {=\"\" count++;=\"\" }=\"\" i++;=\"\" j++;=\"\" }=\"\" return=\"\" count;=\"\" }=\"\" int=\"\" main()=\"\" {=\"\" int=\"\" t;=\"\" cin=\"\">>t;while(t--){ string s1; string s2; cin>>s1; cin>>s2; cout<<cpostion(s1,s2)<<endl; }=\"\" }=\"\">" }, { "code": null, "e": 4530, "s": 4528, "text": "0" }, { "code": null, "e": 4557, "s": 4530, "text": "pratyush shekhar1 year ago" }, { "code": null, "e": 4574, "s": 4557, "text": "pratyush shekhar" }, { "code": null, "e": 4774, "s": 4574, "text": "t=int(input())for i in range(t): s1=input() s2=input() s1=s1.lower() s2=s2.lower() count=0 for i in range(len(s1)): if(s1[i]==s2[i]): count=count+1 print(count)" }, { "code": null, "e": 4920, "s": 4774, "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": 4956, "s": 4920, "text": " Login to access your submissions. " }, { "code": null, "e": 4966, "s": 4956, "text": "\nProblem\n" }, { "code": null, "e": 4976, "s": 4966, "text": "\nContest\n" }, { "code": null, "e": 5039, "s": 4976, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5187, "s": 5039, "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": 5395, "s": 5187, "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": 5501, "s": 5395, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
MongoDB aggregation / math operation to sum score of a specific student
To sum, use aggregate() along with $sum. Let us create a collection with documents − > db.demo434.insertOne({"Name":"Chris","Score":45}); { "acknowledged" : true, "insertedId" : ObjectId("5e771603bbc41e36cc3cae93") } > db.demo434.insertOne({"Name":"David","Score":55}); { "acknowledged" : true, "insertedId" : ObjectId("5e77161abbc41e36cc3cae94") } > db.demo434.insertOne({"Name":"Chris","Score":55}); { "acknowledged" : true, "insertedId" : ObjectId("5e771624bbc41e36cc3cae95") } Display all documents from a collection with the help of find() method − > db.demo434.find(); This will produce the following output − { "_id" : ObjectId("5e771603bbc41e36cc3cae93"), "Name" : "Chris", "Score" : 45 } { "_id" : ObjectId("5e77161abbc41e36cc3cae94"), "Name" : "David", "Score" : 55 } { "_id" : ObjectId("5e771624bbc41e36cc3cae95"), "Name" : "Chris", "Score" : 55 } Following is the query tom sum score of a specific student − > db.demo434.aggregate([ ... { "$match": { "Name": "Chris"} }, ... { "$group": { "_id": null, "TotalScore": { "$sum": "$Score" } } } ... ]); This will produce the following output − { "_id" : null, "TotalScore" : 100 }
[ { "code": null, "e": 1147, "s": 1062, "text": "To sum, use aggregate() along with $sum. Let us create a collection with documents −" }, { "code": null, "e": 1561, "s": 1147, "text": "> db.demo434.insertOne({\"Name\":\"Chris\",\"Score\":45});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e771603bbc41e36cc3cae93\")\n}\n> db.demo434.insertOne({\"Name\":\"David\",\"Score\":55});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e77161abbc41e36cc3cae94\")\n}\n> db.demo434.insertOne({\"Name\":\"Chris\",\"Score\":55});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e771624bbc41e36cc3cae95\")\n}" }, { "code": null, "e": 1634, "s": 1561, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1655, "s": 1634, "text": "> db.demo434.find();" }, { "code": null, "e": 1696, "s": 1655, "text": "This will produce the following output −" }, { "code": null, "e": 1939, "s": 1696, "text": "{ \"_id\" : ObjectId(\"5e771603bbc41e36cc3cae93\"), \"Name\" : \"Chris\", \"Score\" : 45 }\n{ \"_id\" : ObjectId(\"5e77161abbc41e36cc3cae94\"), \"Name\" : \"David\", \"Score\" : 55 }\n{ \"_id\" : ObjectId(\"5e771624bbc41e36cc3cae95\"), \"Name\" : \"Chris\", \"Score\" : 55 }" }, { "code": null, "e": 2000, "s": 1939, "text": "Following is the query tom sum score of a specific student −" }, { "code": null, "e": 2147, "s": 2000, "text": "> db.demo434.aggregate([\n... { \"$match\": { \"Name\": \"Chris\"} },\n... { \"$group\": { \"_id\": null, \"TotalScore\": { \"$sum\": \"$Score\" } } }\n... ]);" }, { "code": null, "e": 2188, "s": 2147, "text": "This will produce the following output −" }, { "code": null, "e": 2225, "s": 2188, "text": "{ \"_id\" : null, \"TotalScore\" : 100 }" } ]
C++ Array Library - end() Function
The C++ function std::array::end() returns an iterator which points to the past-end element of array. Following is the declaration for std::array::end() function form std::array header. iterator end() noexcept; const_iterator end() noexcept; None Returns an iterator pointing to the past-the-end element in the array. This element act as a place-holder and never stores the actual data that is why deferencing this location would result undefined behavior. If array object is const-qualified, method return const iterator otherwise returns iterator. This member function never throws exception. Constant i.e. O(1) The following example shows the usage of std::array::end() function. #include <iostream> #include <array> using namespace std; int main(void) { array<int, 5> arr = {10, 20, 30, 40, 50}; /* iterator pointing at the start of array */ auto start = arr.begin(); /* iterator pointing past−the−end of array */ auto end = arr.end(); /* iterate complete array */ while (start < end) { cout << *start << " "; ++start; } cout << endl; return 0; } Let us compile and run the above program, this will produce the following result − 10 20 30 40 50 Print Add Notes Bookmark this page
[ { "code": null, "e": 2705, "s": 2603, "text": "The C++ function std::array::end() returns an iterator which points to the past-end element of array." }, { "code": null, "e": 2789, "s": 2705, "text": "Following is the declaration for std::array::end() function form std::array header." }, { "code": null, "e": 2845, "s": 2789, "text": "iterator end() noexcept;\nconst_iterator end() noexcept;" }, { "code": null, "e": 2850, "s": 2845, "text": "None" }, { "code": null, "e": 3060, "s": 2850, "text": "Returns an iterator pointing to the past-the-end element in the array. This element act as a place-holder and never stores the actual data that is why deferencing this location would result undefined behavior." }, { "code": null, "e": 3153, "s": 3060, "text": "If array object is const-qualified, method return const iterator otherwise returns iterator." }, { "code": null, "e": 3198, "s": 3153, "text": "This member function never throws exception." }, { "code": null, "e": 3217, "s": 3198, "text": "Constant i.e. O(1)" }, { "code": null, "e": 3286, "s": 3217, "text": "The following example shows the usage of std::array::end() function." }, { "code": null, "e": 3710, "s": 3286, "text": "#include <iostream>\n#include <array>\n\nusing namespace std;\n\nint main(void) {\n\n array<int, 5> arr = {10, 20, 30, 40, 50};\n /* iterator pointing at the start of array */\n auto start = arr.begin(); \n /* iterator pointing past−the−end of array */\n auto end = arr.end(); \n /* iterate complete array */\n while (start < end) {\n cout << *start << \" \";\n ++start;\n }\n\n cout << endl;\n\n return 0;\n}" }, { "code": null, "e": 3793, "s": 3710, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 3809, "s": 3793, "text": "10 20 30 40 50\n" }, { "code": null, "e": 3816, "s": 3809, "text": " Print" }, { "code": null, "e": 3827, "s": 3816, "text": " Add Notes" } ]
IntStream distinct() method in Java
The distinct() method in the IntStream class in Java returns a stream consisting of the distinct elements of this stream. The syntax is as follows IntStream distinct() Let’s say we have the following elements in the stream. Some of them are repeated IntStream intStream = IntStream.of(10, 20, 30, 20, 10, 50, 80, 90, 100, 80); To get the distinct elements, use the IntStream distinct() method. The following is an example to implement IntStream distinct() method in Java Live Demo import java.util.stream.IntStream; public class Demo { public static void main(String[] args) { IntStream intStream = IntStream.of(10, 20, 30, 20, 10, 50, 80, 90, 100, 80); System.out.println("Displaying the distinct elements:"); intStream.distinct().forEach(System.out::println); } } Displaying the distinct elements: 10 20 30 50 80 90 100
[ { "code": null, "e": 1184, "s": 1062, "text": "The distinct() method in the IntStream class in Java returns a stream consisting of the distinct elements of this stream." }, { "code": null, "e": 1209, "s": 1184, "text": "The syntax is as follows" }, { "code": null, "e": 1230, "s": 1209, "text": "IntStream distinct()" }, { "code": null, "e": 1312, "s": 1230, "text": "Let’s say we have the following elements in the stream. Some of them are repeated" }, { "code": null, "e": 1389, "s": 1312, "text": "IntStream intStream = IntStream.of(10, 20, 30, 20, 10, 50, 80, 90, 100, 80);" }, { "code": null, "e": 1456, "s": 1389, "text": "To get the distinct elements, use the IntStream distinct() method." }, { "code": null, "e": 1533, "s": 1456, "text": "The following is an example to implement IntStream distinct() method in Java" }, { "code": null, "e": 1544, "s": 1533, "text": " Live Demo" }, { "code": null, "e": 1853, "s": 1544, "text": "import java.util.stream.IntStream;\npublic class Demo {\n public static void main(String[] args) {\n IntStream intStream = IntStream.of(10, 20, 30, 20, 10, 50, 80, 90, 100, 80);\n System.out.println(\"Displaying the distinct elements:\");\n intStream.distinct().forEach(System.out::println);\n }\n}" }, { "code": null, "e": 1909, "s": 1853, "text": "Displaying the distinct elements:\n10\n20\n30\n50\n80\n90\n100" } ]
Structured natural language processing with Pandas and spaCy | by Conor Mc. | Towards Data Science
Working with natural language data can often be challenging due to its lack of structure. Most data scientists, analysts and product managers are familiar with structured tables, consisting of rows and columns, but less familiar with unstructured documents, consisting of sentences and words. For this reason, knowing how to approach a natural language dataset can be quite challenging. In this post I want to demonstrate how you can use the awesome Python packages, spaCy and Pandas, to structure natural language and extract interesting insights quickly. spaCy is a very popular Python package for advanced NLP — I have a beginner friendly introduction to NLP with SpaCy here. spaCy is the perfect toolkit for applied data scientists when working on NLP projects. The api is very intuitive, the package is blazing fast and it is very well documented. It’s probably fair to say that it is the best general purpose package for NLP available. Before diving into structuring NLP data, it is useful to get familiar with the basics of the spaCy library and api. After installing the package, you can load a model (in this case I am loading the simple Engilsh model, which is optimized for efficiency rather than accuracy) — i.e. the underlying neural network has fewer parameters. import spacynlp = spacy.load("en_core_web_sm") We instantiate this model as nlp by convention. Throughout this post I’ll work with this dataset of famous motivational quotes. Let’s apply the nlp model to a single quote from the data and store it in a variable. doc = nlp(df.quote[819]) print(doc) If we print the document, you can see that it just returns the original quote, but under the hood a lot of NLP magic has happened — we have created a spaCy doc object. So what can we do with it? Well first of all, there are two very cool and interesting visualizations that we can make. The visualization below shows the dependency structure of the document. These dependencies describe the linguistic structure of the sentence by showing how each word relates to other words in the document. It’s worth stopping for a second to marvel at this. Under the hood spaCy has applied a large neural language model to the document, parsed the dependency structure and made it possible for us to easily view this — all with a single line of code. If you want to better understand how to interpret this dependency structure you can use the spacy.explain function to get a definition for each dependency type. The next visualization shows the entities that have been recognized by the language model. In this cases the language model has recognised several words that are date types. We can access these properties of the doc programmatically, as follows. [(i, i.label_) for i in doc.ents] The doc.ents method enables access to the entities that have been predicted by the spaCy language model. As with the dependency tags you can use spacy.explain to understand the meaning of each entity tag. Other useful properties of the doc object are the the sents and noun_chunks methods, which enable you to split the doc into sentences or noun chunks (i.e. nouns plus their descriptors). doc = nlp(df.quote[0])spacy.displacy.render(doc, style="ent")doc_nouns = list(doc.noun_chunks)print(doc_nouns) If we access a single word from the doc we are actually accessing a spaCy token object. Like the docobject, the token object contains many useful properties. For example, we can iterate through the doc to extract each token and it’s various attributes. [(i, i.ent_type_, i.is_stop) for i in doc] Now that we have covered some of the basics of spaCy and the api, let’s take a more structured approach to the data. The goal here is to transform the unstructured documents into a structured table of data. Essentially, we want to move from an unstructured corpus of documents, tokens and their metadata to a structured dataset of rows and columns. Step 1: We first need to apply the spaCy language model to the entire collection of quotes. The easiest and most computationally efficient way to do this is to use the nlp.pipe function. This will iterate over each document and will apply the language model. docs = list(nlp.pipe(df.quote)) Step 2: Define a function to extract all the properties of each word that you want to include in the table. This function will iterate over the tokens in a single doc and will extract various attributes such as the lemma, pos, entity and tag. Use this function to define all the attributes you want to pull out of the token objects. In this case I am extracting common attributes that I use frequently and that will help when analysing the data. Step 3: Define a function to apply the function above to all documents and store the outputs in a Pandas dataframe. If we run these steps we end up with a dataset that looks like this: Each row represents a single token and the columns capture various metadata on that token. Importantly we can also link each individual word back to its doc using the doc_id column. Now that we have the data in this format we can analyse it in the same way we would any other structured dataset. For example, we can count the number of words per doc and visualise this with a histogram. tidy_docs.groupby("doc_id").size().hist(figsize=(14, 7), color="red", alpha=.4, bins=50); Alternatively, we might be interested in understanding the most common entities that have been identified across the corpus: tidy_docs.query("ent_type != ''").ent_type.value_counts() We can do the same thing for words after filtering out stop words and puncutation: tidy_docs.query("is_stop == False & is_punct == False").lemma.value_counts().head(10).plot(kind="barh", figsize=(24, 14), alpha=.7)plt.yticks(fontsize=20)plt.xticks(fontsize=20); Another interesting analysis we can do with the structured data is to look at possessives to understand ownership within the corpus. The code below groups by each document then extracts the preceding and following token, then filters for tokens that are flagged with the POS tag, which indicates a possessive relationship i.e. the object of the previous token owns the subject of the following token. This enables us to understand possessive relationships across the corpus. For example, you can see phrases such as, “One’s courage”, “someone’s prayers” and “today’s games”. Deep! As you can see working with the data becomes quite trivial now that it is in a structured format. This post shows how you can go from unstructured text data to a structured dataset that can be easily analysed. I often find this to be a useful first step when getting a feel for the data on NLP projects and can often reveal interesting and useful insights. Thanks for reading! P.S. All code for this post can be found here.
[ { "code": null, "e": 729, "s": 172, "text": "Working with natural language data can often be challenging due to its lack of structure. Most data scientists, analysts and product managers are familiar with structured tables, consisting of rows and columns, but less familiar with unstructured documents, consisting of sentences and words. For this reason, knowing how to approach a natural language dataset can be quite challenging. In this post I want to demonstrate how you can use the awesome Python packages, spaCy and Pandas, to structure natural language and extract interesting insights quickly." }, { "code": null, "e": 1230, "s": 729, "text": "spaCy is a very popular Python package for advanced NLP — I have a beginner friendly introduction to NLP with SpaCy here. spaCy is the perfect toolkit for applied data scientists when working on NLP projects. The api is very intuitive, the package is blazing fast and it is very well documented. It’s probably fair to say that it is the best general purpose package for NLP available. Before diving into structuring NLP data, it is useful to get familiar with the basics of the spaCy library and api." }, { "code": null, "e": 1449, "s": 1230, "text": "After installing the package, you can load a model (in this case I am loading the simple Engilsh model, which is optimized for efficiency rather than accuracy) — i.e. the underlying neural network has fewer parameters." }, { "code": null, "e": 1496, "s": 1449, "text": "import spacynlp = spacy.load(\"en_core_web_sm\")" }, { "code": null, "e": 1710, "s": 1496, "text": "We instantiate this model as nlp by convention. Throughout this post I’ll work with this dataset of famous motivational quotes. Let’s apply the nlp model to a single quote from the data and store it in a variable." }, { "code": null, "e": 1746, "s": 1710, "text": "doc = nlp(df.quote[819]) print(doc)" }, { "code": null, "e": 1941, "s": 1746, "text": "If we print the document, you can see that it just returns the original quote, but under the hood a lot of NLP magic has happened — we have created a spaCy doc object. So what can we do with it?" }, { "code": null, "e": 2105, "s": 1941, "text": "Well first of all, there are two very cool and interesting visualizations that we can make. The visualization below shows the dependency structure of the document." }, { "code": null, "e": 2646, "s": 2105, "text": "These dependencies describe the linguistic structure of the sentence by showing how each word relates to other words in the document. It’s worth stopping for a second to marvel at this. Under the hood spaCy has applied a large neural language model to the document, parsed the dependency structure and made it possible for us to easily view this — all with a single line of code. If you want to better understand how to interpret this dependency structure you can use the spacy.explain function to get a definition for each dependency type." }, { "code": null, "e": 2820, "s": 2646, "text": "The next visualization shows the entities that have been recognized by the language model. In this cases the language model has recognised several words that are date types." }, { "code": null, "e": 2892, "s": 2820, "text": "We can access these properties of the doc programmatically, as follows." }, { "code": null, "e": 2926, "s": 2892, "text": "[(i, i.label_) for i in doc.ents]" }, { "code": null, "e": 3131, "s": 2926, "text": "The doc.ents method enables access to the entities that have been predicted by the spaCy language model. As with the dependency tags you can use spacy.explain to understand the meaning of each entity tag." }, { "code": null, "e": 3317, "s": 3131, "text": "Other useful properties of the doc object are the the sents and noun_chunks methods, which enable you to split the doc into sentences or noun chunks (i.e. nouns plus their descriptors)." }, { "code": null, "e": 3428, "s": 3317, "text": "doc = nlp(df.quote[0])spacy.displacy.render(doc, style=\"ent\")doc_nouns = list(doc.noun_chunks)print(doc_nouns)" }, { "code": null, "e": 3681, "s": 3428, "text": "If we access a single word from the doc we are actually accessing a spaCy token object. Like the docobject, the token object contains many useful properties. For example, we can iterate through the doc to extract each token and it’s various attributes." }, { "code": null, "e": 3724, "s": 3681, "text": "[(i, i.ent_type_, i.is_stop) for i in doc]" }, { "code": null, "e": 3841, "s": 3724, "text": "Now that we have covered some of the basics of spaCy and the api, let’s take a more structured approach to the data." }, { "code": null, "e": 4073, "s": 3841, "text": "The goal here is to transform the unstructured documents into a structured table of data. Essentially, we want to move from an unstructured corpus of documents, tokens and their metadata to a structured dataset of rows and columns." }, { "code": null, "e": 4332, "s": 4073, "text": "Step 1: We first need to apply the spaCy language model to the entire collection of quotes. The easiest and most computationally efficient way to do this is to use the nlp.pipe function. This will iterate over each document and will apply the language model." }, { "code": null, "e": 4364, "s": 4332, "text": "docs = list(nlp.pipe(df.quote))" }, { "code": null, "e": 4810, "s": 4364, "text": "Step 2: Define a function to extract all the properties of each word that you want to include in the table. This function will iterate over the tokens in a single doc and will extract various attributes such as the lemma, pos, entity and tag. Use this function to define all the attributes you want to pull out of the token objects. In this case I am extracting common attributes that I use frequently and that will help when analysing the data." }, { "code": null, "e": 4926, "s": 4810, "text": "Step 3: Define a function to apply the function above to all documents and store the outputs in a Pandas dataframe." }, { "code": null, "e": 4995, "s": 4926, "text": "If we run these steps we end up with a dataset that looks like this:" }, { "code": null, "e": 5177, "s": 4995, "text": "Each row represents a single token and the columns capture various metadata on that token. Importantly we can also link each individual word back to its doc using the doc_id column." }, { "code": null, "e": 5382, "s": 5177, "text": "Now that we have the data in this format we can analyse it in the same way we would any other structured dataset. For example, we can count the number of words per doc and visualise this with a histogram." }, { "code": null, "e": 5472, "s": 5382, "text": "tidy_docs.groupby(\"doc_id\").size().hist(figsize=(14, 7), color=\"red\", alpha=.4, bins=50);" }, { "code": null, "e": 5597, "s": 5472, "text": "Alternatively, we might be interested in understanding the most common entities that have been identified across the corpus:" }, { "code": null, "e": 5655, "s": 5597, "text": "tidy_docs.query(\"ent_type != ''\").ent_type.value_counts()" }, { "code": null, "e": 5738, "s": 5655, "text": "We can do the same thing for words after filtering out stop words and puncutation:" }, { "code": null, "e": 5917, "s": 5738, "text": "tidy_docs.query(\"is_stop == False & is_punct == False\").lemma.value_counts().head(10).plot(kind=\"barh\", figsize=(24, 14), alpha=.7)plt.yticks(fontsize=20)plt.xticks(fontsize=20);" }, { "code": null, "e": 6318, "s": 5917, "text": "Another interesting analysis we can do with the structured data is to look at possessives to understand ownership within the corpus. The code below groups by each document then extracts the preceding and following token, then filters for tokens that are flagged with the POS tag, which indicates a possessive relationship i.e. the object of the previous token owns the subject of the following token." }, { "code": null, "e": 6498, "s": 6318, "text": "This enables us to understand possessive relationships across the corpus. For example, you can see phrases such as, “One’s courage”, “someone’s prayers” and “today’s games”. Deep!" }, { "code": null, "e": 6596, "s": 6498, "text": "As you can see working with the data becomes quite trivial now that it is in a structured format." }, { "code": null, "e": 6855, "s": 6596, "text": "This post shows how you can go from unstructured text data to a structured dataset that can be easily analysed. I often find this to be a useful first step when getting a feel for the data on NLP projects and can often reveal interesting and useful insights." }, { "code": null, "e": 6875, "s": 6855, "text": "Thanks for reading!" } ]
Product of the maximums of all subsets of an array - GeeksforGeeks
22 Jul, 2021 Given an array arr[] consisting of N positive integers, the task is to find the product of the maximum of all possible subsets of the given array. Since the product can be very large, print it to modulo (109 + 7). Examples: Input: arr[] = {1, 2, 3}Output:Explanation:All possible subsets of the given array with their respective maximum elements are: {1}, the maximum element is 1.{2}, the maximum element is 2.{3}, the maximum element is 3.{1, 2}, the maximum element is 2.{1, 3}, the maximum element is 3.{2, 3}, the maximum element is 3.{1, 2, 3}, the maximum element is 3. {1}, the maximum element is 1. {2}, the maximum element is 2. {3}, the maximum element is 3. {1, 2}, the maximum element is 2. {1, 3}, the maximum element is 3. {2, 3}, the maximum element is 3. {1, 2, 3}, the maximum element is 3. The product of all the above maximum element is 1*2*3*2*3*3*3 = 324. Input: arr[] = {1, 1, 1, 1}Output: 1 Naive Approach: The simplest approach to solve the given problem is to generate all possible subsets of the given array and find the product of the maximum of all the generated subsets modulo (109 + 7) as the resultant product. Time Complexity: O(N*2N)Auxiliary Space: O(1) Efficient Approach: The above approach can also be optimized based on the following observations: The idea is to count the number of times each array element occurs as the maximum element among all possible subsets formed. An array element arr[i] is a maximum if and only if all the elements except arr[i] are smaller than or equal to it. Therefore, the number of subsets formed by all elements smaller than or equal to each array element arr[i] contributes to the count of subsets having arr[i] as the maximum element. Follow the steps below to solve the problem: Initialize a variable, say maximumProduct as 1 that stores the resultant product of maximum elements of all subsets. Sort the given array arr[] in the increasing order. Traverse the array from the end using the variable i and perform the following steps:Find the number of subsets that are smaller than the current element arr[i] as (2i – 1) and store it in a variable say P.Since the array element arr[i] contributes P number of times, therefore multiply the value arr[i], P times to the variable maximumProduct. Find the number of subsets that are smaller than the current element arr[i] as (2i – 1) and store it in a variable say P. Since the array element arr[i] contributes P number of times, therefore multiply the value arr[i], P times to the variable maximumProduct. Find the product of the array element with maximumProduct for including all the subsets of size 1. After completing the above steps, print the value of maximumProduct as the resultant maximum product. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the product of the// maximum of all possible subsetslong maximumProduct(int arr[], int N){ long mod = 1000000007; // Sort the given array arr[] sort(arr, arr + N); // Stores the power of 2 long power[N + 1]; power[0] = 1; // Calculate the power of 2 for (int i = 1; i <= N; i++) { power[i] = 2 * power[i - 1]; power[i] %= mod; } // Stores the resultant product long result = 1; // Traverse the array from the back for (int i = N - 1; i > 0; i--) { // Find the value of 2^i - 1 long value = (power[i] - 1); // Iterate value number of times for (int j = 0; j < value; j++) { // Multiply value with // the result result *= 1LL * arr[i]; result %= mod; } } // Calculate the product of array // elements with result to consider // the subset of size 1 for (int i = 0; i < N; i++) { result *= 1LL * arr[i]; result %= mod; } // Return the resultant product return result;} // Driver Codeint main(){ int arr[] = { 1, 2, 3 }; int N = sizeof(arr) / sizeof(arr[0]); cout << maximumProduct(arr, N); return 0;} // Java program for the above approachimport java.util.Arrays; class GFG{ // Function to find the product of the// maximum of all possible subsetsstatic long maximumProduct(int arr[], int N){ long mod = 1000000007; // Sort the given array arr[] Arrays.sort(arr); // Stores the power of 2 long power[] = new long[N + 1]; power[0] = 1; // Calculate the power of 2 for(int i = 1; i <= N; i++) { power[i] = 2 * power[i - 1]; power[i] %= mod; } // Stores the resultant product long result = 1; // Traverse the array from the back for(int i = N - 1; i > 0; i--) { // Find the value of 2^i - 1 long value = (power[i] - 1); // Iterate value number of times for(int j = 0; j < value; j++) { // Multiply value with // the result result *= arr[i]; result %= mod; } } // Calculate the product of array // elements with result to consider // the subset of size 1 for(int i = 0; i < N; i++) { result *= arr[i]; result %= mod; } // Return the resultant product return result;} // Driver Codepublic static void main(String[] args){ int arr[] = { 1, 2, 3 }; int N = arr.length; System.out.println(maximumProduct(arr, N));}} // This code is contributed by rishavmahato348 # Python3 program for the above approach # Function to find the product of the# maximum of all possible subsetsdef maximumProduct(arr, N): mod = 1000000007 # Sort the given array arr[] arr = sorted(arr) # Stores the power of 2 power = [0] * (N + 1) power[0] = 1 # Calculate the power of 2 for i in range(1, N + 1): power[i] = 2 * power[i - 1] power[i] %= mod # Stores the resultant product result = 1 # Traverse the array from the back for i in range(N - 1, -1, -1): # Find the value of 2^i - 1 value = (power[i] - 1) # Iterate value number of times for j in range(value): # Multiply value with # the result result *= arr[i] result %= mod # Calculate the product of array # elements with result to consider # the subset of size 1 for i in range(N): result *= arr[i] result %= mod # Return the resultant product return result # Driver Codeif __name__ == '__main__': arr = [ 1, 2, 3 ] N = len(arr) print(maximumProduct(arr, N)) # This code is contributed by mohit kumar 29 // C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to find the product of the// maximum of all possible subsetsstatic long maximumProduct(int []arr, int N){ long mod = 1000000007; // Sort the given array arr[] Array.Sort(arr); // Stores the power of 2 long []power = new long[N + 1]; power[0] = 1; // Calculate the power of 2 for (int i = 1; i <= N; i++) { power[i] = 2 * power[i - 1]; power[i] %= mod; } // Stores the resultant product long result = 1; // Traverse the array from the back for (int i = N - 1; i > 0; i--) { // Find the value of 2^i - 1 long value = (power[i] - 1); // Iterate value number of times for (int j = 0; j < value; j++) { // Multiply value with // the result result *= 1 * arr[i]; result %= mod; } } // Calculate the product of array // elements with result to consider // the subset of size 1 for (int i = 0; i < N; i++) { result *= 1 * arr[i]; result %= mod; } // Return the resultant product return result;} // Driver Codepublic static void Main(){ int []arr = {1, 2, 3}; int N = arr.Length; Console.Write(maximumProduct(arr, N));}} // This code is contributed by SURENDRA_GANGWAR. <script> // JavaScript program for the above approach // Function to find the product of the// maximum of all possible subsetsfunction maximumProduct(arr, N){ let mod = 1000000007; // Sort the given array arr[] arr.sort((a, b) => a - b); // Stores the power of 2 let power = new Array(N + 1); power[0] = 1; // Calculate the power of 2 for (let i = 1; i <= N; i++) { power[i] = 2 * power[i - 1]; power[i] %= mod; } // Stores the resultant product let result = 1; // Traverse the array from the back for (let i = N - 1; i > 0; i--) { // Find the value of 2^i - 1 let value = (power[i] - 1); // Iterate value number of times for (let j = 0; j < value; j++) { // Multiply value with // the result result *= 1 * arr[i]; result %= mod; } } // Calculate the product of array // elements with result to consider // the subset of size 1 for (let i = 0; i < N; i++) { result *= 1 * arr[i]; result %= mod; } // Return the resultant product return result;} // Driver Code let arr = [1, 2, 3 ];let N = arr.length;document.write(maximumProduct(arr, N)); </script> 324 Time Complexity: O(N*log N)Auxiliary Space: O(N) mohit kumar 29 rishavmahato348 gfgking SURENDRA_GANGWAR Arcesium interview-preparation subset Arrays Mathematical Sorting Arcesium Arrays Mathematical Sorting subset Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Introduction to Arrays Multidimensional Arrays in Java Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Linked List vs Array Python | Using 2D arrays/lists the right way Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 24801, "s": 24773, "text": "\n22 Jul, 2021" }, { "code": null, "e": 25015, "s": 24801, "text": "Given an array arr[] consisting of N positive integers, the task is to find the product of the maximum of all possible subsets of the given array. Since the product can be very large, print it to modulo (109 + 7)." }, { "code": null, "e": 25025, "s": 25015, "text": "Examples:" }, { "code": null, "e": 25152, "s": 25025, "text": "Input: arr[] = {1, 2, 3}Output:Explanation:All possible subsets of the given array with their respective maximum elements are:" }, { "code": null, "e": 25378, "s": 25152, "text": "{1}, the maximum element is 1.{2}, the maximum element is 2.{3}, the maximum element is 3.{1, 2}, the maximum element is 2.{1, 3}, the maximum element is 3.{2, 3}, the maximum element is 3.{1, 2, 3}, the maximum element is 3." }, { "code": null, "e": 25409, "s": 25378, "text": "{1}, the maximum element is 1." }, { "code": null, "e": 25440, "s": 25409, "text": "{2}, the maximum element is 2." }, { "code": null, "e": 25471, "s": 25440, "text": "{3}, the maximum element is 3." }, { "code": null, "e": 25505, "s": 25471, "text": "{1, 2}, the maximum element is 2." }, { "code": null, "e": 25539, "s": 25505, "text": "{1, 3}, the maximum element is 3." }, { "code": null, "e": 25573, "s": 25539, "text": "{2, 3}, the maximum element is 3." }, { "code": null, "e": 25610, "s": 25573, "text": "{1, 2, 3}, the maximum element is 3." }, { "code": null, "e": 25679, "s": 25610, "text": "The product of all the above maximum element is 1*2*3*2*3*3*3 = 324." }, { "code": null, "e": 25716, "s": 25679, "text": "Input: arr[] = {1, 1, 1, 1}Output: 1" }, { "code": null, "e": 25944, "s": 25716, "text": "Naive Approach: The simplest approach to solve the given problem is to generate all possible subsets of the given array and find the product of the maximum of all the generated subsets modulo (109 + 7) as the resultant product." }, { "code": null, "e": 25990, "s": 25944, "text": "Time Complexity: O(N*2N)Auxiliary Space: O(1)" }, { "code": null, "e": 26088, "s": 25990, "text": "Efficient Approach: The above approach can also be optimized based on the following observations:" }, { "code": null, "e": 26213, "s": 26088, "text": "The idea is to count the number of times each array element occurs as the maximum element among all possible subsets formed." }, { "code": null, "e": 26329, "s": 26213, "text": "An array element arr[i] is a maximum if and only if all the elements except arr[i] are smaller than or equal to it." }, { "code": null, "e": 26510, "s": 26329, "text": "Therefore, the number of subsets formed by all elements smaller than or equal to each array element arr[i] contributes to the count of subsets having arr[i] as the maximum element." }, { "code": null, "e": 26555, "s": 26510, "text": "Follow the steps below to solve the problem:" }, { "code": null, "e": 26672, "s": 26555, "text": "Initialize a variable, say maximumProduct as 1 that stores the resultant product of maximum elements of all subsets." }, { "code": null, "e": 26724, "s": 26672, "text": "Sort the given array arr[] in the increasing order." }, { "code": null, "e": 27069, "s": 26724, "text": "Traverse the array from the end using the variable i and perform the following steps:Find the number of subsets that are smaller than the current element arr[i] as (2i – 1) and store it in a variable say P.Since the array element arr[i] contributes P number of times, therefore multiply the value arr[i], P times to the variable maximumProduct." }, { "code": null, "e": 27191, "s": 27069, "text": "Find the number of subsets that are smaller than the current element arr[i] as (2i – 1) and store it in a variable say P." }, { "code": null, "e": 27330, "s": 27191, "text": "Since the array element arr[i] contributes P number of times, therefore multiply the value arr[i], P times to the variable maximumProduct." }, { "code": null, "e": 27429, "s": 27330, "text": "Find the product of the array element with maximumProduct for including all the subsets of size 1." }, { "code": null, "e": 27531, "s": 27429, "text": "After completing the above steps, print the value of maximumProduct as the resultant maximum product." }, { "code": null, "e": 27582, "s": 27531, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27586, "s": 27582, "text": "C++" }, { "code": null, "e": 27591, "s": 27586, "text": "Java" }, { "code": null, "e": 27599, "s": 27591, "text": "Python3" }, { "code": null, "e": 27602, "s": 27599, "text": "C#" }, { "code": null, "e": 27613, "s": 27602, "text": "Javascript" }, { "code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the product of the// maximum of all possible subsetslong maximumProduct(int arr[], int N){ long mod = 1000000007; // Sort the given array arr[] sort(arr, arr + N); // Stores the power of 2 long power[N + 1]; power[0] = 1; // Calculate the power of 2 for (int i = 1; i <= N; i++) { power[i] = 2 * power[i - 1]; power[i] %= mod; } // Stores the resultant product long result = 1; // Traverse the array from the back for (int i = N - 1; i > 0; i--) { // Find the value of 2^i - 1 long value = (power[i] - 1); // Iterate value number of times for (int j = 0; j < value; j++) { // Multiply value with // the result result *= 1LL * arr[i]; result %= mod; } } // Calculate the product of array // elements with result to consider // the subset of size 1 for (int i = 0; i < N; i++) { result *= 1LL * arr[i]; result %= mod; } // Return the resultant product return result;} // Driver Codeint main(){ int arr[] = { 1, 2, 3 }; int N = sizeof(arr) / sizeof(arr[0]); cout << maximumProduct(arr, N); return 0;}", "e": 28908, "s": 27613, "text": null }, { "code": "// Java program for the above approachimport java.util.Arrays; class GFG{ // Function to find the product of the// maximum of all possible subsetsstatic long maximumProduct(int arr[], int N){ long mod = 1000000007; // Sort the given array arr[] Arrays.sort(arr); // Stores the power of 2 long power[] = new long[N + 1]; power[0] = 1; // Calculate the power of 2 for(int i = 1; i <= N; i++) { power[i] = 2 * power[i - 1]; power[i] %= mod; } // Stores the resultant product long result = 1; // Traverse the array from the back for(int i = N - 1; i > 0; i--) { // Find the value of 2^i - 1 long value = (power[i] - 1); // Iterate value number of times for(int j = 0; j < value; j++) { // Multiply value with // the result result *= arr[i]; result %= mod; } } // Calculate the product of array // elements with result to consider // the subset of size 1 for(int i = 0; i < N; i++) { result *= arr[i]; result %= mod; } // Return the resultant product return result;} // Driver Codepublic static void main(String[] args){ int arr[] = { 1, 2, 3 }; int N = arr.length; System.out.println(maximumProduct(arr, N));}} // This code is contributed by rishavmahato348", "e": 30292, "s": 28908, "text": null }, { "code": "# Python3 program for the above approach # Function to find the product of the# maximum of all possible subsetsdef maximumProduct(arr, N): mod = 1000000007 # Sort the given array arr[] arr = sorted(arr) # Stores the power of 2 power = [0] * (N + 1) power[0] = 1 # Calculate the power of 2 for i in range(1, N + 1): power[i] = 2 * power[i - 1] power[i] %= mod # Stores the resultant product result = 1 # Traverse the array from the back for i in range(N - 1, -1, -1): # Find the value of 2^i - 1 value = (power[i] - 1) # Iterate value number of times for j in range(value): # Multiply value with # the result result *= arr[i] result %= mod # Calculate the product of array # elements with result to consider # the subset of size 1 for i in range(N): result *= arr[i] result %= mod # Return the resultant product return result # Driver Codeif __name__ == '__main__': arr = [ 1, 2, 3 ] N = len(arr) print(maximumProduct(arr, N)) # This code is contributed by mohit kumar 29", "e": 31479, "s": 30292, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to find the product of the// maximum of all possible subsetsstatic long maximumProduct(int []arr, int N){ long mod = 1000000007; // Sort the given array arr[] Array.Sort(arr); // Stores the power of 2 long []power = new long[N + 1]; power[0] = 1; // Calculate the power of 2 for (int i = 1; i <= N; i++) { power[i] = 2 * power[i - 1]; power[i] %= mod; } // Stores the resultant product long result = 1; // Traverse the array from the back for (int i = N - 1; i > 0; i--) { // Find the value of 2^i - 1 long value = (power[i] - 1); // Iterate value number of times for (int j = 0; j < value; j++) { // Multiply value with // the result result *= 1 * arr[i]; result %= mod; } } // Calculate the product of array // elements with result to consider // the subset of size 1 for (int i = 0; i < N; i++) { result *= 1 * arr[i]; result %= mod; } // Return the resultant product return result;} // Driver Codepublic static void Main(){ int []arr = {1, 2, 3}; int N = arr.Length; Console.Write(maximumProduct(arr, N));}} // This code is contributed by SURENDRA_GANGWAR.", "e": 32836, "s": 31479, "text": null }, { "code": "<script> // JavaScript program for the above approach // Function to find the product of the// maximum of all possible subsetsfunction maximumProduct(arr, N){ let mod = 1000000007; // Sort the given array arr[] arr.sort((a, b) => a - b); // Stores the power of 2 let power = new Array(N + 1); power[0] = 1; // Calculate the power of 2 for (let i = 1; i <= N; i++) { power[i] = 2 * power[i - 1]; power[i] %= mod; } // Stores the resultant product let result = 1; // Traverse the array from the back for (let i = N - 1; i > 0; i--) { // Find the value of 2^i - 1 let value = (power[i] - 1); // Iterate value number of times for (let j = 0; j < value; j++) { // Multiply value with // the result result *= 1 * arr[i]; result %= mod; } } // Calculate the product of array // elements with result to consider // the subset of size 1 for (let i = 0; i < N; i++) { result *= 1 * arr[i]; result %= mod; } // Return the resultant product return result;} // Driver Code let arr = [1, 2, 3 ];let N = arr.length;document.write(maximumProduct(arr, N)); </script>", "e": 34068, "s": 32836, "text": null }, { "code": null, "e": 34072, "s": 34068, "text": "324" }, { "code": null, "e": 34123, "s": 34074, "text": "Time Complexity: O(N*log N)Auxiliary Space: O(N)" }, { "code": null, "e": 34138, "s": 34123, "text": "mohit kumar 29" }, { "code": null, "e": 34154, "s": 34138, "text": "rishavmahato348" }, { "code": null, "e": 34162, "s": 34154, "text": "gfgking" }, { "code": null, "e": 34179, "s": 34162, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 34188, "s": 34179, "text": "Arcesium" }, { "code": null, "e": 34210, "s": 34188, "text": "interview-preparation" }, { "code": null, "e": 34217, "s": 34210, "text": "subset" }, { "code": null, "e": 34224, "s": 34217, "text": "Arrays" }, { "code": null, "e": 34237, "s": 34224, "text": "Mathematical" }, { "code": null, "e": 34245, "s": 34237, "text": "Sorting" }, { "code": null, "e": 34254, "s": 34245, "text": "Arcesium" }, { "code": null, "e": 34261, "s": 34254, "text": "Arrays" }, { "code": null, "e": 34274, "s": 34261, "text": "Mathematical" }, { "code": null, "e": 34282, "s": 34274, "text": "Sorting" }, { "code": null, "e": 34289, "s": 34282, "text": "subset" }, { "code": null, "e": 34387, "s": 34289, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34396, "s": 34387, "text": "Comments" }, { "code": null, "e": 34409, "s": 34396, "text": "Old Comments" }, { "code": null, "e": 34432, "s": 34409, "text": "Introduction to Arrays" }, { "code": null, "e": 34464, "s": 34432, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 34549, "s": 34464, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 34570, "s": 34549, "text": "Linked List vs Array" }, { "code": null, "e": 34615, "s": 34570, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 34645, "s": 34615, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 34705, "s": 34645, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 34720, "s": 34705, "text": "C++ Data Types" }, { "code": null, "e": 34763, "s": 34720, "text": "Set in C++ Standard Template Library (STL)" } ]
Docker - Images
In Docker, everything is based on Images. An image is a combination of a file system and parameters. Let’s take an example of the following command in Docker. docker run hello-world The Docker command is specific and tells the Docker program on the Operating System that something needs to be done. The Docker command is specific and tells the Docker program on the Operating System that something needs to be done. The run command is used to mention that we want to create an instance of an image, which is then called a container. The run command is used to mention that we want to create an instance of an image, which is then called a container. Finally, "hello-world" represents the image from which the container is made. Finally, "hello-world" represents the image from which the container is made. Now let’s look at how we can use the CentOS image available in Docker Hub to run CentOS on our Ubuntu machine. We can do this by executing the following command on our Ubuntu machine − sudo docker run -it centos /bin/bash Note the following points about the above sudo command − We are using the sudo command to ensure that it runs with root access. We are using the sudo command to ensure that it runs with root access. Here, centos is the name of the image we want to download from Docker Hub and install on our Ubuntu machine. Here, centos is the name of the image we want to download from Docker Hub and install on our Ubuntu machine. ─it is used to mention that we want to run in interactive mode. ─it is used to mention that we want to run in interactive mode. /bin/bash is used to run the bash shell once CentOS is up and running. /bin/bash is used to run the bash shell once CentOS is up and running. To see the list of Docker images on the system, you can issue the following command. docker images This command is used to display all the images currently installed on the system. docker images None The output will provide the list of images on the system. sudo docker images When we run the above command, it will produce the following result − From the above output, you can see that the server has three images: centos, newcentos, and jenkins. Each image has the following attributes − TAG − This is used to logically tag images. TAG − This is used to logically tag images. Image ID − This is used to uniquely identify the image. Image ID − This is used to uniquely identify the image. Created − The number of days since the image was created. Created − The number of days since the image was created. Virtual Size − The size of the image. Virtual Size − The size of the image. Images can be downloaded from Docker Hub using the Docker run command. Let’s see in detail how we can do this. The following syntax is used to run a command in a Docker container. docker run image Image − This is the name of the image which is used to run the container. Image − This is the name of the image which is used to run the container. The output will run the command in the desired container. sudo docker run centos This command will download the centos image, if it is not already present, and run the OS as a container. When we run the above command, we will get the following result − You will now see the CentOS Docker image downloaded. Now, if we run the Docker images command to see the list of images on the system, we should be able to see the centos image as well. The Docker images on the system can be removed via the docker rmi command. Let’s look at this command in more detail. docker rmi This command is used to remove Docker images. docker rmi ImageID ImageID − This is the ID of the image which needs to be removed. ImageID − This is the ID of the image which needs to be removed. The output will provide the Image ID of the deleted Image. sudo docker rmi 7a86f8ffcb25 Here, 7a86f8ffcb25 is the Image ID of the newcentos image. When we run the above command, it will produce the following result − Let’s see some more Docker commands on images. This command is used to return only the Image ID’s of the images. docker images q − It tells the Docker command to return the Image ID’s only. q − It tells the Docker command to return the Image ID’s only. The output will show only the Image ID’s of the images on the Docker host. sudo docker images -q When we run the above command, it will produce the following result − This command is used see the details of an image or container. docker inspect Repository Repository − This is the name of the Image. Repository − This is the name of the Image. The output will show detailed information on the Image. sudo docker inspect jenkins When we run the above command, it will produce the following result − 70 Lectures 12 hours Anshul Chauhan 41 Lectures 5 hours AR Shankar 31 Lectures 3 hours Abhilash Nelson 15 Lectures 2 hours Harshit Srivastava, Pranjal Srivastava 33 Lectures 4 hours Mumshad Mannambeth 13 Lectures 53 mins Musab Zayadneh Print Add Notes Bookmark this page
[ { "code": null, "e": 2499, "s": 2340, "text": "In Docker, everything is based on Images. An image is a combination of a file system and parameters. Let’s take an example of the following command in Docker." }, { "code": null, "e": 2524, "s": 2499, "text": "docker run hello-world \n" }, { "code": null, "e": 2641, "s": 2524, "text": "The Docker command is specific and tells the Docker program on the Operating System that something needs to be done." }, { "code": null, "e": 2758, "s": 2641, "text": "The Docker command is specific and tells the Docker program on the Operating System that something needs to be done." }, { "code": null, "e": 2875, "s": 2758, "text": "The run command is used to mention that we want to create an instance of an image, which is then called a container." }, { "code": null, "e": 2992, "s": 2875, "text": "The run command is used to mention that we want to create an instance of an image, which is then called a container." }, { "code": null, "e": 3070, "s": 2992, "text": "Finally, \"hello-world\" represents the image from which the container is made." }, { "code": null, "e": 3148, "s": 3070, "text": "Finally, \"hello-world\" represents the image from which the container is made." }, { "code": null, "e": 3333, "s": 3148, "text": "Now let’s look at how we can use the CentOS image available in Docker Hub to run CentOS on our Ubuntu machine. We can do this by executing the following command on our Ubuntu machine −" }, { "code": null, "e": 3371, "s": 3333, "text": "sudo docker run -it centos /bin/bash\n" }, { "code": null, "e": 3428, "s": 3371, "text": "Note the following points about the above sudo command −" }, { "code": null, "e": 3499, "s": 3428, "text": "We are using the sudo command to ensure that it runs with root access." }, { "code": null, "e": 3570, "s": 3499, "text": "We are using the sudo command to ensure that it runs with root access." }, { "code": null, "e": 3679, "s": 3570, "text": "Here, centos is the name of the image we want to download from Docker Hub and install on our Ubuntu machine." }, { "code": null, "e": 3788, "s": 3679, "text": "Here, centos is the name of the image we want to download from Docker Hub and install on our Ubuntu machine." }, { "code": null, "e": 3852, "s": 3788, "text": "─it is used to mention that we want to run in interactive mode." }, { "code": null, "e": 3916, "s": 3852, "text": "─it is used to mention that we want to run in interactive mode." }, { "code": null, "e": 3987, "s": 3916, "text": "/bin/bash is used to run the bash shell once CentOS is up and running." }, { "code": null, "e": 4058, "s": 3987, "text": "/bin/bash is used to run the bash shell once CentOS is up and running." }, { "code": null, "e": 4143, "s": 4058, "text": "To see the list of Docker images on the system, you can issue the following command." }, { "code": null, "e": 4158, "s": 4143, "text": "docker images\n" }, { "code": null, "e": 4240, "s": 4158, "text": "This command is used to display all the images currently installed on the system." }, { "code": null, "e": 4256, "s": 4240, "text": "docker images \n" }, { "code": null, "e": 4261, "s": 4256, "text": "None" }, { "code": null, "e": 4319, "s": 4261, "text": "The output will provide the list of images on the system." }, { "code": null, "e": 4338, "s": 4319, "text": "sudo docker images" }, { "code": null, "e": 4408, "s": 4338, "text": "When we run the above command, it will produce the following result −" }, { "code": null, "e": 4551, "s": 4408, "text": "From the above output, you can see that the server has three images: centos, newcentos, and jenkins. Each image has the following attributes −" }, { "code": null, "e": 4595, "s": 4551, "text": "TAG − This is used to logically tag images." }, { "code": null, "e": 4639, "s": 4595, "text": "TAG − This is used to logically tag images." }, { "code": null, "e": 4695, "s": 4639, "text": "Image ID − This is used to uniquely identify the image." }, { "code": null, "e": 4751, "s": 4695, "text": "Image ID − This is used to uniquely identify the image." }, { "code": null, "e": 4809, "s": 4751, "text": "Created − The number of days since the image was created." }, { "code": null, "e": 4867, "s": 4809, "text": "Created − The number of days since the image was created." }, { "code": null, "e": 4905, "s": 4867, "text": "Virtual Size − The size of the image." }, { "code": null, "e": 4943, "s": 4905, "text": "Virtual Size − The size of the image." }, { "code": null, "e": 5054, "s": 4943, "text": "Images can be downloaded from Docker Hub using the Docker run command. Let’s see in detail how we can do this." }, { "code": null, "e": 5123, "s": 5054, "text": "The following syntax is used to run a command in a Docker container." }, { "code": null, "e": 5142, "s": 5123, "text": "docker run image \n" }, { "code": null, "e": 5216, "s": 5142, "text": "Image − This is the name of the image which is used to run the container." }, { "code": null, "e": 5290, "s": 5216, "text": "Image − This is the name of the image which is used to run the container." }, { "code": null, "e": 5348, "s": 5290, "text": "The output will run the command in the desired container." }, { "code": null, "e": 5371, "s": 5348, "text": "sudo docker run centos" }, { "code": null, "e": 5477, "s": 5371, "text": "This command will download the centos image, if it is not already present, and run the OS as a container." }, { "code": null, "e": 5543, "s": 5477, "text": "When we run the above command, we will get the following result −" }, { "code": null, "e": 5729, "s": 5543, "text": "You will now see the CentOS Docker image downloaded. Now, if we run the Docker images command to see the list of images on the system, we should be able to see the centos image as well." }, { "code": null, "e": 5847, "s": 5729, "text": "The Docker images on the system can be removed via the docker rmi command. Let’s look at this command in more detail." }, { "code": null, "e": 5859, "s": 5847, "text": "docker rmi\n" }, { "code": null, "e": 5905, "s": 5859, "text": "This command is used to remove Docker images." }, { "code": null, "e": 5925, "s": 5905, "text": "docker rmi ImageID\n" }, { "code": null, "e": 5990, "s": 5925, "text": "ImageID − This is the ID of the image which needs to be removed." }, { "code": null, "e": 6055, "s": 5990, "text": "ImageID − This is the ID of the image which needs to be removed." }, { "code": null, "e": 6114, "s": 6055, "text": "The output will provide the Image ID of the deleted Image." }, { "code": null, "e": 6144, "s": 6114, "text": "sudo docker rmi 7a86f8ffcb25 " }, { "code": null, "e": 6203, "s": 6144, "text": "Here, 7a86f8ffcb25 is the Image ID of the newcentos image." }, { "code": null, "e": 6273, "s": 6203, "text": "When we run the above command, it will produce the following result −" }, { "code": null, "e": 6320, "s": 6273, "text": "Let’s see some more Docker commands on images." }, { "code": null, "e": 6386, "s": 6320, "text": "This command is used to return only the Image ID’s of the images." }, { "code": null, "e": 6402, "s": 6386, "text": "docker images \n" }, { "code": null, "e": 6465, "s": 6402, "text": "q − It tells the Docker command to return the Image ID’s only." }, { "code": null, "e": 6528, "s": 6465, "text": "q − It tells the Docker command to return the Image ID’s only." }, { "code": null, "e": 6603, "s": 6528, "text": "The output will show only the Image ID’s of the images on the Docker host." }, { "code": null, "e": 6626, "s": 6603, "text": "sudo docker images -q " }, { "code": null, "e": 6696, "s": 6626, "text": "When we run the above command, it will produce the following result −" }, { "code": null, "e": 6759, "s": 6696, "text": "This command is used see the details of an image or container." }, { "code": null, "e": 6787, "s": 6759, "text": "docker inspect Repository \n" }, { "code": null, "e": 6831, "s": 6787, "text": "Repository − This is the name of the Image." }, { "code": null, "e": 6875, "s": 6831, "text": "Repository − This is the name of the Image." }, { "code": null, "e": 6931, "s": 6875, "text": "The output will show detailed information on the Image." }, { "code": null, "e": 6960, "s": 6931, "text": "sudo docker inspect jenkins " }, { "code": null, "e": 7030, "s": 6960, "text": "When we run the above command, it will produce the following result −" }, { "code": null, "e": 7064, "s": 7030, "text": "\n 70 Lectures \n 12 hours \n" }, { "code": null, "e": 7080, "s": 7064, "text": " Anshul Chauhan" }, { "code": null, "e": 7113, "s": 7080, "text": "\n 41 Lectures \n 5 hours \n" }, { "code": null, "e": 7125, "s": 7113, "text": " AR Shankar" }, { "code": null, "e": 7158, "s": 7125, "text": "\n 31 Lectures \n 3 hours \n" }, { "code": null, "e": 7175, "s": 7158, "text": " Abhilash Nelson" }, { "code": null, "e": 7208, "s": 7175, "text": "\n 15 Lectures \n 2 hours \n" }, { "code": null, "e": 7248, "s": 7208, "text": " Harshit Srivastava, Pranjal Srivastava" }, { "code": null, "e": 7281, "s": 7248, "text": "\n 33 Lectures \n 4 hours \n" }, { "code": null, "e": 7301, "s": 7281, "text": " Mumshad Mannambeth" }, { "code": null, "e": 7333, "s": 7301, "text": "\n 13 Lectures \n 53 mins\n" }, { "code": null, "e": 7349, "s": 7333, "text": " Musab Zayadneh" }, { "code": null, "e": 7356, "s": 7349, "text": " Print" }, { "code": null, "e": 7367, "s": 7356, "text": " Add Notes" } ]
7 Tips for Great CMake Scripts. How to Make Your DevOps Life Easier | by Branislav Holländer | Towards Data Science
CMake has become the de facto standard tool for C++build automation, testing, and packaging. It is widely used for multi-platform development and supports generating build files for most C++ compilers. Since it was introduced 21 years ago, it came a long way and added support for many great features, gaining popularity among C++ developers. In this post, I would like to introduce you to some tips that might help you write better CMake scripts. While you may already be familiar with some of them, I am sure you will find some useful ones as well. Functions like add_definitions, include_directories, link_libraries, and others are still around in modern CMake due to backward compatibility. However, whenever possible, you should prefer using their counterparts target_compile_definitions, target_include_directories, target_sources, or target_link_libraries instead. Since the functions without target_ do not specify a scope, they will leak to all targets specified in the directory. For instance, if you want to build an executable target that additionally depends on a library defined in a subdirectory, you could specify it like this: project(main_project)add_executable(main_project main.cpp)add_subdirectory(dependency_lib)include_directories(include_files) Unfortunately, since the directories specified in include_directories are appended to the list of all targets in the current CMakeLists.txt file, they will also be appended to dependency_lib. Thus, we might end up with a scenario of using the wrong include files in dependency_lib. The same also applies to the other commands. Especially with commands such as add_definitions or add_compile_options, this may cause some hard-to-find compilation errors. On the other hand, using target_include_directories or target_link_libraries, we explicitly specify the target we want to use, avoiding any leakage problems. Furthermore, these commands let us optionally specify the scope to achieve the desired inheritance behavior (see next tip). In modern CMake, target commands let you specify the command scope using INTERFACE, PRIVATE and PUBLIC keywords. This is useful if you want to carry over a dependency from a child target to the parent. Let us consider, for example, the following code: project(main_project)add_executable(main_project main.cpp)add_subdirectory(dependency_lib)target_link_libraries(main_project PRIVATE dependency_lib) In the subdirectory dependency_lib, we have the following CMakeLists.txt: project(dependency_lib)add_library(dependency_lib SHARED library.cpp)add_subdirectory(sub_dependency_lib)target_link_libraries(dependency_lib PRIVATE sub_dependency_lib) Clearly, we have a hierarchy of dependencies. main_project depends on dependency_lib, which in turn depends on sub_dependency_lib. Written like this, sub_dependency_lib is not visible to main_project. This means that main_project won’t be able to use any functions of sub_dependency_lib directly. If you substitute the keyword PRIVATE with PUBLIC, you will also be able to use sub_dependency_lib in main_project. This is useful if dependency_lib does not completely hide the dependency, which is often the case. The INTERFACE keyword is less frequently used and designates a dependency used in “upstream” targets without being used in the target where it is declared (in this example, sub_dependency_lib would be visible to main_project but wouldn’t be used in dependency_lib itself). The default steps you should perform before configuring any CMake build are creating a build subdirectory and then running CMake. However, sometimes you may forget to create the additional directory and run CMake in the root. This “in-source build” pollutes your project and creates many changes in git. If you want to disable in-source builds, put the following lines in your root CMakeLists.txt file: if(${CMAKE_SOURCE_DIR} STREQUAL ${CMAKE_BINARY_DIR})message(FATAL_ERROR “In-source build detected!”)endif() This simple script compares the source directory and build directory and throws an error if they are equal. It is recommended to specify the C++ standard for every CMake project with the following definition: project(main_project LANGUAGES CXX)set(CMAKE_CXX_STANDARD 17)set(CMAKE_CXX_STANDARD_REQUIRED ON)set(CMAKE_CXX_EXTENSIONS OFF) This ensures that the standard will be enforced given compiler support and turns off non-standard C++ features. Avoid setting the C++ standard by adding compile flags. This is not cross-platform compatible since every compiler uses different flags. If you require more fine-tuned control, you may specify concrete C++ features to be supported by the compiler as well: target_compile_features(dependency_lib PUBLIC cxx_nullptr PRIVATE cxx_variadic_templates cxx_lambdas) In this case, we require that dependency_lib is compiled with support for variadic templates, nullptr, and lambdas, while upstream targets should also be compiled with nullptr support. With modern CMake, you aren’t restricted only to C or C++. CMake also supports other languages such as Objective-C or Fortran. One of the more frequently used languages in the C++ world is CUDA, NVIDIA’s GPGPU programming language. Setting up CUDA was traditionally rather difficult. With CMake, you can add CUDA as a programming language in a CMake project like this: cmake_minimum_required(VERSION 3.8 FATAL_ERROR)project(cmake_and_cuda LANGUAGES CXX CUDA) Then you can add new CUDA kernels just as easily as C++ source files: add_executable(cmake_and_cuda kernel.cu kernel.h) To select a specific CUDA architecture(s), you can add the following to the cmake command: cmake -DCMAKE_CUDA_FLAGS=”-arch=sm_75” . As with any other programming languages, CMake also advocates the Do Not Repeat Yourself (DRY) principle. It is always good to put code that you need more than twice into a separate function or macro. A macro in CMake is defined as follows: macro(foo arg) <commands>endmacro() A function, on the other hand, is defined as: function(foo arg) <commands>endfunction() Although these two concepts are very similar, they differ in the scope: a function defines its own scope, while a macro behaves like if you pasted in the code where it is used. For example, a return() statement in a macro, rather than returning control from the macro, returns the enclosing scope's control. If your project depends on a custom target, such as an external repository, you can use the ExternalProject module. The ExternalProject_Add command allows you to download and use a git repo like this: ExternalProject_Add( Eigen GIT_REPOSITORY "https://gitlab.com/libeigen/eigen.git" GIT_TAG "${EXPECTED_EIGEN_VERSION}" SOURCE_DIR eigen BINARY_DIR eigen-build CMAKE_ARGS -DBUILD_TESTING:BOOL=OFF -DBUILD_SHARED_LIBS:BOOL=ON) In this example, we use the popular Eigen3 matrix-vector library by specifying the repository URL, a specific git tag to checkout, a source directory, and a binary directory as in an ordinary CMake project, as well as CMake arguments. Besides git, the command also supports Subversion, CVS, Mercurial, and an ordinary download. The added project is assumed to be a CMake project by default (although it doesn’t need to be). You can specify a separate CMake generator and a separate build command as well. After specifying the external project, it can be used as another CMake target, i.e., your target can depend on it, and the ExternalProject itself can depend on other targets as well. You can find more information about the ExternalProject module in the CMake documentation. Modern CMake is an extensive and extensible system for defining an entire software build. It supports many different platforms and languages and allows you to build a hierarchy of interdependent targets. One last tip: treat your CMake code as a part of your codebase and maintain it well. This will make the build process transparent to all developers on the project. CMake documentation: https://cmake.org/cmake/help/v3.20/ CMake targets explained: https://leimao.github.io/blog/CMake-Public-Private-Interface/ Target transitivity explained: https://pspdfkit.com/blog/2018/modern-cmake-tips/
[ { "code": null, "e": 515, "s": 172, "text": "CMake has become the de facto standard tool for C++build automation, testing, and packaging. It is widely used for multi-platform development and supports generating build files for most C++ compilers. Since it was introduced 21 years ago, it came a long way and added support for many great features, gaining popularity among C++ developers." }, { "code": null, "e": 723, "s": 515, "text": "In this post, I would like to introduce you to some tips that might help you write better CMake scripts. While you may already be familiar with some of them, I am sure you will find some useful ones as well." }, { "code": null, "e": 1044, "s": 723, "text": "Functions like add_definitions, include_directories, link_libraries, and others are still around in modern CMake due to backward compatibility. However, whenever possible, you should prefer using their counterparts target_compile_definitions, target_include_directories, target_sources, or target_link_libraries instead." }, { "code": null, "e": 1316, "s": 1044, "text": "Since the functions without target_ do not specify a scope, they will leak to all targets specified in the directory. For instance, if you want to build an executable target that additionally depends on a library defined in a subdirectory, you could specify it like this:" }, { "code": null, "e": 1441, "s": 1316, "text": "project(main_project)add_executable(main_project main.cpp)add_subdirectory(dependency_lib)include_directories(include_files)" }, { "code": null, "e": 1894, "s": 1441, "text": "Unfortunately, since the directories specified in include_directories are appended to the list of all targets in the current CMakeLists.txt file, they will also be appended to dependency_lib. Thus, we might end up with a scenario of using the wrong include files in dependency_lib. The same also applies to the other commands. Especially with commands such as add_definitions or add_compile_options, this may cause some hard-to-find compilation errors." }, { "code": null, "e": 2176, "s": 1894, "text": "On the other hand, using target_include_directories or target_link_libraries, we explicitly specify the target we want to use, avoiding any leakage problems. Furthermore, these commands let us optionally specify the scope to achieve the desired inheritance behavior (see next tip)." }, { "code": null, "e": 2378, "s": 2176, "text": "In modern CMake, target commands let you specify the command scope using INTERFACE, PRIVATE and PUBLIC keywords. This is useful if you want to carry over a dependency from a child target to the parent." }, { "code": null, "e": 2428, "s": 2378, "text": "Let us consider, for example, the following code:" }, { "code": null, "e": 2577, "s": 2428, "text": "project(main_project)add_executable(main_project main.cpp)add_subdirectory(dependency_lib)target_link_libraries(main_project PRIVATE dependency_lib)" }, { "code": null, "e": 2651, "s": 2577, "text": "In the subdirectory dependency_lib, we have the following CMakeLists.txt:" }, { "code": null, "e": 2821, "s": 2651, "text": "project(dependency_lib)add_library(dependency_lib SHARED library.cpp)add_subdirectory(sub_dependency_lib)target_link_libraries(dependency_lib PRIVATE sub_dependency_lib)" }, { "code": null, "e": 3606, "s": 2821, "text": "Clearly, we have a hierarchy of dependencies. main_project depends on dependency_lib, which in turn depends on sub_dependency_lib. Written like this, sub_dependency_lib is not visible to main_project. This means that main_project won’t be able to use any functions of sub_dependency_lib directly. If you substitute the keyword PRIVATE with PUBLIC, you will also be able to use sub_dependency_lib in main_project. This is useful if dependency_lib does not completely hide the dependency, which is often the case. The INTERFACE keyword is less frequently used and designates a dependency used in “upstream” targets without being used in the target where it is declared (in this example, sub_dependency_lib would be visible to main_project but wouldn’t be used in dependency_lib itself)." }, { "code": null, "e": 3910, "s": 3606, "text": "The default steps you should perform before configuring any CMake build are creating a build subdirectory and then running CMake. However, sometimes you may forget to create the additional directory and run CMake in the root. This “in-source build” pollutes your project and creates many changes in git." }, { "code": null, "e": 4009, "s": 3910, "text": "If you want to disable in-source builds, put the following lines in your root CMakeLists.txt file:" }, { "code": null, "e": 4117, "s": 4009, "text": "if(${CMAKE_SOURCE_DIR} STREQUAL ${CMAKE_BINARY_DIR})message(FATAL_ERROR “In-source build detected!”)endif()" }, { "code": null, "e": 4225, "s": 4117, "text": "This simple script compares the source directory and build directory and throws an error if they are equal." }, { "code": null, "e": 4326, "s": 4225, "text": "It is recommended to specify the C++ standard for every CMake project with the following definition:" }, { "code": null, "e": 4452, "s": 4326, "text": "project(main_project LANGUAGES CXX)set(CMAKE_CXX_STANDARD 17)set(CMAKE_CXX_STANDARD_REQUIRED ON)set(CMAKE_CXX_EXTENSIONS OFF)" }, { "code": null, "e": 4701, "s": 4452, "text": "This ensures that the standard will be enforced given compiler support and turns off non-standard C++ features. Avoid setting the C++ standard by adding compile flags. This is not cross-platform compatible since every compiler uses different flags." }, { "code": null, "e": 4820, "s": 4701, "text": "If you require more fine-tuned control, you may specify concrete C++ features to be supported by the compiler as well:" }, { "code": null, "e": 4949, "s": 4820, "text": "target_compile_features(dependency_lib PUBLIC cxx_nullptr PRIVATE cxx_variadic_templates cxx_lambdas)" }, { "code": null, "e": 5134, "s": 4949, "text": "In this case, we require that dependency_lib is compiled with support for variadic templates, nullptr, and lambdas, while upstream targets should also be compiled with nullptr support." }, { "code": null, "e": 5503, "s": 5134, "text": "With modern CMake, you aren’t restricted only to C or C++. CMake also supports other languages such as Objective-C or Fortran. One of the more frequently used languages in the C++ world is CUDA, NVIDIA’s GPGPU programming language. Setting up CUDA was traditionally rather difficult. With CMake, you can add CUDA as a programming language in a CMake project like this:" }, { "code": null, "e": 5593, "s": 5503, "text": "cmake_minimum_required(VERSION 3.8 FATAL_ERROR)project(cmake_and_cuda LANGUAGES CXX CUDA)" }, { "code": null, "e": 5663, "s": 5593, "text": "Then you can add new CUDA kernels just as easily as C++ source files:" }, { "code": null, "e": 5713, "s": 5663, "text": "add_executable(cmake_and_cuda kernel.cu kernel.h)" }, { "code": null, "e": 5804, "s": 5713, "text": "To select a specific CUDA architecture(s), you can add the following to the cmake command:" }, { "code": null, "e": 5845, "s": 5804, "text": "cmake -DCMAKE_CUDA_FLAGS=”-arch=sm_75” ." }, { "code": null, "e": 6086, "s": 5845, "text": "As with any other programming languages, CMake also advocates the Do Not Repeat Yourself (DRY) principle. It is always good to put code that you need more than twice into a separate function or macro. A macro in CMake is defined as follows:" }, { "code": null, "e": 6123, "s": 6086, "text": "macro(foo arg) <commands>endmacro()" }, { "code": null, "e": 6169, "s": 6123, "text": "A function, on the other hand, is defined as:" }, { "code": null, "e": 6212, "s": 6169, "text": "function(foo arg) <commands>endfunction()" }, { "code": null, "e": 6520, "s": 6212, "text": "Although these two concepts are very similar, they differ in the scope: a function defines its own scope, while a macro behaves like if you pasted in the code where it is used. For example, a return() statement in a macro, rather than returning control from the macro, returns the enclosing scope's control." }, { "code": null, "e": 6721, "s": 6520, "text": "If your project depends on a custom target, such as an external repository, you can use the ExternalProject module. The ExternalProject_Add command allows you to download and use a git repo like this:" }, { "code": null, "e": 6956, "s": 6721, "text": "ExternalProject_Add( Eigen GIT_REPOSITORY \"https://gitlab.com/libeigen/eigen.git\" GIT_TAG \"${EXPECTED_EIGEN_VERSION}\" SOURCE_DIR eigen BINARY_DIR eigen-build CMAKE_ARGS -DBUILD_TESTING:BOOL=OFF -DBUILD_SHARED_LIBS:BOOL=ON)" }, { "code": null, "e": 7461, "s": 6956, "text": "In this example, we use the popular Eigen3 matrix-vector library by specifying the repository URL, a specific git tag to checkout, a source directory, and a binary directory as in an ordinary CMake project, as well as CMake arguments. Besides git, the command also supports Subversion, CVS, Mercurial, and an ordinary download. The added project is assumed to be a CMake project by default (although it doesn’t need to be). You can specify a separate CMake generator and a separate build command as well." }, { "code": null, "e": 7735, "s": 7461, "text": "After specifying the external project, it can be used as another CMake target, i.e., your target can depend on it, and the ExternalProject itself can depend on other targets as well. You can find more information about the ExternalProject module in the CMake documentation." }, { "code": null, "e": 8103, "s": 7735, "text": "Modern CMake is an extensive and extensible system for defining an entire software build. It supports many different platforms and languages and allows you to build a hierarchy of interdependent targets. One last tip: treat your CMake code as a part of your codebase and maintain it well. This will make the build process transparent to all developers on the project." }, { "code": null, "e": 8160, "s": 8103, "text": "CMake documentation: https://cmake.org/cmake/help/v3.20/" }, { "code": null, "e": 8247, "s": 8160, "text": "CMake targets explained: https://leimao.github.io/blog/CMake-Public-Private-Interface/" } ]
How to Add New Lines in Python f-strings | Towards Data Science
In Python, it’s impossible to include backslashes in curly braces {} of f-strings. Doing so will result into a SyntaxError: >>> f'{\}'SyntaxError: f-string expression part cannot include a backslash This behaviour aligns perfectly with PEP-0498 which is about Literal String Interpolation: Backslashes may not appear inside the expression portions of f-strings, so you cannot use them, for example, to escape quotes inside f-strings In the following sections we will explore a couple of options you can use in order to add backslashes (including new lines) in f-strings. As we already discussed, backslashes cannot be used directly in Python f-strings. However, there is an easy workaround that allows us to include backslashes in order to denote for example new lines, tabs etc. Let’s suppose that we have a list of integers we want to print out to the standard output. nums = [10, 20, 30] print(f"Numbers:\n {'\n'.join(map(str, nums))}") As expected, the above will fail with SyntaxError: f-string expression part cannot include a backslash One workaround is to add the new line character (i.e. '\n') into a string variable and then reference that variable when printing out the numbers. For example, new_line = '\n'nums = [10, 20, 30] print(f"Numbers:{new_line}{new_line.join(map(str, nums))}") And the output should be Numbers:102030 Note that you can do this for pretty much every character that requires a backslash. For instance, let’s suppose you want to use a tab in an f-string. The following should to the trick: tab = '\t'print(f'Hello {tab} World!')# OutputHello World! For new lines in particular, there is also another approach that we can follow in order to add new line characters in Python f-strings. The os package comes with some functionality about Miscellaneous System Information. This includes os.linesep that returns the new line character. The string used to separate (or, rather, terminate) lines on the current platform. This may be a single character, such as '\n' for POSIX, or multiple characters, for example, '\r\n' for Windows. For example, import osnums = [10, 20, 30] print(f"Numbers:{os.linesep}{os.linesep.join(map(str, nums))}") And the output will again be Numbers:102030 Note that you must avoid using os.linesep as a line terminator when writing files opened in text mode. Instead, you have to use use a single '\n'. Another possibility, is to use chr() function to generate a new line character. The chr() function in Python returns a string representation of the input integer that corresponds to a Unicode character. The decimal value of 10 in Unicode is equivalent to the line feed (i.e. new line). >>> chr(10)'\n' Therefore, in order to add new lines in f-strings using chr() all you need to do is nums = [10, 20, 30] print(f"Numbers:{chr(10)}{chr(10).join(map(str, nums))}")# Numbers:# 10# 20# 30 In today’s article we discussed one limitation of Python that stops us from using backslashes in f-strings. We introduced a few possible workarounds and we also explored in particular how to implicitly add new lines in Python f-strings. Essentially, you have three options; The first is to define a new line as a string variable and reference that variable in f-string curly braces. The second workaround is to use os.linesep that returns the new line character and the final approach is to use chr(10) that corresponds to the Unicode new line character.
[ { "code": null, "e": 296, "s": 172, "text": "In Python, it’s impossible to include backslashes in curly braces {} of f-strings. Doing so will result into a SyntaxError:" }, { "code": null, "e": 371, "s": 296, "text": ">>> f'{\\}'SyntaxError: f-string expression part cannot include a backslash" }, { "code": null, "e": 462, "s": 371, "text": "This behaviour aligns perfectly with PEP-0498 which is about Literal String Interpolation:" }, { "code": null, "e": 605, "s": 462, "text": "Backslashes may not appear inside the expression portions of f-strings, so you cannot use them, for example, to escape quotes inside f-strings" }, { "code": null, "e": 743, "s": 605, "text": "In the following sections we will explore a couple of options you can use in order to add backslashes (including new lines) in f-strings." }, { "code": null, "e": 952, "s": 743, "text": "As we already discussed, backslashes cannot be used directly in Python f-strings. However, there is an easy workaround that allows us to include backslashes in order to denote for example new lines, tabs etc." }, { "code": null, "e": 1043, "s": 952, "text": "Let’s suppose that we have a list of integers we want to print out to the standard output." }, { "code": null, "e": 1112, "s": 1043, "text": "nums = [10, 20, 30] print(f\"Numbers:\\n {'\\n'.join(map(str, nums))}\")" }, { "code": null, "e": 1150, "s": 1112, "text": "As expected, the above will fail with" }, { "code": null, "e": 1215, "s": 1150, "text": "SyntaxError: f-string expression part cannot include a backslash" }, { "code": null, "e": 1375, "s": 1215, "text": "One workaround is to add the new line character (i.e. '\\n') into a string variable and then reference that variable when printing out the numbers. For example," }, { "code": null, "e": 1470, "s": 1375, "text": "new_line = '\\n'nums = [10, 20, 30] print(f\"Numbers:{new_line}{new_line.join(map(str, nums))}\")" }, { "code": null, "e": 1495, "s": 1470, "text": "And the output should be" }, { "code": null, "e": 1510, "s": 1495, "text": "Numbers:102030" }, { "code": null, "e": 1696, "s": 1510, "text": "Note that you can do this for pretty much every character that requires a backslash. For instance, let’s suppose you want to use a tab in an f-string. The following should to the trick:" }, { "code": null, "e": 1757, "s": 1696, "text": "tab = '\\t'print(f'Hello {tab} World!')# OutputHello World!" }, { "code": null, "e": 1893, "s": 1757, "text": "For new lines in particular, there is also another approach that we can follow in order to add new line characters in Python f-strings." }, { "code": null, "e": 2040, "s": 1893, "text": "The os package comes with some functionality about Miscellaneous System Information. This includes os.linesep that returns the new line character." }, { "code": null, "e": 2236, "s": 2040, "text": "The string used to separate (or, rather, terminate) lines on the current platform. This may be a single character, such as '\\n' for POSIX, or multiple characters, for example, '\\r\\n' for Windows." }, { "code": null, "e": 2249, "s": 2236, "text": "For example," }, { "code": null, "e": 2342, "s": 2249, "text": "import osnums = [10, 20, 30] print(f\"Numbers:{os.linesep}{os.linesep.join(map(str, nums))}\")" }, { "code": null, "e": 2371, "s": 2342, "text": "And the output will again be" }, { "code": null, "e": 2386, "s": 2371, "text": "Numbers:102030" }, { "code": null, "e": 2533, "s": 2386, "text": "Note that you must avoid using os.linesep as a line terminator when writing files opened in text mode. Instead, you have to use use a single '\\n'." }, { "code": null, "e": 2819, "s": 2533, "text": "Another possibility, is to use chr() function to generate a new line character. The chr() function in Python returns a string representation of the input integer that corresponds to a Unicode character. The decimal value of 10 in Unicode is equivalent to the line feed (i.e. new line)." }, { "code": null, "e": 2835, "s": 2819, "text": ">>> chr(10)'\\n'" }, { "code": null, "e": 2919, "s": 2835, "text": "Therefore, in order to add new lines in f-strings using chr() all you need to do is" }, { "code": null, "e": 3019, "s": 2919, "text": "nums = [10, 20, 30] print(f\"Numbers:{chr(10)}{chr(10).join(map(str, nums))}\")# Numbers:# 10# 20# 30" }, { "code": null, "e": 3256, "s": 3019, "text": "In today’s article we discussed one limitation of Python that stops us from using backslashes in f-strings. We introduced a few possible workarounds and we also explored in particular how to implicitly add new lines in Python f-strings." } ]
Java Date and Time
Java does not have a built-in Date class, but we can import the java.time package to work with the date and time API. The package includes many date and time classes. For example: If you don't know what a package is, read our Java Packages Tutorial. To display the current date, import the java.time.LocalDate class, and use its now() method: import java.time.LocalDate; // import the LocalDate class public class Main { public static void main(String[] args) { LocalDate myObj = LocalDate.now(); // Create a date object System.out.println(myObj); // Display the current date } } The output will be: To display the current time (hour, minute, second, and nanoseconds), import the java.time.LocalTime class, and use its now() method: import java.time.LocalTime; // import the LocalTime class public class Main { public static void main(String[] args) { LocalTime myObj = LocalTime.now(); System.out.println(myObj); } } The output will be: To display the current date and time, import the java.time.LocalDateTime class, and use its now() method: import java.time.LocalDateTime; // import the LocalDateTime class public class Main { public static void main(String[] args) { LocalDateTime myObj = LocalDateTime.now(); System.out.println(myObj); } } The output will be: The "T" in the example above is used to separate the date from the time. You can use the DateTimeFormatter class with the ofPattern() method in the same package to format or parse date-time objects. The following example will remove both the "T" and nanoseconds from the date-time: import java.time.LocalDateTime; // Import the LocalDateTime class import java.time.format.DateTimeFormatter; // Import the DateTimeFormatter class public class Main { public static void main(String[] args) { LocalDateTime myDateObj = LocalDateTime.now(); System.out.println("Before formatting: " + myDateObj); DateTimeFormatter myFormatObj = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss"); String formattedDate = myDateObj.format(myFormatObj); System.out.println("After formatting: " + formattedDate); } } The output will be: The ofPattern() method accepts all sorts of values, if you want to display the date and time in a different format. For example: 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": 182, "s": 0, "text": "Java does not have a built-in Date class, but we can import the java.time \npackage to work with the date and time API. The package includes many date and time classes. \nFor example:" }, { "code": null, "e": 252, "s": 182, "text": "If you don't know what a package is, read our Java Packages Tutorial." }, { "code": null, "e": 345, "s": 252, "text": "To display the current date, import the java.time.LocalDate class, and use its now() method:" }, { "code": null, "e": 596, "s": 345, "text": "import java.time.LocalDate; // import the LocalDate class\n\npublic class Main {\n public static void main(String[] args) {\n LocalDate myObj = LocalDate.now(); // Create a date object\n System.out.println(myObj); // Display the current date\n }\n}\n" }, { "code": null, "e": 616, "s": 596, "text": "The output will be:" }, { "code": null, "e": 749, "s": 616, "text": "To display the current time (hour, minute, second, and nanoseconds), import the java.time.LocalTime class, and use its now() method:" }, { "code": null, "e": 948, "s": 749, "text": "import java.time.LocalTime; // import the LocalTime class\n\npublic class Main {\n public static void main(String[] args) {\n LocalTime myObj = LocalTime.now();\n System.out.println(myObj);\n }\n}\n" }, { "code": null, "e": 968, "s": 948, "text": "The output will be:" }, { "code": null, "e": 1074, "s": 968, "text": "To display the current date and time, import the java.time.LocalDateTime class, and use its now() method:" }, { "code": null, "e": 1289, "s": 1074, "text": "import java.time.LocalDateTime; // import the LocalDateTime class\n\npublic class Main {\n public static void main(String[] args) {\n LocalDateTime myObj = LocalDateTime.now();\n System.out.println(myObj);\n }\n}\n" }, { "code": null, "e": 1309, "s": 1289, "text": "The output will be:" }, { "code": null, "e": 1593, "s": 1309, "text": "The \"T\" in the example above is used to separate the date from the time. You can use the DateTimeFormatter class \nwith the ofPattern() method in the same package to format or parse date-time objects. \nThe following example will remove both the \"T\" and nanoseconds from the date-time:" }, { "code": null, "e": 2130, "s": 1593, "text": "import java.time.LocalDateTime; // Import the LocalDateTime class\nimport java.time.format.DateTimeFormatter; // Import the DateTimeFormatter class\n\npublic class Main {\n public static void main(String[] args) {\n LocalDateTime myDateObj = LocalDateTime.now();\n System.out.println(\"Before formatting: \" + myDateObj);\n DateTimeFormatter myFormatObj = DateTimeFormatter.ofPattern(\"dd-MM-yyyy HH:mm:ss\");\n\n String formattedDate = myDateObj.format(myFormatObj);\n System.out.println(\"After formatting: \" + formattedDate);\n }\n}\n" }, { "code": null, "e": 2150, "s": 2130, "text": "The output will be:" }, { "code": null, "e": 2280, "s": 2150, "text": "The ofPattern() method accepts all sorts of values, if you want to display \nthe date and time in a different format. For example:" }, { "code": null, "e": 2313, "s": 2280, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 2355, "s": 2313, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 2462, "s": 2355, "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": 2481, "s": 2462, "text": "help@w3schools.com" } ]
Handling events in React.js
There are some syntactical differences in writing events but it is handled similar to DOM elements event handling. The name of event handlers are written in camel case notations. Event in simple html − <button onclick=”addUser()”> Add User </button> Event in React with jsx: <button onClick={ addUser }> Add User </button> One of the difference is we do not write return false to prevent default behavior in React. Instead of that we specifically write event.preventDefault() In simple Html − <button onclick=”console.log(‘Add user event clicked’); return false;”> Add User </button> In React it will be written as − function addUser(event){ event.preventDefault(); console.log(‘Add user event clicked’); } <button onClick={ addUser }> Add User </button> Here event passed in React is synthetic and cross browser compatible. A method in ES6 can be an event handler. In JavaScript classes, methods are not bound to class by default. These methods in class should be declared in constructor with binding as shown below − constructor(props){ super(props); this.addUser=this.addUser.bind(this); } Or we can use arrow functions which will bind the methods automatically and then no need to add bind in constructor. adduser=()=>{ } If we are not using arrow functions , another alternative is to call the method and binding on React element itself − addUser(){ } <button onClick={ (e)=>{this.addUser(e)}}> Add User </button> The problem with above anonymous callback function is , it will be created every time button renders on the screen and it can affect performance. <button onClick={ (e)=>this.addUser(id, e) }></button> Or <button onClick={ this.addUser.bind(this, id) }></button> In the above event handler we are passing id as an argument and event object as second argument. The event argument is visible in arrow function but in second approach it is passed implicitly so we have not provided it.
[ { "code": null, "e": 1177, "s": 1062, "text": "There are some syntactical differences in writing events but it is handled similar to DOM elements event handling." }, { "code": null, "e": 1241, "s": 1177, "text": "The name of event handlers are written in camel case notations." }, { "code": null, "e": 1264, "s": 1241, "text": "Event in simple html −" }, { "code": null, "e": 1391, "s": 1264, "text": "<button onclick=”addUser()”>\n Add User\n</button>\nEvent in React with jsx:\n<button onClick={ addUser }>\n Add User\n</button>" }, { "code": null, "e": 1544, "s": 1391, "text": "One of the difference is we do not write return false to prevent default behavior in React. Instead of that we specifically write event.preventDefault()" }, { "code": null, "e": 1561, "s": 1544, "text": "In simple Html −" }, { "code": null, "e": 1655, "s": 1561, "text": "<button onclick=”console.log(‘Add user event clicked’); return false;”>\n Add User\n</button>" }, { "code": null, "e": 1688, "s": 1655, "text": "In React it will be written as −" }, { "code": null, "e": 1835, "s": 1688, "text": "function addUser(event){\n event.preventDefault();\n console.log(‘Add user event clicked’);\n}\n<button onClick={ addUser }>\n Add User\n</button>" }, { "code": null, "e": 2099, "s": 1835, "text": "Here event passed in React is synthetic and cross browser compatible. A method in ES6 can be an event handler. In JavaScript classes, methods are not bound to class by default. These methods in class should be declared in constructor with binding as shown below −" }, { "code": null, "e": 2179, "s": 2099, "text": "constructor(props){\n super(props);\n this.addUser=this.addUser.bind(this);\n}" }, { "code": null, "e": 2296, "s": 2179, "text": "Or we can use arrow functions which will bind the methods automatically and then no need to add bind in constructor." }, { "code": null, "e": 2312, "s": 2296, "text": "adduser=()=>{\n}" }, { "code": null, "e": 2430, "s": 2312, "text": "If we are not using arrow functions , another alternative is to call the method and binding on React element itself −" }, { "code": null, "e": 2508, "s": 2430, "text": "addUser(){\n}\n<button onClick={ (e)=>{this.addUser(e)}}>\n Add User\n</button>" }, { "code": null, "e": 2654, "s": 2508, "text": "The problem with above anonymous callback function is , it will be created every time button renders on the screen and it can affect performance." }, { "code": null, "e": 2709, "s": 2654, "text": "<button onClick={ (e)=>this.addUser(id, e) }></button>" }, { "code": null, "e": 2712, "s": 2709, "text": "Or" }, { "code": null, "e": 2770, "s": 2712, "text": "<button onClick={ this.addUser.bind(this, id) }></button>" }, { "code": null, "e": 2990, "s": 2770, "text": "In the above event handler we are passing id as an argument and event object as second argument. The event argument is visible in arrow function but in second approach it is passed implicitly so we have not provided it." } ]
Abstractive Summarization Using Pytorch | by Raymond Cheng | Towards Data Science
Abstractive Summarization is a task in Natural Language Processing (NLP) that aims to generate a concise summary of a source text. Unlike extractive summarization, abstractive summarization does not simply copy important phrases from the source text but also potentially come up with new phrases that are relevant, which can be seen as paraphrasing. Abstractive summarization yields a number of applications in different domains, from books and literature, to science and R&D, to financial research and legal documents analysis. To date, the most recent and effective approach toward abstractive summarization is using transformer models fine-tuned specifically on a summarization dataset. In this article, we demonstrate how you can easily summarize a text using a powerful model within a few simple steps. The model that we are going to be using is already pretrained, so no additional training is required :) So without further ado, let’s get started! The library we are going to be using is Transformers by Huggingface. If you are not familiar with Transformers, you can go ahead and read my previous article on what it can do: towardsdatascience.com To install transformers, you can simply run: pip install transformers Note: Transformers requires Pytorch to be installed beforehand. If you don’t have Pytorch installed yet, head to the Pytorch official website and follow its instructions to install it. After successfully installing transformers, you can now start importing it to your Python script. We can also import os in order to set the environment variable for the GPU to use in the next step. Note that this is completely optional but a good practice to have to prevent overflowing to other GPUs if you have more than one GPUs (if you are using a Jupyter notebook). from transformers import pipelineimport os If you decided to set GPU (e.g. 0), then you can set it as shown below: os.environ["CUDA_VISIBLE_DEVICES"] = "0" Now, we are ready to select the summarization model to use. Huggingface provides two powerful summarization models to use: BART (bart-large-cnn) and t5 (t5-small, t5-base, t5-large, t5–3b, t5–11b). You can read more about them in their official papers (BART paper, t5 paper). To use the BART model, which is trained on the CNN/Daily Mail News Dataset, you can directly use the default parameters via Huggingface’s inbuilt pipeline module: summarizer = pipeline("summarization") If you want to use the t5 model (e.g. t5-base), which is trained on the c4 Common Crawl web corpus, then you can do this: summarizer = pipeline("summarization", model="t5-base", tokenizer="t5-base", framework="tf") You can refer to the Huggingface documentation for more information. Now, after we have our model ready, we can start inputting the text we want to summarize. Imagine, we want to summarize the following text about COVID-19 vaccine taken from an article from MedicineNet: One month after the United States began what has become a troubled rollout of a national COVID vaccination campaign, the effort is finally gathering real steam. Close to a million doses — over 951,000, to be more exact — made their way into the arms of Americans in the past 24 hours, the U.S. Centers for Disease Control and Prevention reported Wednesday. That’s the largest number of shots given in one day since the rollout began and a big jump from the previous day, when just under 340,000 doses were given, CBS News reported. That number is likely to jump quickly after the federal government on Tuesday gave states the OK to vaccinate anyone over 65 and said it would release all the doses of vaccine it has available for distribution. Meanwhile, a number of states have now opened mass vaccination sites in an effort to get larger numbers of people inoculated, CBS News reported. We define our variable: text = """One month after the United States began what has become a troubled rollout of a national COVID vaccination campaign, the effort is finally gathering real steam.Close to a million doses -- over 951,000, to be more exact -- made their way into the arms of Americans in the past 24 hours, the U.S. Centers for Disease Control and Prevention reported Wednesday. That's the largest number of shots given in one day since the rollout began and a big jump from the previous day, when just under 340,000 doses were given, CBS News reported.That number is likely to jump quickly after the federal government on Tuesday gave states the OK to vaccinate anyone over 65 and said it would release all the doses of vaccine it has available for distribution. Meanwhile, a number of states have now opened mass vaccination sites in an effort to get larger numbers of people inoculated, CBS News reported.""" Finally, we can start summarizing the inputted text. Here, we declare the min_length and the max_length we want the summarization output to be, and also turn off sampling to generate a fixed summary. We can do so by running the following: summary_text = summarizer(text, max_length=100, min_length=5, do_sample=False)[0]['summary_text']print(summary_text) Voila! We get our summary text: Over 951,000 doses of vaccine given in one day in the past 24 hours, CDC says . That’s the largest number of shots given in a month since the rollout began . The federal government gave states the OK to vaccinate anyone over 65 on Tuesday . A number of states have now opened mass vaccination sites in an effort to get more people inoculated, CBS News reports . As shown from the summarized text, we can see that the model knows that 24 hours is equivalent to a day and is smart enough to abbreviate the U.S. Centers for Disease Control and Prevention to CDC. In addition, the model successfully links information from the first and second paragraphs by indicating that it is the largest number of shots given since the rollout that began last month. We can see that the performance of this summarization model is quite decent. Congratulations, you now know how to perform abstractive summarization on any piece of text! To put it all together, here’s the entire code in the form of a Jupyter notebook: from transformers import pipeline import os ## Setting to use the 0th GPU os.environ["CUDA_VISIBLE_DEVICES"] = "0" ## Setting to use the bart-large-cnn model for summarization summarizer = pipeline("summarization") ## To use the t5-base model for summarization: ## summarizer = pipeline("summarization", model="t5-base", tokenizer="t5-base", framework="tf") text = """One month after the United States began what has become a troubled rollout of a national COVID vaccination campaign, the effort is finally gathering real steam. Close to a million doses -- over 951,000, to be more exact -- made their way into the arms of Americans in the past 24 hours, the U.S. Centers for Disease Control and Prevention reported Wednesday. That's the largest number of shots given in one day since the rollout began and a big jump from the previous day, when just under 340,000 doses were given, CBS News reported. That number is likely to jump quickly after the federal government on Tuesday gave states the OK to vaccinate anyone over 65 and said it would release all the doses of vaccine it has available for distribution. Meanwhile, a number of states have now opened mass vaccination sites in an effort to get larger numbers of people inoculated, CBS News reported.""" summary_text = summarizer(text, max_length=100, min_length=5, do_sample=False)[0]['summary_text'] print(summary_text) Over 951,000 doses of vaccine given in one day in the past 24 hours, CDC says . That's the largest number of shots given in a month since the rollout began . The federal government gave states the OK to vaccinate anyone over 65 on Tuesday . A number of states have now opened mass vaccination sites in an effort to get more people inoculated, CBS News reports . And that’s all! Hope you enjoyed this post. If you like my work, feel free to take a look at my other articles, and stay tuned for more to come :) towardsdatascience.com towardsdatascience.com towardsdatascience.com towardsdatascience.com towardsdatascience.com [1] Abstractive Text Summarization, Papers With Code [2] 20 Applications of Automatic Summarization in the Enterprise, Fraise [3] Transformers Github, Huggingface [4] Transformers Documentation, Huggingface [5] Pytorch Official Website, Facebook AI Research [6] Lewis, Mike, et al. “Bart: Denoising sequence-to-sequence pre-training for natural language generation, translation, and comprehension.” arXiv preprint arXiv:1910.13461 (2019). [7] Raffel, Colin, et al. “Exploring the limits of transfer learning with a unified text-to-text transformer.” arXiv preprint arXiv:1910.10683 (2019). [8] Tensorflow Datasets, Google [9] U.S. COVID Vaccine Rollout Nears 1 Million a Day, MedicineNet
[ { "code": null, "e": 701, "s": 172, "text": "Abstractive Summarization is a task in Natural Language Processing (NLP) that aims to generate a concise summary of a source text. Unlike extractive summarization, abstractive summarization does not simply copy important phrases from the source text but also potentially come up with new phrases that are relevant, which can be seen as paraphrasing. Abstractive summarization yields a number of applications in different domains, from books and literature, to science and R&D, to financial research and legal documents analysis." }, { "code": null, "e": 1084, "s": 701, "text": "To date, the most recent and effective approach toward abstractive summarization is using transformer models fine-tuned specifically on a summarization dataset. In this article, we demonstrate how you can easily summarize a text using a powerful model within a few simple steps. The model that we are going to be using is already pretrained, so no additional training is required :)" }, { "code": null, "e": 1127, "s": 1084, "text": "So without further ado, let’s get started!" }, { "code": null, "e": 1304, "s": 1127, "text": "The library we are going to be using is Transformers by Huggingface. If you are not familiar with Transformers, you can go ahead and read my previous article on what it can do:" }, { "code": null, "e": 1327, "s": 1304, "text": "towardsdatascience.com" }, { "code": null, "e": 1372, "s": 1327, "text": "To install transformers, you can simply run:" }, { "code": null, "e": 1397, "s": 1372, "text": "pip install transformers" }, { "code": null, "e": 1582, "s": 1397, "text": "Note: Transformers requires Pytorch to be installed beforehand. If you don’t have Pytorch installed yet, head to the Pytorch official website and follow its instructions to install it." }, { "code": null, "e": 1953, "s": 1582, "text": "After successfully installing transformers, you can now start importing it to your Python script. We can also import os in order to set the environment variable for the GPU to use in the next step. Note that this is completely optional but a good practice to have to prevent overflowing to other GPUs if you have more than one GPUs (if you are using a Jupyter notebook)." }, { "code": null, "e": 1996, "s": 1953, "text": "from transformers import pipelineimport os" }, { "code": null, "e": 2068, "s": 1996, "text": "If you decided to set GPU (e.g. 0), then you can set it as shown below:" }, { "code": null, "e": 2109, "s": 2068, "text": "os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"" }, { "code": null, "e": 2385, "s": 2109, "text": "Now, we are ready to select the summarization model to use. Huggingface provides two powerful summarization models to use: BART (bart-large-cnn) and t5 (t5-small, t5-base, t5-large, t5–3b, t5–11b). You can read more about them in their official papers (BART paper, t5 paper)." }, { "code": null, "e": 2548, "s": 2385, "text": "To use the BART model, which is trained on the CNN/Daily Mail News Dataset, you can directly use the default parameters via Huggingface’s inbuilt pipeline module:" }, { "code": null, "e": 2587, "s": 2548, "text": "summarizer = pipeline(\"summarization\")" }, { "code": null, "e": 2709, "s": 2587, "text": "If you want to use the t5 model (e.g. t5-base), which is trained on the c4 Common Crawl web corpus, then you can do this:" }, { "code": null, "e": 2802, "s": 2709, "text": "summarizer = pipeline(\"summarization\", model=\"t5-base\", tokenizer=\"t5-base\", framework=\"tf\")" }, { "code": null, "e": 2871, "s": 2802, "text": "You can refer to the Huggingface documentation for more information." }, { "code": null, "e": 3073, "s": 2871, "text": "Now, after we have our model ready, we can start inputting the text we want to summarize. Imagine, we want to summarize the following text about COVID-19 vaccine taken from an article from MedicineNet:" }, { "code": null, "e": 3234, "s": 3073, "text": "One month after the United States began what has become a troubled rollout of a national COVID vaccination campaign, the effort is finally gathering real steam." }, { "code": null, "e": 3605, "s": 3234, "text": "Close to a million doses — over 951,000, to be more exact — made their way into the arms of Americans in the past 24 hours, the U.S. Centers for Disease Control and Prevention reported Wednesday. That’s the largest number of shots given in one day since the rollout began and a big jump from the previous day, when just under 340,000 doses were given, CBS News reported." }, { "code": null, "e": 3961, "s": 3605, "text": "That number is likely to jump quickly after the federal government on Tuesday gave states the OK to vaccinate anyone over 65 and said it would release all the doses of vaccine it has available for distribution. Meanwhile, a number of states have now opened mass vaccination sites in an effort to get larger numbers of people inoculated, CBS News reported." }, { "code": null, "e": 3985, "s": 3961, "text": "We define our variable:" }, { "code": null, "e": 4886, "s": 3985, "text": "text = \"\"\"One month after the United States began what has become a troubled rollout of a national COVID vaccination campaign, the effort is finally gathering real steam.Close to a million doses -- over 951,000, to be more exact -- made their way into the arms of Americans in the past 24 hours, the U.S. Centers for Disease Control and Prevention reported Wednesday. That's the largest number of shots given in one day since the rollout began and a big jump from the previous day, when just under 340,000 doses were given, CBS News reported.That number is likely to jump quickly after the federal government on Tuesday gave states the OK to vaccinate anyone over 65 and said it would release all the doses of vaccine it has available for distribution. Meanwhile, a number of states have now opened mass vaccination sites in an effort to get larger numbers of people inoculated, CBS News reported.\"\"\"" }, { "code": null, "e": 5125, "s": 4886, "text": "Finally, we can start summarizing the inputted text. Here, we declare the min_length and the max_length we want the summarization output to be, and also turn off sampling to generate a fixed summary. We can do so by running the following:" }, { "code": null, "e": 5242, "s": 5125, "text": "summary_text = summarizer(text, max_length=100, min_length=5, do_sample=False)[0]['summary_text']print(summary_text)" }, { "code": null, "e": 5274, "s": 5242, "text": "Voila! We get our summary text:" }, { "code": null, "e": 5636, "s": 5274, "text": "Over 951,000 doses of vaccine given in one day in the past 24 hours, CDC says . That’s the largest number of shots given in a month since the rollout began . The federal government gave states the OK to vaccinate anyone over 65 on Tuesday . A number of states have now opened mass vaccination sites in an effort to get more people inoculated, CBS News reports ." }, { "code": null, "e": 6102, "s": 5636, "text": "As shown from the summarized text, we can see that the model knows that 24 hours is equivalent to a day and is smart enough to abbreviate the U.S. Centers for Disease Control and Prevention to CDC. In addition, the model successfully links information from the first and second paragraphs by indicating that it is the largest number of shots given since the rollout that began last month. We can see that the performance of this summarization model is quite decent." }, { "code": null, "e": 6277, "s": 6102, "text": "Congratulations, you now know how to perform abstractive summarization on any piece of text! To put it all together, here’s the entire code in the form of a Jupyter notebook:" }, { "code": null, "e": 6322, "s": 6277, "text": "from transformers import pipeline\nimport os\n" }, { "code": null, "e": 6639, "s": 6322, "text": "## Setting to use the 0th GPU\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\n\n## Setting to use the bart-large-cnn model for summarization\nsummarizer = pipeline(\"summarization\")\n\n## To use the t5-base model for summarization:\n## summarizer = pipeline(\"summarization\", model=\"t5-base\", tokenizer=\"t5-base\", framework=\"tf\")\n" }, { "code": null, "e": 7543, "s": 6639, "text": "text = \"\"\"One month after the United States began what has become a troubled rollout of a national COVID vaccination campaign, the effort is finally gathering real steam.\nClose to a million doses -- over 951,000, to be more exact -- made their way into the arms of Americans in the past 24 hours, the U.S. Centers for Disease Control and Prevention reported Wednesday. That's the largest number of shots given in one day since the rollout began and a big jump from the previous day, when just under 340,000 doses were given, CBS News reported.\nThat number is likely to jump quickly after the federal government on Tuesday gave states the OK to vaccinate anyone over 65 and said it would release all the doses of vaccine it has available for distribution. Meanwhile, a number of states have now opened mass vaccination sites in an effort to get larger numbers of people inoculated, CBS News reported.\"\"\"\n" }, { "code": null, "e": 7662, "s": 7543, "text": "summary_text = summarizer(text, max_length=100, min_length=5, do_sample=False)[0]['summary_text']\nprint(summary_text)\n" }, { "code": null, "e": 8026, "s": 7662, "text": " Over 951,000 doses of vaccine given in one day in the past 24 hours, CDC says . That's the largest number of shots given in a month since the rollout began . The federal government gave states the OK to vaccinate anyone over 65 on Tuesday . A number of states have now opened mass vaccination sites in an effort to get more people inoculated, CBS News reports .\n" }, { "code": null, "e": 8173, "s": 8026, "text": "And that’s all! Hope you enjoyed this post. If you like my work, feel free to take a look at my other articles, and stay tuned for more to come :)" }, { "code": null, "e": 8196, "s": 8173, "text": "towardsdatascience.com" }, { "code": null, "e": 8219, "s": 8196, "text": "towardsdatascience.com" }, { "code": null, "e": 8242, "s": 8219, "text": "towardsdatascience.com" }, { "code": null, "e": 8265, "s": 8242, "text": "towardsdatascience.com" }, { "code": null, "e": 8288, "s": 8265, "text": "towardsdatascience.com" }, { "code": null, "e": 8341, "s": 8288, "text": "[1] Abstractive Text Summarization, Papers With Code" }, { "code": null, "e": 8414, "s": 8341, "text": "[2] 20 Applications of Automatic Summarization in the Enterprise, Fraise" }, { "code": null, "e": 8451, "s": 8414, "text": "[3] Transformers Github, Huggingface" }, { "code": null, "e": 8495, "s": 8451, "text": "[4] Transformers Documentation, Huggingface" }, { "code": null, "e": 8546, "s": 8495, "text": "[5] Pytorch Official Website, Facebook AI Research" }, { "code": null, "e": 8727, "s": 8546, "text": "[6] Lewis, Mike, et al. “Bart: Denoising sequence-to-sequence pre-training for natural language generation, translation, and comprehension.” arXiv preprint arXiv:1910.13461 (2019)." }, { "code": null, "e": 8878, "s": 8727, "text": "[7] Raffel, Colin, et al. “Exploring the limits of transfer learning with a unified text-to-text transformer.” arXiv preprint arXiv:1910.10683 (2019)." }, { "code": null, "e": 8910, "s": 8878, "text": "[8] Tensorflow Datasets, Google" } ]
Query for multiple parameters in MongoDB?
To query for multiple parameters in MongoDB, you can use the dot(.) notation. Let us first create a collection with documents − > db.multipleParametersDemo.insertOne( ... { ... "CustomerName" : "Larry", ... "CustomerDetails" : [ ... { ... "CustomerCountryName" : "US", ... "CustomerBankName" : "HDFC", ... "CustomerBalance" : 17363, ... } ... ], ... "Purchase" : 1456, ... ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5cd10f9ce3526dbddbbfb60a") } Following is the query to display all documents from a collection with the help of find() method − > db.multipleParametersDemo.find().pretty(); This will produce the following output − { "_id" : ObjectId("5cd10f9ce3526dbddbbfb60a"), "CustomerName" : "Larry", "CustomerDetails" : [ { "CustomerCountryName" : "US", "CustomerBankName" : "HDFC", "CustomerBalance" : 17363 } ], "Purchase" : 1456 } Following is how you can query for multiple parameters in MongoDB − > db.multipleParametersDemo.find({CustomerName: 'Larry', 'CustomerDetails.CustomerCountryName': 'US'}).count(); This will produce the following output − 1
[ { "code": null, "e": 1190, "s": 1062, "text": "To query for multiple parameters in MongoDB, you can use the dot(.) notation. Let us first create a collection with documents −" }, { "code": null, "e": 1617, "s": 1190, "text": "> db.multipleParametersDemo.insertOne(\n... {\n... \"CustomerName\" : \"Larry\",\n... \"CustomerDetails\" : [\n... {\n... \"CustomerCountryName\" : \"US\",\n... \"CustomerBankName\" : \"HDFC\",\n... \"CustomerBalance\" : 17363,\n... }\n... ],\n... \"Purchase\" : 1456,\n...\n... }\n... );\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cd10f9ce3526dbddbbfb60a\")\n}" }, { "code": null, "e": 1716, "s": 1617, "text": "Following is the query to display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1761, "s": 1716, "text": "> db.multipleParametersDemo.find().pretty();" }, { "code": null, "e": 1802, "s": 1761, "text": "This will produce the following output −" }, { "code": null, "e": 2064, "s": 1802, "text": "{\n \"_id\" : ObjectId(\"5cd10f9ce3526dbddbbfb60a\"),\n \"CustomerName\" : \"Larry\",\n \"CustomerDetails\" : [\n {\n \"CustomerCountryName\" : \"US\",\n \"CustomerBankName\" : \"HDFC\",\n \"CustomerBalance\" : 17363\n }\n ],\n \"Purchase\" : 1456\n}" }, { "code": null, "e": 2132, "s": 2064, "text": "Following is how you can query for multiple parameters in MongoDB −" }, { "code": null, "e": 2244, "s": 2132, "text": "> db.multipleParametersDemo.find({CustomerName: 'Larry', 'CustomerDetails.CustomerCountryName': 'US'}).count();" }, { "code": null, "e": 2285, "s": 2244, "text": "This will produce the following output −" }, { "code": null, "e": 2287, "s": 2285, "text": "1" } ]
Select rows having more than 2 decimal places in MySQL?
To select rows with more than 2 decimal places, use SUBSTR() function from MySQL. Let us first create a table − mysql> create table selectRows2DecimalPlacesDemo -> ( -> Amount varchar(100) -> ); Query OK, 0 rows affected (0.73 sec) Following is the query to insert records in the table using insert command − mysql> insert into selectRows2DecimalPlacesDemo values('234.5678'); Query OK, 1 row affected (0.17 sec) mysql> insert into selectRows2DecimalPlacesDemo values('19.50'); Query OK, 1 row affected (0.19 sec) mysql> insert into selectRows2DecimalPlacesDemo values('23.456'); Query OK, 1 row affected (0.17 sec) mysql> insert into selectRows2DecimalPlacesDemo values('12.123'); Query OK, 1 row affected (0.14 sec) Following is the query to display all records from the table using select statement − mysql> select * from selectRows2DecimalPlacesDemo; This will produce the following output − +----------+ | Amount | +----------+ | 234.5678 | | 19.50 | | 23.456 | | 12.123 | +----------+ 4 rows in set (0.00 sec) Here is the query to select rows with more than two decimal places − mysql> select *from selectRows2DecimalPlacesDemo WHERE LENGTH(SUBSTR(Amount,INSTR(Amount,"."))) >3; This will produce the following output − +----------+ | Amount | +----------+ | 234.5678 | | 23.456 | | 12.123 | +----------+ 3 rows in set (0.00 sec)
[ { "code": null, "e": 1174, "s": 1062, "text": "To select rows with more than 2 decimal places, use SUBSTR() function from MySQL. Let us first create a table −" }, { "code": null, "e": 1303, "s": 1174, "text": "mysql> create table selectRows2DecimalPlacesDemo\n -> (\n -> Amount varchar(100)\n -> );\nQuery OK, 0 rows affected (0.73 sec)" }, { "code": null, "e": 1380, "s": 1303, "text": "Following is the query to insert records in the table using insert command −" }, { "code": null, "e": 1789, "s": 1380, "text": "mysql> insert into selectRows2DecimalPlacesDemo values('234.5678');\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into selectRows2DecimalPlacesDemo values('19.50');\nQuery OK, 1 row affected (0.19 sec)\nmysql> insert into selectRows2DecimalPlacesDemo values('23.456');\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into selectRows2DecimalPlacesDemo values('12.123');\nQuery OK, 1 row affected (0.14 sec)" }, { "code": null, "e": 1875, "s": 1789, "text": "Following is the query to display all records from the table using select statement −" }, { "code": null, "e": 1926, "s": 1875, "text": "mysql> select * from selectRows2DecimalPlacesDemo;" }, { "code": null, "e": 1967, "s": 1926, "text": "This will produce the following output −" }, { "code": null, "e": 2096, "s": 1967, "text": "+----------+\n| Amount |\n+----------+\n| 234.5678 |\n| 19.50 |\n| 23.456 |\n| 12.123 |\n+----------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2165, "s": 2096, "text": "Here is the query to select rows with more than two decimal places −" }, { "code": null, "e": 2265, "s": 2165, "text": "mysql> select *from selectRows2DecimalPlacesDemo WHERE\nLENGTH(SUBSTR(Amount,INSTR(Amount,\".\"))) >3;" }, { "code": null, "e": 2306, "s": 2265, "text": "This will produce the following output −" }, { "code": null, "e": 2422, "s": 2306, "text": "+----------+\n| Amount |\n+----------+\n| 234.5678 |\n| 23.456 |\n| 12.123 |\n+----------+\n3 rows in set (0.00 sec)" } ]
Order statistic tree using fenwick tree (BIT) - GeeksforGeeks
20 Nov, 2020 Given an array of integers with limited range (0 to 1000000). We need to implement an Order statistic tree using fenwick tree. It should support four operations: Insert, Delete, Select and Rank. Here n denotes the size of Fenwick tree and q denotes number of queries. Each query should be one of the following 4 operations. insertElement(x) – Insert element x into Fenwick tree, with O(log n) worst case time complexity deleteElement(x) – Delete element x from fenwick tree, with O(log n) worse case time complexity findKthSmallest(k) – Find the k-th smallest element stored in the tree, with O(log n * log n) worst case time complexity findRank(x) – Find the rank of element x in the tree, i.e. its index in the sorted list of elements of the tree, with O(log n) time complexity Prerequisite: Binary Indexed Tree or Fenwick TreeThe idea is to create a BIT of size with maximum limit. We insert an element in BIT using it as an index. When we insert an element x, we increment values of all ancestors of x by 1. To delete an element, we decrement values of ancestors by 1. We basically call standard function update() of BIT for both insert and delete. To find rank, we simply call standard function sum() of BIT. To find k-th smallest element, we do binary search in BIT. C++ Java // C++ program to find rank of an element// and k-th smallest element.#include <bits/stdc++.h>using namespace std; const int MAX_VAL = 1000001; /* Updates element at index 'i' of BIT. */void update(int i, int add, vector<int>& BIT){ while (i > 0 && i < BIT.size()) { BIT[i] += add; i = i + (i & (-i)); }} /* Returns cumulative sum of all elements of fenwick tree/BIT from start upto and including element at index 'i'. */int sum(int i, vector<int>& BIT){ int ans = 0; while (i > 0) { ans += BIT[i]; i = i - (i & (-i)); } return ans;} // Returns lower bound for k in BIT.int findKthSmallest(int k, vector<int> &BIT){ // Do binary search in BIT[] for given // value k. int l = 0; int h = BIT.size(); while (l < h) { int mid = (l + h) / 2; if (k <= sum(mid, BIT)) h = mid; else l = mid+1; } return l;} // Insert x into BIT. We basically increment// rank of all elements greater than x.void insertElement(int x, vector<int> &BIT){ update(x, 1, BIT);} // Delete x from BIT. We basically decreases// rank of all elements greater than x.void deleteElement(int x, vector<int> &BIT){ update(x, -1, BIT);} // Returns rank of element. We basically// return sum of elements from start to// index x.int findRank(int x, vector<int> &BIT){ return sum(x, BIT);} // Driver codeint main(){ vector<int> BIT(MAX_VAL); insertElement(20, BIT); insertElement(50, BIT); insertElement(30, BIT); insertElement(40, BIT); cout << "2nd Smallest element is " << findKthSmallest(2, BIT) << endl; cout << "Rank of 40 is " << findRank(40, BIT) << endl; deleteElement(40, BIT); cout << "Rank of 50 is " << findRank(50, BIT) << endl; return 0;} // Java program to find rank of an element// and k-th smallest element.import java.util.Arrays; class GFG{ static int MAX_VAL = 1000001; // Updates element at index 'i' of BITstatic void update(int i, int add, Integer[] BIT){ while (i > 0 && i < BIT.length) { BIT[i] += add; i = i + (i & (-i)); }} // Returns cumulative sum of all elements// of fenwick tree/BIT from start upto// and including element at index 'i'.static int sum(int i, Integer[] BIT){ int ans = 0; while (i > 0) { ans += BIT[i]; i = i - (i & (-i)); } return ans;} // Returns lower bound for k in BIT.static int findKthSmallest(int k, Integer[] BIT){ // Do binary search in BIT[] // for given value k. int l = 0; int h = BIT.length; while (l < h) { int mid = (l + h) / 2; if (k <= sum(mid, BIT)) h = mid; else l = mid + 1; } return l;} // Insert x into BIT. We basically// increment rank of all elements// greater than x.static void insertElement(int x, Integer[] BIT){ update(x, 1, BIT);} // Delete x from BIT. We basically// decreases rank of all elements// greater than x.static void deleteElement(int x, Integer[] BIT){ update(x, -1, BIT);} // Returns rank of element. We basically// return sum of elements from start to// index x.static int findRank(int x, Integer[] BIT){ return sum(x, BIT);} // Driver codepublic static void main(String[] args){ Integer[] BIT = new Integer[MAX_VAL]; Arrays.fill(BIT, 0); insertElement(20, BIT); insertElement(50, BIT); insertElement(30, BIT); insertElement(40, BIT); System.out.println("2nd Smallest element is " + findKthSmallest(2, BIT)); System.out.println("Rank of 40 is " + findRank(40, BIT)); deleteElement(40, BIT); System.out.println("Rank of 50 is " + findRank(50, BIT));}} // This code is contributed by sanjeev2552 Output: 2nd Smallest element is 30 Rank of 40 is 3 Rank of 50 is 3 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. kapillamba4 albertoottimo sanjeev2552 BIT Order-Statistics Advanced Data Structure Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Ordered Set and GNU C++ PBDS 2-3 Trees | (Search, Insert and Deletion) Extendible Hashing (Dynamic approach to DBMS) Suffix Array | Set 1 (Introduction) Difference between Backtracking and Branch-N-Bound technique Quad Tree Advantages of Trie Data Structure Implement a Phone Directory String hashing using Polynomial rolling hash function
[ { "code": null, "e": 25733, "s": 25705, "text": "\n20 Nov, 2020" }, { "code": null, "e": 26002, "s": 25733, "text": "Given an array of integers with limited range (0 to 1000000). We need to implement an Order statistic tree using fenwick tree. It should support four operations: Insert, Delete, Select and Rank. Here n denotes the size of Fenwick tree and q denotes number of queries. " }, { "code": null, "e": 26059, "s": 26002, "text": "Each query should be one of the following 4 operations. " }, { "code": null, "e": 26155, "s": 26059, "text": "insertElement(x) – Insert element x into Fenwick tree, with O(log n) worst case time complexity" }, { "code": null, "e": 26251, "s": 26155, "text": "deleteElement(x) – Delete element x from fenwick tree, with O(log n) worse case time complexity" }, { "code": null, "e": 26372, "s": 26251, "text": "findKthSmallest(k) – Find the k-th smallest element stored in the tree, with O(log n * log n) worst case time complexity" }, { "code": null, "e": 26515, "s": 26372, "text": "findRank(x) – Find the rank of element x in the tree, i.e. its index in the sorted list of elements of the tree, with O(log n) time complexity" }, { "code": null, "e": 27008, "s": 26515, "text": "Prerequisite: Binary Indexed Tree or Fenwick TreeThe idea is to create a BIT of size with maximum limit. We insert an element in BIT using it as an index. When we insert an element x, we increment values of all ancestors of x by 1. To delete an element, we decrement values of ancestors by 1. We basically call standard function update() of BIT for both insert and delete. To find rank, we simply call standard function sum() of BIT. To find k-th smallest element, we do binary search in BIT." }, { "code": null, "e": 27012, "s": 27008, "text": "C++" }, { "code": null, "e": 27017, "s": 27012, "text": "Java" }, { "code": "// C++ program to find rank of an element// and k-th smallest element.#include <bits/stdc++.h>using namespace std; const int MAX_VAL = 1000001; /* Updates element at index 'i' of BIT. */void update(int i, int add, vector<int>& BIT){ while (i > 0 && i < BIT.size()) { BIT[i] += add; i = i + (i & (-i)); }} /* Returns cumulative sum of all elements of fenwick tree/BIT from start upto and including element at index 'i'. */int sum(int i, vector<int>& BIT){ int ans = 0; while (i > 0) { ans += BIT[i]; i = i - (i & (-i)); } return ans;} // Returns lower bound for k in BIT.int findKthSmallest(int k, vector<int> &BIT){ // Do binary search in BIT[] for given // value k. int l = 0; int h = BIT.size(); while (l < h) { int mid = (l + h) / 2; if (k <= sum(mid, BIT)) h = mid; else l = mid+1; } return l;} // Insert x into BIT. We basically increment// rank of all elements greater than x.void insertElement(int x, vector<int> &BIT){ update(x, 1, BIT);} // Delete x from BIT. We basically decreases// rank of all elements greater than x.void deleteElement(int x, vector<int> &BIT){ update(x, -1, BIT);} // Returns rank of element. We basically// return sum of elements from start to// index x.int findRank(int x, vector<int> &BIT){ return sum(x, BIT);} // Driver codeint main(){ vector<int> BIT(MAX_VAL); insertElement(20, BIT); insertElement(50, BIT); insertElement(30, BIT); insertElement(40, BIT); cout << \"2nd Smallest element is \" << findKthSmallest(2, BIT) << endl; cout << \"Rank of 40 is \" << findRank(40, BIT) << endl; deleteElement(40, BIT); cout << \"Rank of 50 is \" << findRank(50, BIT) << endl; return 0;}", "e": 28816, "s": 27017, "text": null }, { "code": "// Java program to find rank of an element// and k-th smallest element.import java.util.Arrays; class GFG{ static int MAX_VAL = 1000001; // Updates element at index 'i' of BITstatic void update(int i, int add, Integer[] BIT){ while (i > 0 && i < BIT.length) { BIT[i] += add; i = i + (i & (-i)); }} // Returns cumulative sum of all elements// of fenwick tree/BIT from start upto// and including element at index 'i'.static int sum(int i, Integer[] BIT){ int ans = 0; while (i > 0) { ans += BIT[i]; i = i - (i & (-i)); } return ans;} // Returns lower bound for k in BIT.static int findKthSmallest(int k, Integer[] BIT){ // Do binary search in BIT[] // for given value k. int l = 0; int h = BIT.length; while (l < h) { int mid = (l + h) / 2; if (k <= sum(mid, BIT)) h = mid; else l = mid + 1; } return l;} // Insert x into BIT. We basically// increment rank of all elements// greater than x.static void insertElement(int x, Integer[] BIT){ update(x, 1, BIT);} // Delete x from BIT. We basically// decreases rank of all elements// greater than x.static void deleteElement(int x, Integer[] BIT){ update(x, -1, BIT);} // Returns rank of element. We basically// return sum of elements from start to// index x.static int findRank(int x, Integer[] BIT){ return sum(x, BIT);} // Driver codepublic static void main(String[] args){ Integer[] BIT = new Integer[MAX_VAL]; Arrays.fill(BIT, 0); insertElement(20, BIT); insertElement(50, BIT); insertElement(30, BIT); insertElement(40, BIT); System.out.println(\"2nd Smallest element is \" + findKthSmallest(2, BIT)); System.out.println(\"Rank of 40 is \" + findRank(40, BIT)); deleteElement(40, BIT); System.out.println(\"Rank of 50 is \" + findRank(50, BIT));}} // This code is contributed by sanjeev2552", "e": 30847, "s": 28816, "text": null }, { "code": null, "e": 30856, "s": 30847, "text": "Output: " }, { "code": null, "e": 30917, "s": 30856, "text": "2nd Smallest element is 30\nRank of 40 is 3\nRank of 50 is 3\n\n" }, { "code": null, "e": 31173, "s": 30917, "text": "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": 31185, "s": 31173, "text": "kapillamba4" }, { "code": null, "e": 31199, "s": 31185, "text": "albertoottimo" }, { "code": null, "e": 31211, "s": 31199, "text": "sanjeev2552" }, { "code": null, "e": 31215, "s": 31211, "text": "BIT" }, { "code": null, "e": 31232, "s": 31215, "text": "Order-Statistics" }, { "code": null, "e": 31256, "s": 31232, "text": "Advanced Data Structure" }, { "code": null, "e": 31354, "s": 31256, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31383, "s": 31354, "text": "Ordered Set and GNU C++ PBDS" }, { "code": null, "e": 31425, "s": 31383, "text": "2-3 Trees | (Search, Insert and Deletion)" }, { "code": null, "e": 31471, "s": 31425, "text": "Extendible Hashing (Dynamic approach to DBMS)" }, { "code": null, "e": 31507, "s": 31471, "text": "Suffix Array | Set 1 (Introduction)" }, { "code": null, "e": 31568, "s": 31507, "text": "Difference between Backtracking and Branch-N-Bound technique" }, { "code": null, "e": 31578, "s": 31568, "text": "Quad Tree" }, { "code": null, "e": 31612, "s": 31578, "text": "Advantages of Trie Data Structure" }, { "code": null, "e": 31640, "s": 31612, "text": "Implement a Phone Directory" } ]
Construct an Array of size N in which sum of odd elements is equal to sum of even elements - GeeksforGeeks
17 Nov, 2021 Given an integer N which is always even, the task is to create an array of size N which contains N/2 even numbers and N/2 odd numbers. All the elements of array should be distinct and the sum of even numbers is equal to the sum of odd numbers. If no such array exists then print -1.Examples: Input: N = 8 Output: 2 4 6 8 1 3 5 11 Explanation: The array has 8 distinct elements which have equal sum of odd and even numbers, i.e., (2 + 4 + 6 + 8 = 1 + 3 + 5 + 11).Input: N = 10 Output: -1 Explanation: It is not possible to construct array of size 10. Approach: To solve the problem mentioned above the very first observation is that it is not possible to create an array that has size N which is a multiple of 2 but not multiple of 4. Because, if that happens then the sum of one half which contains odd numbers will always be odd and the sum of another half which contains even numbers will always be even, hence the sum of both halves can’t be the same.Therefore, the array which satisfies the problem statement should always have a size N which is a multiple of 4. The approach is to first construct N/2 even numbers starting from 2, which is the first half of the array. Then create another part of the array starting from 1 and finally calculate the last odd element such that it makes both the halves equal. In order to do so the last element of odd numbers should be (N/2) – 1 + N.Below is the implementation of the above approach: CPP Java Python3 C# Javascript // C++ program to Create an array// of size N consisting of distinct// elements where sum of odd elements// is equal to sum of even elements #include <bits/stdc++.h>using namespace std; // Function to construct the required arrayvoid arrayConstruct(int N){ // To construct first half, // distinct even numbers for (int i = 2; i <= N; i = i + 2) cout << i << " "; // To construct second half, // distinct odd numbers for (int i = 1; i < N - 1; i = i + 2) cout << i << " "; // Calculate the last number of second half // so as to make both the halves equal cout << N - 1 + (N / 2) << endl;} // Function to construct the required arrayvoid createArray(int N){ // check if size is multiple of 4 // then array exist if (N % 4 == 0) // function call to construct array arrayConstruct(N); else cout << -1 << endl;} // Driver codeint main(){ int N = 8; createArray(N); return 0;} // Java program to Create an array// of size N consisting of distinct// elements where sum of odd elements// is equal to sum of even elementsclass GFG{ // Function to construct the required arraystatic void arrayConstruct(int N){ // To confirst half, // distinct even numbers for (int i = 2; i <= N; i = i + 2) System.out.print(i+ " "); // To consecond half, // distinct odd numbers for (int i = 1; i < N - 1; i = i + 2) System.out.print(i+ " "); // Calculate the last number of second half // so as to make both the halves equal System.out.print(N - 1 + (N / 2) +"\n");} // Function to construct the required arraystatic void createArray(int N){ // check if size is multiple of 4 // then array exist if (N % 4 == 0) // function call to conarray arrayConstruct(N); else System.out.print(-1 +"\n");} // Driver codepublic static void main(String[] args){ int N = 8; createArray(N);}} // This code is contributed by Princi Singh # python3 program to Create an array# of size N consisting of distinct# elements where sum of odd elements# is equal to sum of even elements # Function to construct the required arraydef arrayConstruct(N): # To construct first half, # distinct even numbers for i in range(2, N + 1, 2): print(i,end=" ") # To construct second half, # distinct odd numbers for i in range(1, N - 1, 2): print(i, end=" ") # Calculate the last number of second half # so as to make both the halves equal print(N - 1 + (N // 2)) # Function to construct the required arraydef createArray(N): # check if size is multiple of 4 # then array exist if (N % 4 == 0): # function call to construct array arrayConstruct(N) else: cout << -1 << endl # Driver codeif __name__ == '__main__': N = 8 createArray(N) # This code is contributed by mohit kumar 29 // C# program to Create an array// of size N consisting of distinct// elements where sum of odd elements// is equal to sum of even elementsusing System; class GFG{ // Function to construct the required arraystatic void arrayConstruct(int N){ // To confirst half, // distinct even numbers for (int i = 2; i <= N; i = i + 2) Console.Write(i + " "); // To consecond half, // distinct odd numbers for (int i = 1; i < N - 1; i = i + 2) Console.Write(i + " "); // Calculate the last number of second half // so as to make both the halves equal Console.Write(N - 1 + (N / 2) +"\n");} // Function to construct the required arraystatic void createArray(int N){ // check if size is multiple of 4 // then array exist if (N % 4 == 0) // function call to conarray arrayConstruct(N); else Console.Write(-1 +"\n");} // Driver codepublic static void Main(String[] args){ int N = 8; createArray(N);}} // This code is contributed by Rajput-Ji <script>// JavaScript program to Create an array// of size N consisting of distinct// elements where sum of odd elements// is equal to sum of even elements // Function to construct the required arrayfunction arrayConstruct(N){ // To construct first half, // distinct even numbers for (let i = 2; i <= N; i = i + 2) document.write(i + " "); // To construct second half, // distinct odd numbers for (let i = 1; i < N - 1; i = i + 2) document.write(i + " "); // Calculate the last number of second half // so as to make both the halves equal document.write(N - 1 + (N / 2) + "<br>");} // Function to construct the required arrayfunction createArray(N){ // check if size is multiple of 4 // then array exist if (N % 4 == 0) // function call to construct array arrayConstruct(N); else document.write(-1 + "<br>");} // Driver code let N = 8; createArray(N); // This code is contributed by Surbhi Tyagi.</script> 2 4 6 8 1 3 5 11 Time Complexity: O(N) Auxiliary Space: O(1) mohit kumar 29 princi singh Rajput-Ji surbhityagi15 anikakapoor souravmahato348 Algorithms Arrays Competitive Programming Mathematical Pattern Searching Arrays Mathematical Pattern Searching Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SDE SHEET - A Complete Guide for SDE Preparation DSA Sheet by Love Babbar How to Start Learning DSA? Introduction to Algorithms Recursive Practice Problems with Solutions Arrays in Java Arrays in C/C++ Maximum and minimum of an array using minimum number of comparisons Write a program to reverse an array or string Program for array rotation
[ { "code": null, "e": 25639, "s": 25611, "text": "\n17 Nov, 2021" }, { "code": null, "e": 25933, "s": 25639, "text": "Given an integer N which is always even, the task is to create an array of size N which contains N/2 even numbers and N/2 odd numbers. All the elements of array should be distinct and the sum of even numbers is equal to the sum of odd numbers. If no such array exists then print -1.Examples: " }, { "code": null, "e": 26193, "s": 25933, "text": "Input: N = 8 Output: 2 4 6 8 1 3 5 11 Explanation: The array has 8 distinct elements which have equal sum of odd and even numbers, i.e., (2 + 4 + 6 + 8 = 1 + 3 + 5 + 11).Input: N = 10 Output: -1 Explanation: It is not possible to construct array of size 10. " }, { "code": null, "e": 27085, "s": 26195, "text": "Approach: To solve the problem mentioned above the very first observation is that it is not possible to create an array that has size N which is a multiple of 2 but not multiple of 4. Because, if that happens then the sum of one half which contains odd numbers will always be odd and the sum of another half which contains even numbers will always be even, hence the sum of both halves can’t be the same.Therefore, the array which satisfies the problem statement should always have a size N which is a multiple of 4. The approach is to first construct N/2 even numbers starting from 2, which is the first half of the array. Then create another part of the array starting from 1 and finally calculate the last odd element such that it makes both the halves equal. In order to do so the last element of odd numbers should be (N/2) – 1 + N.Below is the implementation of the above approach: " }, { "code": null, "e": 27089, "s": 27085, "text": "CPP" }, { "code": null, "e": 27094, "s": 27089, "text": "Java" }, { "code": null, "e": 27102, "s": 27094, "text": "Python3" }, { "code": null, "e": 27105, "s": 27102, "text": "C#" }, { "code": null, "e": 27116, "s": 27105, "text": "Javascript" }, { "code": "// C++ program to Create an array// of size N consisting of distinct// elements where sum of odd elements// is equal to sum of even elements #include <bits/stdc++.h>using namespace std; // Function to construct the required arrayvoid arrayConstruct(int N){ // To construct first half, // distinct even numbers for (int i = 2; i <= N; i = i + 2) cout << i << \" \"; // To construct second half, // distinct odd numbers for (int i = 1; i < N - 1; i = i + 2) cout << i << \" \"; // Calculate the last number of second half // so as to make both the halves equal cout << N - 1 + (N / 2) << endl;} // Function to construct the required arrayvoid createArray(int N){ // check if size is multiple of 4 // then array exist if (N % 4 == 0) // function call to construct array arrayConstruct(N); else cout << -1 << endl;} // Driver codeint main(){ int N = 8; createArray(N); return 0;}", "e": 28080, "s": 27116, "text": null }, { "code": "// Java program to Create an array// of size N consisting of distinct// elements where sum of odd elements// is equal to sum of even elementsclass GFG{ // Function to construct the required arraystatic void arrayConstruct(int N){ // To confirst half, // distinct even numbers for (int i = 2; i <= N; i = i + 2) System.out.print(i+ \" \"); // To consecond half, // distinct odd numbers for (int i = 1; i < N - 1; i = i + 2) System.out.print(i+ \" \"); // Calculate the last number of second half // so as to make both the halves equal System.out.print(N - 1 + (N / 2) +\"\\n\");} // Function to construct the required arraystatic void createArray(int N){ // check if size is multiple of 4 // then array exist if (N % 4 == 0) // function call to conarray arrayConstruct(N); else System.out.print(-1 +\"\\n\");} // Driver codepublic static void main(String[] args){ int N = 8; createArray(N);}} // This code is contributed by Princi Singh", "e": 29103, "s": 28080, "text": null }, { "code": "# python3 program to Create an array# of size N consisting of distinct# elements where sum of odd elements# is equal to sum of even elements # Function to construct the required arraydef arrayConstruct(N): # To construct first half, # distinct even numbers for i in range(2, N + 1, 2): print(i,end=\" \") # To construct second half, # distinct odd numbers for i in range(1, N - 1, 2): print(i, end=\" \") # Calculate the last number of second half # so as to make both the halves equal print(N - 1 + (N // 2)) # Function to construct the required arraydef createArray(N): # check if size is multiple of 4 # then array exist if (N % 4 == 0): # function call to construct array arrayConstruct(N) else: cout << -1 << endl # Driver codeif __name__ == '__main__': N = 8 createArray(N) # This code is contributed by mohit kumar 29", "e": 30012, "s": 29103, "text": null }, { "code": "// C# program to Create an array// of size N consisting of distinct// elements where sum of odd elements// is equal to sum of even elementsusing System; class GFG{ // Function to construct the required arraystatic void arrayConstruct(int N){ // To confirst half, // distinct even numbers for (int i = 2; i <= N; i = i + 2) Console.Write(i + \" \"); // To consecond half, // distinct odd numbers for (int i = 1; i < N - 1; i = i + 2) Console.Write(i + \" \"); // Calculate the last number of second half // so as to make both the halves equal Console.Write(N - 1 + (N / 2) +\"\\n\");} // Function to construct the required arraystatic void createArray(int N){ // check if size is multiple of 4 // then array exist if (N % 4 == 0) // function call to conarray arrayConstruct(N); else Console.Write(-1 +\"\\n\");} // Driver codepublic static void Main(String[] args){ int N = 8; createArray(N);}} // This code is contributed by Rajput-Ji", "e": 31044, "s": 30012, "text": null }, { "code": "<script>// JavaScript program to Create an array// of size N consisting of distinct// elements where sum of odd elements// is equal to sum of even elements // Function to construct the required arrayfunction arrayConstruct(N){ // To construct first half, // distinct even numbers for (let i = 2; i <= N; i = i + 2) document.write(i + \" \"); // To construct second half, // distinct odd numbers for (let i = 1; i < N - 1; i = i + 2) document.write(i + \" \"); // Calculate the last number of second half // so as to make both the halves equal document.write(N - 1 + (N / 2) + \"<br>\");} // Function to construct the required arrayfunction createArray(N){ // check if size is multiple of 4 // then array exist if (N % 4 == 0) // function call to construct array arrayConstruct(N); else document.write(-1 + \"<br>\");} // Driver code let N = 8; createArray(N); // This code is contributed by Surbhi Tyagi.</script>", "e": 32035, "s": 31044, "text": null }, { "code": null, "e": 32052, "s": 32035, "text": "2 4 6 8 1 3 5 11" }, { "code": null, "e": 32076, "s": 32054, "text": "Time Complexity: O(N)" }, { "code": null, "e": 32098, "s": 32076, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 32113, "s": 32098, "text": "mohit kumar 29" }, { "code": null, "e": 32126, "s": 32113, "text": "princi singh" }, { "code": null, "e": 32136, "s": 32126, "text": "Rajput-Ji" }, { "code": null, "e": 32150, "s": 32136, "text": "surbhityagi15" }, { "code": null, "e": 32162, "s": 32150, "text": "anikakapoor" }, { "code": null, "e": 32178, "s": 32162, "text": "souravmahato348" }, { "code": null, "e": 32189, "s": 32178, "text": "Algorithms" }, { "code": null, "e": 32196, "s": 32189, "text": "Arrays" }, { "code": null, "e": 32220, "s": 32196, "text": "Competitive Programming" }, { "code": null, "e": 32233, "s": 32220, "text": "Mathematical" }, { "code": null, "e": 32251, "s": 32233, "text": "Pattern Searching" }, { "code": null, "e": 32258, "s": 32251, "text": "Arrays" }, { "code": null, "e": 32271, "s": 32258, "text": "Mathematical" }, { "code": null, "e": 32289, "s": 32271, "text": "Pattern Searching" }, { "code": null, "e": 32300, "s": 32289, "text": "Algorithms" }, { "code": null, "e": 32398, "s": 32300, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32447, "s": 32398, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 32472, "s": 32447, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 32499, "s": 32472, "text": "How to Start Learning DSA?" }, { "code": null, "e": 32526, "s": 32499, "text": "Introduction to Algorithms" }, { "code": null, "e": 32569, "s": 32526, "text": "Recursive Practice Problems with Solutions" }, { "code": null, "e": 32584, "s": 32569, "text": "Arrays in Java" }, { "code": null, "e": 32600, "s": 32584, "text": "Arrays in C/C++" }, { "code": null, "e": 32668, "s": 32600, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 32714, "s": 32668, "text": "Write a program to reverse an array or string" } ]
8085 program to find maximum and minimum of 10 numbers - GeeksforGeeks
01 Sep, 2021 Problem – Write an assembly language program in 8085 microprocessor to find maximum and minimum of 10 numbers. Example – Minimum: 01H, Maximum: FFH In CMP instruction: If Accumulator > Register then carry and zero flags are reset If Accumulator = Register then zero flag is set If Accumulator < Register then carry flag is set Assumption – List of numbers from 2050H to 2059H and output at 2060H and 2061H. Algorithm – Maximum number is stored in B register and minimum in C registerLoad counter in D registerLoad starting element in Accumulator, B and C registerCompare Accumulator and B registerIf carry flag is not set then transfer contents of Accumulator to B. Else, compare Accumulator with C register, if carry flag is set transfer contents of Accumulator to CDecrement D registerIf D>0 take next element in Accumulator and go to point 4If D=0, store B and C register in memoryEnd of program Maximum number is stored in B register and minimum in C register Load counter in D register Load starting element in Accumulator, B and C register Compare Accumulator and B register If carry flag is not set then transfer contents of Accumulator to B. Else, compare Accumulator with C register, if carry flag is set transfer contents of Accumulator to C Decrement D register If D>0 take next element in Accumulator and go to point 4 If D=0, store B and C register in memory End of program Program- Explanation – One by one all elements are compared with B and C register.Element is compared with maximum, if it greater than maximum then it is stored in B register. Else, it is compared with minimum and if it is less than minimum then it stored in C register.Loop executes 10 number of times.At the end of 10 iterations, maximum and minimum are stored at 2060H and 2061H respectively. One by one all elements are compared with B and C register. Element is compared with maximum, if it greater than maximum then it is stored in B register. Else, it is compared with minimum and if it is less than minimum then it stored in C register. Loop executes 10 number of times. At the end of 10 iterations, maximum and minimum are stored at 2060H and 2061H respectively. kalrap615 microprocessor system-programming Computer Organization & Architecture microprocessor Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Logical and Physical Address in Operating System Addressing modes in 8085 microprocessor Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput) Architecture of 8085 microprocessor Memory Hierarchy Design and its Characteristics Computer Organization | RISC and CISC 8085 program to add two 8 bit numbers Architecture of 8086 Computer Organization | Booth's Algorithm Pin diagram of 8086 microprocessor
[ { "code": null, "e": 24856, "s": 24828, "text": "\n01 Sep, 2021" }, { "code": null, "e": 24968, "s": 24856, "text": "Problem – Write an assembly language program in 8085 microprocessor to find maximum and minimum of 10 numbers. " }, { "code": null, "e": 24980, "s": 24968, "text": "Example – " }, { "code": null, "e": 25008, "s": 24980, "text": "Minimum: 01H, Maximum: FFH" }, { "code": null, "e": 25188, "s": 25008, "text": "In CMP instruction: If Accumulator > Register then carry and zero flags are reset If Accumulator = Register then zero flag is set If Accumulator < Register then carry flag is set " }, { "code": null, "e": 25269, "s": 25188, "text": "Assumption – List of numbers from 2050H to 2059H and output at 2060H and 2061H. " }, { "code": null, "e": 25283, "s": 25269, "text": "Algorithm – " }, { "code": null, "e": 25763, "s": 25283, "text": "Maximum number is stored in B register and minimum in C registerLoad counter in D registerLoad starting element in Accumulator, B and C registerCompare Accumulator and B registerIf carry flag is not set then transfer contents of Accumulator to B. Else, compare Accumulator with C register, if carry flag is set transfer contents of Accumulator to CDecrement D registerIf D>0 take next element in Accumulator and go to point 4If D=0, store B and C register in memoryEnd of program" }, { "code": null, "e": 25828, "s": 25763, "text": "Maximum number is stored in B register and minimum in C register" }, { "code": null, "e": 25855, "s": 25828, "text": "Load counter in D register" }, { "code": null, "e": 25910, "s": 25855, "text": "Load starting element in Accumulator, B and C register" }, { "code": null, "e": 25945, "s": 25910, "text": "Compare Accumulator and B register" }, { "code": null, "e": 26116, "s": 25945, "text": "If carry flag is not set then transfer contents of Accumulator to B. Else, compare Accumulator with C register, if carry flag is set transfer contents of Accumulator to C" }, { "code": null, "e": 26137, "s": 26116, "text": "Decrement D register" }, { "code": null, "e": 26195, "s": 26137, "text": "If D>0 take next element in Accumulator and go to point 4" }, { "code": null, "e": 26236, "s": 26195, "text": "If D=0, store B and C register in memory" }, { "code": null, "e": 26251, "s": 26236, "text": "End of program" }, { "code": null, "e": 26261, "s": 26251, "text": "Program- " }, { "code": null, "e": 26276, "s": 26261, "text": "Explanation – " }, { "code": null, "e": 26649, "s": 26276, "text": "One by one all elements are compared with B and C register.Element is compared with maximum, if it greater than maximum then it is stored in B register. Else, it is compared with minimum and if it is less than minimum then it stored in C register.Loop executes 10 number of times.At the end of 10 iterations, maximum and minimum are stored at 2060H and 2061H respectively." }, { "code": null, "e": 26709, "s": 26649, "text": "One by one all elements are compared with B and C register." }, { "code": null, "e": 26898, "s": 26709, "text": "Element is compared with maximum, if it greater than maximum then it is stored in B register. Else, it is compared with minimum and if it is less than minimum then it stored in C register." }, { "code": null, "e": 26932, "s": 26898, "text": "Loop executes 10 number of times." }, { "code": null, "e": 27025, "s": 26932, "text": "At the end of 10 iterations, maximum and minimum are stored at 2060H and 2061H respectively." }, { "code": null, "e": 27035, "s": 27025, "text": "kalrap615" }, { "code": null, "e": 27050, "s": 27035, "text": "microprocessor" }, { "code": null, "e": 27069, "s": 27050, "text": "system-programming" }, { "code": null, "e": 27106, "s": 27069, "text": "Computer Organization & Architecture" }, { "code": null, "e": 27121, "s": 27106, "text": "microprocessor" }, { "code": null, "e": 27219, "s": 27121, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27228, "s": 27219, "text": "Comments" }, { "code": null, "e": 27241, "s": 27228, "text": "Old Comments" }, { "code": null, "e": 27290, "s": 27241, "text": "Logical and Physical Address in Operating System" }, { "code": null, "e": 27330, "s": 27290, "text": "Addressing modes in 8085 microprocessor" }, { "code": null, "e": 27425, "s": 27330, "text": "Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)" }, { "code": null, "e": 27461, "s": 27425, "text": "Architecture of 8085 microprocessor" }, { "code": null, "e": 27509, "s": 27461, "text": "Memory Hierarchy Design and its Characteristics" }, { "code": null, "e": 27547, "s": 27509, "text": "Computer Organization | RISC and CISC" }, { "code": null, "e": 27585, "s": 27547, "text": "8085 program to add two 8 bit numbers" }, { "code": null, "e": 27606, "s": 27585, "text": "Architecture of 8086" }, { "code": null, "e": 27648, "s": 27606, "text": "Computer Organization | Booth's Algorithm" } ]
How to create a directly-executable cross-platform GUI app using Python(Tkinter)?
Python is a programming language which can be used to create cross-platform applications that are supported in various operating systems such as Microsoft Windows, Mac OS, and Linux. To create a GUI-based application, we can use the Tkinter library. However, Python provides different modules and extensions which convert a program into an executable application. For Windows executables - PyInstaller, py2exe For Windows executables - PyInstaller, py2exe For Linux executables - Freeze For Linux executables - Freeze For Max executables - py2app For Max executables - py2app For this example, we will first install the PyInstaller module using pip in our Windows operating system. The module can be installed by using the command, pip install pyInstaller Using this module, we will convert our application into an executable file. app.py In this application, we will ask the user to select Particular days from the list. # Import the required libraries from tkinter import * # Create an instance of tkinter frame win = Tk() # Set the size of the tkinter window win.geometry("700x350") # Add a Label Label(win, text="Select a Day from the Menu", font=('Aerial 13')).pack(pady=10) # Create a Variable to store the selection var = StringVar() # Create an OptionMenu Widget and add choices to it option = OptionMenu(win, var, "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday") option.config(bg="gray81", fg="white") option['menu'].config(bg="green3") option.pack(padx=20, pady=30) win.mainloop() Open the command prompt in the directory and write the command for creating an executable file, Open the command prompt in the directory and write the command for creating an executable file, pyinstaller app.py It will create a folder that contains an executable file app.exe. Open the file to run the application. It will create a folder that contains an executable file app.exe. Open the file to run the application.
[ { "code": null, "e": 1245, "s": 1062, "text": "Python is a programming language which can be used to create cross-platform applications that are supported in various operating systems such as Microsoft Windows, Mac OS, and Linux." }, { "code": null, "e": 1426, "s": 1245, "text": "To create a GUI-based application, we can use the Tkinter library. However, Python provides different modules and extensions which convert a program into an executable application." }, { "code": null, "e": 1472, "s": 1426, "text": "For Windows executables - PyInstaller, py2exe" }, { "code": null, "e": 1518, "s": 1472, "text": "For Windows executables - PyInstaller, py2exe" }, { "code": null, "e": 1549, "s": 1518, "text": "For Linux executables - Freeze" }, { "code": null, "e": 1580, "s": 1549, "text": "For Linux executables - Freeze" }, { "code": null, "e": 1609, "s": 1580, "text": "For Max executables - py2app" }, { "code": null, "e": 1638, "s": 1609, "text": "For Max executables - py2app" }, { "code": null, "e": 1794, "s": 1638, "text": "For this example, we will first install the PyInstaller module using pip in our Windows operating system. The module can be installed by using the command," }, { "code": null, "e": 1818, "s": 1794, "text": "pip install pyInstaller" }, { "code": null, "e": 1894, "s": 1818, "text": "Using this module, we will convert our application into an executable file." }, { "code": null, "e": 1901, "s": 1894, "text": "app.py" }, { "code": null, "e": 1984, "s": 1901, "text": "In this application, we will ask the user to select Particular days from the list." }, { "code": null, "e": 2591, "s": 1984, "text": "# Import the required libraries\nfrom tkinter import *\n\n# Create an instance of tkinter frame\nwin = Tk()\n\n# Set the size of the tkinter window\nwin.geometry(\"700x350\")\n\n# Add a Label\nLabel(win, text=\"Select a Day from the Menu\",\n font=('Aerial 13')).pack(pady=10)\n\n# Create a Variable to store the selection\nvar = StringVar()\n\n# Create an OptionMenu Widget and add choices to it\noption = OptionMenu(win, var, \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\")\noption.config(bg=\"gray81\", fg=\"white\")\noption['menu'].config(bg=\"green3\")\noption.pack(padx=20, pady=30)\n\nwin.mainloop()" }, { "code": null, "e": 2687, "s": 2591, "text": "Open the command prompt in the directory and write the command for creating an executable file," }, { "code": null, "e": 2783, "s": 2687, "text": "Open the command prompt in the directory and write the command for creating an executable file," }, { "code": null, "e": 2802, "s": 2783, "text": "pyinstaller app.py" }, { "code": null, "e": 2906, "s": 2802, "text": "It will create a folder that contains an executable file app.exe. Open the file to run the application." }, { "code": null, "e": 3010, "s": 2906, "text": "It will create a folder that contains an executable file app.exe. Open the file to run the application." } ]
C++ Program to Compute Discrete Fourier Transform Using Naive Approach
In discrete Fourier transform (DFT), a finite list is converted of equally spaced samples of a function into the list of coefficients of a finite combination of complex sinusoids. They ordered by their frequencies, that has those same sample values, to convert the sampled function from its original domain (often time or position along a line) to the frequency domain. Begin Take a variable M and initialize it to some integer Declare an array function[M] For i = 0 to M-1 do function[i] = (((a * (double) i) + (b * (double) i)) - c) Done Declare function sine[M] Declare function cosine[M] for i =0 to M-1 do cosine[i] = cos((2 * i * k * PI) / M) sine[i] = sin((2 * i * k * PI) / M) Done Declare DFT_Coeff dft_value[k] for j = 0 to k-1 do for i = 0 to M-1 do dft_value.real += function[i] * cosine[i] dft_value.img += function[i] * sine[i] Done Done Print the value End #include<iostream> #include<math.h> using namespace std; #define PI 3.14159265 class DFT_Coeff { public: double real, img; DFT_Coeff() { real = 0.0; img = 0.0; } }; int main(int argc, char **argv) { int M= 10; cout << "Enter the coefficient of simple linear function:\n"; cout << "ax + by = c\n"; double a, b, c; cin >> a >> b >> c; double function[M]; for (int i = 0; i < M; i++) { function[i] = (((a * (double) i) + (b * (double) i)) - c); //System.out.print( " "+function[i] + " "); } cout << "Enter the max K value: "; int k; cin >> k; double cosine[M]; double sine[M]; for (int i = 0; i < M; i++) { cosine[i] = cos((2 * i * k * PI) / M); sine[i] = sin((2 * i * k * PI) / M); } DFT_Coeff dft_value[k]; cout << "The coefficients are: "; for (int j = 0; j < k; j++) { for (int i = 0; i < M; i++) { dft_value[j].real += function[i] * cosine[i]; dft_value[j].img += function[i] * sine[i]; } cout << "(" << dft_value[j].real << ") - " << "(" << dft_value[j].img <<" i)\n"; } } Enter the coefficient of simple linear function: ax + by = c 4 5 6 Enter the max K value: 10 The coefficients are: (345) - (-1.64772e-05 i) (345) - (-1.64772e-05 i) (345) - (-1.64772e-05 i) (345) - (-1.64772e-05 i) (345) - (-1.64772e-05 i) (345) - (-1.64772e-05 i) (345) - (-1.64772e-05 i) (345) - (-1.64772e-05 i) (345) - (-1.64772e-05 i) (345) - (-1.64772e-05 i)
[ { "code": null, "e": 1432, "s": 1062, "text": "In discrete Fourier transform (DFT), a finite list is converted of equally spaced samples of a function into the list of coefficients of a finite combination of complex sinusoids. They ordered by their frequencies, that has those same sample values, to convert the sampled function from its original domain (often time or position along a line) to the frequency domain." }, { "code": null, "e": 2018, "s": 1432, "text": "Begin\n Take a variable M and initialize it to some integer\n Declare an array function[M]\n For i = 0 to M-1 do\n function[i] = (((a * (double) i) + (b * (double) i)) - c)\n Done\n Declare function sine[M]\n Declare function cosine[M]\n for i =0 to M-1 do\n cosine[i] = cos((2 * i * k * PI) / M)\n sine[i] = sin((2 * i * k * PI) / M)\n Done\n Declare DFT_Coeff dft_value[k]\n for j = 0 to k-1 do\n for i = 0 to M-1 do\n dft_value.real += function[i] * cosine[i]\n dft_value.img += function[i] * sine[i]\n Done\n Done\n Print the value\nEnd" }, { "code": null, "e": 3135, "s": 2018, "text": "#include<iostream>\n#include<math.h>\nusing namespace std;\n#define PI 3.14159265\nclass DFT_Coeff {\n public:\n double real, img;\n DFT_Coeff() {\n real = 0.0;\n img = 0.0;\n }\n};\nint main(int argc, char **argv) {\n int M= 10;\n cout << \"Enter the coefficient of simple linear function:\\n\";\n cout << \"ax + by = c\\n\";\n double a, b, c;\n cin >> a >> b >> c;\n double function[M];\n for (int i = 0; i < M; i++) {\n function[i] = (((a * (double) i) + (b * (double) i)) - c);\n //System.out.print( \" \"+function[i] + \" \");\n }\n cout << \"Enter the max K value: \";\n int k;\n cin >> k;\n double cosine[M];\n double sine[M];\n for (int i = 0; i < M; i++) {\n cosine[i] = cos((2 * i * k * PI) / M);\n sine[i] = sin((2 * i * k * PI) / M);\n }\n DFT_Coeff dft_value[k];\n cout << \"The coefficients are: \";\n for (int j = 0; j < k; j++) {\n for (int i = 0; i < M; i++) {\n dft_value[j].real += function[i] * cosine[i];\n dft_value[j].img += function[i] * sine[i];\n }\n cout << \"(\" << dft_value[j].real << \") - \" << \"(\" << dft_value[j].img <<\" i)\\n\";\n }\n}" }, { "code": null, "e": 3500, "s": 3135, "text": "Enter the coefficient of simple linear function:\nax + by = c\n4 5 6\nEnter the max K value: 10\nThe coefficients are:\n(345) - (-1.64772e-05 i)\n(345) - (-1.64772e-05 i)\n(345) - (-1.64772e-05 i)\n(345) - (-1.64772e-05 i)\n(345) - (-1.64772e-05 i)\n(345) - (-1.64772e-05 i)\n(345) - (-1.64772e-05 i)\n(345) - (-1.64772e-05 i)\n(345) - (-1.64772e-05 i)\n(345) - (-1.64772e-05 i)" } ]
Maximum number by concatenating every element in a rotation of an array - GeeksforGeeks
28 Feb, 2022 Given an array of N elements. The task is to print the maximum number by concatenating every element in each rotation. In every rotation, the first element will take place of the last element in each rotation and vice versa.Examples: Input: a[]: {54, 546, 548, 60} Output: 6054546548 1st Rotation: 5465486054 2nd Rotation: 5486054546 3rd Rotation: 6054546548 4th Rotation: 5454654860Input: a[]: {1, 4, 18, 96} Output: 961418 Approach: On observing carefully, it is found that the number which has the largest left-most digit in all elements will be the first element in the number. Since the concatenation has to be done in terms of rotation of arrays. Concatenate all the numbers from the largest left-most digit index to the end and then concatenate the elements from 0th index to the largest left-most digit index. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ program to print the// Maximum number by concatenating// every element in rotation of array#include <bits/stdc++.h>using namespace std; // Function to print the largest numbervoid printLargest(int a[], int n){ // store the index of largest // left most digit of elements int max = -1; int ind = -1; // Iterate for all numbers for (int i = 0; i < n; i++) { int num = a[i]; // check for the last digit while (num) { int r = num % 10; num = num / 10; if (num == 0) { // check for the largest left most digit if (max < r) { max = r; ind = i; } } } } // print the largest number // print the rotation of array for (int i = ind; i < n; i++) cout << a[i]; // print the rotation of array for (int i = 0; i < ind; i++) cout << a[i];} // Driver Codeint main(){ int a[] = { 54, 546, 548, 60 }; int n = sizeof(a) / sizeof(a[0]); printLargest(a, n); return 0;} // Java program to print the// Maximum number by concatenating// every element in rotation of arrayimport java.util.*;import java.lang.*; public class GFG { // Function to print the largest number static void printLargest(int a[], int n) { // store the index of largest // left most digit of elements int max = -1; int ind = -1; // Iterate for all numbers for (int i = 0; i < n; i++) { int num = a[i]; // check for the last digit while (num > 0) { int r = num % 10; num = num / 10; if (num == 0) { // check for the largest left most digit if (max < r) { max = r; ind = i; } } } } // print the largest number // print the rotation of array for (int i = ind; i < n; i++) System.out.print(a[i]); // print the rotation of array for (int i = 0; i < ind; i++) System.out.print(a[i]); } // Driver Code public static void main(String args[]) { int a[] = { 54, 546, 548, 60 }; int n = a.length; printLargest(a, n); }} # Python program to print the# Maximum number by concatenating# every element in rotation of array # Function to print the largest numberdef printLargest(a, n): # store the index of largest # left most digit of elements max =-1 ind =-1 # Iterate for all numbers for i in range(0, n): num = a[i] # check for the last digit while(num): r = num % 10; num = num / 10; if(num == 0): # check for the largest left most digit if(max<r): max = r ind = i; # print the largest number # print the rotation of array for i in range(ind, n): print(a[i], end =''), # print the rotation of array for i in range(0, ind) : print(a[i], end ='') # Driver Codeif __name__ == "__main__": a = [54, 546, 548, 60] n = len(a) printLargest(a, n) # This code is contributed by Shivi_Aggarwal // C# program to print the// Maximum number by concatenating// every element in rotation of arrayusing System; class GFG { // Function to print the largest number static void printLargest(int[] a, int n) { // store the index of largest // left most digit of elements int max = -1; int ind = -1; // Iterate for all numbers for (int i = 0; i < n; i++) { int num = a[i]; // check for the last digit while (num > 0) { int r = num % 10; num = num / 10; if (num == 0) { // check for the largest left most digit if (max < r) { max = r; ind = i; } } } } // print the largest number // print the rotation of array for (int i = ind; i < n; i++) Console.Write(a[i]); // print the rotation of array for (int i = 0; i < ind; i++) Console.Write(a[i]); } // Driver Code public static void Main() { int[] a = { 54, 546, 548, 60 }; int n = 4; printLargest(a, n); }} // This code is contributed by mohit kumar 29 <?php// PHP program to print// the Maximum number by// concatenating every// element in rotation of array // Function to print// the largest numberfunction printLargest($a, $n){ // store the index of largest // left most digit of elements $max = -1; $ind = -1; // Iterate for // all numbers for($i = 0 ; $i < $n; $i++) { $num = $a[$i]; // check for the // the last digit while($num) { $r = $num % 10; $num = (int)$num / 10; if($num == 0) { // check for the largest // left most digit if($max < $r) { $max = $r; $ind = $i; } } } } // print the largest number // print the // rotation of array for($i = $ind; $i < $n; $i++) echo $a[$i]; // print the // rotation of array for($i = 0; $i < $ind; $i++) echo $a[$i];} // Driver Code$a = array (54, 546, 548, 60);$n = sizeof($a);printLargest($a, $n); // This code is contributed by m_kit?> <script> // Javascript program to print the// Maximum number by concatenating// every element in rotation of array // Function to print the largest number function printLargest(a, n) { // store the index of largest // left most digit of elements let max = -1; let ind = -1; // Iterate for all numbers for (let i = 0; i < n; i++) { let num = a[i]; // check for the last digit while (num > 0) { let r = num % 10; num = Math.floor(num / 10); if (num == 0) { // check for the largest // left most digit if (max < r) { max = r; ind = i; } } } } // print the largest number // print the rotation of array for (let i = ind; i < n; i++) document.write(a[i]); // print the rotation of array for (let i = 0; i < ind; i++) document.write(a[i]); } // driver code let a = [ 54, 546, 548, 60 ]; let n = a.length; printLargest(a, n); </script> 6054546548 Time Complexity: O(n * log10(num)), where n is size of the array and num is the number of digits of maximum element of the array. Auxiliary Space: O(1) jit_t Nishant Tanwar Shivi_Aggarwal mohit kumar 29 AyushKumar34 Akanksha_Rai chinmoy1997pal samim2000 arorakashish0911 Arrays large-numbers Greedy Arrays Greedy Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Split the given array into K sub-arrays such that maximum sum of all sub arrays is minimum Program for First Fit algorithm in Memory Management Optimal Page Replacement Algorithm Program for Best Fit algorithm in Memory Management Bin Packing Problem (Minimize number of used Bins) Program for Worst Fit algorithm in Memory Management Max Flow Problem Introduction Optimal File Merge Patterns Huffman Decoding Maximum items that can be bought from the cost Array based on given conditions
[ { "code": null, "e": 24927, "s": 24899, "text": "\n28 Feb, 2022" }, { "code": null, "e": 25163, "s": 24927, "text": "Given an array of N elements. The task is to print the maximum number by concatenating every element in each rotation. In every rotation, the first element will take place of the last element in each rotation and vice versa.Examples: " }, { "code": null, "e": 25354, "s": 25163, "text": "Input: a[]: {54, 546, 548, 60} Output: 6054546548 1st Rotation: 5465486054 2nd Rotation: 5486054546 3rd Rotation: 6054546548 4th Rotation: 5454654860Input: a[]: {1, 4, 18, 96} Output: 961418" }, { "code": null, "e": 25802, "s": 25356, "text": "Approach: On observing carefully, it is found that the number which has the largest left-most digit in all elements will be the first element in the number. Since the concatenation has to be done in terms of rotation of arrays. Concatenate all the numbers from the largest left-most digit index to the end and then concatenate the elements from 0th index to the largest left-most digit index. Below is the implementation of the above approach: " }, { "code": null, "e": 25806, "s": 25802, "text": "C++" }, { "code": null, "e": 25811, "s": 25806, "text": "Java" }, { "code": null, "e": 25819, "s": 25811, "text": "Python3" }, { "code": null, "e": 25822, "s": 25819, "text": "C#" }, { "code": null, "e": 25826, "s": 25822, "text": "PHP" }, { "code": null, "e": 25837, "s": 25826, "text": "Javascript" }, { "code": "// C++ program to print the// Maximum number by concatenating// every element in rotation of array#include <bits/stdc++.h>using namespace std; // Function to print the largest numbervoid printLargest(int a[], int n){ // store the index of largest // left most digit of elements int max = -1; int ind = -1; // Iterate for all numbers for (int i = 0; i < n; i++) { int num = a[i]; // check for the last digit while (num) { int r = num % 10; num = num / 10; if (num == 0) { // check for the largest left most digit if (max < r) { max = r; ind = i; } } } } // print the largest number // print the rotation of array for (int i = ind; i < n; i++) cout << a[i]; // print the rotation of array for (int i = 0; i < ind; i++) cout << a[i];} // Driver Codeint main(){ int a[] = { 54, 546, 548, 60 }; int n = sizeof(a) / sizeof(a[0]); printLargest(a, n); return 0;}", "e": 26916, "s": 25837, "text": null }, { "code": "// Java program to print the// Maximum number by concatenating// every element in rotation of arrayimport java.util.*;import java.lang.*; public class GFG { // Function to print the largest number static void printLargest(int a[], int n) { // store the index of largest // left most digit of elements int max = -1; int ind = -1; // Iterate for all numbers for (int i = 0; i < n; i++) { int num = a[i]; // check for the last digit while (num > 0) { int r = num % 10; num = num / 10; if (num == 0) { // check for the largest left most digit if (max < r) { max = r; ind = i; } } } } // print the largest number // print the rotation of array for (int i = ind; i < n; i++) System.out.print(a[i]); // print the rotation of array for (int i = 0; i < ind; i++) System.out.print(a[i]); } // Driver Code public static void main(String args[]) { int a[] = { 54, 546, 548, 60 }; int n = a.length; printLargest(a, n); }}", "e": 28188, "s": 26916, "text": null }, { "code": "# Python program to print the# Maximum number by concatenating# every element in rotation of array # Function to print the largest numberdef printLargest(a, n): # store the index of largest # left most digit of elements max =-1 ind =-1 # Iterate for all numbers for i in range(0, n): num = a[i] # check for the last digit while(num): r = num % 10; num = num / 10; if(num == 0): # check for the largest left most digit if(max<r): max = r ind = i; # print the largest number # print the rotation of array for i in range(ind, n): print(a[i], end =''), # print the rotation of array for i in range(0, ind) : print(a[i], end ='') # Driver Codeif __name__ == \"__main__\": a = [54, 546, 548, 60] n = len(a) printLargest(a, n) # This code is contributed by Shivi_Aggarwal", "e": 29223, "s": 28188, "text": null }, { "code": "// C# program to print the// Maximum number by concatenating// every element in rotation of arrayusing System; class GFG { // Function to print the largest number static void printLargest(int[] a, int n) { // store the index of largest // left most digit of elements int max = -1; int ind = -1; // Iterate for all numbers for (int i = 0; i < n; i++) { int num = a[i]; // check for the last digit while (num > 0) { int r = num % 10; num = num / 10; if (num == 0) { // check for the largest left most digit if (max < r) { max = r; ind = i; } } } } // print the largest number // print the rotation of array for (int i = ind; i < n; i++) Console.Write(a[i]); // print the rotation of array for (int i = 0; i < ind; i++) Console.Write(a[i]); } // Driver Code public static void Main() { int[] a = { 54, 546, 548, 60 }; int n = 4; printLargest(a, n); }} // This code is contributed by mohit kumar 29", "e": 30482, "s": 29223, "text": null }, { "code": "<?php// PHP program to print// the Maximum number by// concatenating every// element in rotation of array // Function to print// the largest numberfunction printLargest($a, $n){ // store the index of largest // left most digit of elements $max = -1; $ind = -1; // Iterate for // all numbers for($i = 0 ; $i < $n; $i++) { $num = $a[$i]; // check for the // the last digit while($num) { $r = $num % 10; $num = (int)$num / 10; if($num == 0) { // check for the largest // left most digit if($max < $r) { $max = $r; $ind = $i; } } } } // print the largest number // print the // rotation of array for($i = $ind; $i < $n; $i++) echo $a[$i]; // print the // rotation of array for($i = 0; $i < $ind; $i++) echo $a[$i];} // Driver Code$a = array (54, 546, 548, 60);$n = sizeof($a);printLargest($a, $n); // This code is contributed by m_kit?>", "e": 31637, "s": 30482, "text": null }, { "code": "<script> // Javascript program to print the// Maximum number by concatenating// every element in rotation of array // Function to print the largest number function printLargest(a, n) { // store the index of largest // left most digit of elements let max = -1; let ind = -1; // Iterate for all numbers for (let i = 0; i < n; i++) { let num = a[i]; // check for the last digit while (num > 0) { let r = num % 10; num = Math.floor(num / 10); if (num == 0) { // check for the largest // left most digit if (max < r) { max = r; ind = i; } } } } // print the largest number // print the rotation of array for (let i = ind; i < n; i++) document.write(a[i]); // print the rotation of array for (let i = 0; i < ind; i++) document.write(a[i]); } // driver code let a = [ 54, 546, 548, 60 ]; let n = a.length; printLargest(a, n); </script>", "e": 32844, "s": 31637, "text": null }, { "code": null, "e": 32855, "s": 32844, "text": "6054546548" }, { "code": null, "e": 32987, "s": 32857, "text": "Time Complexity: O(n * log10(num)), where n is size of the array and num is the number of digits of maximum element of the array." }, { "code": null, "e": 33009, "s": 32987, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 33015, "s": 33009, "text": "jit_t" }, { "code": null, "e": 33030, "s": 33015, "text": "Nishant Tanwar" }, { "code": null, "e": 33045, "s": 33030, "text": "Shivi_Aggarwal" }, { "code": null, "e": 33060, "s": 33045, "text": "mohit kumar 29" }, { "code": null, "e": 33073, "s": 33060, "text": "AyushKumar34" }, { "code": null, "e": 33086, "s": 33073, "text": "Akanksha_Rai" }, { "code": null, "e": 33101, "s": 33086, "text": "chinmoy1997pal" }, { "code": null, "e": 33111, "s": 33101, "text": "samim2000" }, { "code": null, "e": 33128, "s": 33111, "text": "arorakashish0911" }, { "code": null, "e": 33135, "s": 33128, "text": "Arrays" }, { "code": null, "e": 33149, "s": 33135, "text": "large-numbers" }, { "code": null, "e": 33156, "s": 33149, "text": "Greedy" }, { "code": null, "e": 33163, "s": 33156, "text": "Arrays" }, { "code": null, "e": 33170, "s": 33163, "text": "Greedy" }, { "code": null, "e": 33268, "s": 33170, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33277, "s": 33268, "text": "Comments" }, { "code": null, "e": 33290, "s": 33277, "text": "Old Comments" }, { "code": null, "e": 33381, "s": 33290, "text": "Split the given array into K sub-arrays such that maximum sum of all sub arrays is minimum" }, { "code": null, "e": 33434, "s": 33381, "text": "Program for First Fit algorithm in Memory Management" }, { "code": null, "e": 33469, "s": 33434, "text": "Optimal Page Replacement Algorithm" }, { "code": null, "e": 33521, "s": 33469, "text": "Program for Best Fit algorithm in Memory Management" }, { "code": null, "e": 33572, "s": 33521, "text": "Bin Packing Problem (Minimize number of used Bins)" }, { "code": null, "e": 33625, "s": 33572, "text": "Program for Worst Fit algorithm in Memory Management" }, { "code": null, "e": 33655, "s": 33625, "text": "Max Flow Problem Introduction" }, { "code": null, "e": 33683, "s": 33655, "text": "Optimal File Merge Patterns" }, { "code": null, "e": 33700, "s": 33683, "text": "Huffman Decoding" } ]
Implement Atoi | Practice | GeeksforGeeks
Your task is to implement the function atoi. The function takes a string(str) as argument and converts it to an integer and returns it. Note: You are not allowed to use inbuilt function. Example 1: Input: str = 123 Output: 123 Example 2: Input: str = 21a Output: -1 Explanation: Output is -1 as all characters are not digit only. Your Task: Complete the function atoi() which takes a string as input parameter and returns integer value of it. if the input string is not a numerical string then returns -1. Note: Numerical strings are the string where either every character is in between 0-9 or where the first character is '-' and the rest all characters are in between 0-9. Expected Time Complexity: O(|S|), |S| = length of string str. Expected Auxiliary Space: O(1) Constraints: 1 ≤ length of S ≤ 10 Note:The Input/Ouput format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code. +1 kumharashvin2043 days ago //Easy solution c++ if(str.size()==0)return 0; int i =0; int sign = +1; long ans = 0; if(str[0]=='-'){ sign = -1; i++; } while(i<str.length()){ if(!isdigit(str[i]))return -1; ans = ans *10+ str[i]-'0'; i++; } return ans*sign; 0 wolfofsv4 days ago Simple Solution int atoi(string str) { //Your code here int ans = 0, factor = 1; if(str[0] == '-'){ factor = -1; str[0] = '0'; } for(auto c : str){ if(c > '9' || c < '0'){ return -1; } ans *= 10; ans += c - '0'; } return factor*ans; } }; 0 rohankundu8595 days ago //C++ Solution int atoi(string str) { //Your code here int result=0; int i=0; bool flag=false; if(str[0]=='-') { flag=true; i=1; } while(i<str.size()) { if(str[i]>='0' && str[i]<='9') { result=result*10+(str[i]-'0'); i++; } else { return -1; } } if(flag) { return -result; } else { return result; } } 0 ashayvsant6 days ago class Solution { int atoi(String str) { // Your code here int result = 0; int n = str.length(); int place = 0; boolean isNegative = false; int end = 0; if(str.charAt(0) == '-') { isNegative=true; end = 1; } for(int i=n-1; i>=end; i--) { //System.out.println((int)Math.pow(10,place)*(int)(str.charAt(i)-'0')); if(str.charAt(i)-'0' < 0 || str.charAt(i)-'0' > 9) return -1; result = result + (int)Math.pow(10,place)*(int)(str.charAt(i)-'0'); place++; } return isNegative ? -1*result : result; } } Java Solution 0 rohitasrani20181 week ago JAVA SOLUTION int atoi(String str) {// Your code herechar ch='\0';if(str.charAt(0)=='-' ){ ch=str.charAt(0); str=str.substring(1,str.length() ); }for(int i=0 ;i<str.length();i++ ){ if(!(str.charAt(i)>='0' && str.charAt(i)<='9') ) { return -1; }}return ch=='\0'? Integer.parseInt(str) : -Integer.parseInt(str) ; } 0 visitant1 week ago int atoi(string str) { //Your code here 52->0 61->9 int ret = 0; int neg = 0; for(int i=0; i< str.length(); i++) { char val = str[i]; if(val == '-') { if(neg == 1) { neg=0; ret = -1; break; } neg = 1; } else if(val > '9' || val < '0') { neg = 0; ret = -1; break; } else { // printf("val is %d, %d", val, val-'0'); ret = ret*10 + ((int)(val-'0')); } } if (neg==1) { return ret*-1; } return ret; } 0 jay12501 week ago #easy python code def atoi(self,string): # Code here try: return int(string) except: return -1 0 abhishekvicky123452 weeks ago class Solution{ int atoi(String str) { int value=0; try { value = Integer.parseInt(str);} catch (NumberFormatException e) { return -1;} return value ; }} 0 akashmarkad22102 weeks ago JAVA Solution int atoi(String str) {// Your code here try { int ans = Integer.parseInt(str); return ans; } catch(Exception e) { return -1; } } 0 suprithsk20012 weeks ago //easy python code val=len(string) count=0 for i in range (val): if(string[i].isdigit()or string[i]=='-'): count=count+1 if(count==val and string.count("-")<=1): return int(string) else: return -1 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": 375, "s": 238, "text": "Your task is to implement the function atoi. The function takes a string(str) as argument and converts it to an integer and returns it." }, { "code": null, "e": 426, "s": 375, "text": "Note: You are not allowed to use inbuilt function." }, { "code": null, "e": 437, "s": 426, "text": "Example 1:" }, { "code": null, "e": 467, "s": 437, "text": "Input:\nstr = 123\nOutput: 123\n" }, { "code": null, "e": 478, "s": 467, "text": "Example 2:" }, { "code": null, "e": 571, "s": 478, "text": "Input:\nstr = 21a\nOutput: -1\nExplanation: Output is -1 as all\ncharacters are not digit only.\n" }, { "code": null, "e": 917, "s": 571, "text": "Your Task:\nComplete the function atoi() which takes a string as input parameter and returns integer value of it. if the input string is not a numerical string then returns -1.\nNote: Numerical strings are the string where either every character is in between 0-9 or where the first character is '-' and the rest all characters are in between 0-9." }, { "code": null, "e": 1356, "s": 917, "text": "Expected Time Complexity: O(|S|), |S| = length of string str.\nExpected Auxiliary Space: O(1)\n\nConstraints:\n1 ≤ length of S ≤ 10\n\n\nNote:The Input/Ouput format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code." }, { "code": null, "e": 1359, "s": 1356, "text": "+1" }, { "code": null, "e": 1385, "s": 1359, "text": "kumharashvin2043 days ago" }, { "code": null, "e": 1405, "s": 1385, "text": "//Easy solution c++" }, { "code": null, "e": 1723, "s": 1405, "text": "if(str.size()==0)return 0; int i =0; int sign = +1; long ans = 0; if(str[0]=='-'){ sign = -1; i++; } while(i<str.length()){ if(!isdigit(str[i]))return -1; ans = ans *10+ str[i]-'0'; i++; } return ans*sign;" }, { "code": null, "e": 1727, "s": 1725, "text": "0" }, { "code": null, "e": 1746, "s": 1727, "text": "wolfofsv4 days ago" }, { "code": null, "e": 1762, "s": 1746, "text": "Simple Solution" }, { "code": null, "e": 2138, "s": 1762, "text": " int atoi(string str) {\n //Your code here\n int ans = 0, factor = 1;\n if(str[0] == '-'){\n factor = -1;\n str[0] = '0';\n }\n\n for(auto c : str){\n if(c > '9' || c < '0'){\n return -1;\n }\n ans *= 10;\n ans += c - '0';\n }\n return factor*ans;\n }\n};\n" }, { "code": null, "e": 2140, "s": 2138, "text": "0" }, { "code": null, "e": 2164, "s": 2140, "text": "rohankundu8595 days ago" }, { "code": null, "e": 2179, "s": 2164, "text": "//C++ Solution" }, { "code": null, "e": 2742, "s": 2181, "text": " int atoi(string str) { //Your code here int result=0; int i=0; bool flag=false; if(str[0]=='-') { flag=true; i=1; } while(i<str.size()) { if(str[i]>='0' && str[i]<='9') { result=result*10+(str[i]-'0'); i++; } else { return -1; } } if(flag) { return -result; } else { return result; } }" }, { "code": null, "e": 2744, "s": 2742, "text": "0" }, { "code": null, "e": 2765, "s": 2744, "text": "ashayvsant6 days ago" }, { "code": null, "e": 3400, "s": 2765, "text": "class Solution\n{\n int atoi(String str) {\n \t// Your code here\n\t int result = 0;\n\t int n = str.length();\n\t int place = 0;\n\t boolean isNegative = false;\n\t int end = 0;\n\t \n\t if(str.charAt(0) == '-') {\n\t isNegative=true;\n\t end = 1;\n\t }\n\t \n\t for(int i=n-1; i>=end; i--) {\n\t //System.out.println((int)Math.pow(10,place)*(int)(str.charAt(i)-'0'));\n\t if(str.charAt(i)-'0' < 0 || str.charAt(i)-'0' > 9) return -1;\n\t result = result + (int)Math.pow(10,place)*(int)(str.charAt(i)-'0'); \n\t place++;\n\t }\n\t \n\t return isNegative ? -1*result : result;\n }\n}" }, { "code": null, "e": 3414, "s": 3400, "text": "Java Solution" }, { "code": null, "e": 3416, "s": 3414, "text": "0" }, { "code": null, "e": 3442, "s": 3416, "text": "rohitasrani20181 week ago" }, { "code": null, "e": 3456, "s": 3442, "text": "JAVA SOLUTION" }, { "code": null, "e": 3786, "s": 3460, "text": "int atoi(String str) {// Your code herechar ch='\\0';if(str.charAt(0)=='-' ){ ch=str.charAt(0); str=str.substring(1,str.length() ); }for(int i=0 ;i<str.length();i++ ){ if(!(str.charAt(i)>='0' && str.charAt(i)<='9') ) { return -1; }}return ch=='\\0'? Integer.parseInt(str) : -Integer.parseInt(str) ; }" }, { "code": null, "e": 3788, "s": 3786, "text": "0" }, { "code": null, "e": 3807, "s": 3788, "text": "visitant1 week ago" }, { "code": null, "e": 4624, "s": 3807, "text": "int atoi(string str) {\n //Your code here 52->0 61->9\n int ret = 0;\n int neg = 0;\n for(int i=0; i< str.length(); i++)\n {\n char val = str[i];\n if(val == '-')\n {\n if(neg == 1)\n {\n neg=0;\n ret = -1;\n break;\n }\n neg = 1;\n }\n else if(val > '9' || val < '0')\n {\n neg = 0;\n ret = -1; \n break;\n }\n else\n {\n // printf(\"val is %d, %d\", val, val-'0');\n ret = ret*10 + ((int)(val-'0'));\n }\n }\n if (neg==1)\n {\n return ret*-1;\n }\n return ret;\n }" }, { "code": null, "e": 4626, "s": 4624, "text": "0" }, { "code": null, "e": 4644, "s": 4626, "text": "jay12501 week ago" }, { "code": null, "e": 4662, "s": 4644, "text": "#easy python code" }, { "code": null, "e": 4777, "s": 4662, "text": "def atoi(self,string): # Code here try: return int(string) except: return -1" }, { "code": null, "e": 4779, "s": 4777, "text": "0" }, { "code": null, "e": 4809, "s": 4779, "text": "abhishekvicky123452 weeks ago" }, { "code": null, "e": 4985, "s": 4809, "text": "class Solution{ int atoi(String str) { int value=0; try { value = Integer.parseInt(str);} catch (NumberFormatException e) { return -1;} return value ; }} " }, { "code": null, "e": 4987, "s": 4985, "text": "0" }, { "code": null, "e": 5014, "s": 4987, "text": "akashmarkad22102 weeks ago" }, { "code": null, "e": 5028, "s": 5014, "text": "JAVA Solution" }, { "code": null, "e": 5205, "s": 5030, "text": "int atoi(String str) {// Your code here try { int ans = Integer.parseInt(str); return ans; } catch(Exception e) { return -1; } } " }, { "code": null, "e": 5207, "s": 5205, "text": "0" }, { "code": null, "e": 5232, "s": 5207, "text": "suprithsk20012 weeks ago" }, { "code": null, "e": 5251, "s": 5232, "text": "//easy python code" }, { "code": null, "e": 5504, "s": 5251, "text": "val=len(string) count=0 for i in range (val): if(string[i].isdigit()or string[i]=='-'): count=count+1 if(count==val and string.count(\"-\")<=1): return int(string) else: return -1" }, { "code": null, "e": 5650, "s": 5504, "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": 5686, "s": 5650, "text": " Login to access your submissions. " }, { "code": null, "e": 5696, "s": 5686, "text": "\nProblem\n" }, { "code": null, "e": 5706, "s": 5696, "text": "\nContest\n" }, { "code": null, "e": 5769, "s": 5706, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5917, "s": 5769, "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": 6125, "s": 5917, "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": 6231, "s": 6125, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Read Only Properties in Python - GeeksforGeeks
10 Jul, 2020 Prerequisites: Python Classes and Objects A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. To put it in simple words, let us assume a class Student, a student can have many properties such as Name, Course, Student’s ID, etc. Now let us assume we have a Student named Anita pursuing MBA, Anita is an object of class Student. Example: class student: def __init__(self, name, course): self.name = name self.course = course def studentid(self): return "student's identification number is \ {}{}".format(self.name, self.course) student1 = student("Anita", "MBA")print(student1.studentid()) Output: student's identification number is AnitaMBA Now, We want to access student id as a property and not as a method. For this all required is to add @property decorator before the method. Example: class student: def __init__(self, name, course): self.name = name self.course = course @property def studentid(self): return "student's identification number is \ {}{}".format(self.name, self.course) student1 = student("Anita", "MBA")print(student1.studentid) Output: student's identification number is AnitaMBA A Read-Only-Property is a property decorator without a setter. The student id here is a read-only-property since it doesn’t have a setter. In general terms, it means that the value is not changeable. To understand let’s take one more example: Example: class employee: def __init__(self, basesalary, yearsofworking): self.basesalary = basesalary self.yearsofworking = yearsofworking @property def salary(self): self.salary = 50000 amit = employee(20000, 5)amit.salary = 10000print(amit.basesalary, amit.yearsworking, amit.salary) Output: Traceback (most recent call last):File “/home/e029e0b9ccad85905e22dd5a91943897.py”, line 14, in amit.salary = 10000AttributeError: can’t set attribute To fix this one setter is to be added in this code. After doing this, it will no longer be a read-only-property. Example: class employee: def __init__(self, basesalary, yearsofworking): self.basesalary = basesalary self.yearsofworking = yearsofworking self._salary = 0 @property def salary(self): return self._salary @salary.setter def salary(self, salary): self._salary = salary amit = employee(20000, 5)amit.salary = 10000print(amit.basesalary, amit.yearsofworking, amit.salary) Output: 20000 5 10000 python-oop-concepts Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby() Python | Get unique values from a list
[ { "code": null, "e": 25647, "s": 25619, "text": "\n10 Jul, 2020" }, { "code": null, "e": 25689, "s": 25647, "text": "Prerequisites: Python Classes and Objects" }, { "code": null, "e": 26171, "s": 25689, "text": "A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. To put it in simple words, let us assume a class Student, a student can have many properties such as Name, Course, Student’s ID, etc. Now let us assume we have a Student named Anita pursuing MBA, Anita is an object of class Student." }, { "code": null, "e": 26180, "s": 26171, "text": "Example:" }, { "code": "class student: def __init__(self, name, course): self.name = name self.course = course def studentid(self): return \"student's identification number is \\ {}{}\".format(self.name, self.course) student1 = student(\"Anita\", \"MBA\")print(student1.studentid())", "e": 26475, "s": 26180, "text": null }, { "code": null, "e": 26483, "s": 26475, "text": "Output:" }, { "code": null, "e": 26527, "s": 26483, "text": "student's identification number is AnitaMBA" }, { "code": null, "e": 26667, "s": 26527, "text": "Now, We want to access student id as a property and not as a method. For this all required is to add @property decorator before the method." }, { "code": null, "e": 26676, "s": 26667, "text": "Example:" }, { "code": "class student: def __init__(self, name, course): self.name = name self.course = course @property def studentid(self): return \"student's identification number is \\ {}{}\".format(self.name, self.course) student1 = student(\"Anita\", \"MBA\")print(student1.studentid)", "e": 26982, "s": 26676, "text": null }, { "code": null, "e": 26990, "s": 26982, "text": "Output:" }, { "code": null, "e": 27034, "s": 26990, "text": "student's identification number is AnitaMBA" }, { "code": null, "e": 27277, "s": 27034, "text": "A Read-Only-Property is a property decorator without a setter. The student id here is a read-only-property since it doesn’t have a setter. In general terms, it means that the value is not changeable. To understand let’s take one more example:" }, { "code": null, "e": 27286, "s": 27277, "text": "Example:" }, { "code": "class employee: def __init__(self, basesalary, yearsofworking): self.basesalary = basesalary self.yearsofworking = yearsofworking @property def salary(self): self.salary = 50000 amit = employee(20000, 5)amit.salary = 10000print(amit.basesalary, amit.yearsworking, amit.salary)", "e": 27600, "s": 27286, "text": null }, { "code": null, "e": 27608, "s": 27600, "text": "Output:" }, { "code": null, "e": 27759, "s": 27608, "text": "Traceback (most recent call last):File “/home/e029e0b9ccad85905e22dd5a91943897.py”, line 14, in amit.salary = 10000AttributeError: can’t set attribute" }, { "code": null, "e": 27872, "s": 27759, "text": "To fix this one setter is to be added in this code. After doing this, it will no longer be a read-only-property." }, { "code": null, "e": 27881, "s": 27872, "text": "Example:" }, { "code": "class employee: def __init__(self, basesalary, yearsofworking): self.basesalary = basesalary self.yearsofworking = yearsofworking self._salary = 0 @property def salary(self): return self._salary @salary.setter def salary(self, salary): self._salary = salary amit = employee(20000, 5)amit.salary = 10000print(amit.basesalary, amit.yearsofworking, amit.salary)", "e": 28299, "s": 27881, "text": null }, { "code": null, "e": 28307, "s": 28299, "text": "Output:" }, { "code": null, "e": 28321, "s": 28307, "text": "20000 5 10000" }, { "code": null, "e": 28341, "s": 28321, "text": "python-oop-concepts" }, { "code": null, "e": 28348, "s": 28341, "text": "Python" }, { "code": null, "e": 28446, "s": 28348, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28478, "s": 28446, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28520, "s": 28478, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28562, "s": 28520, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28618, "s": 28562, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28645, "s": 28618, "text": "Python Classes and Objects" }, { "code": null, "e": 28676, "s": 28645, "text": "Python | os.path.join() method" }, { "code": null, "e": 28705, "s": 28676, "text": "Create a directory in Python" }, { "code": null, "e": 28727, "s": 28705, "text": "Defaultdict in Python" }, { "code": null, "e": 28763, "s": 28727, "text": "Python | Pandas dataframe.groupby()" } ]
Train a Support Vector Machine to recognize facial features in C++ - GeeksforGeeks
30 Jan, 2019 Let’s see how to train a model of support vector machine, save the trained model and test the model to check the percentage of its prediction accuracy using the OpenCV. Using imagenetscraper and autocrop , we collect data from the web, crop faces and resize them to smaller sizes in bulk. The collected data needs to be organized meaningfully so we can access it programmatically and manually. Use the below folder structure- FFR_dataset/ |-- Age | |-- adult | |-- child | |-- old | |-- teen |-- Emotion | |-- anger | |-- contempt | |-- happy | |-- neutral | |-- sad | |-- surprise |-- Gender |-- female |-- male We use the same directory names in the code to access them to train, save and predict the recognition results. A minimum of 50 images in each folder is required to train the models to get good prediction results. Training more images can improve the results but not recommended as it takes a lot of time to execute that and does not give significant improvements. By making use of the sample provided in the official opencv repo to train the SVM with HOG, train_HOG.cpp, we implement the c++ code to train, save and predict the facial features on an image with multiple faces. There are three feature types- Age, Emotion and Gender. Four age groups, six emotions and two gender types. Hence an n-class classifier is implemented to recognize each feature on a face data. Step #1: For each feature type i.e. (Age, Emotion or Gender) loop through ‘n’ run times. // CTrainTestHOG::Run(int run_times)for (auto ft : m_FeatureList) { DEBUGLW("\tFeature type=[%s]\n", ft.first.c_str()); std::vector<float> predictionAccuracyList; predictionAccuracyList.reserve(run_times); for (int run = 0; run < run_times; ++run) { DEBUGLW("\t\tRun=[%d]\n", run); vector<Mat> trainData, predData; vector<int> trainLabels, predLabels; this->get_ft_dataset(ft.first, trainData, predData, trainLabels, predLabels); // ... train, predict and measure the SVM model. }} Step #2: In each run, iterate through the feature values in the feature type and get the images into a vector or array, i.e. get all the images from folders Gender->Male and Gender->Female. // CTrainTestHOG::get_ft_dataset()std::set<cv::String>& featureValueList = m_FeatureList.find(ft)->second; for (auto fv : featureValueList) { DEBUGLW("\t\t\tFeature value=[%s]\n", fv.c_str()); std::vector<cv::Mat> _trainData; std::vector<cv::Mat> _predData; std::vector<int> _trainLabels; std::vector<int> _predLabels; errCode = this->get_ftfv_dataset(ft, fv, _trainData, _predData, _trainLabels, _predLabels); if (errCode != EXIT_SUCCESS) break; trainData.insert(trainData.end(), _trainData.begin(), _trainData.end()); predData.insert(predData.end(), _predData.begin(), _predData.end()); trainLabels.insert(trainLabels.end(), _trainLabels.begin(), _trainLabels.end()); predLabels.insert(predLabels.end(), _predLabels.begin(), _predLabels.end());} Step #3 to #6: Crop the images in the vector to the face rectangles and update the images vector with the new faces list. Perform any pre-processing tasks such as resizing to smaller size (64, 64) on each image in faces list. Shuffle the pre-processed face images in vector randomly to introduce random input data. Split the dataset into training(80%) and prediction(20%) data. // CTrainTestHOG::get_ftfv_dataset()std::vector<cv::Mat> imgList;this->get_images(folderName, imgList);this->get_cropped_faces(imgList);this->get_preprocessed_faces(imgList); //-- return on empty img list to prevent seg faultif (imgList.empty()) { errCode = EXIT_FAILURE; DEBUGLE("Error img list is empty!\n"); break;}DEBUGLD("\t\t\timgList.size()=[%ld]\n", imgList.size()); std::random_shuffle(imgList.begin(), imgList.end()); // 80% for trainingint trainPart = imgList.size() * 0.8; // 20% for predictingint predPart = imgList.size() - trainPart;DEBUGLD("\t\t\ttrainPart=[%d], predPart=[%d]\n", trainPart, predPart); trainData.reserve(trainPart);predData.reserve(predPart); ft_t::iterator ft_iter = m_FeatureList.find(ft);fv_t::iterator fv_iter = ft_iter->second.find(fv);int label = std::distance(ft_iter->second.begin(), fv_iter);DEBUGLD("\t\t\tlabel=[%d]\n", label); int i = 0;for (; i < trainPart; ++i) { trainData.push_back(imgList.at(i)); trainLabels.push_back(label);}DEBUGLD("\t\t\ti=[%d], trainData.size()=[%ld], trainLabels.size() = [% ld]\n ", i, trainData.size(), trainLabels.size()); for (; i < imgList.size(); ++i) { predData.push_back(imgList.at(i)); predLabels.push_back(label);}DEBUGLD("\t\t\ti=[%d], predData.size()=[%ld], predLabels.size() = [% ld]\n ", i, predData.size(), predLabels.size()); Step #7 : Compute HOG for each image in training data. // CTrainTestHOG::computeHOGs()HOGDescriptor hog;vector<Mat> hogMats;vector<float> descriptors;for (auto img : imgHogList) { hog.winSize = img.size() / 8 * 8; hog.compute(img, descriptors); cv::Mat descriptors_mat(Mat(descriptors).clone()); hogMats.push_back(descriptors_mat);}imgHogList.swap(hogMats); Step #8 : Convert the training data vector to opencv Mat object to train SVM. // CTrainTestHOG::convert_to_ml()for (size_t i = 0; i < train_samples.size(); ++i) { CV_Assert(train_samples[i].cols == 1 || train_samples[i].rows == 1); if (train_samples[i].cols == 1) { cv::transpose(train_samples[i], tmp); tmp.copyTo(trainData.row((int)i)); } else if (train_samples[i].rows == 1) { train_samples[i].copyTo(trainData.row((int)i)); }} Step #9 : Pass the training data Mat object to svm train function along with a vector of labels for the training data. // CTrainTestHOG::Run()trainLabels.resize(ml_train_data.rows);// train svmDEBUGLW("\t\tTraining SVM - begin\n");m_pSVM->train(ml_train_data, ROW_SAMPLE, trainLabels);DEBUGLW("\t\tTraining SVM - end\n"); Step #10: Save the trained model. //-- step 10, CTrainTestHOG::Run()cv::String svmModelFileName = cv::format("%s/cv4_svm_%s_model.xml", getenv(FFR_DATASET_PATH), ft.first.c_str()); m_pSVM->save(svmModelFileName.c_str());DEBUGLW("\t\tSaved SVM model=[%s]\n", svmModelFileName.c_str()); Step #11: Predict the model by computing the HOG for each prediction image, convert the prediction dataset to opencv mat object and call svm predict with a vector of labels to store the result. //-- step 11, CTrainTestHOG::Run()// test the model// compute HOG for each pre-processed faceerrCode = this->computeHOGs(predData);if (errCode != EXIT_SUCCESS) { DEBUGLE("Error in computing HOGs for the feature " "type=[%s]\n", ft.first.c_str()); break;} // convert HOG feature vectors to SVM dataMat ml_pred_data;vector<int> resultLabels;errCode = this->convert_to_ml(predData, ml_pred_data);if (errCode != EXIT_SUCCESS) { DEBUGLE("Error in converting to ml for the " "feature type=[%s]\n", ft.first.c_str()); break;}predLabels.resize(ml_pred_data.rows);// resultLabels.resize(ml_pred_data.rows);// test svmDEBUGLW("\t\tTesting SVM - begin\n");Mat responses_mat;m_pSVM->predict(ml_pred_data, responses_mat);for (size_t i = 0; i < ml_pred_data.rows; ++i) { resultLabels.push_back(responses_mat.at<int>(i));}DEBUGLW("\t\tTesting SVM - end\n"); Step #12 and #13: Calculate the percentage of its accuracy by comparing the expected prediction labels with the predicted labels. // CTrainTestHOG::Run()// check the accuracyfloat accuracy = 0.0f;this->get_prediction_accuracy(predLabels, resultLabels, accuracy);DEBUGLW("\t\tPrediction accuracy=[%lf]\n", accuracy);predictionAccuracyList.push_back(accuracy); //-- step 13, CTrainTestHOG::Run()// check the mean accuracy of 'n' runsfloat sum_of_accuracies = std::accumulate( predictionAccuracyList.begin(), predictionAccuracyList.end(), 0.0);float mean_accuracy = sum_of_accuracies / predictionAccuracyList.size();DEBUGLW("\t\tMean prediction accuracy=[%lf]\n", mean_accuracy); Run the executable with below command line arguments. ./train_hog --test --in= --out= --show Input: Output: Results log for HOG SVM using OpenCV 2.4Results log for HOG SVM using OpenCV 4.0 Note: Due to long hair for all three people in the image it is detecting the gender as ‘female’ which is a false positive. In machine learning algorithms the false positives are always common given the input sample image has ambiguous features. Image-Processing OpenCV C++ Machine Learning Machine Learning CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Friend class and function in C++ Sorting a vector in C++ std::string class in C++ Naive Bayes Classifiers Linear Regression (Python Implementation) ML | Linear Regression Agents in Artificial Intelligence Removing stop words with NLTK in Python
[ { "code": null, "e": 25453, "s": 25425, "text": "\n30 Jan, 2019" }, { "code": null, "e": 25622, "s": 25453, "text": "Let’s see how to train a model of support vector machine, save the trained model and test the model to check the percentage of its prediction accuracy using the OpenCV." }, { "code": null, "e": 25879, "s": 25622, "text": "Using imagenetscraper and autocrop , we collect data from the web, crop faces and resize them to smaller sizes in bulk. The collected data needs to be organized meaningfully so we can access it programmatically and manually. Use the below folder structure-" }, { "code": null, "e": 26095, "s": 25879, "text": "FFR_dataset/\n|-- Age\n| |-- adult\n| |-- child\n| |-- old\n| |-- teen\n|-- Emotion\n| |-- anger\n| |-- contempt\n| |-- happy\n| |-- neutral\n| |-- sad\n| |-- surprise\n|-- Gender\n |-- female\n |-- male\n" }, { "code": null, "e": 26459, "s": 26095, "text": "We use the same directory names in the code to access them to train, save and predict the recognition results. A minimum of 50 images in each folder is required to train the models to get good prediction results. Training more images can improve the results but not recommended as it takes a lot of time to execute that and does not give significant improvements." }, { "code": null, "e": 26672, "s": 26459, "text": "By making use of the sample provided in the official opencv repo to train the SVM with HOG, train_HOG.cpp, we implement the c++ code to train, save and predict the facial features on an image with multiple faces." }, { "code": null, "e": 26865, "s": 26672, "text": "There are three feature types- Age, Emotion and Gender. Four age groups, six emotions and two gender types. Hence an n-class classifier is implemented to recognize each feature on a face data." }, { "code": null, "e": 26954, "s": 26865, "text": "Step #1: For each feature type i.e. (Age, Emotion or Gender) loop through ‘n’ run times." }, { "code": "// CTrainTestHOG::Run(int run_times)for (auto ft : m_FeatureList) { DEBUGLW(\"\\tFeature type=[%s]\\n\", ft.first.c_str()); std::vector<float> predictionAccuracyList; predictionAccuracyList.reserve(run_times); for (int run = 0; run < run_times; ++run) { DEBUGLW(\"\\t\\tRun=[%d]\\n\", run); vector<Mat> trainData, predData; vector<int> trainLabels, predLabels; this->get_ft_dataset(ft.first, trainData, predData, trainLabels, predLabels); // ... train, predict and measure the SVM model. }}", "e": 27525, "s": 26954, "text": null }, { "code": null, "e": 27715, "s": 27525, "text": "Step #2: In each run, iterate through the feature values in the feature type and get the images into a vector or array, i.e. get all the images from folders Gender->Male and Gender->Female." }, { "code": "// CTrainTestHOG::get_ft_dataset()std::set<cv::String>& featureValueList = m_FeatureList.find(ft)->second; for (auto fv : featureValueList) { DEBUGLW(\"\\t\\t\\tFeature value=[%s]\\n\", fv.c_str()); std::vector<cv::Mat> _trainData; std::vector<cv::Mat> _predData; std::vector<int> _trainLabels; std::vector<int> _predLabels; errCode = this->get_ftfv_dataset(ft, fv, _trainData, _predData, _trainLabels, _predLabels); if (errCode != EXIT_SUCCESS) break; trainData.insert(trainData.end(), _trainData.begin(), _trainData.end()); predData.insert(predData.end(), _predData.begin(), _predData.end()); trainLabels.insert(trainLabels.end(), _trainLabels.begin(), _trainLabels.end()); predLabels.insert(predLabels.end(), _predLabels.begin(), _predLabels.end());}", "e": 28544, "s": 27715, "text": null }, { "code": null, "e": 28559, "s": 28544, "text": "Step #3 to #6:" }, { "code": null, "e": 28666, "s": 28559, "text": "Crop the images in the vector to the face rectangles and update the images vector with the new faces list." }, { "code": null, "e": 28770, "s": 28666, "text": "Perform any pre-processing tasks such as resizing to smaller size (64, 64) on each image in faces list." }, { "code": null, "e": 28859, "s": 28770, "text": "Shuffle the pre-processed face images in vector randomly to introduce random input data." }, { "code": null, "e": 28922, "s": 28859, "text": "Split the dataset into training(80%) and prediction(20%) data." }, { "code": "// CTrainTestHOG::get_ftfv_dataset()std::vector<cv::Mat> imgList;this->get_images(folderName, imgList);this->get_cropped_faces(imgList);this->get_preprocessed_faces(imgList); //-- return on empty img list to prevent seg faultif (imgList.empty()) { errCode = EXIT_FAILURE; DEBUGLE(\"Error img list is empty!\\n\"); break;}DEBUGLD(\"\\t\\t\\timgList.size()=[%ld]\\n\", imgList.size()); std::random_shuffle(imgList.begin(), imgList.end()); // 80% for trainingint trainPart = imgList.size() * 0.8; // 20% for predictingint predPart = imgList.size() - trainPart;DEBUGLD(\"\\t\\t\\ttrainPart=[%d], predPart=[%d]\\n\", trainPart, predPart); trainData.reserve(trainPart);predData.reserve(predPart); ft_t::iterator ft_iter = m_FeatureList.find(ft);fv_t::iterator fv_iter = ft_iter->second.find(fv);int label = std::distance(ft_iter->second.begin(), fv_iter);DEBUGLD(\"\\t\\t\\tlabel=[%d]\\n\", label); int i = 0;for (; i < trainPart; ++i) { trainData.push_back(imgList.at(i)); trainLabels.push_back(label);}DEBUGLD(\"\\t\\t\\ti=[%d], trainData.size()=[%ld], trainLabels.size() = [% ld]\\n \", i, trainData.size(), trainLabels.size()); for (; i < imgList.size(); ++i) { predData.push_back(imgList.at(i)); predLabels.push_back(label);}DEBUGLD(\"\\t\\t\\ti=[%d], predData.size()=[%ld], predLabels.size() = [% ld]\\n \", i, predData.size(), predLabels.size());", "e": 30321, "s": 28922, "text": null }, { "code": null, "e": 30376, "s": 30321, "text": "Step #7 : Compute HOG for each image in training data." }, { "code": "// CTrainTestHOG::computeHOGs()HOGDescriptor hog;vector<Mat> hogMats;vector<float> descriptors;for (auto img : imgHogList) { hog.winSize = img.size() / 8 * 8; hog.compute(img, descriptors); cv::Mat descriptors_mat(Mat(descriptors).clone()); hogMats.push_back(descriptors_mat);}imgHogList.swap(hogMats);", "e": 30691, "s": 30376, "text": null }, { "code": null, "e": 30769, "s": 30691, "text": "Step #8 : Convert the training data vector to opencv Mat object to train SVM." }, { "code": "// CTrainTestHOG::convert_to_ml()for (size_t i = 0; i < train_samples.size(); ++i) { CV_Assert(train_samples[i].cols == 1 || train_samples[i].rows == 1); if (train_samples[i].cols == 1) { cv::transpose(train_samples[i], tmp); tmp.copyTo(trainData.row((int)i)); } else if (train_samples[i].rows == 1) { train_samples[i].copyTo(trainData.row((int)i)); }}", "e": 31159, "s": 30769, "text": null }, { "code": null, "e": 31278, "s": 31159, "text": "Step #9 : Pass the training data Mat object to svm train function along with a vector of labels for the training data." }, { "code": "// CTrainTestHOG::Run()trainLabels.resize(ml_train_data.rows);// train svmDEBUGLW(\"\\t\\tTraining SVM - begin\\n\");m_pSVM->train(ml_train_data, ROW_SAMPLE, trainLabels);DEBUGLW(\"\\t\\tTraining SVM - end\\n\");", "e": 31482, "s": 31278, "text": null }, { "code": null, "e": 31516, "s": 31482, "text": "Step #10: Save the trained model." }, { "code": "//-- step 10, CTrainTestHOG::Run()cv::String svmModelFileName = cv::format(\"%s/cv4_svm_%s_model.xml\", getenv(FFR_DATASET_PATH), ft.first.c_str()); m_pSVM->save(svmModelFileName.c_str());DEBUGLW(\"\\t\\tSaved SVM model=[%s]\\n\", svmModelFileName.c_str());", "e": 31855, "s": 31516, "text": null }, { "code": null, "e": 32049, "s": 31855, "text": "Step #11: Predict the model by computing the HOG for each prediction image, convert the prediction dataset to opencv mat object and call svm predict with a vector of labels to store the result." }, { "code": "//-- step 11, CTrainTestHOG::Run()// test the model// compute HOG for each pre-processed faceerrCode = this->computeHOGs(predData);if (errCode != EXIT_SUCCESS) { DEBUGLE(\"Error in computing HOGs for the feature \" \"type=[%s]\\n\", ft.first.c_str()); break;} // convert HOG feature vectors to SVM dataMat ml_pred_data;vector<int> resultLabels;errCode = this->convert_to_ml(predData, ml_pred_data);if (errCode != EXIT_SUCCESS) { DEBUGLE(\"Error in converting to ml for the \" \"feature type=[%s]\\n\", ft.first.c_str()); break;}predLabels.resize(ml_pred_data.rows);// resultLabels.resize(ml_pred_data.rows);// test svmDEBUGLW(\"\\t\\tTesting SVM - begin\\n\");Mat responses_mat;m_pSVM->predict(ml_pred_data, responses_mat);for (size_t i = 0; i < ml_pred_data.rows; ++i) { resultLabels.push_back(responses_mat.at<int>(i));}DEBUGLW(\"\\t\\tTesting SVM - end\\n\");", "e": 32952, "s": 32049, "text": null }, { "code": null, "e": 33082, "s": 32952, "text": "Step #12 and #13: Calculate the percentage of its accuracy by comparing the expected prediction labels with the predicted labels." }, { "code": "// CTrainTestHOG::Run()// check the accuracyfloat accuracy = 0.0f;this->get_prediction_accuracy(predLabels, resultLabels, accuracy);DEBUGLW(\"\\t\\tPrediction accuracy=[%lf]\\n\", accuracy);predictionAccuracyList.push_back(accuracy); //-- step 13, CTrainTestHOG::Run()// check the mean accuracy of 'n' runsfloat sum_of_accuracies = std::accumulate( predictionAccuracyList.begin(), predictionAccuracyList.end(), 0.0);float mean_accuracy = sum_of_accuracies / predictionAccuracyList.size();DEBUGLW(\"\\t\\tMean prediction accuracy=[%lf]\\n\", mean_accuracy);", "e": 33644, "s": 33082, "text": null }, { "code": null, "e": 33698, "s": 33644, "text": "Run the executable with below command line arguments." }, { "code": null, "e": 33737, "s": 33698, "text": "./train_hog --test --in= --out= --show" }, { "code": null, "e": 33744, "s": 33737, "text": "Input:" }, { "code": null, "e": 33752, "s": 33744, "text": "Output:" }, { "code": null, "e": 33833, "s": 33752, "text": "Results log for HOG SVM using OpenCV 2.4Results log for HOG SVM using OpenCV 4.0" }, { "code": null, "e": 34078, "s": 33833, "text": "Note: Due to long hair for all three people in the image it is detecting the gender as ‘female’ which is a false positive. In machine learning algorithms the false positives are always common given the input sample image has ambiguous features." }, { "code": null, "e": 34095, "s": 34078, "text": "Image-Processing" }, { "code": null, "e": 34102, "s": 34095, "text": "OpenCV" }, { "code": null, "e": 34106, "s": 34102, "text": "C++" }, { "code": null, "e": 34123, "s": 34106, "text": "Machine Learning" }, { "code": null, "e": 34140, "s": 34123, "text": "Machine Learning" }, { "code": null, "e": 34144, "s": 34140, "text": "CPP" }, { "code": null, "e": 34242, "s": 34144, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34270, "s": 34242, "text": "Operator Overloading in C++" }, { "code": null, "e": 34290, "s": 34270, "text": "Polymorphism in C++" }, { "code": null, "e": 34323, "s": 34290, "text": "Friend class and function in C++" }, { "code": null, "e": 34347, "s": 34323, "text": "Sorting a vector in C++" }, { "code": null, "e": 34372, "s": 34347, "text": "std::string class in C++" }, { "code": null, "e": 34396, "s": 34372, "text": "Naive Bayes Classifiers" }, { "code": null, "e": 34438, "s": 34396, "text": "Linear Regression (Python Implementation)" }, { "code": null, "e": 34461, "s": 34438, "text": "ML | Linear Regression" }, { "code": null, "e": 34495, "s": 34461, "text": "Agents in Artificial Intelligence" } ]
Python Program to create a List using custom key-value pair of a dictionary - GeeksforGeeks
02 Feb, 2021 Given a dictionary list, the task here is to write a python program that can convert it to a dictionary with items from values of custom keys. Input : test_list = [{‘gfg’ : 1, ‘is’ : 4, ‘best’ : 6}, {‘gfg’ : 10, ‘is’ : 3, ‘best’ : 7}, {‘gfg’ : 9, ‘is’ : 4, ‘best’ : 2}, {‘gfg’ : 4, ‘is’ : 1, ‘best’ : 0}, {‘gfg’ : 6, ‘is’ : 3, ‘best’ : 8}], key, value = ‘gfg’, ‘best’ Output : {1: 6, 10: 7, 9: 2, 4: 0, 6: 8} Explanation : Dictionary with ‘gfg”s keys and ‘best”s values is constructed. Input : test_list = [{‘gfg’ : 1, ‘is’ : 4, ‘best’ : 6}, {‘gfg’ : 10, ‘is’ : 3, ‘best’ : 7}, {‘gfg’ : 9, ‘is’ : 4, ‘best’ : 2}], key, value = ‘gfg’, ‘best’ Output : {1: 6, 10: 7, 9: 2} Explanation : Dictionary with ‘gfg”s keys and ‘best”s values is constructed. Method 1 : Using loop In this, dictionary list is iterated and values of required custom keys are extracted to declare key value pairs of result dictionary. Example: Python3 # initializing listtest_list = [{'gfg': 1, 'is': 4, 'best': 6}, {'gfg': 10, 'is': 3, 'best': 7}, {'gfg': 9, 'is': 4, 'best': 2}, {'gfg': 4, 'is': 1, 'best': 0}, {'gfg': 6, 'is': 3, 'best': 8}] # printing original listprint("The original list is : " + str(test_list)) # initializing key-valueskey, value = 'gfg', 'best' res = dict()for sub in test_list: # constructed values res[sub[key]] = sub[value] # printing resultprint("Dictionary values : " + str(res)) Output: The original list is : [{‘gfg’: 1, ‘is’: 4, ‘best’: 6}, {‘gfg’: 10, ‘is’: 3, ‘best’: 7}, {‘gfg’: 9, ‘is’: 4, ‘best’: 2}, {‘gfg’: 4, ‘is’: 1, ‘best’: 0}, {‘gfg’: 6, ‘is’: 3, ‘best’: 8}] Dictionary values : {1: 6, 10: 7, 9: 2, 4: 0, 6: 8} Method 2 : Using dictionary comprehension In this, we perform similar task as above method, difference being dictionary comprehension is used to offer one liner alternative to solution. Example: Python3 # initializing listtest_list = [{'gfg': 1, 'is': 4, 'best': 6}, {'gfg': 10, 'is': 3, 'best': 7}, {'gfg': 9, 'is': 4, 'best': 2}, {'gfg': 4, 'is': 1, 'best': 0}, {'gfg': 6, 'is': 3, 'best': 8}] # printing original listprint("The original list is : " + str(test_list)) # initializing key-valueskey, value = 'gfg', 'best' # dictionary comprehension for one linerres = {sub[key]: sub[value] for sub in test_list} # printing resultprint("Dictionary values : " + str(res)) Output: The original list is : [{‘gfg’: 1, ‘is’: 4, ‘best’: 6}, {‘gfg’: 10, ‘is’: 3, ‘best’: 7}, {‘gfg’: 9, ‘is’: 4, ‘best’: 2}, {‘gfg’: 4, ‘is’: 1, ‘best’: 0}, {‘gfg’: 6, ‘is’: 3, ‘best’: 8}] Dictionary values : {1: 6, 10: 7, 9: 2, 4: 0, 6: 8} Python dictionary-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25647, "s": 25619, "text": "\n02 Feb, 2021" }, { "code": null, "e": 25790, "s": 25647, "text": "Given a dictionary list, the task here is to write a python program that can convert it to a dictionary with items from values of custom keys." }, { "code": null, "e": 25846, "s": 25790, "text": "Input : test_list = [{‘gfg’ : 1, ‘is’ : 4, ‘best’ : 6}," }, { "code": null, "e": 25895, "s": 25846, "text": " {‘gfg’ : 10, ‘is’ : 3, ‘best’ : 7}," }, { "code": null, "e": 25943, "s": 25895, "text": " {‘gfg’ : 9, ‘is’ : 4, ‘best’ : 2}," }, { "code": null, "e": 25991, "s": 25943, "text": " {‘gfg’ : 4, ‘is’ : 1, ‘best’ : 0}," }, { "code": null, "e": 26067, "s": 25991, "text": " {‘gfg’ : 6, ‘is’ : 3, ‘best’ : 8}], key, value = ‘gfg’, ‘best’" }, { "code": null, "e": 26108, "s": 26067, "text": "Output : {1: 6, 10: 7, 9: 2, 4: 0, 6: 8}" }, { "code": null, "e": 26185, "s": 26108, "text": "Explanation : Dictionary with ‘gfg”s keys and ‘best”s values is constructed." }, { "code": null, "e": 26241, "s": 26185, "text": "Input : test_list = [{‘gfg’ : 1, ‘is’ : 4, ‘best’ : 6}," }, { "code": null, "e": 26290, "s": 26241, "text": " {‘gfg’ : 10, ‘is’ : 3, ‘best’ : 7}," }, { "code": null, "e": 26366, "s": 26290, "text": " {‘gfg’ : 9, ‘is’ : 4, ‘best’ : 2}], key, value = ‘gfg’, ‘best’" }, { "code": null, "e": 26395, "s": 26366, "text": "Output : {1: 6, 10: 7, 9: 2}" }, { "code": null, "e": 26472, "s": 26395, "text": "Explanation : Dictionary with ‘gfg”s keys and ‘best”s values is constructed." }, { "code": null, "e": 26494, "s": 26472, "text": "Method 1 : Using loop" }, { "code": null, "e": 26629, "s": 26494, "text": "In this, dictionary list is iterated and values of required custom keys are extracted to declare key value pairs of result dictionary." }, { "code": null, "e": 26638, "s": 26629, "text": "Example:" }, { "code": null, "e": 26646, "s": 26638, "text": "Python3" }, { "code": "# initializing listtest_list = [{'gfg': 1, 'is': 4, 'best': 6}, {'gfg': 10, 'is': 3, 'best': 7}, {'gfg': 9, 'is': 4, 'best': 2}, {'gfg': 4, 'is': 1, 'best': 0}, {'gfg': 6, 'is': 3, 'best': 8}] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing key-valueskey, value = 'gfg', 'best' res = dict()for sub in test_list: # constructed values res[sub[key]] = sub[value] # printing resultprint(\"Dictionary values : \" + str(res))", "e": 27165, "s": 26646, "text": null }, { "code": null, "e": 27173, "s": 27165, "text": "Output:" }, { "code": null, "e": 27358, "s": 27173, "text": "The original list is : [{‘gfg’: 1, ‘is’: 4, ‘best’: 6}, {‘gfg’: 10, ‘is’: 3, ‘best’: 7}, {‘gfg’: 9, ‘is’: 4, ‘best’: 2}, {‘gfg’: 4, ‘is’: 1, ‘best’: 0}, {‘gfg’: 6, ‘is’: 3, ‘best’: 8}]" }, { "code": null, "e": 27410, "s": 27358, "text": "Dictionary values : {1: 6, 10: 7, 9: 2, 4: 0, 6: 8}" }, { "code": null, "e": 27452, "s": 27410, "text": "Method 2 : Using dictionary comprehension" }, { "code": null, "e": 27596, "s": 27452, "text": "In this, we perform similar task as above method, difference being dictionary comprehension is used to offer one liner alternative to solution." }, { "code": null, "e": 27605, "s": 27596, "text": "Example:" }, { "code": null, "e": 27613, "s": 27605, "text": "Python3" }, { "code": "# initializing listtest_list = [{'gfg': 1, 'is': 4, 'best': 6}, {'gfg': 10, 'is': 3, 'best': 7}, {'gfg': 9, 'is': 4, 'best': 2}, {'gfg': 4, 'is': 1, 'best': 0}, {'gfg': 6, 'is': 3, 'best': 8}] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing key-valueskey, value = 'gfg', 'best' # dictionary comprehension for one linerres = {sub[key]: sub[value] for sub in test_list} # printing resultprint(\"Dictionary values : \" + str(res))", "e": 28132, "s": 27613, "text": null }, { "code": null, "e": 28140, "s": 28132, "text": "Output:" }, { "code": null, "e": 28325, "s": 28140, "text": "The original list is : [{‘gfg’: 1, ‘is’: 4, ‘best’: 6}, {‘gfg’: 10, ‘is’: 3, ‘best’: 7}, {‘gfg’: 9, ‘is’: 4, ‘best’: 2}, {‘gfg’: 4, ‘is’: 1, ‘best’: 0}, {‘gfg’: 6, ‘is’: 3, ‘best’: 8}]" }, { "code": null, "e": 28377, "s": 28325, "text": "Dictionary values : {1: 6, 10: 7, 9: 2, 4: 0, 6: 8}" }, { "code": null, "e": 28404, "s": 28377, "text": "Python dictionary-programs" }, { "code": null, "e": 28411, "s": 28404, "text": "Python" }, { "code": null, "e": 28427, "s": 28411, "text": "Python Programs" }, { "code": null, "e": 28525, "s": 28427, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28557, "s": 28525, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28599, "s": 28557, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28641, "s": 28599, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28697, "s": 28641, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28724, "s": 28697, "text": "Python Classes and Objects" }, { "code": null, "e": 28746, "s": 28724, "text": "Defaultdict in Python" }, { "code": null, "e": 28785, "s": 28746, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28831, "s": 28785, "text": "Python | Split string into list of characters" }, { "code": null, "e": 28869, "s": 28831, "text": "Python | Convert a list to dictionary" } ]
Publicly inherit a base class but making some of public method as private - GeeksforGeeks
25 Feb, 2018 There are certain situation when we want to make some of the public base class functions as private in the derived class. Suppose both base and child class has getter and setter methods // CPP program to demonstrate that all base// class public functions become available// in derived class if we use public inheritance.#include <iostream>using namespace std; class Base { int i; public: Base() {} void setBaseProperties(int i) { this->i = i; } void showBaseProperties() { std::cout << endl << "i = " << i; } virtual ~Base() {}}; class Child : public Base { int j; int k; public: void setChildProperties(int i, int j, int k) { setBaseProperties(i); this->j = j; this->k = k; } void showChildProperties() { showBaseProperties(); cout << " j = " << j << " k = " << k; }}; int main(){ Child c; c.setChildProperties(1, 2, 3); // this exposed function is undesirable c.setBaseProperties(4); c.showChildProperties(); return 0;} i = 4 j = 2 k = 3 Here if we need to restrict the call of function “setBaseProperties” and “showBaseProperties” with Child class object “c”. This can be achieved without overriding the function as below: We re-declare base class functions in derived class scope using “using” syntax. We do it in private section of derived class. // CPP program to demonstrate that some of// base class public functions cane be restricted// in derived class if we re-declare them with // "using" in private section of derived class#include <iostream>using namespace std; class Base { int i; public: Base() {} void setBaseProperties(int i) { this->i = i; } void showBaseProperties() { std::cout << endl << "i = " << i; } virtual ~Base() {}}; class Child : public Base { int j; int k; // Redeclaring scope of base class // functions in private section of // derived class. using Base::showBaseProperties; using Base::setBaseProperties; public: void setChildProperties(int i, int j, int k) { setBaseProperties(i); this->j = j; this->k = k; } void showChildProperties() { showBaseProperties(); cout << " j = " << j << " k = " << k; }}; int main(){ Child c; c.setChildProperties(1, 2, 3); // if we uncomment this part of code, it causes // compilation error as the function is private // now // c.setBaseProperties(4); c.showChildProperties(); return 0;} i = 1 j = 2 k = 3 cpp-inheritance C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Friend class and function in C++ Sorting a vector in C++ std::string class in C++ Inline Functions in C++ Pair in C++ Standard Template Library (STL) Array of Strings in C++ (5 Different Ways to Create) Convert string to char array in C++ List in C++ Standard Template Library (STL)
[ { "code": null, "e": 25477, "s": 25449, "text": "\n25 Feb, 2018" }, { "code": null, "e": 25663, "s": 25477, "text": "There are certain situation when we want to make some of the public base class functions as private in the derived class. Suppose both base and child class has getter and setter methods" }, { "code": "// CPP program to demonstrate that all base// class public functions become available// in derived class if we use public inheritance.#include <iostream>using namespace std; class Base { int i; public: Base() {} void setBaseProperties(int i) { this->i = i; } void showBaseProperties() { std::cout << endl << \"i = \" << i; } virtual ~Base() {}}; class Child : public Base { int j; int k; public: void setChildProperties(int i, int j, int k) { setBaseProperties(i); this->j = j; this->k = k; } void showChildProperties() { showBaseProperties(); cout << \" j = \" << j << \" k = \" << k; }}; int main(){ Child c; c.setChildProperties(1, 2, 3); // this exposed function is undesirable c.setBaseProperties(4); c.showChildProperties(); return 0;}", "e": 26544, "s": 25663, "text": null }, { "code": null, "e": 26563, "s": 26544, "text": "i = 4 j = 2 k = 3\n" }, { "code": null, "e": 26749, "s": 26563, "text": "Here if we need to restrict the call of function “setBaseProperties” and “showBaseProperties” with Child class object “c”. This can be achieved without overriding the function as below:" }, { "code": null, "e": 26875, "s": 26749, "text": "We re-declare base class functions in derived class scope using “using” syntax. We do it in private section of derived class." }, { "code": "// CPP program to demonstrate that some of// base class public functions cane be restricted// in derived class if we re-declare them with // \"using\" in private section of derived class#include <iostream>using namespace std; class Base { int i; public: Base() {} void setBaseProperties(int i) { this->i = i; } void showBaseProperties() { std::cout << endl << \"i = \" << i; } virtual ~Base() {}}; class Child : public Base { int j; int k; // Redeclaring scope of base class // functions in private section of // derived class. using Base::showBaseProperties; using Base::setBaseProperties; public: void setChildProperties(int i, int j, int k) { setBaseProperties(i); this->j = j; this->k = k; } void showChildProperties() { showBaseProperties(); cout << \" j = \" << j << \" k = \" << k; }}; int main(){ Child c; c.setChildProperties(1, 2, 3); // if we uncomment this part of code, it causes // compilation error as the function is private // now // c.setBaseProperties(4); c.showChildProperties(); return 0;}", "e": 28048, "s": 26875, "text": null }, { "code": null, "e": 28067, "s": 28048, "text": "i = 1 j = 2 k = 3\n" }, { "code": null, "e": 28083, "s": 28067, "text": "cpp-inheritance" }, { "code": null, "e": 28087, "s": 28083, "text": "C++" }, { "code": null, "e": 28091, "s": 28087, "text": "CPP" }, { "code": null, "e": 28189, "s": 28091, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28217, "s": 28189, "text": "Operator Overloading in C++" }, { "code": null, "e": 28237, "s": 28217, "text": "Polymorphism in C++" }, { "code": null, "e": 28270, "s": 28237, "text": "Friend class and function in C++" }, { "code": null, "e": 28294, "s": 28270, "text": "Sorting a vector in C++" }, { "code": null, "e": 28319, "s": 28294, "text": "std::string class in C++" }, { "code": null, "e": 28343, "s": 28319, "text": "Inline Functions in C++" }, { "code": null, "e": 28387, "s": 28343, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 28440, "s": 28387, "text": "Array of Strings in C++ (5 Different Ways to Create)" }, { "code": null, "e": 28476, "s": 28440, "text": "Convert string to char array in C++" } ]
Carmichael Numbers - GeeksforGeeks
22 Jan, 2022 A number n is said to be a Carmichael number if it satisfies the following modular arithmetic condition: power(b, n-1) MOD n = 1, for all b ranging from 1 to n such that b and n are relatively prime, i.e, gcd(b, n) = 1 Given a positive integer n, find if it is a Carmichael number. These numbers have importance in Fermat Method for primality testing.Examples : Input : n = 8 Output : false Explanation : 8 is not a Carmichael number because 3 is relatively prime to 8 and (38-1) % 8 = 2187 % 8 is not 1. Input : n = 561 Output : true The idea is simple, we iterate through all numbers from 1 to n and for every relatively prime number, we check if its (n-1)th power under modulo n is 1 or not. Below is a the program to check if a given number is Carmichael or not. C++ Java Python3 C# PHP Javascript C // A C++ program to check if a number is// Carmichael or not.#include <iostream>using namespace std; // utility function to find gcd of two numbersint gcd(int a, int b){ if (a < b) return gcd(b, a); if (a % b == 0) return b; return gcd(b, a % b);} // utility function to find pow(x, y) under// given modulo modint power(int x, int y, int mod){ if (y == 0) return 1; int temp = power(x, y / 2, mod) % mod; temp = (temp * temp) % mod; if (y % 2 == 1) temp = (temp * x) % mod; return temp;} // This function receives an integer n and// finds if it's a Carmichael numberbool isCarmichaelNumber(int n){ for (int b = 2; b < n; b++) { // If "b" is relatively prime to n if (gcd(b, n) == 1) // And pow(b, n-1)%n is not 1, // return false. if (power(b, n - 1, n) != 1) return false; } return true;} // Driver functionint main(){ cout << isCarmichaelNumber(500) << endl; cout << isCarmichaelNumber(561) << endl; cout << isCarmichaelNumber(1105) << endl; return 0;} // JAVA program to check if a number is// Carmichael or not.import java.io.*; class GFG { // utility function to find gcd of // two numbers static int gcd(int a, int b) { if (a < b) return gcd(b, a); if (a % b == 0) return b; return gcd(b, a % b); } // utility function to find pow(x, y) // under given modulo mod static int power(int x, int y, int mod) { if (y == 0) return 1; int temp = power(x, y / 2, mod) % mod; temp = (temp * temp) % mod; if (y % 2 == 1) temp = (temp * x) % mod; return temp; } // This function receives an integer n and // finds if it's a Carmichael number static int isCarmichaelNumber(int n) { for (int b = 2; b < n; b++) { // If "b" is relatively prime to n if (gcd(b, n) == 1) // And pow(b, n-1)%n is not 1, // return false. if (power(b, n - 1, n) != 1) return 0; } return 1; } // Driver function public static void main(String args[]) { System.out.println(isCarmichaelNumber(500)); System.out.println(isCarmichaelNumber(561)); System.out.println(isCarmichaelNumber(1105)); }}// This code is contributed by Nikita Tiwari. # A Python program to check if a number is# Carmichael or not. # utility function to find gcd of two numbersdef gcd( a, b) : if (a < b) : return gcd(b, a) if (a % b == 0) : return b return gcd(b, a % b) # utility function to find pow(x, y) under# given modulo moddef power(x, y, mod) : if (y == 0) : return 1 temp = power(x, y // 2, mod) % mod temp = (temp * temp) % mod if (y % 2 == 1) : temp = (temp * x) % mod return temp # This function receives an integer n and# finds if it's a Carmichael numberdef isCarmichaelNumber( n) : b = 2 while b<n : # If "b" is relatively prime to n if (gcd(b, n) == 1) : # And pow(b, n-1)% n is not 1, # return false. if (power(b, n - 1, n) != 1): return 0 b = b + 1 return 1 # Driver functionprint (isCarmichaelNumber(500))print (isCarmichaelNumber(561))print (isCarmichaelNumber(1105)) # This code is contributed by Nikita Tiwari. // C# program to check if a number is// Carmichael or not.using System; class GFG { // utility function to find gcd of // two numbers static int gcd(int a, int b) { if (a < b) return gcd(b, a); if (a % b == 0) return b; return gcd(b, a % b); } // utility function to find pow(x, y) // under given modulo mod static int power(int x, int y, int mod) { if (y == 0) return 1; int temp = power(x, y / 2, mod) % mod; temp = (temp * temp) % mod; if (y % 2 == 1) temp = (temp * x) % mod; return temp; } // This function receives an integer n and // finds if it's a Carmichael number static int isCarmichaelNumber(int n) { for (int b = 2; b < n; b++) { // If "b" is relatively prime to n if (gcd(b, n) == 1) // And pow(b, n-1)%n is not 1, // return false. if (power(b, n - 1, n) != 1) return 0; } return 1; } // Driver function public static void Main() { Console.WriteLine(isCarmichaelNumber(500)); Console.WriteLine(isCarmichaelNumber(561)); Console.WriteLine(isCarmichaelNumber(1105)); }} // This code is contributed by vt_m. <?php// PHP program to check if a// number is Carmichael or not. // utility function to find// gcd of two numbersfunction gcd($a, $b){ if ($a < $b) return gcd($b, $a); if ($a % $b == 0) return $b; return gcd($b, $a % $b);} // utility function to find// pow(x, y) under given modulo modfunction power($x, $y, $mod){ if ($y == 0) return 1; $temp = power($x, $y / 2, $mod) % $mod; $temp = ($temp * $temp) % $mod; if ($y % 2 == 1) $temp = ($temp * $x) % $mod; return $temp;} // This function receives an integer// n and finds if it's a Carmichael// numberfunction isCarmichaelNumber($n){ for ($b = 2; $b <= $n; $b++) { // If "b" is relatively // prime to n if (gcd($b, $n) == 1) // And pow(b, n - 1) % n // is not 1, return false. if (power($b, $n - 1, $n) != 1) return 0; } return 1;} // Driver Codeecho isCarmichaelNumber(500), " \n";echo isCarmichaelNumber(561), "\n";echo isCarmichaelNumber(1105), "\n"; // This code is contributed by ajit?> <script> // Javascript program to check if a number is // Carmichael or not. // utility function to find gcd of // two numbers function gcd(a, b) { if (a < b) return gcd(b, a); if (a % b == 0) return b; return gcd(b, a % b); } // utility function to find pow(x, y) // under given modulo mod function power(x, y, mod) { if (y == 0) return 1; let temp = power(x, parseInt(y / 2, 10), mod) % mod; temp = (temp * temp) % mod; if (y % 2 == 1) temp = (temp * x) % mod; return temp; } // This function receives an integer n and // finds if it's a Carmichael number function isCarmichaelNumber(n) { for (let b = 2; b < n; b++) { // If "b" is relatively prime to n if (gcd(b, n) == 1) // And pow(b, n-1)%n is not 1, // return false. if (power(b, n - 1, n) != 1) return 0; } return 1; } document.write(isCarmichaelNumber(500) + "</br>"); document.write(isCarmichaelNumber(561) + "</br>"); document.write(isCarmichaelNumber(1105)); </script> // C Program to find if a number is Carmichael Number#include<stdio.h>int gcd(int a, int b) //Function to find GCD{if (a<b)return gcd(b, a);if (a % b == 0)return b;return gcd(b, a % b);} // Function to find pow(x,y) under given modulo modint power(int x, int y, int mod) {if (y == 0)return 1;int temp = power(x, y / 2, mod) % mod;temp = (temp * temp) % mod;if (y % 2 == 1)temp = (temp * x) % mod;return temp;} //Function to find if received number n is a Carmichael numberint carmichaelnumber(int n) {for (int b=2;b<n;b++){if (gcd(b,n)==1)if (power(b,n-1,n)!= 1){printf("0");return 0;}}printf("1");return 0;};int main(){carmichaelnumber(500);printf("\n");carmichaelnumber(561);printf("\n");carmichaelnumber(1105);return 0; // This code is contributed by Susobhan Akhuli } Output: 0 1 1 This article is contributed by Ashutosh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. jit_t divyeshrabadiya07 susobhanakhuli amartyaghoshgfg number-theory series Mathematical number-theory Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Algorithm to solve Rubik's Cube Modular multiplicative inverse Program to multiply two matrices Program to convert a given number to words Count ways to reach the n'th stair Fizz Buzz Implementation Singular Value Decomposition (SVD) Program to print prime numbers from 1 to N. Find first and last digits of a number Check if a number is Palindrome
[ { "code": null, "e": 24638, "s": 24610, "text": "\n22 Jan, 2022" }, { "code": null, "e": 24745, "s": 24638, "text": "A number n is said to be a Carmichael number if it satisfies the following modular arithmetic condition: " }, { "code": null, "e": 24868, "s": 24745, "text": " power(b, n-1) MOD n = 1, \n for all b ranging from 1 to n such that b and \n n are relatively prime, i.e, gcd(b, n) = 1 " }, { "code": null, "e": 25013, "s": 24868, "text": "Given a positive integer n, find if it is a Carmichael number. These numbers have importance in Fermat Method for primality testing.Examples : " }, { "code": null, "e": 25232, "s": 25013, "text": "Input : n = 8\nOutput : false\nExplanation : 8 is not a Carmichael number because 3 is \n relatively prime to 8 and (38-1) % 8\n = 2187 % 8 is not 1.\n \nInput : n = 561\nOutput : true" }, { "code": null, "e": 25468, "s": 25234, "text": "The idea is simple, we iterate through all numbers from 1 to n and for every relatively prime number, we check if its (n-1)th power under modulo n is 1 or not. Below is a the program to check if a given number is Carmichael or not. " }, { "code": null, "e": 25472, "s": 25468, "text": "C++" }, { "code": null, "e": 25477, "s": 25472, "text": "Java" }, { "code": null, "e": 25485, "s": 25477, "text": "Python3" }, { "code": null, "e": 25488, "s": 25485, "text": "C#" }, { "code": null, "e": 25492, "s": 25488, "text": "PHP" }, { "code": null, "e": 25503, "s": 25492, "text": "Javascript" }, { "code": null, "e": 25505, "s": 25503, "text": "C" }, { "code": "// A C++ program to check if a number is// Carmichael or not.#include <iostream>using namespace std; // utility function to find gcd of two numbersint gcd(int a, int b){ if (a < b) return gcd(b, a); if (a % b == 0) return b; return gcd(b, a % b);} // utility function to find pow(x, y) under// given modulo modint power(int x, int y, int mod){ if (y == 0) return 1; int temp = power(x, y / 2, mod) % mod; temp = (temp * temp) % mod; if (y % 2 == 1) temp = (temp * x) % mod; return temp;} // This function receives an integer n and// finds if it's a Carmichael numberbool isCarmichaelNumber(int n){ for (int b = 2; b < n; b++) { // If \"b\" is relatively prime to n if (gcd(b, n) == 1) // And pow(b, n-1)%n is not 1, // return false. if (power(b, n - 1, n) != 1) return false; } return true;} // Driver functionint main(){ cout << isCarmichaelNumber(500) << endl; cout << isCarmichaelNumber(561) << endl; cout << isCarmichaelNumber(1105) << endl; return 0;}", "e": 26596, "s": 25505, "text": null }, { "code": "// JAVA program to check if a number is// Carmichael or not.import java.io.*; class GFG { // utility function to find gcd of // two numbers static int gcd(int a, int b) { if (a < b) return gcd(b, a); if (a % b == 0) return b; return gcd(b, a % b); } // utility function to find pow(x, y) // under given modulo mod static int power(int x, int y, int mod) { if (y == 0) return 1; int temp = power(x, y / 2, mod) % mod; temp = (temp * temp) % mod; if (y % 2 == 1) temp = (temp * x) % mod; return temp; } // This function receives an integer n and // finds if it's a Carmichael number static int isCarmichaelNumber(int n) { for (int b = 2; b < n; b++) { // If \"b\" is relatively prime to n if (gcd(b, n) == 1) // And pow(b, n-1)%n is not 1, // return false. if (power(b, n - 1, n) != 1) return 0; } return 1; } // Driver function public static void main(String args[]) { System.out.println(isCarmichaelNumber(500)); System.out.println(isCarmichaelNumber(561)); System.out.println(isCarmichaelNumber(1105)); }}// This code is contributed by Nikita Tiwari.", "e": 27936, "s": 26596, "text": null }, { "code": "# A Python program to check if a number is# Carmichael or not. # utility function to find gcd of two numbersdef gcd( a, b) : if (a < b) : return gcd(b, a) if (a % b == 0) : return b return gcd(b, a % b) # utility function to find pow(x, y) under# given modulo moddef power(x, y, mod) : if (y == 0) : return 1 temp = power(x, y // 2, mod) % mod temp = (temp * temp) % mod if (y % 2 == 1) : temp = (temp * x) % mod return temp # This function receives an integer n and# finds if it's a Carmichael numberdef isCarmichaelNumber( n) : b = 2 while b<n : # If \"b\" is relatively prime to n if (gcd(b, n) == 1) : # And pow(b, n-1)% n is not 1, # return false. if (power(b, n - 1, n) != 1): return 0 b = b + 1 return 1 # Driver functionprint (isCarmichaelNumber(500))print (isCarmichaelNumber(561))print (isCarmichaelNumber(1105)) # This code is contributed by Nikita Tiwari.", "e": 28943, "s": 27936, "text": null }, { "code": "// C# program to check if a number is// Carmichael or not.using System; class GFG { // utility function to find gcd of // two numbers static int gcd(int a, int b) { if (a < b) return gcd(b, a); if (a % b == 0) return b; return gcd(b, a % b); } // utility function to find pow(x, y) // under given modulo mod static int power(int x, int y, int mod) { if (y == 0) return 1; int temp = power(x, y / 2, mod) % mod; temp = (temp * temp) % mod; if (y % 2 == 1) temp = (temp * x) % mod; return temp; } // This function receives an integer n and // finds if it's a Carmichael number static int isCarmichaelNumber(int n) { for (int b = 2; b < n; b++) { // If \"b\" is relatively prime to n if (gcd(b, n) == 1) // And pow(b, n-1)%n is not 1, // return false. if (power(b, n - 1, n) != 1) return 0; } return 1; } // Driver function public static void Main() { Console.WriteLine(isCarmichaelNumber(500)); Console.WriteLine(isCarmichaelNumber(561)); Console.WriteLine(isCarmichaelNumber(1105)); }} // This code is contributed by vt_m.", "e": 30256, "s": 28943, "text": null }, { "code": "<?php// PHP program to check if a// number is Carmichael or not. // utility function to find// gcd of two numbersfunction gcd($a, $b){ if ($a < $b) return gcd($b, $a); if ($a % $b == 0) return $b; return gcd($b, $a % $b);} // utility function to find// pow(x, y) under given modulo modfunction power($x, $y, $mod){ if ($y == 0) return 1; $temp = power($x, $y / 2, $mod) % $mod; $temp = ($temp * $temp) % $mod; if ($y % 2 == 1) $temp = ($temp * $x) % $mod; return $temp;} // This function receives an integer// n and finds if it's a Carmichael// numberfunction isCarmichaelNumber($n){ for ($b = 2; $b <= $n; $b++) { // If \"b\" is relatively // prime to n if (gcd($b, $n) == 1) // And pow(b, n - 1) % n // is not 1, return false. if (power($b, $n - 1, $n) != 1) return 0; } return 1;} // Driver Codeecho isCarmichaelNumber(500), \" \\n\";echo isCarmichaelNumber(561), \"\\n\";echo isCarmichaelNumber(1105), \"\\n\"; // This code is contributed by ajit?>", "e": 31332, "s": 30256, "text": null }, { "code": "<script> // Javascript program to check if a number is // Carmichael or not. // utility function to find gcd of // two numbers function gcd(a, b) { if (a < b) return gcd(b, a); if (a % b == 0) return b; return gcd(b, a % b); } // utility function to find pow(x, y) // under given modulo mod function power(x, y, mod) { if (y == 0) return 1; let temp = power(x, parseInt(y / 2, 10), mod) % mod; temp = (temp * temp) % mod; if (y % 2 == 1) temp = (temp * x) % mod; return temp; } // This function receives an integer n and // finds if it's a Carmichael number function isCarmichaelNumber(n) { for (let b = 2; b < n; b++) { // If \"b\" is relatively prime to n if (gcd(b, n) == 1) // And pow(b, n-1)%n is not 1, // return false. if (power(b, n - 1, n) != 1) return 0; } return 1; } document.write(isCarmichaelNumber(500) + \"</br>\"); document.write(isCarmichaelNumber(561) + \"</br>\"); document.write(isCarmichaelNumber(1105)); </script>", "e": 32559, "s": 31332, "text": null }, { "code": "// C Program to find if a number is Carmichael Number#include<stdio.h>int gcd(int a, int b) //Function to find GCD{if (a<b)return gcd(b, a);if (a % b == 0)return b;return gcd(b, a % b);} // Function to find pow(x,y) under given modulo modint power(int x, int y, int mod) {if (y == 0)return 1;int temp = power(x, y / 2, mod) % mod;temp = (temp * temp) % mod;if (y % 2 == 1)temp = (temp * x) % mod;return temp;} //Function to find if received number n is a Carmichael numberint carmichaelnumber(int n) {for (int b=2;b<n;b++){if (gcd(b,n)==1)if (power(b,n-1,n)!= 1){printf(\"0\");return 0;}}printf(\"1\");return 0;};int main(){carmichaelnumber(500);printf(\"\\n\");carmichaelnumber(561);printf(\"\\n\");carmichaelnumber(1105);return 0; // This code is contributed by Susobhan Akhuli }", "e": 33341, "s": 32559, "text": null }, { "code": null, "e": 33350, "s": 33341, "text": "Output: " }, { "code": null, "e": 33356, "s": 33350, "text": "0\n1\n1" }, { "code": null, "e": 33779, "s": 33356, "text": "This article is contributed by Ashutosh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 33785, "s": 33779, "text": "jit_t" }, { "code": null, "e": 33803, "s": 33785, "text": "divyeshrabadiya07" }, { "code": null, "e": 33818, "s": 33803, "text": "susobhanakhuli" }, { "code": null, "e": 33834, "s": 33818, "text": "amartyaghoshgfg" }, { "code": null, "e": 33848, "s": 33834, "text": "number-theory" }, { "code": null, "e": 33855, "s": 33848, "text": "series" }, { "code": null, "e": 33868, "s": 33855, "text": "Mathematical" }, { "code": null, "e": 33882, "s": 33868, "text": "number-theory" }, { "code": null, "e": 33895, "s": 33882, "text": "Mathematical" }, { "code": null, "e": 33902, "s": 33895, "text": "series" }, { "code": null, "e": 34000, "s": 33902, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34009, "s": 34000, "text": "Comments" }, { "code": null, "e": 34022, "s": 34009, "text": "Old Comments" }, { "code": null, "e": 34054, "s": 34022, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 34085, "s": 34054, "text": "Modular multiplicative inverse" }, { "code": null, "e": 34118, "s": 34085, "text": "Program to multiply two matrices" }, { "code": null, "e": 34161, "s": 34118, "text": "Program to convert a given number to words" }, { "code": null, "e": 34196, "s": 34161, "text": "Count ways to reach the n'th stair" }, { "code": null, "e": 34221, "s": 34196, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 34256, "s": 34221, "text": "Singular Value Decomposition (SVD)" }, { "code": null, "e": 34300, "s": 34256, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 34339, "s": 34300, "text": "Find first and last digits of a number" } ]
Find all possible coordinates of parallelogram - GeeksforGeeks
24 Nov, 2021 Find the all the possible coordinate from the given three coordinates to make a parallelogram of a non-zero area.Let’s call A,B,C are the three given points. We can have only the three possible situations: (1) AB and AC are sides, and BC a diagonal (2) AB and BC are sides, and AC a diagonal (3) BC and AC are sides, and AB a diagonal Hence, we can say that only 3 coordinates are possible from which we can generate a parallelogram if three coordinates are given.To prove that all the three points are different let’s suppose it’s wrong. Without losing of generality suppose that the points got in cases AD and BC are equal. Consider the system of two equations for the equality of these points: Bx + Cx - Ax = Ax + Cx - Bx By + Cy - Ay = Ay + Cy - By It can be simplified as- Ax = Bx Ay = By And we got a contradiction, as all the points A, B, C are distinct. Examples: Input : A = (0 0) B = (1 0) C = (0 1) Output : 1 -1 -1 1 1 1 Input : A = (-1 -1) B = (0 1) C = (1 1) Output : -2 -1 0 -1 2 3 Since the opposite sides are equal, AD = BC and AB = CD, we can calculate the co-ordinates of the missing point (D) as: AD = BC (Dx - Ax, Dy - Ay) = (Cx - Bx, Cy - By) Dx = Ax + Cx - Bx Dy = Ay + Cy - By The cases where the diagonals are AD and BC, CD and AB are processed in the same way.Reference: https://math.stackexchange.com/questions/1322535/how-many-different-parallelograms-can-be-drawn-if-given-three-co-ordinates-in-3d Below is the implementation of above approach: C++ Java Python3 C# PHP Javascript // C++ program to all possible points // of a parallelogram #include <bits/stdc++.h> using namespace std; // main method int main() { int ax = 5, ay = 0; //coordinates of A int bx = 1, by = 1; //coordinates of B int cx = 2, cy = 5; //coordinates of C cout << ax + bx - cx << ", " << ay + by - cy <<endl; cout << ax + cx - bx << ", " << ay + cy - by <<endl; cout << cx + bx - ax << ", " << cy + by - ax <<endl; return 0; } // Java program to all possible // points of a parallelogram public class ParallelogramPoints{ // Driver code public static void main(String[] s) { int ax = 5, ay = 0; //coordinates of A int bx = 1, by = 1; //coordinates of B int cx = 2, cy = 5; //coordinates of C System.out.println(ax + bx - cx + ", " + (ay + by - cy)); System.out.println(ax + cx - bx + ", " + (ay + cy - by)); System.out.println(cx + bx - ax + ", " + (cy + by - ax)); } } // This code is contributed by Prerna Saini # Python3 program to find all possible points # of a parallelogram ax = 5 ay = 0 #coordinates of A bx = 1 by = 1 #coordinates of B cx = 2 cy = 5 #coordinates of C print(ax + bx - cx, ", ", ay + by - cy) print(ax + cx - bx, ", ", ay + cy - by) print(cx + bx - ax, ", ", cy + by - ax) // C# program to all possible // points of a parallelogram using System; public class ParallelogramPoints { // Driver code public static void Main() { //coordinates of A int ax = 5, ay = 0; //coordinates of B int bx = 1, by = 1; //coordinates of C int cx = 2, cy = 5; Console.WriteLine(ax + bx - cx + ", " + (ay + by - cy)); Console.WriteLine(ax + cx - bx + ", " + (ay + cy - by)); Console.WriteLine(cx + bx - ax + ", " + (cy + by - ax)); } } // This code is contributed by vt_m. <?php // PHP program to all // possible points // of a parallelogram // Driver Code //coordinates of A $ax = 5; $ay = 0; //coordinates of B $bx = 1; $by = 1; //coordinates of C $cx = 2; $cy = 5; echo $ax + $bx - $cx , ", " , $ay + $by - $cy ,"\n"; echo $ax + $cx - $bx , ", " , $ay + $cy - $by,"\n" ; echo $cx + $bx - $ax , ", " , $cy + $by - $ax ; // This code is contributed by anuj_67. ?> <script> // JavaScript program to all possible // points of a parallelogram // Driver Code let ax = 5, ay = 0; // Coordinates of A let bx = 1, by = 1; // Coordinates of B let cx = 2, cy = 5; // Coordinates of C document.write(ax + bx - cx + ", " + (ay + by - cy) + "<br/>"); document.write(ax + cx - bx + ", " + (ay + cy - by) + "<br/>"); document.write(cx + bx - ax + ", " + (cy + by - ax) + "<br/>"); // This code is contributed by susmitakundugoaldanga </script> Output: 4, -4 6, 4 -2, 1 Time Complexity: O(1) vt_m susmitakundugoaldanga Geometric Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping) Line Clipping | Set 1 (Cohen–Sutherland Algorithm) Convex Hull | Set 2 (Graham Scan) Check whether a given point lies inside a triangle or not Convex Hull using Divide and Conquer Algorithm Program for Fibonacci numbers C++ Data Types Write a program to print all permutations of a given string Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 26535, "s": 26504, "text": " \n24 Nov, 2021\n" }, { "code": null, "e": 26742, "s": 26535, "text": "Find the all the possible coordinate from the given three coordinates to make a parallelogram of a non-zero area.Let’s call A,B,C are the three given points. We can have only the three possible situations: " }, { "code": null, "e": 26873, "s": 26742, "text": "(1) AB and AC are sides, and BC a diagonal\n(2) AB and BC are sides, and AC a diagonal \n(3) BC and AC are sides, and AB a diagonal " }, { "code": null, "e": 27165, "s": 26873, "text": "Hence, we can say that only 3 coordinates are possible from which we can generate a parallelogram if three coordinates are given.To prove that all the three points are different let’s suppose it’s wrong. Without losing of generality suppose that the points got in cases AD and BC are equal. " }, { "code": null, "e": 27238, "s": 27165, "text": "Consider the system of two equations for the equality of these points: " }, { "code": null, "e": 27337, "s": 27238, "text": "Bx + Cx - Ax = Ax + Cx - Bx\nBy + Cy - Ay = Ay + Cy - By\n\nIt can be simplified as-\n\nAx = Bx\nAy = By" }, { "code": null, "e": 27405, "s": 27337, "text": "And we got a contradiction, as all the points A, B, C are distinct." }, { "code": null, "e": 27416, "s": 27405, "text": "Examples: " }, { "code": null, "e": 27620, "s": 27416, "text": "Input : A = (0 0)\n B = (1 0)\n C = (0 1)\nOutput : 1 -1\n -1 1\n 1 1\n\nInput : A = (-1 -1)\n B = (0 1)\n C = (1 1)\nOutput : -2 -1\n 0 -1\n 2 3" }, { "code": null, "e": 27743, "s": 27622, "text": "Since the opposite sides are equal, AD = BC and AB = CD, we can calculate the co-ordinates of the missing point (D) as: " }, { "code": null, "e": 27828, "s": 27743, "text": "AD = BC\n(Dx - Ax, Dy - Ay) = (Cx - Bx, Cy - By)\nDx = Ax + Cx - Bx \nDy = Ay + Cy - By" }, { "code": null, "e": 28054, "s": 27828, "text": "The cases where the diagonals are AD and BC, CD and AB are processed in the same way.Reference: https://math.stackexchange.com/questions/1322535/how-many-different-parallelograms-can-be-drawn-if-given-three-co-ordinates-in-3d" }, { "code": null, "e": 28103, "s": 28054, "text": "Below is the implementation of above approach: " }, { "code": null, "e": 28107, "s": 28103, "text": "C++" }, { "code": null, "e": 28112, "s": 28107, "text": "Java" }, { "code": null, "e": 28120, "s": 28112, "text": "Python3" }, { "code": null, "e": 28123, "s": 28120, "text": "C#" }, { "code": null, "e": 28127, "s": 28123, "text": "PHP" }, { "code": null, "e": 28138, "s": 28127, "text": "Javascript" }, { "code": "\n\n\n\n\n\n\n// C++ program to all possible points \n// of a parallelogram \n#include <bits/stdc++.h> \nusing namespace std; \n \n// main method \nint main() \n{ \n int ax = 5, ay = 0; //coordinates of A \n int bx = 1, by = 1; //coordinates of B \n int cx = 2, cy = 5; //coordinates of C \n cout << ax + bx - cx << \", \"\n << ay + by - cy <<endl; \n cout << ax + cx - bx << \", \"\n << ay + cy - by <<endl; \n cout << cx + bx - ax << \", \"\n << cy + by - ax <<endl; \n return 0; \n} \n\n\n\n\n\n", "e": 28654, "s": 28148, "text": null }, { "code": "\n\n\n\n\n\n\n// Java program to all possible \n// points of a parallelogram \npublic class ParallelogramPoints{ \n \n // Driver code \n public static void main(String[] s) \n { \n int ax = 5, ay = 0; //coordinates of A \n int bx = 1, by = 1; //coordinates of B \n int cx = 2, cy = 5; //coordinates of C \n System.out.println(ax + bx - cx + \", \" \n + (ay + by - cy)); \n System.out.println(ax + cx - bx + \", \"\n + (ay + cy - by)); \n System.out.println(cx + bx - ax + \", \"\n + (cy + by - ax)); \n } \n} \n \n// This code is contributed by Prerna Saini \n\n\n\n\n\n", "e": 29337, "s": 28664, "text": null }, { "code": "\n\n\n\n\n\n\n# Python3 program to find all possible points \n# of a parallelogram \n \nax = 5\nay = 0 #coordinates of A \nbx = 1\nby = 1 #coordinates of B \ncx = 2\ncy = 5 #coordinates of C \nprint(ax + bx - cx, \", \", ay + by - cy) \nprint(ax + cx - bx, \", \", ay + cy - by) \nprint(cx + bx - ax, \", \", cy + by - ax) \n\n\n\n\n\n", "e": 29654, "s": 29347, "text": null }, { "code": "\n\n\n\n\n\n\n// C# program to all possible \n// points of a parallelogram \nusing System; \n \npublic class ParallelogramPoints \n{ \n \n // Driver code \n public static void Main() \n { \n \n //coordinates of A \n int ax = 5, ay = 0; \n \n //coordinates of B \n int bx = 1, by = 1; \n \n //coordinates of C \n int cx = 2, cy = 5; \n \n Console.WriteLine(ax + bx - cx + \", \"\n + (ay + by - cy)); \n Console.WriteLine(ax + cx - bx + \", \"\n + (ay + cy - by)); \n Console.WriteLine(cx + bx - ax + \", \"\n + (cy + by - ax)); \n } \n} \n \n// This code is contributed by vt_m. \n\n\n\n\n\n", "e": 30399, "s": 29664, "text": null }, { "code": "\n\n\n\n\n\n\n<?php \n// PHP program to all \n// possible points \n// of a parallelogram \n \n// Driver Code \n \n//coordinates of A \n$ax = 5; $ay = 0; \n \n//coordinates of B \n$bx = 1; $by = 1; \n \n//coordinates of C \n$cx = 2; $cy = 5; \n \n echo $ax + $bx - $cx , \", \"\n , $ay + $by - $cy ,\"\\n\"; \n echo $ax + $cx - $bx , \", \"\n , $ay + $cy - $by,\"\\n\" ; \n echo $cx + $bx - $ax , \", \"\n , $cy + $by - $ax ; \n \n// This code is contributed by anuj_67. \n?> \n\n\n\n\n\n", "e": 30888, "s": 30409, "text": null }, { "code": "\n\n\n\n\n\n\n<script> \n \n// JavaScript program to all possible \n// points of a parallelogram \n \n// Driver Code \nlet ax = 5, ay = 0; // Coordinates of A \nlet bx = 1, by = 1; // Coordinates of B \nlet cx = 2, cy = 5; // Coordinates of C \n \ndocument.write(ax + bx - cx + \", \" + \n (ay + by - cy) + \"<br/>\"); \ndocument.write(ax + cx - bx + \", \" + \n (ay + cy - by) + \"<br/>\"); \ndocument.write(cx + bx - ax + \", \" + \n (cy + by - ax) + \"<br/>\"); \n \n// This code is contributed by susmitakundugoaldanga \n \n</script> \n\n\n\n\n\n", "e": 31480, "s": 30898, "text": null }, { "code": null, "e": 31489, "s": 31480, "text": "Output: " }, { "code": null, "e": 31506, "s": 31489, "text": "4, -4\n6, 4\n-2, 1" }, { "code": null, "e": 31529, "s": 31506, "text": "Time Complexity: O(1) " }, { "code": null, "e": 31534, "s": 31529, "text": "vt_m" }, { "code": null, "e": 31556, "s": 31534, "text": "susmitakundugoaldanga" }, { "code": null, "e": 31568, "s": 31556, "text": "\nGeometric\n" }, { "code": null, "e": 31583, "s": 31568, "text": "\nMathematical\n" }, { "code": null, "e": 31788, "s": 31583, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 31841, "s": 31788, "text": "Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)" }, { "code": null, "e": 31892, "s": 31841, "text": "Line Clipping | Set 1 (Cohen–Sutherland Algorithm)" }, { "code": null, "e": 31926, "s": 31892, "text": "Convex Hull | Set 2 (Graham Scan)" }, { "code": null, "e": 31984, "s": 31926, "text": "Check whether a given point lies inside a triangle or not" }, { "code": null, "e": 32031, "s": 31984, "text": "Convex Hull using Divide and Conquer Algorithm" }, { "code": null, "e": 32061, "s": 32031, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 32076, "s": 32061, "text": "C++ Data Types" }, { "code": null, "e": 32137, "s": 32076, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 32180, "s": 32137, "text": "Set in C++ Standard Template Library (STL)" } ]
How ‘Big’ should be your Data?. An experimental study on how size of... | by Monik Raj | Towards Data Science
A simple question, that comes to all data scientists’ mind while designing a machine learning model is, “How big should be the data set? How many features should be used for modelling?”. This article will walk you through an experimental study of how you can make decisions on data set size and number of features required for model. Below is the link to my github repository. It contains the python codes used for the analysis. You can fork or clone the repository and get your hands dirty with code :-P github.com Below is the link to the data repository from UCI Machine Learning Repository. It contains the information related to data set and attributes. Here it mentions that, the problem is a regression problem. https://archive.ics.uci.edu/ml/datasets/Physicochemical+Properties+of+Protein+Tertiary+Structure Description of DatasetDataset inititally has 10 columns. Column with name 'RMSD' is the target column of our data setRest 9 columns with name F1, F2, ... , F9 are the features columns of the data set. m = Number of observations in the data setDimension of Y : m X 1Dimension of X : m X 9 Now, I will show you the correlation matrix between every column of the data frame, including RMSD (Data frame is a terminology to denote the data set read by Pandas module of Python). From the above figure, we can conclude that RMSD is pretty much independent with other columns, since theory says if, correlation(x,y)~0, then ‘x’ and ‘y’ are independent of each other (where ‘x’ and ‘y’ are vectors of same dimension). In cases, where we don’t know which column is to be selected as the target column, we can find the correlation matrix and find the column which is mostly independent with all the other columns. Here is the Correlation matrix plot between all the feature columns in X. For column ‘i’ and column ‘j’ of X, it shows the scatter plot between the two variabls, when ‘i’ != ‘j’. If ‘i’==’j’, then it shows the frequency distribution of the variable. The above figure tells about the relationship between the variables with each other. From the same, we can graphically infer about the correlation between matrix for better analysis. Frequency distribution of the variables shows about the kind of distribution it follows, and if follows a known and standard distribution like ‘Gaussian’ distribution or ‘Rayleigh’ distribution, we can predict and analyze the behaviour of the variable, which can be handy in further investigation of the data. Note: Frequency distribution of the variable or Histogram are generally used for fitting a variable to a standard distribution. Now I would like to draw your attention towards feature selection. Here I will throw light on method to decide which features to keep. I am going to use SelectKBest module of Sci-kit learn module from Python to do so. They use F-test estimates to find the best features from the data set. More information on the module and theory can be found in the reference. from sklearn.feature_selection import SelectKBest, f_regression#Assuming X and Y are numpy array of dimension (m,9) and (m,1) #respectively#We use f_regression function since our's is a regression problemX_best = SelectKBest(f_regression, k=5).fit_transform(X,Y)'''After the code snippet is run, X_best keeps top k=5 features from X.''' I will now show you the effect of best ‘k’ features on ‘R2-score’ metric of the model using linear regression. Here you can see that by increasing the value of ‘k’, we get better R2-score for our linear regression model. I have also stored the descending order of features with respect to ‘SelectKBest’ method. The code for same can be found in my github link above. With this, we can select a suitable value of ‘k’ for a corresponding value of R2-score of the model, which is acceptable for our problem statement (I may go with k=5, but for you, it may differ as per the demand of the problem). Here is the list of ‘k’ features in descending order : [F3, F4, F2, F9, F6, F1, F5, F7, F8] One of the major application of Feature Selection is to reduce dimensionality of the data, for better computation performance. Principal Component Analysis is another method to decompose the dimensions (features) into smaller dimension spcace. Major benefits of using Principal Component Analysis are: Dimensionality reduction Visualization of higher dimension space data by converting it to lower dimension space data Below are the visualizations of the data after decomposing higher dimension space into lower dimension space (for ‘X’). I will now show you the effect of projecting data onto ‘p’ components feature space, on ‘R2-score’ metric of the model using linear regression. Here you can see that by increasing the value of ‘p’, we get better R2-score for our linear regression model. Looking at the graph, we can select a suitable value of ‘p’ for our solution. The value of ‘p’ should be selected by corresponding acceptable value of R2-score, as per the requirement of the problem. Now I will discuss the effect of the size of data set, ‘m’ = Number of observations in data set. I have kept the 9 features, as originally present in the data set, I have varied the ‘m’, trained on train set(80%) and calculated the R2-score for each ‘m’ on test set(20%) using linear regression model. Analyzing the above graph, we can infer the following things: Inital spike in R2-score is because of the bias in data because of the lower ‘m’. Following the spike, the R2-score saturates to some extent (ignoring the intermediate spikes, which is because of the random selection of data points while splitting into ‘m’ %), which says gradually increasing the data set size, eventually increases the R2-score, till saturation. After a certain point, it saturates and increasing the ‘m’, doesn’t affect the R2-score. Lower ‘m’ results in either bias in model or lower R2-score. Designing a machine learning model includes many factors like selection of features, deciding on size of data for better performance of model, computation costs, feasibility in achieving real time data (for some cases), and many more as per the requirement of the problem. It’s always a exploratory analysis of the data, which leads to a better model design, because Every problem is different in Machine learning Reference: Sci-kit Module : http://scikit-learn.orgSelectKBest Module : http://scikit-learn.org/stable/modules/feature_selection.htmlPandas Module : https://pandas.pydata.org/pandas-docs/stable/Seaborn Module for visualization : https://seaborn.pydata.org/Principal Component Analysis : https://en.wikipedia.org/wiki/Principal_component_analysis Sci-kit Module : http://scikit-learn.org SelectKBest Module : http://scikit-learn.org/stable/modules/feature_selection.html Pandas Module : https://pandas.pydata.org/pandas-docs/stable/ Seaborn Module for visualization : https://seaborn.pydata.org/ Principal Component Analysis : https://en.wikipedia.org/wiki/Principal_component_analysis
[ { "code": null, "e": 506, "s": 172, "text": "A simple question, that comes to all data scientists’ mind while designing a machine learning model is, “How big should be the data set? How many features should be used for modelling?”. This article will walk you through an experimental study of how you can make decisions on data set size and number of features required for model." }, { "code": null, "e": 677, "s": 506, "text": "Below is the link to my github repository. It contains the python codes used for the analysis. You can fork or clone the repository and get your hands dirty with code :-P" }, { "code": null, "e": 688, "s": 677, "text": "github.com" }, { "code": null, "e": 891, "s": 688, "text": "Below is the link to the data repository from UCI Machine Learning Repository. It contains the information related to data set and attributes. Here it mentions that, the problem is a regression problem." }, { "code": null, "e": 988, "s": 891, "text": "https://archive.ics.uci.edu/ml/datasets/Physicochemical+Properties+of+Protein+Tertiary+Structure" }, { "code": null, "e": 1276, "s": 988, "text": "Description of DatasetDataset inititally has 10 columns. Column with name 'RMSD' is the target column of our data setRest 9 columns with name F1, F2, ... , F9 are the features columns of the data set. m = Number of observations in the data setDimension of Y : m X 1Dimension of X : m X 9" }, { "code": null, "e": 1461, "s": 1276, "text": "Now, I will show you the correlation matrix between every column of the data frame, including RMSD (Data frame is a terminology to denote the data set read by Pandas module of Python)." }, { "code": null, "e": 1697, "s": 1461, "text": "From the above figure, we can conclude that RMSD is pretty much independent with other columns, since theory says if, correlation(x,y)~0, then ‘x’ and ‘y’ are independent of each other (where ‘x’ and ‘y’ are vectors of same dimension)." }, { "code": null, "e": 1891, "s": 1697, "text": "In cases, where we don’t know which column is to be selected as the target column, we can find the correlation matrix and find the column which is mostly independent with all the other columns." }, { "code": null, "e": 1965, "s": 1891, "text": "Here is the Correlation matrix plot between all the feature columns in X." }, { "code": null, "e": 2141, "s": 1965, "text": "For column ‘i’ and column ‘j’ of X, it shows the scatter plot between the two variabls, when ‘i’ != ‘j’. If ‘i’==’j’, then it shows the frequency distribution of the variable." }, { "code": null, "e": 2324, "s": 2141, "text": "The above figure tells about the relationship between the variables with each other. From the same, we can graphically infer about the correlation between matrix for better analysis." }, { "code": null, "e": 2634, "s": 2324, "text": "Frequency distribution of the variables shows about the kind of distribution it follows, and if follows a known and standard distribution like ‘Gaussian’ distribution or ‘Rayleigh’ distribution, we can predict and analyze the behaviour of the variable, which can be handy in further investigation of the data." }, { "code": null, "e": 2762, "s": 2634, "text": "Note: Frequency distribution of the variable or Histogram are generally used for fitting a variable to a standard distribution." }, { "code": null, "e": 3124, "s": 2762, "text": "Now I would like to draw your attention towards feature selection. Here I will throw light on method to decide which features to keep. I am going to use SelectKBest module of Sci-kit learn module from Python to do so. They use F-test estimates to find the best features from the data set. More information on the module and theory can be found in the reference." }, { "code": null, "e": 3461, "s": 3124, "text": "from sklearn.feature_selection import SelectKBest, f_regression#Assuming X and Y are numpy array of dimension (m,9) and (m,1) #respectively#We use f_regression function since our's is a regression problemX_best = SelectKBest(f_regression, k=5).fit_transform(X,Y)'''After the code snippet is run, X_best keeps top k=5 features from X.'''" }, { "code": null, "e": 3828, "s": 3461, "text": "I will now show you the effect of best ‘k’ features on ‘R2-score’ metric of the model using linear regression. Here you can see that by increasing the value of ‘k’, we get better R2-score for our linear regression model. I have also stored the descending order of features with respect to ‘SelectKBest’ method. The code for same can be found in my github link above." }, { "code": null, "e": 4149, "s": 3828, "text": "With this, we can select a suitable value of ‘k’ for a corresponding value of R2-score of the model, which is acceptable for our problem statement (I may go with k=5, but for you, it may differ as per the demand of the problem). Here is the list of ‘k’ features in descending order : [F3, F4, F2, F9, F6, F1, F5, F7, F8]" }, { "code": null, "e": 4276, "s": 4149, "text": "One of the major application of Feature Selection is to reduce dimensionality of the data, for better computation performance." }, { "code": null, "e": 4451, "s": 4276, "text": "Principal Component Analysis is another method to decompose the dimensions (features) into smaller dimension spcace. Major benefits of using Principal Component Analysis are:" }, { "code": null, "e": 4476, "s": 4451, "text": "Dimensionality reduction" }, { "code": null, "e": 4568, "s": 4476, "text": "Visualization of higher dimension space data by converting it to lower dimension space data" }, { "code": null, "e": 4688, "s": 4568, "text": "Below are the visualizations of the data after decomposing higher dimension space into lower dimension space (for ‘X’)." }, { "code": null, "e": 4942, "s": 4688, "text": "I will now show you the effect of projecting data onto ‘p’ components feature space, on ‘R2-score’ metric of the model using linear regression. Here you can see that by increasing the value of ‘p’, we get better R2-score for our linear regression model." }, { "code": null, "e": 5142, "s": 4942, "text": "Looking at the graph, we can select a suitable value of ‘p’ for our solution. The value of ‘p’ should be selected by corresponding acceptable value of R2-score, as per the requirement of the problem." }, { "code": null, "e": 5444, "s": 5142, "text": "Now I will discuss the effect of the size of data set, ‘m’ = Number of observations in data set. I have kept the 9 features, as originally present in the data set, I have varied the ‘m’, trained on train set(80%) and calculated the R2-score for each ‘m’ on test set(20%) using linear regression model." }, { "code": null, "e": 5506, "s": 5444, "text": "Analyzing the above graph, we can infer the following things:" }, { "code": null, "e": 5588, "s": 5506, "text": "Inital spike in R2-score is because of the bias in data because of the lower ‘m’." }, { "code": null, "e": 5870, "s": 5588, "text": "Following the spike, the R2-score saturates to some extent (ignoring the intermediate spikes, which is because of the random selection of data points while splitting into ‘m’ %), which says gradually increasing the data set size, eventually increases the R2-score, till saturation." }, { "code": null, "e": 5959, "s": 5870, "text": "After a certain point, it saturates and increasing the ‘m’, doesn’t affect the R2-score." }, { "code": null, "e": 6020, "s": 5959, "text": "Lower ‘m’ results in either bias in model or lower R2-score." }, { "code": null, "e": 6387, "s": 6020, "text": "Designing a machine learning model includes many factors like selection of features, deciding on size of data for better performance of model, computation costs, feasibility in achieving real time data (for some cases), and many more as per the requirement of the problem. It’s always a exploratory analysis of the data, which leads to a better model design, because" }, { "code": null, "e": 6434, "s": 6387, "text": "Every problem is different in Machine learning" }, { "code": null, "e": 6445, "s": 6434, "text": "Reference:" }, { "code": null, "e": 6780, "s": 6445, "text": "Sci-kit Module : http://scikit-learn.orgSelectKBest Module : http://scikit-learn.org/stable/modules/feature_selection.htmlPandas Module : https://pandas.pydata.org/pandas-docs/stable/Seaborn Module for visualization : https://seaborn.pydata.org/Principal Component Analysis : https://en.wikipedia.org/wiki/Principal_component_analysis" }, { "code": null, "e": 6821, "s": 6780, "text": "Sci-kit Module : http://scikit-learn.org" }, { "code": null, "e": 6904, "s": 6821, "text": "SelectKBest Module : http://scikit-learn.org/stable/modules/feature_selection.html" }, { "code": null, "e": 6966, "s": 6904, "text": "Pandas Module : https://pandas.pydata.org/pandas-docs/stable/" }, { "code": null, "e": 7029, "s": 6966, "text": "Seaborn Module for visualization : https://seaborn.pydata.org/" } ]
How to remove an item from the List in Python? - GeeksforGeeks
29 Aug, 2020 Python Lists have various in-built methods to remove items from the list. Apart from these, we can also use del statement to remove an element from the list by specifying a position. Let’s look at these methods – Method 1: Using del statementThe del statement is not a function of List. Items of the list can be deleted using del statement by specifying the index of item (element) to be deleted. # Python 3 code to# remove an item from list# using del statement lst = ['Iris', 'Orchids', 'Rose', 'Lavender', 'Lily', 'Carnations']print("Original List is :", lst) # using del statement# to delete item (Orchids at index 1) # from the listdel lst[1]print("After deleting the item :", lst) Output: Original List is : [‘Iris’, ‘Orchids’, ‘Rose’, ‘Lavender’, ‘Lily’, ‘Carnations’]After deleting the item : [‘Iris’, ‘Rose’, ‘Lavender’, ‘Lily’, ‘Carnations’] Method 2: Using remove()We can remove an item from the list by passing the value of the item to be deleted as the parameter to remove() function. # Python 3 code to# remove an item from list# using function remove() lst = ['Iris', 'Orchids', 'Rose', 'Lavender', 'Lily', 'Carnations']print("Original List is :", lst) # using remove()# to delete item ('Orchids') # from the listlst.remove('Orchids')print("After deleting the item :", lst) Output: Original List is : [‘Iris’, ‘Orchids’, ‘Rose’, ‘Lavender’, ‘Lily’, ‘Carnations’]After deleting the item : [‘Iris’, ‘Rose’, ‘Lavender’, ‘Lily’, ‘Carnations’] Method 3: Using pop()pop() is also a method of list. We can remove the element at the specified index and get the value of that element using pop(). # Python 3 code to# remove an item from list# using function pop() lst = ['Iris', 'Orchids', 'Rose', 'Lavender', 'Lily', 'Carnations']print("Original List is :", lst) # using pop()# to delete item ('Orchids' at index 1) # from the lista = lst.pop(1)print("Item popped :", a)print("After deleting the item :", lst) Output – Original List is : [‘Iris’, ‘Orchids’, ‘Rose’, ‘Lavender’, ‘Lily’, ‘Carnations’]Item popped : OrchidsAfter deleting the item : [‘Iris’, ‘Rose’, ‘Lavender’, ‘Lily’, ‘Carnations’] python-list python-list-functions Python python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() Reading and Writing to text files in Python Create a Pandas DataFrame from Lists *args and **kwargs in Python Check if element exists in list in Python Convert integer to string in Python
[ { "code": null, "e": 24452, "s": 24424, "text": "\n29 Aug, 2020" }, { "code": null, "e": 24665, "s": 24452, "text": "Python Lists have various in-built methods to remove items from the list. Apart from these, we can also use del statement to remove an element from the list by specifying a position. Let’s look at these methods –" }, { "code": null, "e": 24849, "s": 24665, "text": "Method 1: Using del statementThe del statement is not a function of List. Items of the list can be deleted using del statement by specifying the index of item (element) to be deleted." }, { "code": "# Python 3 code to# remove an item from list# using del statement lst = ['Iris', 'Orchids', 'Rose', 'Lavender', 'Lily', 'Carnations']print(\"Original List is :\", lst) # using del statement# to delete item (Orchids at index 1) # from the listdel lst[1]print(\"After deleting the item :\", lst)", "e": 25147, "s": 24849, "text": null }, { "code": null, "e": 25155, "s": 25147, "text": "Output:" }, { "code": null, "e": 25312, "s": 25155, "text": "Original List is : [‘Iris’, ‘Orchids’, ‘Rose’, ‘Lavender’, ‘Lily’, ‘Carnations’]After deleting the item : [‘Iris’, ‘Rose’, ‘Lavender’, ‘Lily’, ‘Carnations’]" }, { "code": null, "e": 25458, "s": 25312, "text": "Method 2: Using remove()We can remove an item from the list by passing the value of the item to be deleted as the parameter to remove() function." }, { "code": "# Python 3 code to# remove an item from list# using function remove() lst = ['Iris', 'Orchids', 'Rose', 'Lavender', 'Lily', 'Carnations']print(\"Original List is :\", lst) # using remove()# to delete item ('Orchids') # from the listlst.remove('Orchids')print(\"After deleting the item :\", lst)", "e": 25757, "s": 25458, "text": null }, { "code": null, "e": 25765, "s": 25757, "text": "Output:" }, { "code": null, "e": 25922, "s": 25765, "text": "Original List is : [‘Iris’, ‘Orchids’, ‘Rose’, ‘Lavender’, ‘Lily’, ‘Carnations’]After deleting the item : [‘Iris’, ‘Rose’, ‘Lavender’, ‘Lily’, ‘Carnations’]" }, { "code": null, "e": 26071, "s": 25922, "text": "Method 3: Using pop()pop() is also a method of list. We can remove the element at the specified index and get the value of that element using pop()." }, { "code": "# Python 3 code to# remove an item from list# using function pop() lst = ['Iris', 'Orchids', 'Rose', 'Lavender', 'Lily', 'Carnations']print(\"Original List is :\", lst) # using pop()# to delete item ('Orchids' at index 1) # from the lista = lst.pop(1)print(\"Item popped :\", a)print(\"After deleting the item :\", lst)", "e": 26394, "s": 26071, "text": null }, { "code": null, "e": 26403, "s": 26394, "text": "Output –" }, { "code": null, "e": 26581, "s": 26403, "text": "Original List is : [‘Iris’, ‘Orchids’, ‘Rose’, ‘Lavender’, ‘Lily’, ‘Carnations’]Item popped : OrchidsAfter deleting the item : [‘Iris’, ‘Rose’, ‘Lavender’, ‘Lily’, ‘Carnations’]" }, { "code": null, "e": 26593, "s": 26581, "text": "python-list" }, { "code": null, "e": 26615, "s": 26593, "text": "python-list-functions" }, { "code": null, "e": 26622, "s": 26615, "text": "Python" }, { "code": null, "e": 26634, "s": 26622, "text": "python-list" }, { "code": null, "e": 26732, "s": 26634, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26764, "s": 26732, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26786, "s": 26764, "text": "Enumerate() in Python" }, { "code": null, "e": 26828, "s": 26786, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26858, "s": 26828, "text": "Iterate over a list in Python" }, { "code": null, "e": 26884, "s": 26858, "text": "Python String | replace()" }, { "code": null, "e": 26928, "s": 26884, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 26965, "s": 26928, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 26994, "s": 26965, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27036, "s": 26994, "text": "Check if element exists in list in Python" } ]
Finding cabs nearby using Great Circle Distance formula
19 Jan, 2018 Given GPS co-ordinates(in degrees) of a person who needs a cab and co-ordinates of all the cabs in the city stored in a text file in JSON format, find the user-id and name of all the cab drivers available in 50 km proximity. Examples: Input : file customers.json which contains GPS co-ordinates of a person who needs a cab in degrees and co-ordinates of all the cabs in the city stored in a text file in JSON format. Output : file answers.json which contains user-id and Name of all the cab drivers available in 50 km proximity stored in a new file. Approach Used:1. Obtain latitude and longitude of each cab in string format along with theiruser-id and name from the JSON encoded input file. 2. Convert latitude and longitude of the cab present in string format to double. 3. Convert latitude and longitude of both, the user and the cab present indegrees to radians. 4. Calculate distance between the user’s location and the cab using Great CircleDistance formula. 5. If distance is found to be less than or equal to 50 kms then output the user-id and name of the cab driver to a new file else take no action. Procedure to run the program :1. Save the code and the file customers.json in a same location.2. Now, compile the code(using cmd : g++ file_name.cpp) and run it(using cmd : ./a.out /home/gfg/customers.json) with passing file name customers.json along with proper location(e.g. /home/gfg/customers.json).3. A file named answers.json will be created on the same location where code and customers.json file is existing. // C++ code to find cabs nearby#include <bits/stdc++.h>using namespace std; // Latitude of customer who needs a cab.#define lat1d 12.9611159 // Longitude of customer who needs a cab.#define lon1d 77.6362214 #define pi 3.14159265358979323846#define earth_radius 6371.0 ifstream customer_list ("customers.json");ofstream out ("answer.json"); // Function to convert degree to radian.double degtorad(double deg){ return ( deg * pi / 180);} // Function to calculate distance// between 2 given locations // using Great Circle Distance Formula.double distanceEarth(double lat2d, double lon2d){ double lat1, lon1, lat2, lon2, delta_lon, central_ang; lat1 = degtorad(lat1d); lon1 = degtorad(lon1d); lat2 = degtorad(lat2d); lon2 = degtorad(lon2d); delta_lon = lon2 - lon1; // great circle distance formula. central_ang = acos ( sin(lat1) * sin(lat2) + cos(lat1) * cos(lat2) * cos(delta_lon) ); return (earth_radius * central_ang);} // Structure which contains data and// functions for accessing and processing// data from the given customers.json file.struct json{ /* i and j are used to access various elements of the char arrays. x is used to measure the size of the element of latitude_as_string array. y is used to measure the size of the element of longitude_as_string array. m is used to measure the size of the element of id_as_string array. n is used to measure the size of the element of name array. f keeps count of " " " symbol. fi keeps count of " : " symbol. */ long long int length, i, j, x, y, m, n, f, fi, id[100000]; char latitude_as_string[1000], longitude_as_string[1000], id_as_string[1000], name[1000]; double lat2d, lon2d; // To get each line of customers.json // file as string. string line; // Function to check whether distance between // 2 points is less than 50km or not. void distance_calculator() { if (distanceEarth(lat2d, lon2d) <= 50.0000) { // Converting id to int format. id[i] = atoll(id_as_string); i++; out << "{\"user_id\": " << id[i - 1] << ", \"name\": " << name << "}" << endl; } } // Function to read various attributes // like latitude, longitude, name , id, // etc, from customers.json file. simplistic // approach is used to get JSON attributes. void json_parser() { if (customer_list.is_open()) { while (getline(customer_list, line)) { f = 0; x = 0; y = 0; fi = 0; m = 0, n = 0; length = line.size(); for (j = 0; j < length; j++) { if (line[j] == '"') f++; else if (line[j] == ':') fi++; // To get latitude of the location. if (f == 3) { j++; while (line[j] != '"') { latitude_as_string[x] = line[j]; x++; j++; } j--; latitude_as_string[x] = '\0'; } // To get longitude of the location. else if (f == 13) { j++; while (line[j] != '"') { longitude_as_string[y] = line[j]; y++; j++; } j--; longitude_as_string[y] = '\0'; } // To get id of the friend. if (fi == 2) { j += 2; while (line[j] != ',') { id_as_string[m] = line[j]; m++; j++; } j--; id_as_string[m] = '\0'; fi++; } // To get name of the friend. else if (fi == 4) { j += 2; while (line[j] != ',') { name[n] = line[j]; n++; j++; } j--; name[n] = '\0'; fi++; f += 2; } } // Converting latitude and longitude // in string to float. lat2d = atof(latitude_as_string); lon2d = atof(longitude_as_string); distance_calculator(); } } // closing stream of customer's file. customer_list.close(); // closing stream of answer's file. out.close(); }}; int main(){ // Creating object of the structure json json obj; // To read customers.json file. obj.json_parser(); return 0;} Input file (customers.json) : {"latitude": "12.986375", "user_id": 12, "name": "Chris", "longitude": "77.043701"} {"latitude": "11.92893", "user_id": 1, "name": "Alice", "longitude": "78.27699"} {"latitude": "11.8856167", "user_id": 2, "name": "Ian", "longitude": "78.4240911"} {"latitude": "12.3191841", "user_id": 3, "name": "Jack", "longitude": "78.5072391"} {"latitude": "13.807778", "user_id": 28, "name": "Charlie", "longitude": "76.714444"} {"latitude": "13.4692815", "user_id": 7, "name": "Frank", "longitude": "-9.436036"} {"latitude": "14.0894797", "user_id": 8, "name": "Eoin", "longitude": "77.18671"} {"latitude": "13.038056", "user_id": 26, "name": "Stephen", "longitude": "76.613889"} {"latitude": "14.1225", "user_id": 27, "name": "Enid", "longitude": "78.143333"} {"latitude": "13.1229599", "user_id": 6, "name": "Theresa", "longitude": "77.2701202"} {"latitude": "12.2559432", "user_id": 9, "name": "Jack", "longitude": "76.1048927"} {"latitude": "12.240382", "user_id": 10, "name": "Georgina", "longitude": "77.972413"} {"latitude": "13.2411022", "user_id": 4, "name": "Ian", "longitude": "77.238335"} {"latitude": "13.1302756", "user_id": 5, "name": "Nora", "longitude": "77.2397222"} {"latitude": "13.008769", "user_id": 11, "name": "Richard", "longitude": "77.1056711"} {"latitude": "13.1489345", "user_id": 31, "name": "Alan", "longitude": "77.8422408"} {"latitude": "13", "user_id": 13, "name": "Olive", "longitude": "76"} {"latitude": "11.999447", "user_id": 14, "name": "Helen", "longitude": "-9.742744"} {"latitude": "12.966", "user_id": 15, "name": "Michael", "longitude": "77.463"} {"latitude": "12.366037", "user_id": 16, "name": "Ian", "longitude": "78.179118"} {"latitude": "14.180238", "user_id": 17, "name": "Patricia", "longitude": "-5.920898"} {"latitude": "13.0033946", "user_id": 39, "name": "Lisa", "longitude": "77.3877505"} {"latitude": "12.228056", "user_id": 18, "name": "Bob", "longitude": "76.915833"} {"latitude": "14.133333", "user_id": 24, "name": "Rose", "longitude": "77.433333"} {"latitude": "55.033", "user_id": 19, "name": "Enid", "longitude": "78.112"} {"latitude": "13.121111", "user_id": 20, "name": "Enid", "longitude": "-9.831111"} {"latitude": "11.802", "user_id": 21, "name": "David", "longitude": "-9.442"} {"latitude": "14.374208", "user_id": 22, "name": "Charlie", "longitude": "78.371639"} {"latitude": "13.74412", "user_id": 29, "name": "Oliver", "longitude": "76.11167"} {"latitude": "13.761389", "user_id": 30, "name": "Nick", "longitude": "76.2875"} {"latitude": "14.080556", "user_id": 23, "name": "Eoin", "longitude": "77.361944"} {"latitude": "12.833502", "user_id": 25, "name": "David", "longitude": "78.122366"} Output File (answers.json) : {"user_id": 6, "name": "Theresa"} {"user_id": 5, "name": "Nora"} {"user_id": 31, "name": "Alan"} {"user_id": 15, "name": "Michael"} {"user_id": 39, "name": "Lisa"} Reference: Great Circle Distance C++ Programs Project Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Shallow Copy and Deep Copy in C++ C++ Program to check if a given String is Palindrome or not How to find the minimum and maximum element of a Vector using STL in C++? C++ Program for QuickSort delete keyword in C++ SDE SHEET - A Complete Guide for SDE Preparation Implementing Web Scraping in Python with BeautifulSoup Working with zip files in Python XML parsing in Python Python | Simple GUI calculator using Tkinter
[ { "code": null, "e": 54, "s": 26, "text": "\n19 Jan, 2018" }, { "code": null, "e": 279, "s": 54, "text": "Given GPS co-ordinates(in degrees) of a person who needs a cab and co-ordinates of all the cabs in the city stored in a text file in JSON format, find the user-id and name of all the cab drivers available in 50 km proximity." }, { "code": null, "e": 289, "s": 279, "text": "Examples:" }, { "code": null, "e": 471, "s": 289, "text": "Input : file customers.json which contains GPS co-ordinates of a person who needs a cab in degrees and co-ordinates of all the cabs in the city stored in a text file in JSON format." }, { "code": null, "e": 604, "s": 471, "text": "Output : file answers.json which contains user-id and Name of all the cab drivers available in 50 km proximity stored in a new file." }, { "code": null, "e": 747, "s": 604, "text": "Approach Used:1. Obtain latitude and longitude of each cab in string format along with theiruser-id and name from the JSON encoded input file." }, { "code": null, "e": 828, "s": 747, "text": "2. Convert latitude and longitude of the cab present in string format to double." }, { "code": null, "e": 922, "s": 828, "text": "3. Convert latitude and longitude of both, the user and the cab present indegrees to radians." }, { "code": null, "e": 1020, "s": 922, "text": "4. Calculate distance between the user’s location and the cab using Great CircleDistance formula." }, { "code": null, "e": 1165, "s": 1020, "text": "5. If distance is found to be less than or equal to 50 kms then output the user-id and name of the cab driver to a new file else take no action." }, { "code": null, "e": 1582, "s": 1165, "text": "Procedure to run the program :1. Save the code and the file customers.json in a same location.2. Now, compile the code(using cmd : g++ file_name.cpp) and run it(using cmd : ./a.out /home/gfg/customers.json) with passing file name customers.json along with proper location(e.g. /home/gfg/customers.json).3. A file named answers.json will be created on the same location where code and customers.json file is existing." }, { "code": "// C++ code to find cabs nearby#include <bits/stdc++.h>using namespace std; // Latitude of customer who needs a cab.#define lat1d 12.9611159 // Longitude of customer who needs a cab.#define lon1d 77.6362214 #define pi 3.14159265358979323846#define earth_radius 6371.0 ifstream customer_list (\"customers.json\");ofstream out (\"answer.json\"); // Function to convert degree to radian.double degtorad(double deg){ return ( deg * pi / 180);} // Function to calculate distance// between 2 given locations // using Great Circle Distance Formula.double distanceEarth(double lat2d, double lon2d){ double lat1, lon1, lat2, lon2, delta_lon, central_ang; lat1 = degtorad(lat1d); lon1 = degtorad(lon1d); lat2 = degtorad(lat2d); lon2 = degtorad(lon2d); delta_lon = lon2 - lon1; // great circle distance formula. central_ang = acos ( sin(lat1) * sin(lat2) + cos(lat1) * cos(lat2) * cos(delta_lon) ); return (earth_radius * central_ang);} // Structure which contains data and// functions for accessing and processing// data from the given customers.json file.struct json{ /* i and j are used to access various elements of the char arrays. x is used to measure the size of the element of latitude_as_string array. y is used to measure the size of the element of longitude_as_string array. m is used to measure the size of the element of id_as_string array. n is used to measure the size of the element of name array. f keeps count of \" \" \" symbol. fi keeps count of \" : \" symbol. */ long long int length, i, j, x, y, m, n, f, fi, id[100000]; char latitude_as_string[1000], longitude_as_string[1000], id_as_string[1000], name[1000]; double lat2d, lon2d; // To get each line of customers.json // file as string. string line; // Function to check whether distance between // 2 points is less than 50km or not. void distance_calculator() { if (distanceEarth(lat2d, lon2d) <= 50.0000) { // Converting id to int format. id[i] = atoll(id_as_string); i++; out << \"{\\\"user_id\\\": \" << id[i - 1] << \", \\\"name\\\": \" << name << \"}\" << endl; } } // Function to read various attributes // like latitude, longitude, name , id, // etc, from customers.json file. simplistic // approach is used to get JSON attributes. void json_parser() { if (customer_list.is_open()) { while (getline(customer_list, line)) { f = 0; x = 0; y = 0; fi = 0; m = 0, n = 0; length = line.size(); for (j = 0; j < length; j++) { if (line[j] == '\"') f++; else if (line[j] == ':') fi++; // To get latitude of the location. if (f == 3) { j++; while (line[j] != '\"') { latitude_as_string[x] = line[j]; x++; j++; } j--; latitude_as_string[x] = '\\0'; } // To get longitude of the location. else if (f == 13) { j++; while (line[j] != '\"') { longitude_as_string[y] = line[j]; y++; j++; } j--; longitude_as_string[y] = '\\0'; } // To get id of the friend. if (fi == 2) { j += 2; while (line[j] != ',') { id_as_string[m] = line[j]; m++; j++; } j--; id_as_string[m] = '\\0'; fi++; } // To get name of the friend. else if (fi == 4) { j += 2; while (line[j] != ',') { name[n] = line[j]; n++; j++; } j--; name[n] = '\\0'; fi++; f += 2; } } // Converting latitude and longitude // in string to float. lat2d = atof(latitude_as_string); lon2d = atof(longitude_as_string); distance_calculator(); } } // closing stream of customer's file. customer_list.close(); // closing stream of answer's file. out.close(); }}; int main(){ // Creating object of the structure json json obj; // To read customers.json file. obj.json_parser(); return 0;}", "e": 6974, "s": 1582, "text": null }, { "code": null, "e": 7004, "s": 6974, "text": "Input file (customers.json) :" }, { "code": null, "e": 9660, "s": 7004, "text": "{\"latitude\": \"12.986375\", \"user_id\": 12, \"name\": \"Chris\", \"longitude\": \"77.043701\"}\n{\"latitude\": \"11.92893\", \"user_id\": 1, \"name\": \"Alice\", \"longitude\": \"78.27699\"}\n{\"latitude\": \"11.8856167\", \"user_id\": 2, \"name\": \"Ian\", \"longitude\": \"78.4240911\"}\n{\"latitude\": \"12.3191841\", \"user_id\": 3, \"name\": \"Jack\", \"longitude\": \"78.5072391\"}\n{\"latitude\": \"13.807778\", \"user_id\": 28, \"name\": \"Charlie\", \"longitude\": \"76.714444\"}\n{\"latitude\": \"13.4692815\", \"user_id\": 7, \"name\": \"Frank\", \"longitude\": \"-9.436036\"}\n{\"latitude\": \"14.0894797\", \"user_id\": 8, \"name\": \"Eoin\", \"longitude\": \"77.18671\"}\n{\"latitude\": \"13.038056\", \"user_id\": 26, \"name\": \"Stephen\", \"longitude\": \"76.613889\"}\n{\"latitude\": \"14.1225\", \"user_id\": 27, \"name\": \"Enid\", \"longitude\": \"78.143333\"}\n{\"latitude\": \"13.1229599\", \"user_id\": 6, \"name\": \"Theresa\", \"longitude\": \"77.2701202\"}\n{\"latitude\": \"12.2559432\", \"user_id\": 9, \"name\": \"Jack\", \"longitude\": \"76.1048927\"}\n{\"latitude\": \"12.240382\", \"user_id\": 10, \"name\": \"Georgina\", \"longitude\": \"77.972413\"}\n{\"latitude\": \"13.2411022\", \"user_id\": 4, \"name\": \"Ian\", \"longitude\": \"77.238335\"}\n{\"latitude\": \"13.1302756\", \"user_id\": 5, \"name\": \"Nora\", \"longitude\": \"77.2397222\"}\n{\"latitude\": \"13.008769\", \"user_id\": 11, \"name\": \"Richard\", \"longitude\": \"77.1056711\"}\n{\"latitude\": \"13.1489345\", \"user_id\": 31, \"name\": \"Alan\", \"longitude\": \"77.8422408\"}\n{\"latitude\": \"13\", \"user_id\": 13, \"name\": \"Olive\", \"longitude\": \"76\"}\n{\"latitude\": \"11.999447\", \"user_id\": 14, \"name\": \"Helen\", \"longitude\": \"-9.742744\"}\n{\"latitude\": \"12.966\", \"user_id\": 15, \"name\": \"Michael\", \"longitude\": \"77.463\"}\n{\"latitude\": \"12.366037\", \"user_id\": 16, \"name\": \"Ian\", \"longitude\": \"78.179118\"}\n{\"latitude\": \"14.180238\", \"user_id\": 17, \"name\": \"Patricia\", \"longitude\": \"-5.920898\"}\n{\"latitude\": \"13.0033946\", \"user_id\": 39, \"name\": \"Lisa\", \"longitude\": \"77.3877505\"}\n{\"latitude\": \"12.228056\", \"user_id\": 18, \"name\": \"Bob\", \"longitude\": \"76.915833\"}\n{\"latitude\": \"14.133333\", \"user_id\": 24, \"name\": \"Rose\", \"longitude\": \"77.433333\"}\n{\"latitude\": \"55.033\", \"user_id\": 19, \"name\": \"Enid\", \"longitude\": \"78.112\"}\n{\"latitude\": \"13.121111\", \"user_id\": 20, \"name\": \"Enid\", \"longitude\": \"-9.831111\"}\n{\"latitude\": \"11.802\", \"user_id\": 21, \"name\": \"David\", \"longitude\": \"-9.442\"}\n{\"latitude\": \"14.374208\", \"user_id\": 22, \"name\": \"Charlie\", \"longitude\": \"78.371639\"}\n{\"latitude\": \"13.74412\", \"user_id\": 29, \"name\": \"Oliver\", \"longitude\": \"76.11167\"}\n{\"latitude\": \"13.761389\", \"user_id\": 30, \"name\": \"Nick\", \"longitude\": \"76.2875\"}\n{\"latitude\": \"14.080556\", \"user_id\": 23, \"name\": \"Eoin\", \"longitude\": \"77.361944\"}\n{\"latitude\": \"12.833502\", \"user_id\": 25, \"name\": \"David\", \"longitude\": \"78.122366\"}\n" }, { "code": null, "e": 9689, "s": 9660, "text": "Output File (answers.json) :" }, { "code": null, "e": 9854, "s": 9689, "text": "{\"user_id\": 6, \"name\": \"Theresa\"}\n{\"user_id\": 5, \"name\": \"Nora\"}\n{\"user_id\": 31, \"name\": \"Alan\"}\n{\"user_id\": 15, \"name\": \"Michael\"}\n{\"user_id\": 39, \"name\": \"Lisa\"}\n" }, { "code": null, "e": 9887, "s": 9854, "text": "Reference: Great Circle Distance" }, { "code": null, "e": 9900, "s": 9887, "text": "C++ Programs" }, { "code": null, "e": 9908, "s": 9900, "text": "Project" }, { "code": null, "e": 10006, "s": 9908, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10040, "s": 10006, "text": "Shallow Copy and Deep Copy in C++" }, { "code": null, "e": 10100, "s": 10040, "text": "C++ Program to check if a given String is Palindrome or not" }, { "code": null, "e": 10174, "s": 10100, "text": "How to find the minimum and maximum element of a Vector using STL in C++?" }, { "code": null, "e": 10200, "s": 10174, "text": "C++ Program for QuickSort" }, { "code": null, "e": 10222, "s": 10200, "text": "delete keyword in C++" }, { "code": null, "e": 10271, "s": 10222, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 10326, "s": 10271, "text": "Implementing Web Scraping in Python with BeautifulSoup" }, { "code": null, "e": 10359, "s": 10326, "text": "Working with zip files in Python" }, { "code": null, "e": 10381, "s": 10359, "text": "XML parsing in Python" } ]
Python PIL | MinFilter() and MaxFilter() method
25 Jun, 2019 PIL.ImageFilter.MinFilter() method creates a min filter. Picks the lowest pixel value in a window with the given size. Syntax: PIL.ImageFilter.MinFilter(size=3) Parameters: size: The kernel size, in pixels. Image used: # Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter # creating a image objectim1 = Image.open(r"C:\Users\sadow984\Desktop\download2.JPG") # applying the min filterim2 = im1.filter(ImageFilter.MinFilter(size = 3)) im2.show() Output: PIL.ImageFilter.MinFilter() method creates a max filter. Picks the largest pixel value in a window with the given size. Syntax: PIL.ImageFilter.MaxFilter(size=3) Parameters: size: The kernel size, in pixels. # Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter # creating a image objectim1 = Image.open(r"C:\Users\sadow984\Desktop\download2.JPG") # applying the max filterim2 = im1.filter(ImageFilter.MaxFilter(size = 3)) im2.show() Output: python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Jun, 2019" }, { "code": null, "e": 147, "s": 28, "text": "PIL.ImageFilter.MinFilter() method creates a min filter. Picks the lowest pixel value in a window with the given size." }, { "code": null, "e": 238, "s": 147, "text": "Syntax: PIL.ImageFilter.MinFilter(size=3)\n\nParameters: \nsize: The kernel size, in pixels.\n" }, { "code": null, "e": 250, "s": 238, "text": "Image used:" }, { "code": "# Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter # creating a image objectim1 = Image.open(r\"C:\\Users\\sadow984\\Desktop\\download2.JPG\") # applying the min filterim2 = im1.filter(ImageFilter.MinFilter(size = 3)) im2.show()", "e": 521, "s": 250, "text": null }, { "code": null, "e": 529, "s": 521, "text": "Output:" }, { "code": null, "e": 649, "s": 529, "text": "PIL.ImageFilter.MinFilter() method creates a max filter. Picks the largest pixel value in a window with the given size." }, { "code": null, "e": 740, "s": 649, "text": "Syntax: PIL.ImageFilter.MaxFilter(size=3)\n\nParameters: \nsize: The kernel size, in pixels.\n" }, { "code": "# Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter # creating a image objectim1 = Image.open(r\"C:\\Users\\sadow984\\Desktop\\download2.JPG\") # applying the max filterim2 = im1.filter(ImageFilter.MaxFilter(size = 3)) im2.show()", "e": 1011, "s": 740, "text": null }, { "code": null, "e": 1019, "s": 1011, "text": "Output:" }, { "code": null, "e": 1034, "s": 1019, "text": "python-utility" }, { "code": null, "e": 1041, "s": 1034, "text": "Python" }, { "code": null, "e": 1139, "s": 1041, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1157, "s": 1139, "text": "Python Dictionary" }, { "code": null, "e": 1199, "s": 1157, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1221, "s": 1199, "text": "Enumerate() in Python" }, { "code": null, "e": 1256, "s": 1221, "text": "Read a file line by line in Python" }, { "code": null, "e": 1282, "s": 1256, "text": "Python String | replace()" }, { "code": null, "e": 1314, "s": 1282, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1343, "s": 1314, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1370, "s": 1343, "text": "Python Classes and Objects" }, { "code": null, "e": 1400, "s": 1370, "text": "Iterate over a list in Python" } ]
PyQt5 – How to stop radio button from getting checked
22 Apr, 2020 In this article we will see how to stop the radio button for getting checked, some times there is a need of blocking a radio button so that user can’t check it. In order to stop the radio button from getting checked we have to change the check-able property of radio button and set it to False. Syntax : radio_button.setCheckable(False) Argument : It takes bool as argument Action : It will not allow button to get checked. Below is the implementation. # importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a radio button self.radio_button = QRadioButton(self) # setting geometry of radio button self.radio_button.setGeometry(200, 150, 120, 40) # setting text to radio button self.radio_button.setText("Radio Button") # changing check-able property of radio button self.radio_button.setCheckable(False) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Apr, 2020" }, { "code": null, "e": 189, "s": 28, "text": "In this article we will see how to stop the radio button for getting checked, some times there is a need of blocking a radio button so that user can’t check it." }, { "code": null, "e": 323, "s": 189, "text": "In order to stop the radio button from getting checked we have to change the check-able property of radio button and set it to False." }, { "code": null, "e": 365, "s": 323, "text": "Syntax : radio_button.setCheckable(False)" }, { "code": null, "e": 402, "s": 365, "text": "Argument : It takes bool as argument" }, { "code": null, "e": 452, "s": 402, "text": "Action : It will not allow button to get checked." }, { "code": null, "e": 481, "s": 452, "text": "Below is the implementation." }, { "code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a radio button self.radio_button = QRadioButton(self) # setting geometry of radio button self.radio_button.setGeometry(200, 150, 120, 40) # setting text to radio button self.radio_button.setText(\"Radio Button\") # changing check-able property of radio button self.radio_button.setCheckable(False) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 1515, "s": 481, "text": null }, { "code": null, "e": 1524, "s": 1515, "text": "Output :" }, { "code": null, "e": 1535, "s": 1524, "text": "Python-gui" }, { "code": null, "e": 1547, "s": 1535, "text": "Python-PyQt" }, { "code": null, "e": 1554, "s": 1547, "text": "Python" } ]
Python | Extract numbers from list of strings
25 Apr, 2019 Sometimes, we can data in many forms and we desire to perform both conversions and extractions of certain specific parts of a whole. One such issue can be extracting a number from a string and extending this, sometimes it can be more than just an element string but a list of it. Let’s discuss certain ways in which this can be solved. Method #1 : Using list comprehension + split() This particular problem can be solved using the list comprehension function to extend the logic to all the items and split function performs the task of splitting and to fetch the target desired element. # Python3 code to demonstrate# Extracting numbers from list of strings# using list comprehension + split() # initializing listtest_list = ['Rs. 24', 'Rs. 18', 'Rs. 8', 'Rs. 21'] # printing original listprint("The original list : " + str(test_list)) # using list comprehension + split()# Extracting numbers from list of stringsres = [int(sub.split('.')[1]) for sub in test_list] # print resultprint("The list after Extracting numbers : " + str(res)) The original list : ['Rs. 24', 'Rs. 18', 'Rs. 8', 'Rs. 21'] The list after Extracting numbers : [24, 18, 8, 21] Method #2 : Using join() + isnumeric() + list comprehension + map() This method is preferred in the instances in which it is not predefined that the numbers will be ordered in a particular way i.e, this method gives the flexibility of getting the number from whichever position possible. # Python3 code to demonstrate# Extracting numbers from list of strings# using join() + isnumeric() + list comprehension + map() # initializing listtest_list = ['Rs. 24', 'Rs. 18', 'Rs. 8', 'Rs. 21'] # printing original listprint("The original list : " + str(test_list)) # using join() + isnumeric() + list comprehension + map()# Extracting numbers from list of stringsres = list(map(lambda sub:int(''.join( [ele for ele in sub if ele.isnumeric()])), test_list)) # print resultprint("The list after Extracting numbers : " + str(res)) The original list : ['Rs. 24', 'Rs. 18', 'Rs. 8', 'Rs. 21'] The list after Extracting numbers : [24, 18, 8, 21] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Apr, 2019" }, { "code": null, "e": 364, "s": 28, "text": "Sometimes, we can data in many forms and we desire to perform both conversions and extractions of certain specific parts of a whole. One such issue can be extracting a number from a string and extending this, sometimes it can be more than just an element string but a list of it. Let’s discuss certain ways in which this can be solved." }, { "code": null, "e": 411, "s": 364, "text": "Method #1 : Using list comprehension + split()" }, { "code": null, "e": 615, "s": 411, "text": "This particular problem can be solved using the list comprehension function to extend the logic to all the items and split function performs the task of splitting and to fetch the target desired element." }, { "code": "# Python3 code to demonstrate# Extracting numbers from list of strings# using list comprehension + split() # initializing listtest_list = ['Rs. 24', 'Rs. 18', 'Rs. 8', 'Rs. 21'] # printing original listprint(\"The original list : \" + str(test_list)) # using list comprehension + split()# Extracting numbers from list of stringsres = [int(sub.split('.')[1]) for sub in test_list] # print resultprint(\"The list after Extracting numbers : \" + str(res))", "e": 1068, "s": 615, "text": null }, { "code": null, "e": 1181, "s": 1068, "text": "The original list : ['Rs. 24', 'Rs. 18', 'Rs. 8', 'Rs. 21']\nThe list after Extracting numbers : [24, 18, 8, 21]\n" }, { "code": null, "e": 1251, "s": 1183, "text": "Method #2 : Using join() + isnumeric() + list comprehension + map()" }, { "code": null, "e": 1471, "s": 1251, "text": "This method is preferred in the instances in which it is not predefined that the numbers will be ordered in a particular way i.e, this method gives the flexibility of getting the number from whichever position possible." }, { "code": "# Python3 code to demonstrate# Extracting numbers from list of strings# using join() + isnumeric() + list comprehension + map() # initializing listtest_list = ['Rs. 24', 'Rs. 18', 'Rs. 8', 'Rs. 21'] # printing original listprint(\"The original list : \" + str(test_list)) # using join() + isnumeric() + list comprehension + map()# Extracting numbers from list of stringsres = list(map(lambda sub:int(''.join( [ele for ele in sub if ele.isnumeric()])), test_list)) # print resultprint(\"The list after Extracting numbers : \" + str(res))", "e": 2013, "s": 1471, "text": null }, { "code": null, "e": 2126, "s": 2013, "text": "The original list : ['Rs. 24', 'Rs. 18', 'Rs. 8', 'Rs. 21']\nThe list after Extracting numbers : [24, 18, 8, 21]\n" }, { "code": null, "e": 2147, "s": 2126, "text": "Python list-programs" }, { "code": null, "e": 2154, "s": 2147, "text": "Python" }, { "code": null, "e": 2170, "s": 2154, "text": "Python Programs" } ]
GATE | GATE-CS-2017 (Set 1) | Question 30
13 Aug, 2021 Consider the C code fragment given below. typedef struct node { int data; node* next ; } node; void join(node* m, node* n) { node* p = n; while (p->next != NULL) { p = p->next; } p–>next = m; } Assuming that m and n point to valid NULL- terminated linked lists, invocation of join will(A) append list m to the end of list n for all inputs(B) either cause a null pointer dereference or append list m to the end of list n(C) cause a null pointer dereference for all inputs.(D) append list n to the end of list m for all inputs.Answer: (B)Explanation: As it is stated in the question, that m and n are valid Lists but not explicitly specified if the lists are empty or not. We can have two cases: Case 1: If lists are not NULL : Invocation of join will append list m to the end of list n if the lists are not NULL. For Example:Before join operation :m =1->2->3->4->5->nulln =6->7->8->9->nullAfter join operation :6->7->8->9->1->2->3->4->5->nullCase 2: If lists are NULL : If the list n is empty and itself NULL, then joining and referencing would obviously create NULL pointer issue. Case 1: If lists are not NULL : Invocation of join will append list m to the end of list n if the lists are not NULL. For Example:Before join operation :m =1->2->3->4->5->nulln =6->7->8->9->nullAfter join operation :6->7->8->9->1->2->3->4->5->null Case 2: If lists are NULL : If the list n is empty and itself NULL, then joining and referencing would obviously create NULL pointer issue. Therefore option B is correct GATE PYQs 2017 and 2018 with Shubham Agrawal | GeeksforGeeks GATE CSE - YouTubeGeeksforGeeks GATE Computer Science17.5K subscribersGATE PYQs 2017 and 2018 with Shubham Agrawal | GeeksforGeeks GATE CSEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:006:09 / 1:11:13•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=j9Vmf5yRw-I" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question GATE-CS-2017 (Set 1) GATE-GATE-CS-2017 (Set 1) GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | GATE-CS-2014-(Set-2) | Question 65 GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33 GATE | GATE CS 2008 | Question 46 GATE | GATE-CS-2015 (Set 3) | Question 65 GATE | GATE CS 2008 | Question 40 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE CS 1996 | Question 63 GATE | GATE CS 2011 | Question 49 GATE | GATE-CS-2014-(Set-1) | Question 51 GATE | GATE CS 1996 | Question 38
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Aug, 2021" }, { "code": null, "e": 70, "s": 28, "text": "Consider the C code fragment given below." }, { "code": null, "e": 260, "s": 70, "text": "typedef struct node\n{\n int data;\n node* next ;\n} node;\n\nvoid join(node* m, node* n)\n{\n node* p = n;\n while (p->next != NULL)\n {\n p = p->next;\n }\n p–>next = m;\n}\n" }, { "code": null, "e": 760, "s": 260, "text": "Assuming that m and n point to valid NULL- terminated linked lists, invocation of join will(A) append list m to the end of list n for all inputs(B) either cause a null pointer dereference or append list m to the end of list n(C) cause a null pointer dereference for all inputs.(D) append list n to the end of list m for all inputs.Answer: (B)Explanation: As it is stated in the question, that m and n are valid Lists but not explicitly specified if the lists are empty or not. We can have two cases:" }, { "code": null, "e": 1147, "s": 760, "text": "Case 1: If lists are not NULL : Invocation of join will append list m to the end of list n if the lists are not NULL. For Example:Before join operation :m =1->2->3->4->5->nulln =6->7->8->9->nullAfter join operation :6->7->8->9->1->2->3->4->5->nullCase 2: If lists are NULL : If the list n is empty and itself NULL, then joining and referencing would obviously create NULL pointer issue." }, { "code": null, "e": 1395, "s": 1147, "text": "Case 1: If lists are not NULL : Invocation of join will append list m to the end of list n if the lists are not NULL. For Example:Before join operation :m =1->2->3->4->5->nulln =6->7->8->9->nullAfter join operation :6->7->8->9->1->2->3->4->5->null" }, { "code": null, "e": 1535, "s": 1395, "text": "Case 2: If lists are NULL : If the list n is empty and itself NULL, then joining and referencing would obviously create NULL pointer issue." }, { "code": null, "e": 1565, "s": 1535, "text": "Therefore option B is correct" }, { "code": null, "e": 2536, "s": 1565, "text": "GATE PYQs 2017 and 2018 with Shubham Agrawal | GeeksforGeeks GATE CSE - YouTubeGeeksforGeeks GATE Computer Science17.5K subscribersGATE PYQs 2017 and 2018 with Shubham Agrawal | GeeksforGeeks GATE CSEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:006:09 / 1:11:13•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=j9Vmf5yRw-I\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question" }, { "code": null, "e": 2557, "s": 2536, "text": "GATE-CS-2017 (Set 1)" }, { "code": null, "e": 2583, "s": 2557, "text": "GATE-GATE-CS-2017 (Set 1)" }, { "code": null, "e": 2588, "s": 2583, "text": "GATE" }, { "code": null, "e": 2686, "s": 2588, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2728, "s": 2686, "text": "GATE | GATE-CS-2014-(Set-2) | Question 65" }, { "code": null, "e": 2790, "s": 2728, "text": "GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33" }, { "code": null, "e": 2824, "s": 2790, "text": "GATE | GATE CS 2008 | Question 46" }, { "code": null, "e": 2866, "s": 2824, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 2900, "s": 2866, "text": "GATE | GATE CS 2008 | Question 40" }, { "code": null, "e": 2942, "s": 2900, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 2976, "s": 2942, "text": "GATE | GATE CS 1996 | Question 63" }, { "code": null, "e": 3010, "s": 2976, "text": "GATE | GATE CS 2011 | Question 49" }, { "code": null, "e": 3052, "s": 3010, "text": "GATE | GATE-CS-2014-(Set-1) | Question 51" } ]
How to create tables in HTML?
To create table in HTML, use the <table> tag. A table consist of rows and columns, which can be set using one or more <tr>, <th>, and <td> elements. A table row is defined by the <tr> tag. To set table header, use the <th> tag. For a table cell, use the <td> tag. Just keep in mind, table attributes such as align, bgcolor, border, cellpadding, cellspacing deprecated and isn’t supported by HTML5. Do not use them. You can try the following code to create a table in HTML. We’re also using the <style> tag to style the table border <!DOCTYPE html> <html> <head> <style> table, th, td { border: 1px solid black; } </style> </head> <body> <h1>Programming Languages</h1> <table> <tr> <th>Language</th> <th>Release Year</th> </tr> <tr> <td>Java</td> <td>1995</td> </tr> <tr> <td>Pascal</td> <td>1970</td> </tr> </table> </body> </html>
[ { "code": null, "e": 1451, "s": 1187, "text": "To create table in HTML, use the <table> tag. A table consist of rows and columns, which can be set using one or more <tr>, <th>, and <td> elements. A table row is defined by the <tr> tag. To set table header, use the <th> tag. For a table cell, use the <td> tag." }, { "code": null, "e": 1602, "s": 1451, "text": "Just keep in mind, table attributes such as align, bgcolor, border, cellpadding, cellspacing deprecated and isn’t supported by HTML5. Do not use them." }, { "code": null, "e": 1719, "s": 1602, "text": "You can try the following code to create a table in HTML. We’re also using the <style> tag to style the table border" }, { "code": null, "e": 2218, "s": 1719, "text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n table, th, td {\n border: 1px solid black;\n }\n </style>\n </head>\n\n <body>\n <h1>Programming Languages</h1>\n <table>\n <tr>\n <th>Language</th>\n <th>Release Year</th>\n </tr>\n <tr>\n <td>Java</td>\n <td>1995</td>\n </tr>\n <tr>\n <td>Pascal</td>\n <td>1970</td>\n </tr>\n </table>\n </body>\n</html>" } ]
Kotlin Recursion
12 Jun, 2019 In this tutorial we will learn Kotlin Recursive function. Like other programming languages, we can use recursion in Kotlin.A function which calls itself is called as recursive function and this process of repetition is called recursion. Whenever a function is called then there are two possibilities – Normal function callRecursive function call Normal function call Recursive function call When a function is called from main() block then it is called a normal function call. In below example, sum() is called at a time and it executes its instruction and terminate with returning the sum of number. If we want to execute the function again then we should call sum() from the main block one more time. Calling sum() function from main() block – When a function calls itself then it is called recursive function call. Every recursive function should have terminate condition else program executions enters in infinite loop and results into stack overflow error. Calling callMe() function from its own block – Here, we have used terminate condition if( a > 0) else it enters the infinite loop. And it prints the value from 5 down to 0. Example 1: Find the factorial of a number without using terminate condition // Kotlin program of factorial using recursionfun Fact(num: Int):Long{ return num*Fact(num-1) // no terminate condition} //main methodfun main() { println("Factorial of 5 is: "+Fact(5))//Recursive call} Output: Exception in thread "main" java.lang.StackOverflowError Example 2: Find the factorial of a number with using terminate condition. // Kotlin program of factorial using recursionfun Fact(num: Int):Long{ return if(num==1) num.toLong() // terminate condition else num*Fact(num-1)}//main methodfun main() { println("Factorial of 5 is: "+Fact(5))//Recursive call} Output: Factorial of 5 is: 120 The recursive call of Fact() is explained step by step in the following figure:- Example 3: Find the sum of elements of an array using recursion // two parameters passed an array and size of arrayfun sum(args: Array<Int> , index:Int ):Int{ return if(index<=0) 0 else (sum(args ,index-1) + args[index-1]) // recursive function call} fun main() { // array initialization val array = arrayOf(1,2,3,4,5,6,7,8,9,10) // size of array val n = array.size val result = sum(array,n) // normal function call println("The sum of array elements is: $result")} Output: The sum of array elements is: 55 Explanation:Here, we have initialized an array and passed as an argument to the sum() function. In each recursive call the index value decrement by one. If the index equal to zero or less than then terminate it and return the sum of all the elements. Kotlin Functions Picked Kotlin Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Add Views Dynamically and Store Data in Arraylist in Android? Android RecyclerView in Kotlin How to Communicate Between Fragments in Android? Retrofit with Kotlin Coroutine in Android Kotlin constructor Suspend Function In Kotlin Coroutines MVP (Model View Presenter) Architecture Pattern in Android with Example Kotlin when expression Kotlin Android Tutorial
[ { "code": null, "e": 52, "s": 24, "text": "\n12 Jun, 2019" }, { "code": null, "e": 289, "s": 52, "text": "In this tutorial we will learn Kotlin Recursive function. Like other programming languages, we can use recursion in Kotlin.A function which calls itself is called as recursive function and this process of repetition is called recursion." }, { "code": null, "e": 354, "s": 289, "text": "Whenever a function is called then there are two possibilities –" }, { "code": null, "e": 398, "s": 354, "text": "Normal function callRecursive function call" }, { "code": null, "e": 419, "s": 398, "text": "Normal function call" }, { "code": null, "e": 443, "s": 419, "text": "Recursive function call" }, { "code": null, "e": 755, "s": 443, "text": "When a function is called from main() block then it is called a normal function call. In below example, sum() is called at a time and it executes its instruction and terminate with returning the sum of number. If we want to execute the function again then we should call sum() from the main block one more time." }, { "code": null, "e": 798, "s": 755, "text": "Calling sum() function from main() block –" }, { "code": null, "e": 1014, "s": 798, "text": "When a function calls itself then it is called recursive function call. Every recursive function should have terminate condition else program executions enters in infinite loop and results into stack overflow error." }, { "code": null, "e": 1061, "s": 1014, "text": "Calling callMe() function from its own block –" }, { "code": null, "e": 1187, "s": 1061, "text": "Here, we have used terminate condition if( a > 0) else it enters the infinite loop. And it prints the value from 5 down to 0." }, { "code": null, "e": 1263, "s": 1187, "text": "Example 1: Find the factorial of a number without using terminate condition" }, { "code": "// Kotlin program of factorial using recursionfun Fact(num: Int):Long{ return num*Fact(num-1) // no terminate condition} //main methodfun main() { println(\"Factorial of 5 is: \"+Fact(5))//Recursive call}", "e": 1477, "s": 1263, "text": null }, { "code": null, "e": 1485, "s": 1477, "text": "Output:" }, { "code": null, "e": 1541, "s": 1485, "text": "Exception in thread \"main\" java.lang.StackOverflowError" }, { "code": null, "e": 1615, "s": 1541, "text": "Example 2: Find the factorial of a number with using terminate condition." }, { "code": "// Kotlin program of factorial using recursionfun Fact(num: Int):Long{ return if(num==1) num.toLong() // terminate condition else num*Fact(num-1)}//main methodfun main() { println(\"Factorial of 5 is: \"+Fact(5))//Recursive call}", "e": 1859, "s": 1615, "text": null }, { "code": null, "e": 1867, "s": 1859, "text": "Output:" }, { "code": null, "e": 1890, "s": 1867, "text": "Factorial of 5 is: 120" }, { "code": null, "e": 1971, "s": 1890, "text": "The recursive call of Fact() is explained step by step in the following figure:-" }, { "code": null, "e": 2035, "s": 1971, "text": "Example 3: Find the sum of elements of an array using recursion" }, { "code": " // two parameters passed an array and size of arrayfun sum(args: Array<Int> , index:Int ):Int{ return if(index<=0) 0 else (sum(args ,index-1) + args[index-1]) // recursive function call} fun main() { // array initialization val array = arrayOf(1,2,3,4,5,6,7,8,9,10) // size of array val n = array.size val result = sum(array,n) // normal function call println(\"The sum of array elements is: $result\")}", "e": 2494, "s": 2035, "text": null }, { "code": null, "e": 2502, "s": 2494, "text": "Output:" }, { "code": null, "e": 2535, "s": 2502, "text": "The sum of array elements is: 55" }, { "code": null, "e": 2786, "s": 2535, "text": "Explanation:Here, we have initialized an array and passed as an argument to the sum() function. In each recursive call the index value decrement by one. If the index equal to zero or less than then terminate it and return the sum of all the elements." }, { "code": null, "e": 2803, "s": 2786, "text": "Kotlin Functions" }, { "code": null, "e": 2810, "s": 2803, "text": "Picked" }, { "code": null, "e": 2817, "s": 2810, "text": "Kotlin" }, { "code": null, "e": 2915, "s": 2817, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2984, "s": 2915, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 3015, "s": 2984, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 3064, "s": 3015, "text": "How to Communicate Between Fragments in Android?" }, { "code": null, "e": 3106, "s": 3064, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 3125, "s": 3106, "text": "Kotlin constructor" }, { "code": null, "e": 3163, "s": 3125, "text": "Suspend Function In Kotlin Coroutines" }, { "code": null, "e": 3235, "s": 3163, "text": "MVP (Model View Presenter) Architecture Pattern in Android with Example" }, { "code": null, "e": 3258, "s": 3235, "text": "Kotlin when expression" } ]
Largest Divisor for each element in an array other than 1 and the number itself
30 Jan, 2022 Given an array arr[] of N integers, the task is to find the largest divisor for each element in an array other than 1 and the number itself. If there is no such divisor, print -1. Examples: Input: arr[] = {5, 6, 7, 8, 9, 10} Output: -1 3 -1 4 3 5 Divisors(5) = {1, 5} -> Since there is no divisor other than 1 and the number itself, therefore largest divisor = -1 Divisors(6) = [1, 2, 3, 6] -> largest divisor other than 1 and the number itself = 3 Divisors(7) = [1, 7] -> Since there is no divisor other than 1 and the number itself, therefore largest divisor = -1 Divisors(8) = [1, 2, 4, 8] -> largest divisor other than 1 and the number itself = 4 Divisors(9) = [1, 3, 9] -> largest divisor other than 1 and the number itself = 3 Divisors(10) = [1, 2, 5, 10] -> largest divisor other than 1 and the number itself = 5 Input: arr[] = {15, 16, 17, 18, 19, 20, 21} Output: 5 8 -1 9 -1 10 7 Naive approach: The idea is to iterate over all the array elements and find the largest divisor for each of the element using the approach discussed in this article. Time Complexity: O(N * √N) Efficient approach: A better solution is to precompute the maximum divisor of the numbers from 2 to 105 and then just run a loop for array and print precomputed answer. Use Sieve of Eratosthenes to mark the prime numbers and store the smallest prime divisor of each number. Now largest divisor for any number will be number / smallest_prime_divisor. Find the Largest divisor for each number using the precomputed answer. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach #include <bits/stdc++.h>using namespace std; #define int long longconst int maxin = 100001; // Divisors array to keep track// of the maximum divisorint divisors[maxin]; // Function to pre-compute the prime// numbers and largest divisorsvoid Calc_Max_Div(int arr[], int n){ // Visited array to keep // track of prime numbers bool vis[maxin]; memset(vis, 1, maxin); // 0 and 1 are not prime numbers vis[0] = vis[1] = 0; // Initialising divisors[i] = i for (int i = 1; i <= maxin; i++) divisors[i] = i; // For all the numbers divisible by 2 // the maximum divisor will be number / 2 for (int i = 4; i <= maxin; i += 2) { vis[i] = 0; divisors[i] = i / 2; } for (int i = 3; i <= maxin; i += 2) { // If divisors[i] is not equal to i then // this means that divisors[i] contains // minimum prime divisor for the number if (divisors[i] != i) { // Update the answer to // i / smallest_prime_divisor[i] divisors[i] = i / divisors[i]; } // Condition if i is a prime number if (vis[i] == 1) { for (int j = i * i; j < maxin; j += i) { vis[j] = 0; // If divisors[j] is equal to j then // this means that i is the first prime // divisor for j so we update divi[j] = i if (divisors[j] == j) divisors[j] = i; } } } for (int i = 0; i < n; i++) { // If the current element is prime // then it has no divisors // other than 1 and itself if (divisors[arr[i]] == arr[i]) cout << "-1 "; else cout << divisors[arr[i]] << " "; }} // Driver codeint32_t main(){ int arr[] = { 5, 6, 7, 8, 9, 10 }; int n = sizeof(arr) / sizeof(int); Calc_Max_Div(arr, n); return 0;} // Java implementation of the approachclass GFG{ final static int maxin = 10001; // Divisors array to keep track // of the maximum divisor static int divisors[] = new int[maxin + 1]; // Function to pre-compute the prime // numbers and largest divisors static void Calc_Max_Div(int arr[], int n) { // Visited array to keep // track of prime numbers int vis[] = new int[maxin + 1]; for(int i = 0;i <maxin+1 ; i++) vis[i] = 1; // 0 and 1 are not prime numbers vis[0] = vis[1] = 0; // Initialising divisors[i] = i for (int i = 1; i <= maxin; i++) divisors[i] = i; // For all the numbers divisible by 2 // the maximum divisor will be number / 2 for (int i = 4; i <= maxin; i += 2) { vis[i] = 0; divisors[i] = i / 2; } for (int i = 3; i <= maxin; i += 2) { // If divisors[i] is not equal to i then // this means that divisors[i] contains // minimum prime divisor for the number if (divisors[i] != i) { // Update the answer to // i / smallest_prime_divisor[i] divisors[i] = i / divisors[i]; } // Condition if i is a prime number if (vis[i] == 1) { for (int j = i * i; j < maxin; j += i) { vis[j] = 0; // If divisors[j] is equal to j then // this means that i is the first prime // divisor for j so we update divi[j] = i if (divisors[j] == j) divisors[j] = i; } } } for (int i = 0; i < n; i++) { // If the current element is prime // then it has no divisors // other than 1 and itself if (divisors[arr[i]] == arr[i]) System.out.print("-1 "); else System.out.print(divisors[arr[i]] + " "); } } // Driver code public static void main (String[] args) { int []arr = { 5, 6, 7, 8, 9, 10 }; int n = arr.length; Calc_Max_Div(arr, n); }} // This code is contributed by AnkitRai01 # Python3 implementation of the approachmaxin = 100001; # Divisors array to keep track# of the maximum divisordivisors = [0] * (maxin + 1); # Function to pre-compute the prime# numbers and largest divisorsdef Calc_Max_Div(arr, n) : # Visited array to keep # track of prime numbers vis = [1] * (maxin + 1); # 0 and 1 are not prime numbers vis[0] = vis[1] = 0; # Initialising divisors[i] = i for i in range(1, maxin + 1) : divisors[i] = i; # For all the numbers divisible by 2 # the maximum divisor will be number / 2 for i in range(4 , maxin + 1, 2) : vis[i] = 0; divisors[i] = i // 2; for i in range(3, maxin + 1, 2) : # If divisors[i] is not equal to i then # this means that divisors[i] contains # minimum prime divisor for the number if (divisors[i] != i) : # Update the answer to # i / smallest_prime_divisor[i] divisors[i] = i // divisors[i]; # Condition if i is a prime number if (vis[i] == 1) : for j in range( i * i, maxin, i) : vis[j] = 0; # If divisors[j] is equal to j then # this means that i is the first prime # divisor for j so we update divi[j] = i if (divisors[j] == j) : divisors[j] = i; for i in range(n) : # If the current element is prime # then it has no divisors # other than 1 and itself if (divisors[arr[i]] == arr[i]) : print("-1 ", end = ""); else : print(divisors[arr[i]], end = " "); # Driver codeif __name__ == "__main__" : arr = [ 5, 6, 7, 8, 9, 10 ]; n = len(arr); Calc_Max_Div(arr, n); # This code is contributed by AnkitRai01 // C# implementation of the approachusing System; class GFG{ static int maxin = 10001; // Divisors array to keep track // of the maximum divisor static int []divisors = new int[maxin + 1]; // Function to pre-compute the prime // numbers and largest divisors static void Calc_Max_Div(int []arr, int n) { // Visited array to keep // track of prime numbers int []vis = new int[maxin + 1]; for(int i = 0; i < maxin + 1 ; i++) vis[i] = 1; // 0 and 1 are not prime numbers vis[0] = vis[1] = 0; // Initialising divisors[i] = i for (int i = 1; i <= maxin; i++) divisors[i] = i; // For all the numbers divisible by 2 // the maximum divisor will be number / 2 for (int i = 4; i <= maxin; i += 2) { vis[i] = 0; divisors[i] = i / 2; } for (int i = 3; i <= maxin; i += 2) { // If divisors[i] is not equal to i then // this means that divisors[i] contains // minimum prime divisor for the number if (divisors[i] != i) { // Update the answer to // i / smallest_prime_divisor[i] divisors[i] = i / divisors[i]; } // Condition if i is a prime number if (vis[i] == 1) { for (int j = i * i; j < maxin; j += i) { vis[j] = 0; // If divisors[j] is equal to j then // this means that i is the first prime // divisor for j so we update divi[j] = i if (divisors[j] == j) divisors[j] = i; } } } for (int i = 0; i < n; i++) { // If the current element is prime // then it has no divisors // other than 1 and itself if (divisors[arr[i]] == arr[i]) Console.Write("-1 "); else Console.Write(divisors[arr[i]] + " "); } } // Driver code public static void Main() { int []arr = { 5, 6, 7, 8, 9, 10 }; int n = arr.Length; Calc_Max_Div(arr, n); }} // This code is contributed by AnkitRai01 <script> // Javascript implementation of the approachvar maxin = 100001; // Divisors array to keep track// of the maximum divisorvar divisors = Array(maxin).fill(0); // Function to pre-compute the prime// numbers and largest divisorsfunction Calc_Max_Div(arr, n){ // Visited array to keep // track of prime numbers var vis = Array(maxin).fill(1); // 0 and 1 are not prime numbers vis[0] = vis[1] = 0; var i,j; // Initialising divisors[i] = i for(i = 1; i <= maxin; i++) divisors[i] = i; // For all the numbers divisible by 2 // the maximum divisor will be number / 2 for(i = 4; i <= maxin; i += 2) { vis[i] = 0; divisors[i] = i / 2; } for(i = 3; i <= maxin; i += 2) { // If divisors[i] is not equal to i then // this means that divisors[i] contains // minimum prime divisor for the number if (divisors[i] != i) { // Update the answer to // i / smallest_prime_divisor[i] divisors[i] = i / divisors[i]; } // Condition if i is a prime number if (vis[i] == 1) { for(j = i * i; j < maxin; j += i) { vis[j] = 0; // If divisors[j] is equal to j then // this means that i is the first prime // divisor for j so we update divi[j] = i if (divisors[j] == j) divisors[j] = i; } } } for(i = 0; i < n; i++) { // If the current element is prime // then it has no divisors // other than 1 and itself if (divisors[arr[i]] == arr[i]) document.write("-1 "); else document.write(divisors[arr[i]] + " "); }} // Driver codevar arr = [ 5, 6, 7, 8, 9, 10 ];var n = arr.length; Calc_Max_Div(arr, n); // This code is contributed by bgangwar59 </script> -1 3 -1 4 3 5 Time Complexity: O(N) Auxiliary Space: O(100001) ankthon bgangwar59 subham348 divisors Technical Scripter 2019 Arrays Mathematical Technical Scripter Arrays Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Stack Data Structure (Introduction and Program) Linear Search Program for Fibonacci numbers Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string C++ Data Types Merge two sorted arrays
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Jan, 2022" }, { "code": null, "e": 232, "s": 52, "text": "Given an array arr[] of N integers, the task is to find the largest divisor for each element in an array other than 1 and the number itself. If there is no such divisor, print -1." }, { "code": null, "e": 244, "s": 232, "text": "Examples: " }, { "code": null, "e": 874, "s": 244, "text": "Input: arr[] = {5, 6, 7, 8, 9, 10} Output: -1 3 -1 4 3 5 Divisors(5) = {1, 5} -> Since there is no divisor other than 1 and the number itself, therefore largest divisor = -1 Divisors(6) = [1, 2, 3, 6] -> largest divisor other than 1 and the number itself = 3 Divisors(7) = [1, 7] -> Since there is no divisor other than 1 and the number itself, therefore largest divisor = -1 Divisors(8) = [1, 2, 4, 8] -> largest divisor other than 1 and the number itself = 4 Divisors(9) = [1, 3, 9] -> largest divisor other than 1 and the number itself = 3 Divisors(10) = [1, 2, 5, 10] -> largest divisor other than 1 and the number itself = 5" }, { "code": null, "e": 945, "s": 874, "text": "Input: arr[] = {15, 16, 17, 18, 19, 20, 21} Output: 5 8 -1 9 -1 10 7 " }, { "code": null, "e": 1138, "s": 945, "text": "Naive approach: The idea is to iterate over all the array elements and find the largest divisor for each of the element using the approach discussed in this article. Time Complexity: O(N * √N)" }, { "code": null, "e": 1308, "s": 1138, "text": "Efficient approach: A better solution is to precompute the maximum divisor of the numbers from 2 to 105 and then just run a loop for array and print precomputed answer. " }, { "code": null, "e": 1413, "s": 1308, "text": "Use Sieve of Eratosthenes to mark the prime numbers and store the smallest prime divisor of each number." }, { "code": null, "e": 1489, "s": 1413, "text": "Now largest divisor for any number will be number / smallest_prime_divisor." }, { "code": null, "e": 1560, "s": 1489, "text": "Find the Largest divisor for each number using the precomputed answer." }, { "code": null, "e": 1613, "s": 1560, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1617, "s": 1613, "text": "C++" }, { "code": null, "e": 1622, "s": 1617, "text": "Java" }, { "code": null, "e": 1630, "s": 1622, "text": "Python3" }, { "code": null, "e": 1633, "s": 1630, "text": "C#" }, { "code": null, "e": 1644, "s": 1633, "text": "Javascript" }, { "code": "// C++ implementation of the approach #include <bits/stdc++.h>using namespace std; #define int long longconst int maxin = 100001; // Divisors array to keep track// of the maximum divisorint divisors[maxin]; // Function to pre-compute the prime// numbers and largest divisorsvoid Calc_Max_Div(int arr[], int n){ // Visited array to keep // track of prime numbers bool vis[maxin]; memset(vis, 1, maxin); // 0 and 1 are not prime numbers vis[0] = vis[1] = 0; // Initialising divisors[i] = i for (int i = 1; i <= maxin; i++) divisors[i] = i; // For all the numbers divisible by 2 // the maximum divisor will be number / 2 for (int i = 4; i <= maxin; i += 2) { vis[i] = 0; divisors[i] = i / 2; } for (int i = 3; i <= maxin; i += 2) { // If divisors[i] is not equal to i then // this means that divisors[i] contains // minimum prime divisor for the number if (divisors[i] != i) { // Update the answer to // i / smallest_prime_divisor[i] divisors[i] = i / divisors[i]; } // Condition if i is a prime number if (vis[i] == 1) { for (int j = i * i; j < maxin; j += i) { vis[j] = 0; // If divisors[j] is equal to j then // this means that i is the first prime // divisor for j so we update divi[j] = i if (divisors[j] == j) divisors[j] = i; } } } for (int i = 0; i < n; i++) { // If the current element is prime // then it has no divisors // other than 1 and itself if (divisors[arr[i]] == arr[i]) cout << \"-1 \"; else cout << divisors[arr[i]] << \" \"; }} // Driver codeint32_t main(){ int arr[] = { 5, 6, 7, 8, 9, 10 }; int n = sizeof(arr) / sizeof(int); Calc_Max_Div(arr, n); return 0;}", "e": 3575, "s": 1644, "text": null }, { "code": "// Java implementation of the approachclass GFG{ final static int maxin = 10001; // Divisors array to keep track // of the maximum divisor static int divisors[] = new int[maxin + 1]; // Function to pre-compute the prime // numbers and largest divisors static void Calc_Max_Div(int arr[], int n) { // Visited array to keep // track of prime numbers int vis[] = new int[maxin + 1]; for(int i = 0;i <maxin+1 ; i++) vis[i] = 1; // 0 and 1 are not prime numbers vis[0] = vis[1] = 0; // Initialising divisors[i] = i for (int i = 1; i <= maxin; i++) divisors[i] = i; // For all the numbers divisible by 2 // the maximum divisor will be number / 2 for (int i = 4; i <= maxin; i += 2) { vis[i] = 0; divisors[i] = i / 2; } for (int i = 3; i <= maxin; i += 2) { // If divisors[i] is not equal to i then // this means that divisors[i] contains // minimum prime divisor for the number if (divisors[i] != i) { // Update the answer to // i / smallest_prime_divisor[i] divisors[i] = i / divisors[i]; } // Condition if i is a prime number if (vis[i] == 1) { for (int j = i * i; j < maxin; j += i) { vis[j] = 0; // If divisors[j] is equal to j then // this means that i is the first prime // divisor for j so we update divi[j] = i if (divisors[j] == j) divisors[j] = i; } } } for (int i = 0; i < n; i++) { // If the current element is prime // then it has no divisors // other than 1 and itself if (divisors[arr[i]] == arr[i]) System.out.print(\"-1 \"); else System.out.print(divisors[arr[i]] + \" \"); } } // Driver code public static void main (String[] args) { int []arr = { 5, 6, 7, 8, 9, 10 }; int n = arr.length; Calc_Max_Div(arr, n); }} // This code is contributed by AnkitRai01", "e": 5967, "s": 3575, "text": null }, { "code": "# Python3 implementation of the approachmaxin = 100001; # Divisors array to keep track# of the maximum divisordivisors = [0] * (maxin + 1); # Function to pre-compute the prime# numbers and largest divisorsdef Calc_Max_Div(arr, n) : # Visited array to keep # track of prime numbers vis = [1] * (maxin + 1); # 0 and 1 are not prime numbers vis[0] = vis[1] = 0; # Initialising divisors[i] = i for i in range(1, maxin + 1) : divisors[i] = i; # For all the numbers divisible by 2 # the maximum divisor will be number / 2 for i in range(4 , maxin + 1, 2) : vis[i] = 0; divisors[i] = i // 2; for i in range(3, maxin + 1, 2) : # If divisors[i] is not equal to i then # this means that divisors[i] contains # minimum prime divisor for the number if (divisors[i] != i) : # Update the answer to # i / smallest_prime_divisor[i] divisors[i] = i // divisors[i]; # Condition if i is a prime number if (vis[i] == 1) : for j in range( i * i, maxin, i) : vis[j] = 0; # If divisors[j] is equal to j then # this means that i is the first prime # divisor for j so we update divi[j] = i if (divisors[j] == j) : divisors[j] = i; for i in range(n) : # If the current element is prime # then it has no divisors # other than 1 and itself if (divisors[arr[i]] == arr[i]) : print(\"-1 \", end = \"\"); else : print(divisors[arr[i]], end = \" \"); # Driver codeif __name__ == \"__main__\" : arr = [ 5, 6, 7, 8, 9, 10 ]; n = len(arr); Calc_Max_Div(arr, n); # This code is contributed by AnkitRai01", "e": 7759, "s": 5967, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ static int maxin = 10001; // Divisors array to keep track // of the maximum divisor static int []divisors = new int[maxin + 1]; // Function to pre-compute the prime // numbers and largest divisors static void Calc_Max_Div(int []arr, int n) { // Visited array to keep // track of prime numbers int []vis = new int[maxin + 1]; for(int i = 0; i < maxin + 1 ; i++) vis[i] = 1; // 0 and 1 are not prime numbers vis[0] = vis[1] = 0; // Initialising divisors[i] = i for (int i = 1; i <= maxin; i++) divisors[i] = i; // For all the numbers divisible by 2 // the maximum divisor will be number / 2 for (int i = 4; i <= maxin; i += 2) { vis[i] = 0; divisors[i] = i / 2; } for (int i = 3; i <= maxin; i += 2) { // If divisors[i] is not equal to i then // this means that divisors[i] contains // minimum prime divisor for the number if (divisors[i] != i) { // Update the answer to // i / smallest_prime_divisor[i] divisors[i] = i / divisors[i]; } // Condition if i is a prime number if (vis[i] == 1) { for (int j = i * i; j < maxin; j += i) { vis[j] = 0; // If divisors[j] is equal to j then // this means that i is the first prime // divisor for j so we update divi[j] = i if (divisors[j] == j) divisors[j] = i; } } } for (int i = 0; i < n; i++) { // If the current element is prime // then it has no divisors // other than 1 and itself if (divisors[arr[i]] == arr[i]) Console.Write(\"-1 \"); else Console.Write(divisors[arr[i]] + \" \"); } } // Driver code public static void Main() { int []arr = { 5, 6, 7, 8, 9, 10 }; int n = arr.Length; Calc_Max_Div(arr, n); }} // This code is contributed by AnkitRai01", "e": 10141, "s": 7759, "text": null }, { "code": "<script> // Javascript implementation of the approachvar maxin = 100001; // Divisors array to keep track// of the maximum divisorvar divisors = Array(maxin).fill(0); // Function to pre-compute the prime// numbers and largest divisorsfunction Calc_Max_Div(arr, n){ // Visited array to keep // track of prime numbers var vis = Array(maxin).fill(1); // 0 and 1 are not prime numbers vis[0] = vis[1] = 0; var i,j; // Initialising divisors[i] = i for(i = 1; i <= maxin; i++) divisors[i] = i; // For all the numbers divisible by 2 // the maximum divisor will be number / 2 for(i = 4; i <= maxin; i += 2) { vis[i] = 0; divisors[i] = i / 2; } for(i = 3; i <= maxin; i += 2) { // If divisors[i] is not equal to i then // this means that divisors[i] contains // minimum prime divisor for the number if (divisors[i] != i) { // Update the answer to // i / smallest_prime_divisor[i] divisors[i] = i / divisors[i]; } // Condition if i is a prime number if (vis[i] == 1) { for(j = i * i; j < maxin; j += i) { vis[j] = 0; // If divisors[j] is equal to j then // this means that i is the first prime // divisor for j so we update divi[j] = i if (divisors[j] == j) divisors[j] = i; } } } for(i = 0; i < n; i++) { // If the current element is prime // then it has no divisors // other than 1 and itself if (divisors[arr[i]] == arr[i]) document.write(\"-1 \"); else document.write(divisors[arr[i]] + \" \"); }} // Driver codevar arr = [ 5, 6, 7, 8, 9, 10 ];var n = arr.length; Calc_Max_Div(arr, n); // This code is contributed by bgangwar59 </script>", "e": 12081, "s": 10141, "text": null }, { "code": null, "e": 12095, "s": 12081, "text": "-1 3 -1 4 3 5" }, { "code": null, "e": 12119, "s": 12097, "text": "Time Complexity: O(N)" }, { "code": null, "e": 12147, "s": 12119, "text": "Auxiliary Space: O(100001) " }, { "code": null, "e": 12155, "s": 12147, "text": "ankthon" }, { "code": null, "e": 12166, "s": 12155, "text": "bgangwar59" }, { "code": null, "e": 12176, "s": 12166, "text": "subham348" }, { "code": null, "e": 12185, "s": 12176, "text": "divisors" }, { "code": null, "e": 12209, "s": 12185, "text": "Technical Scripter 2019" }, { "code": null, "e": 12216, "s": 12209, "text": "Arrays" }, { "code": null, "e": 12229, "s": 12216, "text": "Mathematical" }, { "code": null, "e": 12248, "s": 12229, "text": "Technical Scripter" }, { "code": null, "e": 12255, "s": 12248, "text": "Arrays" }, { "code": null, "e": 12268, "s": 12255, "text": "Mathematical" }, { "code": null, "e": 12366, "s": 12268, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 12434, "s": 12366, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 12478, "s": 12434, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 12510, "s": 12478, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 12558, "s": 12510, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 12572, "s": 12558, "text": "Linear Search" }, { "code": null, "e": 12602, "s": 12572, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 12645, "s": 12602, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 12705, "s": 12645, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 12720, "s": 12705, "text": "C++ Data Types" } ]
Linked List representation of Disjoint Set Data Structures
12 Jul, 2022 Prerequisites : Union Find (or Disjoint Set), Disjoint Set Data Structures (Java Implementation) A disjoint-set data structure maintains a collection S = {S1, S2,...., Sk} of disjoint dynamic sets. We identify each set by a representative, which is some member of the set. In some applications, it doesn’t matter which member is used as the representative; we care only that if we ask for the representative of a dynamic set twice without modifying the set between the requests, we get the same answer both times. Other applications may require a prespecified rule for choosing the representative, such as choosing the smallest member in the set. Example: Determining the connected components of an undirected graph. Below figure, shows a graph with four connected components. Solution : One procedure X that follows uses the disjoint-set operations to compute the connected components of a graph. Once X has pre-processed the graph, the procedure Y answers queries about whether two vertices are in the same connected component. Below figure shows the collection of disjoint sets after processing each edge. See here as the above example was discussed earlier. Figure (a) Linked-list representations of two sets. Set S1 contains members d, f, and g, with representative f, and set S2 contains members b, c, e, and h, with representative c. Each object in the list contains a set member, a pointer to the next object in the list, and a pointer back to the set object. Each set object has pointers head and tail to the first and last objects, respectively. b) The result of UNION(e, g), which appends the linked list containing e to the linked list containing g. The representative of the resulting set is f . The set object for e’s list, S2, is destroyed. Above three figures are taken from the Cormen(CLRS) book. Above Figure shows a simple way to implement a disjoint-set data structure: each set is represented by its own linked list. The object for each set has attributes head, pointing to the 1st object in the list, and tail, pointing to the last object. Each object in the list contains a set member, a pointer to the next object in the list, and a pointer back to the set object. Within each linked list, the objects may appear in any order. The representative is the set member in the 1st object in the list. To carry out MAKE-SET (x), we create a new linked list whose only object is x. For FIND-SET(x), we just follow the pointer from x back to its set object and then return the member in the object that head points to. For example, in the Figure, the call FIND-SET(g) would return f. Algorithm: Letting x denote an object, we wish to support the following operations: MAKE-SET(x) creates a new set whose only member (and thus representative) is x. Since the sets are disjoint, we require that x not already be in some other set. UNION (x, y) unites the dynamic sets that contain x and y, say Sx and Sy, into a new set that is the union of these two sets. We assume that the two sets are disjoint prior to the operation. The representative of the resulting set is any member of Sx U Sy, although many implementations of UNION specifically choose the representative of either Sx or Sy as the new representative. Since we require the sets in the collection to be disjoint, conceptually we destroy sets Sx and Sy, removing them from the collection S. In practice, we often absorb the elements of one of the sets into the other set. FIND-SET(x) returns a pointer to the representative of the (unique) set containing x. Based on the above explanation, below are implementations: CPP // C++ program for implementation of disjoint// set data structure using linked list#include <bits/stdc++.h>using namespace std; // to represent linked list which is a setstruct Item; // to represent Node of linked list. Every// node has a pointer to representativestruct Node{ int val; Node *next; Item *itemPtr;}; // A list has a pointer to head and tailstruct Item{ Node *hd, *tl;}; // To represent union setclass ListSet{private: // Hash to store addresses of set representatives // for given values. It is made global for ease of // implementation. And second part of hash is actually // address of Nodes. We typecast addresses to long // before storing them. unordered_map<int, Node *> nodeAddress; public: void makeset(int a); Item* find(int key); void Union(Item *i1, Item *i2);}; // To make a set with one object// with its representativevoid ListSet::makeset(int a){ // Create a new Set Item *newSet = new Item; // Create a new linked list node // to store given key newSet->hd = new Node; // Initialize head and tail newSet->tl = newSet->hd; nodeAddress[a] = newSet->hd; // Create a new set newSet->hd->val = a; newSet->hd->itemPtr = newSet; newSet->hd->next = NULL;} // To find representative address of a// keyItem *ListSet::find(int key){ Node *ptr = nodeAddress[key]; return (ptr->itemPtr);} // union function for joining two subsets// of a universe. Merges set2 into set1// and deletes set1.void ListSet::Union(Item *set1, Item *set2){ Node *cur = set2->hd; while (cur != 0) { cur->itemPtr = set1; cur = cur->next; } // Join the tail of the set to head // of the input set (set1->tl)->next = set2->hd; set1->tl = set2->tl; delete set2;} // Driver codeint main(){ ListSet a; a.makeset(13); //a new set is made with one object only a.makeset(25); a.makeset(45); a.makeset(65); cout << "find(13): " << a.find(13) << endl; cout << "find(25): " << a.find(25) << endl; cout << "find(65): " << a.find(65) << endl; cout << "find(45): " << a.find(45) << endl << endl; cout << "Union(find(65), find(45)) \n"; a.Union(a.find(65), a.find(45)); cout << "find(65]): " << a.find(65) << endl; cout << "find(45]): " << a.find(45) << endl; return 0;} find(13): 0x2304e70 find(25): 0x2304ef0 find(65): 0x2304ed0 find(45): 0x2304f50 Union(find(65), find(45)) find(65]): 0x2304ed0 find(45]): 0x2304ed0 Note: The node address will change every time, we run the program. Time complexities of MAKE-SET and FIND-SET are O(1). Time complexity for UNION is O(n). This article is contributed by Yash Sangai. 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. ShayekhBinIslam surinderdawra388 hardikkoriintern Linked List Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n12 Jul, 2022" }, { "code": null, "e": 152, "s": 54, "text": "Prerequisites : Union Find (or Disjoint Set), Disjoint Set Data Structures (Java Implementation) " }, { "code": null, "e": 703, "s": 152, "text": "A disjoint-set data structure maintains a collection S = {S1, S2,...., Sk} of disjoint dynamic sets. We identify each set by a representative, which is some member of the set. In some applications, it doesn’t matter which member is used as the representative; we care only that if we ask for the representative of a dynamic set twice without modifying the set between the requests, we get the same answer both times. Other applications may require a prespecified rule for choosing the representative, such as choosing the smallest member in the set. " }, { "code": null, "e": 834, "s": 703, "text": "Example: Determining the connected components of an undirected graph. Below figure, shows a graph with four connected components. " }, { "code": null, "e": 1168, "s": 834, "text": " Solution : One procedure X that follows uses the disjoint-set operations to compute the connected components of a graph. Once X has pre-processed the graph, the procedure Y answers queries about whether two vertices are in the same connected component. Below figure shows the collection of disjoint sets after processing each edge. " }, { "code": null, "e": 1223, "s": 1168, "text": " See here as the above example was discussed earlier. " }, { "code": null, "e": 1232, "s": 1223, "text": " Figure " }, { "code": null, "e": 1620, "s": 1232, "text": "(a) Linked-list representations of two sets. Set S1 contains members d, f, and g, with representative f, and set S2 contains members b, c, e, and h, with representative c. Each object in the list contains a set member, a pointer to the next object in the list, and a pointer back to the set object. Each set object has pointers head and tail to the first and last objects, respectively. " }, { "code": null, "e": 2664, "s": 1620, "text": "b) The result of UNION(e, g), which appends the linked list containing e to the linked list containing g. The representative of the resulting set is f . The set object for e’s list, S2, is destroyed. Above three figures are taken from the Cormen(CLRS) book. Above Figure shows a simple way to implement a disjoint-set data structure: each set is represented by its own linked list. The object for each set has attributes head, pointing to the 1st object in the list, and tail, pointing to the last object. Each object in the list contains a set member, a pointer to the next object in the list, and a pointer back to the set object. Within each linked list, the objects may appear in any order. The representative is the set member in the 1st object in the list. To carry out MAKE-SET (x), we create a new linked list whose only object is x. For FIND-SET(x), we just follow the pointer from x back to its set object and then return the member in the object that head points to. For example, in the Figure, the call FIND-SET(g) would return f. " }, { "code": null, "e": 2676, "s": 2664, "text": "Algorithm: " }, { "code": null, "e": 2750, "s": 2676, "text": "Letting x denote an object, we wish to support the following operations: " }, { "code": null, "e": 2912, "s": 2750, "text": "MAKE-SET(x) creates a new set whose only member (and thus representative) is x. Since the sets are disjoint, we require that x not already be in some other set. " }, { "code": null, "e": 3512, "s": 2912, "text": "UNION (x, y) unites the dynamic sets that contain x and y, say Sx and Sy, into a new set that is the union of these two sets. We assume that the two sets are disjoint prior to the operation. The representative of the resulting set is any member of Sx U Sy, although many implementations of UNION specifically choose the representative of either Sx or Sy as the new representative. Since we require the sets in the collection to be disjoint, conceptually we destroy sets Sx and Sy, removing them from the collection S. In practice, we often absorb the elements of one of the sets into the other set. " }, { "code": null, "e": 3599, "s": 3512, "text": "FIND-SET(x) returns a pointer to the representative of the (unique) set containing x. " }, { "code": null, "e": 3659, "s": 3599, "text": "Based on the above explanation, below are implementations: " }, { "code": null, "e": 3663, "s": 3659, "text": "CPP" }, { "code": "// C++ program for implementation of disjoint// set data structure using linked list#include <bits/stdc++.h>using namespace std; // to represent linked list which is a setstruct Item; // to represent Node of linked list. Every// node has a pointer to representativestruct Node{ int val; Node *next; Item *itemPtr;}; // A list has a pointer to head and tailstruct Item{ Node *hd, *tl;}; // To represent union setclass ListSet{private: // Hash to store addresses of set representatives // for given values. It is made global for ease of // implementation. And second part of hash is actually // address of Nodes. We typecast addresses to long // before storing them. unordered_map<int, Node *> nodeAddress; public: void makeset(int a); Item* find(int key); void Union(Item *i1, Item *i2);}; // To make a set with one object// with its representativevoid ListSet::makeset(int a){ // Create a new Set Item *newSet = new Item; // Create a new linked list node // to store given key newSet->hd = new Node; // Initialize head and tail newSet->tl = newSet->hd; nodeAddress[a] = newSet->hd; // Create a new set newSet->hd->val = a; newSet->hd->itemPtr = newSet; newSet->hd->next = NULL;} // To find representative address of a// keyItem *ListSet::find(int key){ Node *ptr = nodeAddress[key]; return (ptr->itemPtr);} // union function for joining two subsets// of a universe. Merges set2 into set1// and deletes set1.void ListSet::Union(Item *set1, Item *set2){ Node *cur = set2->hd; while (cur != 0) { cur->itemPtr = set1; cur = cur->next; } // Join the tail of the set to head // of the input set (set1->tl)->next = set2->hd; set1->tl = set2->tl; delete set2;} // Driver codeint main(){ ListSet a; a.makeset(13); //a new set is made with one object only a.makeset(25); a.makeset(45); a.makeset(65); cout << \"find(13): \" << a.find(13) << endl; cout << \"find(25): \" << a.find(25) << endl; cout << \"find(65): \" << a.find(65) << endl; cout << \"find(45): \" << a.find(45) << endl << endl; cout << \"Union(find(65), find(45)) \\n\"; a.Union(a.find(65), a.find(45)); cout << \"find(65]): \" << a.find(65) << endl; cout << \"find(45]): \" << a.find(45) << endl; return 0;}", "e": 6020, "s": 3663, "text": null }, { "code": null, "e": 6170, "s": 6020, "text": "find(13): 0x2304e70\nfind(25): 0x2304ef0\nfind(65): 0x2304ed0\nfind(45): 0x2304f50\n\nUnion(find(65), find(45)) \nfind(65]): 0x2304ed0\nfind(45]): 0x2304ed0" }, { "code": null, "e": 6326, "s": 6170, "text": "Note: The node address will change every time, we run the program. Time complexities of MAKE-SET and FIND-SET are O(1). Time complexity for UNION is O(n). " }, { "code": null, "e": 6621, "s": 6326, "text": "This article is contributed by Yash Sangai. 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": 6637, "s": 6621, "text": "ShayekhBinIslam" }, { "code": null, "e": 6654, "s": 6637, "text": "surinderdawra388" }, { "code": null, "e": 6671, "s": 6654, "text": "hardikkoriintern" }, { "code": null, "e": 6683, "s": 6671, "text": "Linked List" }, { "code": null, "e": 6695, "s": 6683, "text": "Linked List" } ]
Hide Axis, Borders and White Spaces in Matplotlib
11 Dec, 2020 When we draw plots using Matplotlib, the ticks and labels along x-axis & y-axis are drawn too. For drawing creative graphs, many times we hide x-axis & y-axis. The matplotlib.pyplot.axis(‘off’) command us used to hide the axis(both x-axis & y-axis) in the matplotlib figure. Example: Let us consider the following figure in which we have to hide the axis. Python3 # codeimport numpy as npimport matplotlib.pyplot as plt # Marks of RAM in different subjects out of 100.x = ['Science', 'Maths', 'English', 'History', 'Geography']y = [75, 85, 88, 78, 74] plt.bar(x, y)plt.xlabel("Subject")plt.ylabel("Ram's marks out of 100")plt.show() Output: Example: Hiding the axis in the above figure. Python3 # codeimport numpy as npimport matplotlib.pyplot as plt # Marks of RAM in different subjects out of 100.x = ['Science', 'Maths', 'English', 'History', 'Geography']y = [75, 85, 88, 78, 74] plt.xlabel("Subject")plt.ylabel("Ram's marks out of 100")plt.bar(x, y)plt.axis('off') # command for hiding the axis. plt.show() Output: If we just want to turn either the X-axis or Y-axis off, we can use plt.xticks( ) or plt.yticks( ) method respectively. Example: Hiding Y-axis Python3 # Hiding Y-axis labelimport numpy as npimport matplotlib.pyplot as plt # Marks of RAM in different subjects out of 100.x = ['Science', 'Maths', 'English', 'History', 'Geography']y = [75, 85, 88, 78, 74] plt.bar(x, y)plt.xlabel("Subject")plt.ylabel("Ram's marks out of 100")plt.yticks([]) # Command for hiding y-axis plt.show() Output: Example: Hiding X-axis Python3 # Hiding X-axisimport numpy as npimport matplotlib.pyplot as plt # Marks of RAM in different subjects out of 100.x = ['Science', 'Maths', 'English', 'History', 'Geography']y = [75, 85, 88, 78, 74] plt.bar(x, y)plt.xlabel("Subject")plt.ylabel("Ram's marks out of 100")plt.xticks([]) # Command for hiding x-axis plt.show() Output: When we use plt.axis(‘off’) command it hides the axis, but we get whitespaces around the image’s border while saving it. To remove/hide whitespace around the border, we can set bbox_inches=’tight’ in the savefig() method. Similarly, to remove the white border around the image while we set pad_inches = 0 in the savefig() method. Example: Python3 # codeimport numpy as npimport matplotlib.pyplot as plt # Marks of RAM in different subjects out of 100.x = ['Science', 'Maths', 'English', 'History', 'Geography']y = [75, 85, 88, 78, 74] fig = plt.bar(x, y)plt.xlabel("Subject")plt.ylabel("Ram's marks out of 100")plt.axis('off')# Command used for hiding whitespaces and border.plt.savefig('image.png', bbox_inches='tight', pad_inches=0) plt.show() Output: Note: If you have noticed that when we use plt.axis(‘off’) it automatically hides the Axis, Whitespaces and Borders. 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 Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Python Dictionary 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": 54, "s": 26, "text": "\n11 Dec, 2020" }, { "code": null, "e": 215, "s": 54, "text": "When we draw plots using Matplotlib, the ticks and labels along x-axis & y-axis are drawn too. For drawing creative graphs, many times we hide x-axis & y-axis." }, { "code": null, "e": 330, "s": 215, "text": "The matplotlib.pyplot.axis(‘off’) command us used to hide the axis(both x-axis & y-axis) in the matplotlib figure." }, { "code": null, "e": 339, "s": 330, "text": "Example:" }, { "code": null, "e": 411, "s": 339, "text": "Let us consider the following figure in which we have to hide the axis." }, { "code": null, "e": 419, "s": 411, "text": "Python3" }, { "code": "# codeimport numpy as npimport matplotlib.pyplot as plt # Marks of RAM in different subjects out of 100.x = ['Science', 'Maths', 'English', 'History', 'Geography']y = [75, 85, 88, 78, 74] plt.bar(x, y)plt.xlabel(\"Subject\")plt.ylabel(\"Ram's marks out of 100\")plt.show()", "e": 690, "s": 419, "text": null }, { "code": null, "e": 698, "s": 690, "text": "Output:" }, { "code": null, "e": 707, "s": 698, "text": "Example:" }, { "code": null, "e": 745, "s": 707, "text": " Hiding the axis in the above figure." }, { "code": null, "e": 753, "s": 745, "text": "Python3" }, { "code": "# codeimport numpy as npimport matplotlib.pyplot as plt # Marks of RAM in different subjects out of 100.x = ['Science', 'Maths', 'English', 'History', 'Geography']y = [75, 85, 88, 78, 74] plt.xlabel(\"Subject\")plt.ylabel(\"Ram's marks out of 100\")plt.bar(x, y)plt.axis('off') # command for hiding the axis. plt.show()", "e": 1073, "s": 753, "text": null }, { "code": null, "e": 1081, "s": 1073, "text": "Output:" }, { "code": null, "e": 1203, "s": 1081, "text": "If we just want to turn either the X-axis or Y-axis off, we can use plt.xticks( ) or plt.yticks( ) method respectively." }, { "code": null, "e": 1212, "s": 1203, "text": "Example:" }, { "code": null, "e": 1226, "s": 1212, "text": "Hiding Y-axis" }, { "code": null, "e": 1234, "s": 1226, "text": "Python3" }, { "code": "# Hiding Y-axis labelimport numpy as npimport matplotlib.pyplot as plt # Marks of RAM in different subjects out of 100.x = ['Science', 'Maths', 'English', 'History', 'Geography']y = [75, 85, 88, 78, 74] plt.bar(x, y)plt.xlabel(\"Subject\")plt.ylabel(\"Ram's marks out of 100\")plt.yticks([]) # Command for hiding y-axis plt.show()", "e": 1565, "s": 1234, "text": null }, { "code": null, "e": 1573, "s": 1565, "text": "Output:" }, { "code": null, "e": 1582, "s": 1573, "text": "Example:" }, { "code": null, "e": 1598, "s": 1582, "text": " Hiding X-axis " }, { "code": null, "e": 1606, "s": 1598, "text": "Python3" }, { "code": "# Hiding X-axisimport numpy as npimport matplotlib.pyplot as plt # Marks of RAM in different subjects out of 100.x = ['Science', 'Maths', 'English', 'History', 'Geography']y = [75, 85, 88, 78, 74] plt.bar(x, y)plt.xlabel(\"Subject\")plt.ylabel(\"Ram's marks out of 100\")plt.xticks([]) # Command for hiding x-axis plt.show()", "e": 1931, "s": 1606, "text": null }, { "code": null, "e": 1939, "s": 1931, "text": "Output:" }, { "code": null, "e": 2162, "s": 1939, "text": "When we use plt.axis(‘off’) command it hides the axis, but we get whitespaces around the image’s border while saving it. To remove/hide whitespace around the border, we can set bbox_inches=’tight’ in the savefig() method. " }, { "code": null, "e": 2270, "s": 2162, "text": "Similarly, to remove the white border around the image while we set pad_inches = 0 in the savefig() method." }, { "code": null, "e": 2279, "s": 2270, "text": "Example:" }, { "code": null, "e": 2287, "s": 2279, "text": "Python3" }, { "code": "# codeimport numpy as npimport matplotlib.pyplot as plt # Marks of RAM in different subjects out of 100.x = ['Science', 'Maths', 'English', 'History', 'Geography']y = [75, 85, 88, 78, 74] fig = plt.bar(x, y)plt.xlabel(\"Subject\")plt.ylabel(\"Ram's marks out of 100\")plt.axis('off')# Command used for hiding whitespaces and border.plt.savefig('image.png', bbox_inches='tight', pad_inches=0) plt.show()", "e": 2689, "s": 2287, "text": null }, { "code": null, "e": 2697, "s": 2689, "text": "Output:" }, { "code": null, "e": 2814, "s": 2697, "text": "Note: If you have noticed that when we use plt.axis(‘off’) it automatically hides the Axis, Whitespaces and Borders." }, { "code": null, "e": 2832, "s": 2814, "text": "Python-matplotlib" }, { "code": null, "e": 2856, "s": 2832, "text": "Technical Scripter 2020" }, { "code": null, "e": 2863, "s": 2856, "text": "Python" }, { "code": null, "e": 2882, "s": 2863, "text": "Technical Scripter" }, { "code": null, "e": 2980, "s": 2882, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3008, "s": 2980, "text": "Read JSON file using Python" }, { "code": null, "e": 3058, "s": 3008, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 3080, "s": 3058, "text": "Python map() function" }, { "code": null, "e": 3124, "s": 3080, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 3142, "s": 3124, "text": "Python Dictionary" }, { "code": null, "e": 3184, "s": 3142, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3207, "s": 3184, "text": "Taking input in Python" }, { "code": null, "e": 3229, "s": 3207, "text": "Enumerate() in Python" }, { "code": null, "e": 3264, "s": 3229, "text": "Read a file line by line in Python" } ]
Python | Pandas MultiIndex.from_product()
24 Dec, 2018 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas MultiIndex.from_product() function make a MultiIndex from the cartesian product of multiple iterables. Syntax: MultiIndex.from_product(iterables, sortorder=None, names=None) Parameters :iterables : Each iterable has unique labels for each level of the index.sortorder : Level of sortedness (must be lexicographically sorted by that level).names : Names for the levels in the index. Returns: index : MultiIndex Example #1: Use MultiIndex.from_product() function to construct a MultiIndex from the cartesian product of multiple iterables. # importing pandas as pdimport pandas as pd # Create the first iterablePrice =[20, 35, 60, 85] # Create the second iterableName =['Vanilla', 'Strawberry'] # Print the first iterableprint(Price) # Print the second iterableprint("\n", Name) Output : Now let’s create the MultiIndex using the above two iterables. # Creating the MultiIndexmidx = pd.MultiIndex.from_product([Name, Price], names =['Name', 'Price']) # Print the MultiIndexprint(midx) Output :As we can see in the output, the function has created a MultiIndex object using the cartesian product of these two iterables. Example #2: Use MultiIndex.from_product() function to construct a MultiIndex from the cartesian product of multiple iterables. # importing pandas as pdimport pandas as pd # Create the first iterableSnake =['Viper', 'Cobra'] # Create the second iterableVariety =['Brown', 'Yellow', 'Black'] # Print the first iterableprint(Snake) # Print the second iterableprint("\n", Variety) Output : Now let’s create the MultiIndex using the above two iterables. # Creating the MultiIndexmidx = pd.MultiIndex.from_product([Snake, Variety], names =['Snake', 'Variety']) # Print the MultiIndexprint(midx) Output :The function has created a MultiIndex using the two iterables. Python pandas-multiIndex Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Dec, 2018" }, { "code": null, "e": 242, "s": 28, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 352, "s": 242, "text": "Pandas MultiIndex.from_product() function make a MultiIndex from the cartesian product of multiple iterables." }, { "code": null, "e": 423, "s": 352, "text": "Syntax: MultiIndex.from_product(iterables, sortorder=None, names=None)" }, { "code": null, "e": 631, "s": 423, "text": "Parameters :iterables : Each iterable has unique labels for each level of the index.sortorder : Level of sortedness (must be lexicographically sorted by that level).names : Names for the levels in the index." }, { "code": null, "e": 659, "s": 631, "text": "Returns: index : MultiIndex" }, { "code": null, "e": 786, "s": 659, "text": "Example #1: Use MultiIndex.from_product() function to construct a MultiIndex from the cartesian product of multiple iterables." }, { "code": "# importing pandas as pdimport pandas as pd # Create the first iterablePrice =[20, 35, 60, 85] # Create the second iterableName =['Vanilla', 'Strawberry'] # Print the first iterableprint(Price) # Print the second iterableprint(\"\\n\", Name)", "e": 1029, "s": 786, "text": null }, { "code": null, "e": 1038, "s": 1029, "text": "Output :" }, { "code": null, "e": 1101, "s": 1038, "text": "Now let’s create the MultiIndex using the above two iterables." }, { "code": "# Creating the MultiIndexmidx = pd.MultiIndex.from_product([Name, Price], names =['Name', 'Price']) # Print the MultiIndexprint(midx)", "e": 1258, "s": 1101, "text": null }, { "code": null, "e": 1519, "s": 1258, "text": "Output :As we can see in the output, the function has created a MultiIndex object using the cartesian product of these two iterables. Example #2: Use MultiIndex.from_product() function to construct a MultiIndex from the cartesian product of multiple iterables." }, { "code": "# importing pandas as pdimport pandas as pd # Create the first iterableSnake =['Viper', 'Cobra'] # Create the second iterableVariety =['Brown', 'Yellow', 'Black'] # Print the first iterableprint(Snake) # Print the second iterableprint(\"\\n\", Variety)", "e": 1773, "s": 1519, "text": null }, { "code": null, "e": 1782, "s": 1773, "text": "Output :" }, { "code": null, "e": 1845, "s": 1782, "text": "Now let’s create the MultiIndex using the above two iterables." }, { "code": "# Creating the MultiIndexmidx = pd.MultiIndex.from_product([Snake, Variety], names =['Snake', 'Variety']) # Print the MultiIndexprint(midx)", "e": 2009, "s": 1845, "text": null }, { "code": null, "e": 2080, "s": 2009, "text": "Output :The function has created a MultiIndex using the two iterables." }, { "code": null, "e": 2105, "s": 2080, "text": "Python pandas-multiIndex" }, { "code": null, "e": 2119, "s": 2105, "text": "Python-pandas" }, { "code": null, "e": 2126, "s": 2119, "text": "Python" }, { "code": null, "e": 2224, "s": 2126, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2256, "s": 2224, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2283, "s": 2256, "text": "Python Classes and Objects" }, { "code": null, "e": 2304, "s": 2283, "text": "Python OOPs Concepts" }, { "code": null, "e": 2327, "s": 2304, "text": "Introduction To PYTHON" }, { "code": null, "e": 2383, "s": 2327, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2414, "s": 2383, "text": "Python | os.path.join() method" }, { "code": null, "e": 2456, "s": 2414, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2498, "s": 2456, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2537, "s": 2498, "text": "Python | Get unique values from a list" } ]
wait() Method in Java With Examples
06 Jun, 2021 Inter-Thread communication is a way by which synchronized threads can communicate with each other using the methods namely wait(), notify() and notifyAll(). wait() method is a part of java.lang.Object class. When wait() method is called, the calling thread stops its execution until notify() or notifyAll() method is invoked by some other Thread. Syntax: public final void wait() throws InterruptedException Exceptions InterruptedException – if any thread interrupted the current thread before or while the current thread was waiting for a notification. IllegalMonitorStateException – if the current thread is not the owner of the object’s monitor. Working: In java, synchronized methods and blocks allow only one thread to acquire the lock on a resource at a time. So, when wait() method is called by a thread, then it gives up the lock on that resource and goes to sleep until some other thread enters the same monitor and invokes the notify() or notifyAll() method. Calling notify() wakes only one thread and calling notifyAll() wakes up all the threads on the same object. Calling both these methods does not give up the lock on the resource, rather its job is to wake up the threads that have been sent to the sleep state using wait() method. A big difference between sleep() method and wait() method is that sleep() method causes a thread to sleep for a specified amount of time while wait() causes the thread to sleep until notify() and notifyAll() are invoked. In the code mentioned below, we have created a class GunFight which contains a member variable bullets that is initialized to 40 and two methods fire() and reload(). The fire() method fires the number of bullets passed to it until the bullets become 0 and when bullets become 0 it invokes the wait() method which caused the calling thread to sleep and release the lock on the object while reload() method increased the bullets by 40 and invokes the notify() method which wakes up the waiting thread. Java // Java program to demonstrate the use of wait() methodclass GunFight { private int bullets = 40; // This method fires the number of bullets that are // passed it. When the bullet in magazine becomes zero, // it calls the wait() method and releases the lock. synchronized public void fire(int bulletsToBeFired) { for (int i = 1; i <= bulletsToBeFired; i++) { if (bullets == 0) { System.out.println(i - 1 + " bullets fired and " + bullets + " remains"); System.out.println( "Invoking the wait() method"); try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println( "Continuing the fire after reloading"); } bullets--; } System.out.println( "The firing process is complete"); } // reload() increases the bullets by 40 everytime it is // invoked and calls the notify() method which wakes up // the thread that was sent to sleep using wait() inside // of fire() method synchronized public void reload() { System.out.println( "Reloading the magazine and resuming " + "the thread using notify()"); bullets += 40; notify(); }} public class WaitDemo extends Thread { public static void main(String[] args) { GunFight gf = new GunFight(); // Creating a new thread and invoking // our fire() method on it new Thread() { @Override public void run() { gf.fire(60); } }.start(); // Creating a new thread and invoking // our reload method on it new Thread() { @Override public void run() { gf.reload(); } }.start(); }} 40 bullets fired and 0 remains Invoking the wait() method Reloading the magazine and resuming the thread using notify() Continuing the fire after reloading The firing process is complete Java-Multithreading Picked Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Jun, 2021" }, { "code": null, "e": 375, "s": 28, "text": "Inter-Thread communication is a way by which synchronized threads can communicate with each other using the methods namely wait(), notify() and notifyAll(). wait() method is a part of java.lang.Object class. When wait() method is called, the calling thread stops its execution until notify() or notifyAll() method is invoked by some other Thread." }, { "code": null, "e": 383, "s": 375, "text": "Syntax:" }, { "code": null, "e": 436, "s": 383, "text": "public final void wait() throws InterruptedException" }, { "code": null, "e": 447, "s": 436, "text": "Exceptions" }, { "code": null, "e": 582, "s": 447, "text": "InterruptedException – if any thread interrupted the current thread before or while the current thread was waiting for a notification." }, { "code": null, "e": 677, "s": 582, "text": "IllegalMonitorStateException – if the current thread is not the owner of the object’s monitor." }, { "code": null, "e": 686, "s": 677, "text": "Working:" }, { "code": null, "e": 997, "s": 686, "text": "In java, synchronized methods and blocks allow only one thread to acquire the lock on a resource at a time. So, when wait() method is called by a thread, then it gives up the lock on that resource and goes to sleep until some other thread enters the same monitor and invokes the notify() or notifyAll() method." }, { "code": null, "e": 1276, "s": 997, "text": "Calling notify() wakes only one thread and calling notifyAll() wakes up all the threads on the same object. Calling both these methods does not give up the lock on the resource, rather its job is to wake up the threads that have been sent to the sleep state using wait() method." }, { "code": null, "e": 1497, "s": 1276, "text": "A big difference between sleep() method and wait() method is that sleep() method causes a thread to sleep for a specified amount of time while wait() causes the thread to sleep until notify() and notifyAll() are invoked." }, { "code": null, "e": 1997, "s": 1497, "text": "In the code mentioned below, we have created a class GunFight which contains a member variable bullets that is initialized to 40 and two methods fire() and reload(). The fire() method fires the number of bullets passed to it until the bullets become 0 and when bullets become 0 it invokes the wait() method which caused the calling thread to sleep and release the lock on the object while reload() method increased the bullets by 40 and invokes the notify() method which wakes up the waiting thread." }, { "code": null, "e": 2002, "s": 1997, "text": "Java" }, { "code": "// Java program to demonstrate the use of wait() methodclass GunFight { private int bullets = 40; // This method fires the number of bullets that are // passed it. When the bullet in magazine becomes zero, // it calls the wait() method and releases the lock. synchronized public void fire(int bulletsToBeFired) { for (int i = 1; i <= bulletsToBeFired; i++) { if (bullets == 0) { System.out.println(i - 1 + \" bullets fired and \" + bullets + \" remains\"); System.out.println( \"Invoking the wait() method\"); try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println( \"Continuing the fire after reloading\"); } bullets--; } System.out.println( \"The firing process is complete\"); } // reload() increases the bullets by 40 everytime it is // invoked and calls the notify() method which wakes up // the thread that was sent to sleep using wait() inside // of fire() method synchronized public void reload() { System.out.println( \"Reloading the magazine and resuming \" + \"the thread using notify()\"); bullets += 40; notify(); }} public class WaitDemo extends Thread { public static void main(String[] args) { GunFight gf = new GunFight(); // Creating a new thread and invoking // our fire() method on it new Thread() { @Override public void run() { gf.fire(60); } }.start(); // Creating a new thread and invoking // our reload method on it new Thread() { @Override public void run() { gf.reload(); } }.start(); }}", "e": 3945, "s": 2002, "text": null }, { "code": null, "e": 4132, "s": 3945, "text": "40 bullets fired and 0 remains\nInvoking the wait() method\nReloading the magazine and resuming the thread using notify()\nContinuing the fire after reloading\nThe firing process is complete" }, { "code": null, "e": 4152, "s": 4132, "text": "Java-Multithreading" }, { "code": null, "e": 4159, "s": 4152, "text": "Picked" }, { "code": null, "e": 4164, "s": 4159, "text": "Java" }, { "code": null, "e": 4169, "s": 4164, "text": "Java" } ]
Print the matrix diagonally downwards
20 Jun, 2022 Given a matrix of size n*n, print the matrix in the following pattern. Output: 1 2 5 3 6 9 4 7 10 13 8 11 14 12 15 16Examples: Input :matrix[2][2]= { {1, 2}, {3, 4} } Output : 1 2 3 4 Input :matrix[3][3]= { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} } Output : 1 2 4 3 5 7 6 8 9 Following is the C++ implementation for the above pattern. C++ Java Python 3 C# Javascript // CPP program to print matrix downward#include <bits/stdc++.h>using namespace std; void printMatrixDiagonallyDown(vector<vector<int> > matrix, int n){ // printing elements above and on // second diagonal for (int k = 0; k < n; k++) { // traversing downwards starting // from first row int row = 0, col = k; while (col >= 0) { cout << matrix[row][col] << " "; row++, col--; } } // printing elements below second // diagonal for (int j = 1; j < n; j++) { // traversing downwards starting // from last column int col = n - 1, row = j; while (row < n) { cout << matrix[row][col] << " "; row++, col--; } }} int main(){ vector<vector<int> > matrix{ { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; int n = 3; printMatrixDiagonallyDown(matrix, n); return 0;} // JAVA program to print// matrix downwardclass GFG{static void printMatrixDiagonallyDown(int[][] matrix, int n){ // printing elements above and on // second diagonal for (int k = 0; k < n; k++) { // traversing downwards // starting from first row int row = 0, col = k; while (col >= 0) { System.out.print(matrix[row][col] + " "); row++; col--; } } // printing elements below // second diagonal for (int j = 1; j < n; j++) { // traversing downwards starting // from last column int col = n - 1, row = j; while (row < n) { System.out.print(matrix[row][col] + " "); row++; col--; } }} // Driver codepublic static void main(String[] args){ int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; int n = 3; printMatrixDiagonallyDown(matrix, n);}} // This code is contributed by Rajput-Ji # Python 3 program to print matrix downward def printMatrixDiagonallyDown(matrix,n): # printing elements above and on # second diagonal for k in range(n): # traversing downwards starting # from first row row = 0 col = k while (col >= 0): print(matrix[row][col],end = " ") row += 1 col -= 1 # printing elements below second # diagonal for j in range(1,n): # traversing downwards starting # from last column col = n - 1 row = j while (row < n): print(matrix[row][col],end = " ") row += 1 col -= 1 if __name__ == '__main__': matrix = [[1, 2, 3],[4, 5, 6],[7, 8, 9]] n = 3 printMatrixDiagonallyDown(matrix, n) # This code is contributed by Surendra_Gangwar // C# program to print// matrix downwardusing System;class GFG{static void printMatrixDiagonallyDown(int[,] matrix, int n){ // printing elements above and on // second diagonal for (int k = 0; k < n; k++) { // traversing downwards // starting from first row int row = 0, col = k; while (col >= 0) { Console.Write(matrix[row,col] + " "); row++; col--; } } // printing elements below // second diagonal for (int j = 1; j < n; j++) { // traversing downwards starting // from last column int col = n - 1, row = j; while (row < n) { Console.Write(matrix[row,col] + " "); row++; col--; } }} // Driver codepublic static void Main(String[] args){ int[,] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; int n = 3; printMatrixDiagonallyDown(matrix, n);}} // This code is contributed by Amit Katiyar <script> // JavaScript program to print// matrix downwardfunction printMatrixDiagonallyDown(matrix,n){// printing elements above and on// second diagonalfor (let k = 0; k < n; k++){ // traversing downwards // starting from first row let row = 0, col = k; while (col >= 0) { document.write(matrix[row][col] + " "); row++; col--; }} // printing elements below// second diagonalfor (let j = 1; j < n; j++){ // traversing downwards starting // from last column let col = n - 1, row = j; while (row < n) { document.write(matrix[row][col] + " "); row++; col--; }}} // Driver code let matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];let n = 3;printMatrixDiagonallyDown(matrix, n); // This code is contributed by sravan kumar </script> Output: 1 2 4 3 5 7 6 8 9 Time Complexity: O(n2) Auxiliary Space: 1 pqrss SURENDRA_GANGWAR Rajput-Ji amit143katiyar sravankumar8128 technophpfij pattern-printing Matrix pattern-printing Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n20 Jun, 2022" }, { "code": null, "e": 124, "s": 52, "text": "Given a matrix of size n*n, print the matrix in the following pattern. " }, { "code": null, "e": 181, "s": 124, "text": "Output: 1 2 5 3 6 9 4 7 10 13 8 11 14 12 15 16Examples: " }, { "code": null, "e": 392, "s": 181, "text": "Input :matrix[2][2]= { {1, 2},\n {3, 4} }\nOutput : 1 2 3 4\n\nInput :matrix[3][3]= { {1, 2, 3},\n {4, 5, 6},\n {7, 8, 9} }\nOutput : 1 2 4 3 5 7 6 8 9" }, { "code": null, "e": 453, "s": 392, "text": "Following is the C++ implementation for the above pattern. " }, { "code": null, "e": 457, "s": 453, "text": "C++" }, { "code": null, "e": 462, "s": 457, "text": "Java" }, { "code": null, "e": 471, "s": 462, "text": "Python 3" }, { "code": null, "e": 474, "s": 471, "text": "C#" }, { "code": null, "e": 485, "s": 474, "text": "Javascript" }, { "code": "// CPP program to print matrix downward#include <bits/stdc++.h>using namespace std; void printMatrixDiagonallyDown(vector<vector<int> > matrix, int n){ // printing elements above and on // second diagonal for (int k = 0; k < n; k++) { // traversing downwards starting // from first row int row = 0, col = k; while (col >= 0) { cout << matrix[row][col] << \" \"; row++, col--; } } // printing elements below second // diagonal for (int j = 1; j < n; j++) { // traversing downwards starting // from last column int col = n - 1, row = j; while (row < n) { cout << matrix[row][col] << \" \"; row++, col--; } }} int main(){ vector<vector<int> > matrix{ { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; int n = 3; printMatrixDiagonallyDown(matrix, n); return 0;}", "e": 1498, "s": 485, "text": null }, { "code": "// JAVA program to print// matrix downwardclass GFG{static void printMatrixDiagonallyDown(int[][] matrix, int n){ // printing elements above and on // second diagonal for (int k = 0; k < n; k++) { // traversing downwards // starting from first row int row = 0, col = k; while (col >= 0) { System.out.print(matrix[row][col] + \" \"); row++; col--; } } // printing elements below // second diagonal for (int j = 1; j < n; j++) { // traversing downwards starting // from last column int col = n - 1, row = j; while (row < n) { System.out.print(matrix[row][col] + \" \"); row++; col--; } }} // Driver codepublic static void main(String[] args){ int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; int n = 3; printMatrixDiagonallyDown(matrix, n);}} // This code is contributed by Rajput-Ji", "e": 2434, "s": 1498, "text": null }, { "code": "# Python 3 program to print matrix downward def printMatrixDiagonallyDown(matrix,n): # printing elements above and on # second diagonal for k in range(n): # traversing downwards starting # from first row row = 0 col = k while (col >= 0): print(matrix[row][col],end = \" \") row += 1 col -= 1 # printing elements below second # diagonal for j in range(1,n): # traversing downwards starting # from last column col = n - 1 row = j while (row < n): print(matrix[row][col],end = \" \") row += 1 col -= 1 if __name__ == '__main__': matrix = [[1, 2, 3],[4, 5, 6],[7, 8, 9]] n = 3 printMatrixDiagonallyDown(matrix, n) # This code is contributed by Surendra_Gangwar", "e": 3251, "s": 2434, "text": null }, { "code": "// C# program to print// matrix downwardusing System;class GFG{static void printMatrixDiagonallyDown(int[,] matrix, int n){ // printing elements above and on // second diagonal for (int k = 0; k < n; k++) { // traversing downwards // starting from first row int row = 0, col = k; while (col >= 0) { Console.Write(matrix[row,col] + \" \"); row++; col--; } } // printing elements below // second diagonal for (int j = 1; j < n; j++) { // traversing downwards starting // from last column int col = n - 1, row = j; while (row < n) { Console.Write(matrix[row,col] + \" \"); row++; col--; } }} // Driver codepublic static void Main(String[] args){ int[,] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; int n = 3; printMatrixDiagonallyDown(matrix, n);}} // This code is contributed by Amit Katiyar", "e": 4194, "s": 3251, "text": null }, { "code": "<script> // JavaScript program to print// matrix downwardfunction printMatrixDiagonallyDown(matrix,n){// printing elements above and on// second diagonalfor (let k = 0; k < n; k++){ // traversing downwards // starting from first row let row = 0, col = k; while (col >= 0) { document.write(matrix[row][col] + \" \"); row++; col--; }} // printing elements below// second diagonalfor (let j = 1; j < n; j++){ // traversing downwards starting // from last column let col = n - 1, row = j; while (row < n) { document.write(matrix[row][col] + \" \"); row++; col--; }}} // Driver code let matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];let n = 3;printMatrixDiagonallyDown(matrix, n); // This code is contributed by sravan kumar </script>", "e": 5009, "s": 4194, "text": null }, { "code": null, "e": 5019, "s": 5009, "text": "Output: " }, { "code": null, "e": 5037, "s": 5019, "text": "1 2 4 3 5 7 6 8 9" }, { "code": null, "e": 5061, "s": 5037, "text": "Time Complexity: O(n2) " }, { "code": null, "e": 5080, "s": 5061, "text": "Auxiliary Space: 1" }, { "code": null, "e": 5086, "s": 5080, "text": "pqrss" }, { "code": null, "e": 5103, "s": 5086, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 5113, "s": 5103, "text": "Rajput-Ji" }, { "code": null, "e": 5128, "s": 5113, "text": "amit143katiyar" }, { "code": null, "e": 5144, "s": 5128, "text": "sravankumar8128" }, { "code": null, "e": 5157, "s": 5144, "text": "technophpfij" }, { "code": null, "e": 5174, "s": 5157, "text": "pattern-printing" }, { "code": null, "e": 5181, "s": 5174, "text": "Matrix" }, { "code": null, "e": 5198, "s": 5181, "text": "pattern-printing" }, { "code": null, "e": 5205, "s": 5198, "text": "Matrix" } ]
ElGamal Encryption Algorithm
20 Oct, 2021 ElGamal encryption is a public-key cryptosystem. It uses asymmetric key encryption for communicating between two parties and encrypting the message. This cryptosystem is based on the difficulty of finding discrete logarithm in a cyclic group that is even if we know ga and gk, it is extremely difficult to compute gak.Idea of ElGamal cryptosystem Suppose Alice wants to communicate with Bob. Bob generates public and private keys: Bob chooses a very large number q and a cyclic group Fq.From the cyclic group Fq, he choose any element g andan element a such that gcd(a, q) = 1.Then he computes h = ga.Bob publishes F, h = ga, q, and g as his public key and retains a as private key.Alice encrypts data using Bob’s public key : Alice selects an element k from cyclic group F such that gcd(k, q) = 1.Then she computes p = gk and s = hk = gak.She multiples s with M.Then she sends (p, M*s) = (gk, M*s).Bob decrypts the message : Bob calculates s′ = pa = gak.He divides M*s by s′ to obtain M as s = s′. Bob generates public and private keys: Bob chooses a very large number q and a cyclic group Fq.From the cyclic group Fq, he choose any element g andan element a such that gcd(a, q) = 1.Then he computes h = ga.Bob publishes F, h = ga, q, and g as his public key and retains a as private key. Bob chooses a very large number q and a cyclic group Fq. From the cyclic group Fq, he choose any element g andan element a such that gcd(a, q) = 1. Then he computes h = ga. Bob publishes F, h = ga, q, and g as his public key and retains a as private key. Alice encrypts data using Bob’s public key : Alice selects an element k from cyclic group F such that gcd(k, q) = 1.Then she computes p = gk and s = hk = gak.She multiples s with M.Then she sends (p, M*s) = (gk, M*s). Alice selects an element k from cyclic group F such that gcd(k, q) = 1. Then she computes p = gk and s = hk = gak. She multiples s with M. Then she sends (p, M*s) = (gk, M*s). Bob decrypts the message : Bob calculates s′ = pa = gak.He divides M*s by s′ to obtain M as s = s′. Bob calculates s′ = pa = gak. He divides M*s by s′ to obtain M as s = s′. Following is the implementation of the ElGamal cryptosystem in Python Python3 # Python program to illustrate ElGamal encryption import randomfrom math import pow a = random.randint(2, 10) def gcd(a, b): if a < b: return gcd(b, a) elif a % b == 0: return b; else: return gcd(b, a % b) # Generating large random numbersdef gen_key(q): key = random.randint(pow(10, 20), q) while gcd(q, key) != 1: key = random.randint(pow(10, 20), q) return key # Modular exponentiationdef power(a, b, c): x = 1 y = a while b > 0: if b % 2 != 0: x = (x * y) % c; y = (y * y) % c b = int(b / 2) return x % c # Asymmetric encryptiondef encrypt(msg, q, h, g): en_msg = [] k = gen_key(q)# Private key for sender s = power(h, k, q) p = power(g, k, q) for i in range(0, len(msg)): en_msg.append(msg[i]) print("g^k used : ", p) print("g^ak used : ", s) for i in range(0, len(en_msg)): en_msg[i] = s * ord(en_msg[i]) return en_msg, p def decrypt(en_msg, p, key, q): dr_msg = [] h = power(p, key, q) for i in range(0, len(en_msg)): dr_msg.append(chr(int(en_msg[i]/h))) return dr_msg # Driver codedef main(): msg = 'encryption' print("Original Message :", msg) q = random.randint(pow(10, 20), pow(10, 50)) g = random.randint(2, q) key = gen_key(q)# Private key for receiver h = power(g, key, q) print("g used : ", g) print("g^a used : ", h) en_msg, p = encrypt(msg, q, h, g) dr_msg = decrypt(en_msg, p, key, q) dmsg = ''.join(dr_msg) print("Decrypted Message :", dmsg); if __name__ == '__main__': main() Sample Output : Original Message : encryption g used : 5860696954522417707188952371547944035333315907890 g^a used : 4711309755639364289552454834506215144653958055252 g^k used : 12475188089503227615789015740709091911412567126782 g^ak used : 39448787632167136161153337226654906357756740068295 Decrypted Message : encryption In this cryptosystem, the original message M is masked by multiplying gak to it. To remove the mask, a clue is given in form of gk. Unless someone knows a, he will not be able to retrieve M. This is because finding discrete log in a cyclic group is difficult and simplifying knowing ga and gk is not good enough to compute gak. SamanvayaPanda volumezero9786 eqttonytony Pushpender007 cryptography number-theory Computer Networks number-theory cryptography Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Wireless Application Protocol GSM in Wireless Communication Secure Socket Layer (SSL) Mobile Internet Protocol (or Mobile IP) Advanced Encryption Standard (AES) Introduction of Mobile Ad hoc Network (MANET) Difference between MANET and VANET Difference between FDMA, TDMA and CDMA Cryptography and its Types Dynamic Host Configuration Protocol (DHCP)
[ { "code": null, "e": 52, "s": 24, "text": "\n20 Oct, 2021" }, { "code": null, "e": 446, "s": 52, "text": "ElGamal encryption is a public-key cryptosystem. It uses asymmetric key encryption for communicating between two parties and encrypting the message. This cryptosystem is based on the difficulty of finding discrete logarithm in a cyclic group that is even if we know ga and gk, it is extremely difficult to compute gak.Idea of ElGamal cryptosystem Suppose Alice wants to communicate with Bob. " }, { "code": null, "e": 1053, "s": 446, "text": "Bob generates public and private keys: Bob chooses a very large number q and a cyclic group Fq.From the cyclic group Fq, he choose any element g andan element a such that gcd(a, q) = 1.Then he computes h = ga.Bob publishes F, h = ga, q, and g as his public key and retains a as private key.Alice encrypts data using Bob’s public key : Alice selects an element k from cyclic group F such that gcd(k, q) = 1.Then she computes p = gk and s = hk = gak.She multiples s with M.Then she sends (p, M*s) = (gk, M*s).Bob decrypts the message : Bob calculates s′ = pa = gak.He divides M*s by s′ to obtain M as s = s′." }, { "code": null, "e": 1344, "s": 1053, "text": "Bob generates public and private keys: Bob chooses a very large number q and a cyclic group Fq.From the cyclic group Fq, he choose any element g andan element a such that gcd(a, q) = 1.Then he computes h = ga.Bob publishes F, h = ga, q, and g as his public key and retains a as private key." }, { "code": null, "e": 1401, "s": 1344, "text": "Bob chooses a very large number q and a cyclic group Fq." }, { "code": null, "e": 1492, "s": 1401, "text": "From the cyclic group Fq, he choose any element g andan element a such that gcd(a, q) = 1." }, { "code": null, "e": 1517, "s": 1492, "text": "Then he computes h = ga." }, { "code": null, "e": 1599, "s": 1517, "text": "Bob publishes F, h = ga, q, and g as his public key and retains a as private key." }, { "code": null, "e": 1817, "s": 1599, "text": "Alice encrypts data using Bob’s public key : Alice selects an element k from cyclic group F such that gcd(k, q) = 1.Then she computes p = gk and s = hk = gak.She multiples s with M.Then she sends (p, M*s) = (gk, M*s)." }, { "code": null, "e": 1889, "s": 1817, "text": "Alice selects an element k from cyclic group F such that gcd(k, q) = 1." }, { "code": null, "e": 1932, "s": 1889, "text": "Then she computes p = gk and s = hk = gak." }, { "code": null, "e": 1956, "s": 1932, "text": "She multiples s with M." }, { "code": null, "e": 1993, "s": 1956, "text": "Then she sends (p, M*s) = (gk, M*s)." }, { "code": null, "e": 2093, "s": 1993, "text": "Bob decrypts the message : Bob calculates s′ = pa = gak.He divides M*s by s′ to obtain M as s = s′." }, { "code": null, "e": 2123, "s": 2093, "text": "Bob calculates s′ = pa = gak." }, { "code": null, "e": 2167, "s": 2123, "text": "He divides M*s by s′ to obtain M as s = s′." }, { "code": null, "e": 2239, "s": 2167, "text": "Following is the implementation of the ElGamal cryptosystem in Python " }, { "code": null, "e": 2247, "s": 2239, "text": "Python3" }, { "code": "# Python program to illustrate ElGamal encryption import randomfrom math import pow a = random.randint(2, 10) def gcd(a, b): if a < b: return gcd(b, a) elif a % b == 0: return b; else: return gcd(b, a % b) # Generating large random numbersdef gen_key(q): key = random.randint(pow(10, 20), q) while gcd(q, key) != 1: key = random.randint(pow(10, 20), q) return key # Modular exponentiationdef power(a, b, c): x = 1 y = a while b > 0: if b % 2 != 0: x = (x * y) % c; y = (y * y) % c b = int(b / 2) return x % c # Asymmetric encryptiondef encrypt(msg, q, h, g): en_msg = [] k = gen_key(q)# Private key for sender s = power(h, k, q) p = power(g, k, q) for i in range(0, len(msg)): en_msg.append(msg[i]) print(\"g^k used : \", p) print(\"g^ak used : \", s) for i in range(0, len(en_msg)): en_msg[i] = s * ord(en_msg[i]) return en_msg, p def decrypt(en_msg, p, key, q): dr_msg = [] h = power(p, key, q) for i in range(0, len(en_msg)): dr_msg.append(chr(int(en_msg[i]/h))) return dr_msg # Driver codedef main(): msg = 'encryption' print(\"Original Message :\", msg) q = random.randint(pow(10, 20), pow(10, 50)) g = random.randint(2, q) key = gen_key(q)# Private key for receiver h = power(g, key, q) print(\"g used : \", g) print(\"g^a used : \", h) en_msg, p = encrypt(msg, q, h, g) dr_msg = decrypt(en_msg, p, key, q) dmsg = ''.join(dr_msg) print(\"Decrypted Message :\", dmsg); if __name__ == '__main__': main()", "e": 3860, "s": 2247, "text": null }, { "code": null, "e": 3878, "s": 3860, "text": "Sample Output : " }, { "code": null, "e": 4188, "s": 3878, "text": "Original Message : encryption\ng used : 5860696954522417707188952371547944035333315907890\ng^a used : 4711309755639364289552454834506215144653958055252\ng^k used : 12475188089503227615789015740709091911412567126782\ng^ak used : 39448787632167136161153337226654906357756740068295\nDecrypted Message : encryption" }, { "code": null, "e": 4517, "s": 4188, "text": "In this cryptosystem, the original message M is masked by multiplying gak to it. To remove the mask, a clue is given in form of gk. Unless someone knows a, he will not be able to retrieve M. This is because finding discrete log in a cyclic group is difficult and simplifying knowing ga and gk is not good enough to compute gak. " }, { "code": null, "e": 4532, "s": 4517, "text": "SamanvayaPanda" }, { "code": null, "e": 4547, "s": 4532, "text": "volumezero9786" }, { "code": null, "e": 4559, "s": 4547, "text": "eqttonytony" }, { "code": null, "e": 4573, "s": 4559, "text": "Pushpender007" }, { "code": null, "e": 4586, "s": 4573, "text": "cryptography" }, { "code": null, "e": 4600, "s": 4586, "text": "number-theory" }, { "code": null, "e": 4618, "s": 4600, "text": "Computer Networks" }, { "code": null, "e": 4632, "s": 4618, "text": "number-theory" }, { "code": null, "e": 4645, "s": 4632, "text": "cryptography" }, { "code": null, "e": 4663, "s": 4645, "text": "Computer Networks" }, { "code": null, "e": 4761, "s": 4663, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4791, "s": 4761, "text": "Wireless Application Protocol" }, { "code": null, "e": 4821, "s": 4791, "text": "GSM in Wireless Communication" }, { "code": null, "e": 4847, "s": 4821, "text": "Secure Socket Layer (SSL)" }, { "code": null, "e": 4887, "s": 4847, "text": "Mobile Internet Protocol (or Mobile IP)" }, { "code": null, "e": 4922, "s": 4887, "text": "Advanced Encryption Standard (AES)" }, { "code": null, "e": 4968, "s": 4922, "text": "Introduction of Mobile Ad hoc Network (MANET)" }, { "code": null, "e": 5003, "s": 4968, "text": "Difference between MANET and VANET" }, { "code": null, "e": 5042, "s": 5003, "text": "Difference between FDMA, TDMA and CDMA" }, { "code": null, "e": 5069, "s": 5042, "text": "Cryptography and its Types" } ]
Time Series Analysis in R
16 Dec, 2021 Time Series in R is used to see how an object behaves over a period of time. In R, it can be easily done by ts() function with some parameters. Time series takes the data vector and each data is connected with timestamp value as given by the user. This function is mostly used to learn and forecast the behavior of an asset in business for a period of time. For example, sales analysis of a company, inventory analysis, price analysis of a particular stock or market, population analysis, etc. Syntax: objectName <- ts(data, start, end, frequency) where, data represents the data vector start represents the first observation in time series end represents the last observation in time series frequency represents number of observations per unit time. For example, frequency=1 for monthly data. Note: To know about more optional parameters, use the following command in R console: help("ts") Example: Let’s take the example of COVID-19 pandemic situation. Taking a total number of positive cases of COVID-19 cases weekly from 22 January 2020 to 15 April 2020 of the world in data vector. R # Weekly data of COVID-19 positive cases from# 22 January, 2020 to 15 April, 2020x <- c(580, 7813, 28266, 59287, 75700, 87820, 95314, 126214, 218843, 471497, 936851, 1508725, 2072113) # library required for decimal_date() functionlibrary(lubridate) # output to be created as png filepng(file ="timeSeries.png") # creating time series object# from date 22 January, 2020mts <- ts(x, start = decimal_date(ymd("2020-01-22")), frequency = 365.25 / 7) # plotting the graphplot(mts, xlab ="Weekly Data", ylab ="Total Positive Cases", main ="COVID-19 Pandemic", col.main ="darkgreen") # saving the filedev.off() Output: Multivariate Time Series is creating multiple time series in a single chart. Example: Taking data of total positive cases and total deaths from COVID-19 weekly from 22 January 2020 to 15 April 2020 in data vector. R # Weekly data of COVID-19 positive cases and# weekly deaths from 22 January, 2020 to# 15 April, 2020positiveCases <- c(580, 7813, 28266, 59287, 75700, 87820, 95314, 126214, 218843, 471497, 936851, 1508725, 2072113) deaths <- c(17, 270, 565, 1261, 2126, 2800, 3285, 4628, 8951, 21283, 47210, 88480, 138475) # library required for decimal_date() functionlibrary(lubridate) # output to be created as png filepng(file ="multivariateTimeSeries.png") # creating multivariate time series object# from date 22 January, 2020mts <- ts(cbind(positiveCases, deaths),start = decimal_date(ymd("2020-01-22")), frequency = 365.25 / 7) # plotting the graphplot(mts, xlab ="Weekly Data", main ="COVID-19 Cases", col.main ="darkgreen") # saving the filedev.off() Output: Forecasting can be done on time series using some models present in R. In this example, Arima automated model is used. To know about more parameters of arima() function, use the below command. help("arima") In the below code, forecasting is done using forecast library and so, installation of forecast library is necessary. R # Weekly data of COVID-19 cases from# 22 January, 2020 to 15 April, 2020x <- c(580, 7813, 28266, 59287, 75700, 87820, 95314, 126214, 218843, 471497, 936851, 1508725, 2072113) # library required for decimal_date() functionlibrary(lubridate) # library required for forecastinglibrary(forecast) # output to be created as png filepng(file ="forecastTimeSeries.png") # creating time series object# from date 22 January, 2020mts <- ts(x, start = decimal_date(ymd("2020-01-22")), frequency = 365.25 / 7) # forecasting model using arima modelfit <- auto.arima(mts) # Next 5 forecasted valuesforecast(fit, 5) # plotting the graph with next# 5 weekly forecasted valuesplot(forecast(fit, 5), xlab ="Weekly Data",ylab ="Total Positive Cases",main ="COVID-19 Pandemic", col.main ="darkgreen") # saving the filedev.off() Output : After executing the above code, the following forecasted results are produced. Point Forecast Lo 80 Hi 80 Lo 95 Hi 95 2020.307 2547989 2491957 2604020 2462296 2633682 2020.326 2915130 2721277 3108983 2618657 3211603 2020.345 3202354 2783402 3621307 2561622 3843087 2020.364 3462692 2748533 4176851 2370480 4554904 2020.383 3745054 2692884 4797225 2135898 5354210 Below graph plots estimated forecasted values of COVID-19 if it continues to be widespread for the next 5 weeks. kumar_satyam data-science Picked R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change column name of a given DataFrame in R Filter data by multiple conditions in R using Dplyr How to Replace specific values in column in R DataFrame ? Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Loops in R (for, while, repeat) Group by function in R using Dplyr Adding elements in a vector in R programming - append() method How to change Row Names of DataFrame in R ? Convert Factor to Numeric and Numeric to Factor in R Programming
[ { "code": null, "e": 52, "s": 24, "text": "\n16 Dec, 2021" }, { "code": null, "e": 546, "s": 52, "text": "Time Series in R is used to see how an object behaves over a period of time. In R, it can be easily done by ts() function with some parameters. Time series takes the data vector and each data is connected with timestamp value as given by the user. This function is mostly used to learn and forecast the behavior of an asset in business for a period of time. For example, sales analysis of a company, inventory analysis, price analysis of a particular stock or market, population analysis, etc." }, { "code": null, "e": 601, "s": 546, "text": "Syntax: objectName <- ts(data, start, end, frequency)" }, { "code": null, "e": 608, "s": 601, "text": "where," }, { "code": null, "e": 640, "s": 608, "text": "data represents the data vector" }, { "code": null, "e": 694, "s": 640, "text": "start represents the first observation in time series" }, { "code": null, "e": 745, "s": 694, "text": "end represents the last observation in time series" }, { "code": null, "e": 847, "s": 745, "text": "frequency represents number of observations per unit time. For example, frequency=1 for monthly data." }, { "code": null, "e": 934, "s": 847, "text": "Note: To know about more optional parameters, use the following command in R console: " }, { "code": null, "e": 945, "s": 934, "text": "help(\"ts\")" }, { "code": null, "e": 1141, "s": 945, "text": "Example: Let’s take the example of COVID-19 pandemic situation. Taking a total number of positive cases of COVID-19 cases weekly from 22 January 2020 to 15 April 2020 of the world in data vector." }, { "code": null, "e": 1143, "s": 1141, "text": "R" }, { "code": "# Weekly data of COVID-19 positive cases from# 22 January, 2020 to 15 April, 2020x <- c(580, 7813, 28266, 59287, 75700, 87820, 95314, 126214, 218843, 471497, 936851, 1508725, 2072113) # library required for decimal_date() functionlibrary(lubridate) # output to be created as png filepng(file =\"timeSeries.png\") # creating time series object# from date 22 January, 2020mts <- ts(x, start = decimal_date(ymd(\"2020-01-22\")), frequency = 365.25 / 7) # plotting the graphplot(mts, xlab =\"Weekly Data\", ylab =\"Total Positive Cases\", main =\"COVID-19 Pandemic\", col.main =\"darkgreen\") # saving the filedev.off()", "e": 1801, "s": 1143, "text": null }, { "code": null, "e": 1810, "s": 1801, "text": "Output: " }, { "code": null, "e": 1887, "s": 1810, "text": "Multivariate Time Series is creating multiple time series in a single chart." }, { "code": null, "e": 2025, "s": 1887, "text": "Example: Taking data of total positive cases and total deaths from COVID-19 weekly from 22 January 2020 to 15 April 2020 in data vector. " }, { "code": null, "e": 2027, "s": 2025, "text": "R" }, { "code": "# Weekly data of COVID-19 positive cases and# weekly deaths from 22 January, 2020 to# 15 April, 2020positiveCases <- c(580, 7813, 28266, 59287, 75700, 87820, 95314, 126214, 218843, 471497, 936851, 1508725, 2072113) deaths <- c(17, 270, 565, 1261, 2126, 2800, 3285, 4628, 8951, 21283, 47210, 88480, 138475) # library required for decimal_date() functionlibrary(lubridate) # output to be created as png filepng(file =\"multivariateTimeSeries.png\") # creating multivariate time series object# from date 22 January, 2020mts <- ts(cbind(positiveCases, deaths),start = decimal_date(ymd(\"2020-01-22\")), frequency = 365.25 / 7) # plotting the graphplot(mts, xlab =\"Weekly Data\", main =\"COVID-19 Cases\", col.main =\"darkgreen\") # saving the filedev.off()", "e": 2863, "s": 2027, "text": null }, { "code": null, "e": 2872, "s": 2863, "text": "Output: " }, { "code": null, "e": 3066, "s": 2872, "text": "Forecasting can be done on time series using some models present in R. In this example, Arima automated model is used. To know about more parameters of arima() function, use the below command. " }, { "code": null, "e": 3080, "s": 3066, "text": "help(\"arima\")" }, { "code": null, "e": 3198, "s": 3080, "text": "In the below code, forecasting is done using forecast library and so, installation of forecast library is necessary. " }, { "code": null, "e": 3200, "s": 3198, "text": "R" }, { "code": "# Weekly data of COVID-19 cases from# 22 January, 2020 to 15 April, 2020x <- c(580, 7813, 28266, 59287, 75700, 87820, 95314, 126214, 218843, 471497, 936851, 1508725, 2072113) # library required for decimal_date() functionlibrary(lubridate) # library required for forecastinglibrary(forecast) # output to be created as png filepng(file =\"forecastTimeSeries.png\") # creating time series object# from date 22 January, 2020mts <- ts(x, start = decimal_date(ymd(\"2020-01-22\")), frequency = 365.25 / 7) # forecasting model using arima modelfit <- auto.arima(mts) # Next 5 forecasted valuesforecast(fit, 5) # plotting the graph with next# 5 weekly forecasted valuesplot(forecast(fit, 5), xlab =\"Weekly Data\",ylab =\"Total Positive Cases\",main =\"COVID-19 Pandemic\", col.main =\"darkgreen\") # saving the filedev.off()", "e": 4040, "s": 3200, "text": null }, { "code": null, "e": 4128, "s": 4040, "text": "Output : After executing the above code, the following forecasted results are produced." }, { "code": null, "e": 4464, "s": 4128, "text": " Point Forecast Lo 80 Hi 80 Lo 95 Hi 95\n2020.307 2547989 2491957 2604020 2462296 2633682\n2020.326 2915130 2721277 3108983 2618657 3211603\n2020.345 3202354 2783402 3621307 2561622 3843087\n2020.364 3462692 2748533 4176851 2370480 4554904\n2020.383 3745054 2692884 4797225 2135898 5354210" }, { "code": null, "e": 4578, "s": 4464, "text": "Below graph plots estimated forecasted values of COVID-19 if it continues to be widespread for the next 5 weeks. " }, { "code": null, "e": 4591, "s": 4578, "text": "kumar_satyam" }, { "code": null, "e": 4604, "s": 4591, "text": "data-science" }, { "code": null, "e": 4611, "s": 4604, "text": "Picked" }, { "code": null, "e": 4622, "s": 4611, "text": "R Language" }, { "code": null, "e": 4720, "s": 4622, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4765, "s": 4720, "text": "Change column name of a given DataFrame in R" }, { "code": null, "e": 4817, "s": 4765, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 4875, "s": 4817, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 4927, "s": 4875, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 4985, "s": 4927, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 5017, "s": 4985, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 5052, "s": 5017, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 5115, "s": 5052, "text": "Adding elements in a vector in R programming - append() method" }, { "code": null, "e": 5159, "s": 5115, "text": "How to change Row Names of DataFrame in R ?" } ]
Singleton Pattern in Python – A Complete Guide
27 Aug, 2021 A Singleton pattern in python is a design pattern that allows you to create just one instance of a class, throughout the lifetime of a program. Using a singleton pattern has many benefits. A few of them are: To limit concurrent access to a shared resource. To create a global point of access for a resource. To create just one instance of a class, throughout the lifetime of a program. Different ways to implement a Singleton: A singleton pattern can be implemented in three different ways. They are as follows: Module-level Singleton Classic Singleton Borg Singleton Module-level Singleton: All modules are singleton, by definition. Let’s create a simple module-level singleton where the data is shared among other modules. Here we will create three python files – singleton.py, sample_module1.py, and sample_module2.py – in which the other sample modules share a variable from singleton.py. ## singleton.py shared_variable = "Shared Variable" singleton.py ## samplemodule1.py import singleton print(singleton.shared_variable) singleton.shared_variable += "(modified by samplemodule1)" samplemodule1.py ##samplemodule2.py import singleton print(singleton.shared_variable) samplemodule2.py Let’s look into the output. Here, the value changed by samplemodule1 is also reflected in samplemodule2. Classic Singleton: Classic Singleton creates an instance only if there is no instance created so far; otherwise, it will return the instance that is already created. Let’s take a look at the below code. Python3 class SingletonClass(object): def __new__(cls): if not hasattr(cls, 'instance'): cls.instance = super(SingletonClass, cls).__new__(cls) return cls.instance singleton = SingletonClass()new_singleton = SingletonClass() print(singleton is new_singleton) singleton.singl_variable = "Singleton Variable"print(new_singleton.singl_variable) True Singleton Variable Here, in the __new__ method, we will check whether an instance is created or not. If created, it will return the instance; otherwise, it will create a new instance. You can notice that singleton and new_singleton return the same instance and have the same variable. Let’s check what happens when we subclass a singleton class. Python3 class SingletonClass(object): def __new__(cls): if not hasattr(cls, 'instance'): cls.instance = super(SingletonClass, cls).__new__(cls) return cls.instance class SingletonChild(SingletonClass): pass singleton = SingletonClass() child = SingletonChild()print(child is singleton) singleton.singl_variable = "Singleton Variable"print(child.singl_variable) True Singleton Variable Here, you can see that SingletonChild has the same instance of SingletonClass and also shares the same state. But there are scenarios, where we need a different instance, but should share the same state. This state sharing can be achieved using Borg singleton. Borg Singleton: Borg singleton is a design pattern in Python that allows state sharing for different instances. Let’s look into the following code. Python3 class BorgSingleton(object): _shared_borg_state = {} def __new__(cls, *args, **kwargs): obj = super(BorgSingleton, cls).__new__(cls, *args, **kwargs) obj.__dict__ = cls._shared_borg_state return obj borg = BorgSingleton()borg.shared_variable = "Shared Variable" class ChildBorg(BorgSingleton): pass childBorg = ChildBorg()print(childBorg is borg)print(childBorg.shared_variable) False Shared Variable Along with the new instance creation process, a shared state is also defined in the __new__ method. Here the shared state is retained using the shared_borg_state attribute and it is stored in the __dict__ dictionary of each instance. If you want a different state, then you can reset the shared_borg_state attribute. Let’s see how to reset a shared state. Python3 class BorgSingleton(object): _shared_borg_state = {} def __new__(cls, *args, **kwargs): obj = super(BorgSingleton, cls).__new__(cls, *args, **kwargs) obj.__dict__ = cls._shared_borg_state return obj borg = BorgSingleton()borg.shared_variable = "Shared Variable" class NewChildBorg(BorgSingleton): _shared_borg_state = {} newChildBorg = NewChildBorg()print(newChildBorg.shared_variable) Here, we have reset the shared state and tried to access the shared_variable. Let’s see the error. Traceback (most recent call last): File "/home/329d68500c5916767fbaf351710ebb13.py", line 16, in <module> print(newChildBorg.shared_variable) AttributeError: 'NewChildBorg' object has no attribute 'shared_variable' Use cases of a Singleton: Let’s list a few of the use cases of a singleton class. They are as follows: Managing a database connection Global point access to writing log messages File Manager Print spooler Create a Web Crawler using Classic Singleton: Let’s create a webcrawler that uses the benefit of a classic singleton. In this practical example, the crawler scans a webpage, fetch the links associated with the same website, and download all the images in it. Here, we have two main classes and two main functions. CrawlerSingleton: This class acts a classic singleton ParallelDownloader: This class provides thread functionality to download images navigate_site: This function crawls the website and fetches the links that belong to the same website. And, finally, it arranges the link to download images. download_images: This function crawls the page link and downloads the images. Apart from the above classes and functions, we use two sets of libraries to parse the web page – BeautifulSoap and HTTP Client. Have a look at the below code. Note: Execute the code in your local machine Python3 import httplib2import osimport reimport threadingimport urllibimport urllib.requestfrom urllib.parse import urlparse, urljoinfrom bs4 import BeautifulSoup class CrawlerSingleton(object): def __new__(cls): """ creates a singleton object, if it is not created, or else returns the previous singleton object""" if not hasattr(cls, 'instance'): cls.instance = super(CrawlerSingleton, cls).__new__(cls) return cls.instance def navigate_site(max_links = 5): """ navigate the website using BFS algorithm, find links and arrange them for downloading images """ # singleton instance parser_crawlersingleton = CrawlerSingleton() # During the initial stage, url_queue has the main_url. # Upon parsing the main_url page, new links that belong to the # same website is added to the url_queue until # it equals to max _links. while parser_crawlersingleton.url_queue: # checks whether it reached the max. link if len(parser_crawlersingleton.visited_url) == max_links: return # pop the url from the queue url = parser_crawlersingleton.url_queue.pop() # connect to the web page http = httplib2.Http() try: status, response = http.request(url) except Exception: continue # add the link to download the images parser_crawlersingleton.visited_url.add(url) print(url) # crawl the web page and fetch the links within # the main page bs = BeautifulSoup(response, "html.parser") for link in BeautifulSoup.findAll(bs, 'a'): link_url = link.get('href') if not link_url: continue # parse the fetched link parsed = urlparse(link_url) # skip the link, if it leads to an external page if parsed.netloc and parsed.netloc != parsed_url.netloc: continue scheme = parsed_url.scheme netloc = parsed.netloc or parsed_url.netloc path = parsed.path # construct a full url link_url = scheme +'://' +netloc + path # skip, if the link is already added if link_url in parser_crawlersingleton.visited_url: continue # Add the new link fetched, # so that the while loop continues with next iteration. parser_crawlersingleton.url_queue = [link_url] +\ parser_crawlersingleton.url_queue class ParallelDownloader(threading.Thread): """ Download the images parallelly """ def __init__(self, thread_id, name, counter): threading.Thread.__init__(self) self.name = name def run(self): print('Starting thread', self.name) # function to download the images download_images(self.name) print('Finished thread', self.name) def download_images(thread_name): # singleton instance singleton = CrawlerSingleton() # visited_url has a set of URLs. # Here we will fetch each URL and # download the images in it. while singleton.visited_url: # pop the url to download the images url = singleton.visited_url.pop() http = httplib2.Http() print(thread_name, 'Downloading images from', url) try: status, response = http.request(url) except Exception: continue # parse the web page to find all images bs = BeautifulSoup(response, "html.parser") # Find all <img> tags images = BeautifulSoup.findAll(bs, 'img') for image in images: src = image.get('src') src = urljoin(url, src) basename = os.path.basename(src) print('basename:', basename) if basename != '': if src not in singleton.image_downloaded: singleton.image_downloaded.add(src) print('Downloading', src) # Download the images to local system urllib.request.urlretrieve(src, os.path.join('images', basename)) print(thread_name, 'finished downloading images from', url) def main(): # singleton instance crwSingltn = CrawlerSingleton() # adding the url to the queue for parsing crwSingltn.url_queue = [main_url] # initializing a set to store all visited URLs # for downloading images. crwSingltn.visited_url = set() # initializing a set to store path of the downloaded images crwSingltn.image_downloaded = set() # invoking the method to crawl the website navigate_site() ## create images directory if not exists if not os.path.exists('images'): os.makedirs('images') thread1 = ParallelDownloader(1, "Thread-1", 1) thread2 = ParallelDownloader(2, "Thread-2", 2) # Start new threads thread1.start() thread2.start() if __name__ == "__main__": main_url = ("https://www.geeksforgeeks.org/") parsed_url = urlparse(main_url) main() Let’s look into the downloaded images and python shell output. Downloaded Images Python Shell Output Summary: Singleton pattern is a design pattern in Python that restricts the instantiation of a class to one object. It can limit concurrent access to a shared resource, and also it helps to create a global point of access for a resource. anikaseth98 saurabh1990aror clintra python-design-pattern Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 52, "s": 24, "text": "\n27 Aug, 2021" }, { "code": null, "e": 260, "s": 52, "text": "A Singleton pattern in python is a design pattern that allows you to create just one instance of a class, throughout the lifetime of a program. Using a singleton pattern has many benefits. A few of them are:" }, { "code": null, "e": 309, "s": 260, "text": "To limit concurrent access to a shared resource." }, { "code": null, "e": 360, "s": 309, "text": "To create a global point of access for a resource." }, { "code": null, "e": 438, "s": 360, "text": "To create just one instance of a class, throughout the lifetime of a program." }, { "code": null, "e": 479, "s": 438, "text": "Different ways to implement a Singleton:" }, { "code": null, "e": 564, "s": 479, "text": "A singleton pattern can be implemented in three different ways. They are as follows:" }, { "code": null, "e": 587, "s": 564, "text": "Module-level Singleton" }, { "code": null, "e": 605, "s": 587, "text": "Classic Singleton" }, { "code": null, "e": 620, "s": 605, "text": "Borg Singleton" }, { "code": null, "e": 644, "s": 620, "text": "Module-level Singleton:" }, { "code": null, "e": 947, "s": 644, "text": "All modules are singleton, by definition. Let’s create a simple module-level singleton where the data is shared among other modules. Here we will create three python files – singleton.py, sample_module1.py, and sample_module2.py – in which the other sample modules share a variable from singleton.py. " }, { "code": null, "e": 999, "s": 947, "text": "## singleton.py\nshared_variable = \"Shared Variable\"" }, { "code": null, "e": 1013, "s": 999, "text": " singleton.py" }, { "code": null, "e": 1142, "s": 1013, "text": "## samplemodule1.py\nimport singleton\nprint(singleton.shared_variable)\nsingleton.shared_variable += \"(modified by samplemodule1)\"" }, { "code": null, "e": 1159, "s": 1142, "text": "samplemodule1.py" }, { "code": null, "e": 1228, "s": 1159, "text": "##samplemodule2.py\nimport singleton\nprint(singleton.shared_variable)" }, { "code": null, "e": 1245, "s": 1228, "text": "samplemodule2.py" }, { "code": null, "e": 1273, "s": 1245, "text": "Let’s look into the output." }, { "code": null, "e": 1350, "s": 1273, "text": "Here, the value changed by samplemodule1 is also reflected in samplemodule2." }, { "code": null, "e": 1369, "s": 1350, "text": "Classic Singleton:" }, { "code": null, "e": 1553, "s": 1369, "text": "Classic Singleton creates an instance only if there is no instance created so far; otherwise, it will return the instance that is already created. Let’s take a look at the below code." }, { "code": null, "e": 1561, "s": 1553, "text": "Python3" }, { "code": "class SingletonClass(object): def __new__(cls): if not hasattr(cls, 'instance'): cls.instance = super(SingletonClass, cls).__new__(cls) return cls.instance singleton = SingletonClass()new_singleton = SingletonClass() print(singleton is new_singleton) singleton.singl_variable = \"Singleton Variable\"print(new_singleton.singl_variable)", "e": 1909, "s": 1561, "text": null }, { "code": null, "e": 1933, "s": 1909, "text": "True\nSingleton Variable" }, { "code": null, "e": 2199, "s": 1933, "text": "Here, in the __new__ method, we will check whether an instance is created or not. If created, it will return the instance; otherwise, it will create a new instance. You can notice that singleton and new_singleton return the same instance and have the same variable." }, { "code": null, "e": 2261, "s": 2199, "text": "Let’s check what happens when we subclass a singleton class. " }, { "code": null, "e": 2269, "s": 2261, "text": "Python3" }, { "code": "class SingletonClass(object): def __new__(cls): if not hasattr(cls, 'instance'): cls.instance = super(SingletonClass, cls).__new__(cls) return cls.instance class SingletonChild(SingletonClass): pass singleton = SingletonClass() child = SingletonChild()print(child is singleton) singleton.singl_variable = \"Singleton Variable\"print(child.singl_variable)", "e": 2641, "s": 2269, "text": null }, { "code": null, "e": 2668, "s": 2644, "text": "True\nSingleton Variable" }, { "code": null, "e": 2929, "s": 2668, "text": "Here, you can see that SingletonChild has the same instance of SingletonClass and also shares the same state. But there are scenarios, where we need a different instance, but should share the same state. This state sharing can be achieved using Borg singleton." }, { "code": null, "e": 2946, "s": 2929, "text": "Borg Singleton: " }, { "code": null, "e": 3078, "s": 2946, "text": "Borg singleton is a design pattern in Python that allows state sharing for different instances. Let’s look into the following code." }, { "code": null, "e": 3086, "s": 3078, "text": "Python3" }, { "code": "class BorgSingleton(object): _shared_borg_state = {} def __new__(cls, *args, **kwargs): obj = super(BorgSingleton, cls).__new__(cls, *args, **kwargs) obj.__dict__ = cls._shared_borg_state return obj borg = BorgSingleton()borg.shared_variable = \"Shared Variable\" class ChildBorg(BorgSingleton): pass childBorg = ChildBorg()print(childBorg is borg)print(childBorg.shared_variable)", "e": 3482, "s": 3086, "text": null }, { "code": null, "e": 3504, "s": 3482, "text": "False\nShared Variable" }, { "code": null, "e": 3738, "s": 3504, "text": "Along with the new instance creation process, a shared state is also defined in the __new__ method. Here the shared state is retained using the shared_borg_state attribute and it is stored in the __dict__ dictionary of each instance." }, { "code": null, "e": 3861, "s": 3738, "text": "If you want a different state, then you can reset the shared_borg_state attribute. Let’s see how to reset a shared state." }, { "code": null, "e": 3869, "s": 3861, "text": "Python3" }, { "code": "class BorgSingleton(object): _shared_borg_state = {} def __new__(cls, *args, **kwargs): obj = super(BorgSingleton, cls).__new__(cls, *args, **kwargs) obj.__dict__ = cls._shared_borg_state return obj borg = BorgSingleton()borg.shared_variable = \"Shared Variable\" class NewChildBorg(BorgSingleton): _shared_borg_state = {} newChildBorg = NewChildBorg()print(newChildBorg.shared_variable)", "e": 4274, "s": 3869, "text": null }, { "code": null, "e": 4373, "s": 4274, "text": "Here, we have reset the shared state and tried to access the shared_variable. Let’s see the error." }, { "code": null, "e": 4594, "s": 4373, "text": "Traceback (most recent call last):\n File \"/home/329d68500c5916767fbaf351710ebb13.py\", line 16, in <module>\n print(newChildBorg.shared_variable)\nAttributeError: 'NewChildBorg' object has no attribute 'shared_variable'" }, { "code": null, "e": 4620, "s": 4594, "text": "Use cases of a Singleton:" }, { "code": null, "e": 4697, "s": 4620, "text": "Let’s list a few of the use cases of a singleton class. They are as follows:" }, { "code": null, "e": 4728, "s": 4697, "text": "Managing a database connection" }, { "code": null, "e": 4772, "s": 4728, "text": "Global point access to writing log messages" }, { "code": null, "e": 4785, "s": 4772, "text": "File Manager" }, { "code": null, "e": 4799, "s": 4785, "text": "Print spooler" }, { "code": null, "e": 4845, "s": 4799, "text": "Create a Web Crawler using Classic Singleton:" }, { "code": null, "e": 5113, "s": 4845, "text": "Let’s create a webcrawler that uses the benefit of a classic singleton. In this practical example, the crawler scans a webpage, fetch the links associated with the same website, and download all the images in it. Here, we have two main classes and two main functions." }, { "code": null, "e": 5167, "s": 5113, "text": "CrawlerSingleton: This class acts a classic singleton" }, { "code": null, "e": 5247, "s": 5167, "text": "ParallelDownloader: This class provides thread functionality to download images" }, { "code": null, "e": 5405, "s": 5247, "text": "navigate_site: This function crawls the website and fetches the links that belong to the same website. And, finally, it arranges the link to download images." }, { "code": null, "e": 5483, "s": 5405, "text": "download_images: This function crawls the page link and downloads the images." }, { "code": null, "e": 5611, "s": 5483, "text": "Apart from the above classes and functions, we use two sets of libraries to parse the web page – BeautifulSoap and HTTP Client." }, { "code": null, "e": 5643, "s": 5611, "text": "Have a look at the below code. " }, { "code": null, "e": 5688, "s": 5643, "text": "Note: Execute the code in your local machine" }, { "code": null, "e": 5696, "s": 5688, "text": "Python3" }, { "code": "import httplib2import osimport reimport threadingimport urllibimport urllib.requestfrom urllib.parse import urlparse, urljoinfrom bs4 import BeautifulSoup class CrawlerSingleton(object): def __new__(cls): \"\"\" creates a singleton object, if it is not created, or else returns the previous singleton object\"\"\" if not hasattr(cls, 'instance'): cls.instance = super(CrawlerSingleton, cls).__new__(cls) return cls.instance def navigate_site(max_links = 5): \"\"\" navigate the website using BFS algorithm, find links and arrange them for downloading images \"\"\" # singleton instance parser_crawlersingleton = CrawlerSingleton() # During the initial stage, url_queue has the main_url. # Upon parsing the main_url page, new links that belong to the # same website is added to the url_queue until # it equals to max _links. while parser_crawlersingleton.url_queue: # checks whether it reached the max. link if len(parser_crawlersingleton.visited_url) == max_links: return # pop the url from the queue url = parser_crawlersingleton.url_queue.pop() # connect to the web page http = httplib2.Http() try: status, response = http.request(url) except Exception: continue # add the link to download the images parser_crawlersingleton.visited_url.add(url) print(url) # crawl the web page and fetch the links within # the main page bs = BeautifulSoup(response, \"html.parser\") for link in BeautifulSoup.findAll(bs, 'a'): link_url = link.get('href') if not link_url: continue # parse the fetched link parsed = urlparse(link_url) # skip the link, if it leads to an external page if parsed.netloc and parsed.netloc != parsed_url.netloc: continue scheme = parsed_url.scheme netloc = parsed.netloc or parsed_url.netloc path = parsed.path # construct a full url link_url = scheme +'://' +netloc + path # skip, if the link is already added if link_url in parser_crawlersingleton.visited_url: continue # Add the new link fetched, # so that the while loop continues with next iteration. parser_crawlersingleton.url_queue = [link_url] +\\ parser_crawlersingleton.url_queue class ParallelDownloader(threading.Thread): \"\"\" Download the images parallelly \"\"\" def __init__(self, thread_id, name, counter): threading.Thread.__init__(self) self.name = name def run(self): print('Starting thread', self.name) # function to download the images download_images(self.name) print('Finished thread', self.name) def download_images(thread_name): # singleton instance singleton = CrawlerSingleton() # visited_url has a set of URLs. # Here we will fetch each URL and # download the images in it. while singleton.visited_url: # pop the url to download the images url = singleton.visited_url.pop() http = httplib2.Http() print(thread_name, 'Downloading images from', url) try: status, response = http.request(url) except Exception: continue # parse the web page to find all images bs = BeautifulSoup(response, \"html.parser\") # Find all <img> tags images = BeautifulSoup.findAll(bs, 'img') for image in images: src = image.get('src') src = urljoin(url, src) basename = os.path.basename(src) print('basename:', basename) if basename != '': if src not in singleton.image_downloaded: singleton.image_downloaded.add(src) print('Downloading', src) # Download the images to local system urllib.request.urlretrieve(src, os.path.join('images', basename)) print(thread_name, 'finished downloading images from', url) def main(): # singleton instance crwSingltn = CrawlerSingleton() # adding the url to the queue for parsing crwSingltn.url_queue = [main_url] # initializing a set to store all visited URLs # for downloading images. crwSingltn.visited_url = set() # initializing a set to store path of the downloaded images crwSingltn.image_downloaded = set() # invoking the method to crawl the website navigate_site() ## create images directory if not exists if not os.path.exists('images'): os.makedirs('images') thread1 = ParallelDownloader(1, \"Thread-1\", 1) thread2 = ParallelDownloader(2, \"Thread-2\", 2) # Start new threads thread1.start() thread2.start() if __name__ == \"__main__\": main_url = (\"https://www.geeksforgeeks.org/\") parsed_url = urlparse(main_url) main()", "e": 10811, "s": 5696, "text": null }, { "code": null, "e": 10874, "s": 10811, "text": "Let’s look into the downloaded images and python shell output." }, { "code": null, "e": 10892, "s": 10874, "text": "Downloaded Images" }, { "code": null, "e": 10912, "s": 10892, "text": "Python Shell Output" }, { "code": null, "e": 10921, "s": 10912, "text": "Summary:" }, { "code": null, "e": 11151, "s": 10921, "text": "Singleton pattern is a design pattern in Python that restricts the instantiation of a class to one object. It can limit concurrent access to a shared resource, and also it helps to create a global point of access for a resource. " }, { "code": null, "e": 11163, "s": 11151, "text": "anikaseth98" }, { "code": null, "e": 11179, "s": 11163, "text": "saurabh1990aror" }, { "code": null, "e": 11187, "s": 11179, "text": "clintra" }, { "code": null, "e": 11209, "s": 11187, "text": "python-design-pattern" }, { "code": null, "e": 11216, "s": 11209, "text": "Python" }, { "code": null, "e": 11314, "s": 11216, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11346, "s": 11314, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 11373, "s": 11346, "text": "Python Classes and Objects" }, { "code": null, "e": 11394, "s": 11373, "text": "Python OOPs Concepts" }, { "code": null, "e": 11417, "s": 11394, "text": "Introduction To PYTHON" }, { "code": null, "e": 11473, "s": 11417, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 11504, "s": 11473, "text": "Python | os.path.join() method" }, { "code": null, "e": 11546, "s": 11504, "text": "Check if element exists in list in Python" }, { "code": null, "e": 11588, "s": 11546, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 11627, "s": 11588, "text": "Python | Get unique values from a list" } ]
Introduction to pywhatkit module
13 Jun, 2022 Python offers numerous inbuilt libraries to ease our work. Among them pywhatkit is a Python library for sending WhatsApp messages at a certain time, it has several other features too. Following are some features of pywhatkit module: Send WhatsApp messages.Play a YouTube video.Perform a Google Search.Get information on a particular topic. Send WhatsApp messages. Play a YouTube video. Perform a Google Search. Get information on a particular topic. The pywhatkit module can also be used for converting text into handwritten text images. In Python3 pywhatkit module will not come pre-installed, so you can install it by using the command: pip install pywhatkit Here, we will learn the simplest way of using pywhatkit module which utilises the WhatsApp webpage to automate messages sending to any number on WhatsApp. But make sure that you have logged into your WhatsApp in your browser. Syntax: pywhatkit.sendmsg(“receiver mobile number”,”message”,hours,minutes) Parameters: Receiver mobile number: The Receiver’s mobile number must be in string format and the country code must be mentioned before the mobile number. Message: Message to be sent(Must be in string format). Hours: This module follows the 24 hrs time format. Minutes: Mention minutes of the scheduled time for the message(00-59). Example: Python3 # importing the moduleimport pywhatkit # using Exception Handling to avoid# unprecedented errorstry: # sending message to receiver # using pywhatkit pywhatkit.sendwhatmsg("+91xxxxxxxxxx", "Hello from GeeksforGeeks", 22, 28) print("Successfully Sent!") except: # handling exception # and printing error message print("An Unexpected Error!") Function pywhatkit.playonyt(), opens the YouTube in your default browser and plays the video you mentioned in the function. If you pass the topic name as parameter, it plays the random video on that topic. On passing the URL of the video as the parameter, it open that exact video. Syntax: pywhatkit.playonyt(“url/topic name”) Parameters: URL/Topic Name: Mention the topic name or URL of the YouTube video Example: Python3 # importing the moduleimport pywhatkit # using Exception Handling# to avoid exceptionstry: # it plays a random YouTube # video of GeeksforGeeks pywhatkit.playonyt("GeeksforGeeks") print("Playing...") except: # printing the error message print("Network Error Occurred") Output: You can perform a Google search using the following simple command. It opens your browser and searches for the topic you have given in your code. Syntax: pywhatkit.search(“Keyword”) Parameters: Keyword: It open your browser and performs search operation. Example: Python3 # importing the moduleimport pywhatkit # use Try Except to# handle the Exceptionstry: # it will perform the Google search pywhatkit.search("GeeksforGeeks") print("Searching...") except: # Printing Error Message print("An unknown error occurred") Output: We can get brief information on a particular topic. We can also limit the number of lines to be printed. Also, make sure that you are searching for the topics that are available on Wikipedia. Syntax: pywhatkit.info(“topic”,lines=x) Parameters: Topic: Gives the output on the topic mentioned. lines: It prints the searched topic in the specified number of lines. Example: Python3 # importing the moduleimport pywhatkit # using Exception Handling for# handling unprecedented errorstry: # it will perform google search pywhatkit.info("Google", lines = 4) print("\nSuccessfully Searched") except: # printing error message print("An Unknown Error Occurred") Output: Google LLC is an American multinational technology company that specializes in Internet-related services and products, which include online advertising technologies, a search engine, cloud computing, software, and hardware. It is considered one of the Big Four technology companies alongside Amazon, Apple and Microsoft.Google was founded in September 1998 by Larry Page and Sergey Brin while they were Ph.D. students at Stanford University in California. Together they own about 14 percent of its shares and control 56 percent of the stockholder voting power through supervoting stock. They incorporated Google as a California privately held company on September 4, 1998, in California. Successfully Searched astharamwala sagar0719kumar harshmaster07705 surinderdawra388 python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n13 Jun, 2022" }, { "code": null, "e": 237, "s": 53, "text": "Python offers numerous inbuilt libraries to ease our work. Among them pywhatkit is a Python library for sending WhatsApp messages at a certain time, it has several other features too." }, { "code": null, "e": 286, "s": 237, "text": "Following are some features of pywhatkit module:" }, { "code": null, "e": 393, "s": 286, "text": "Send WhatsApp messages.Play a YouTube video.Perform a Google Search.Get information on a particular topic." }, { "code": null, "e": 417, "s": 393, "text": "Send WhatsApp messages." }, { "code": null, "e": 439, "s": 417, "text": "Play a YouTube video." }, { "code": null, "e": 464, "s": 439, "text": "Perform a Google Search." }, { "code": null, "e": 503, "s": 464, "text": "Get information on a particular topic." }, { "code": null, "e": 592, "s": 503, "text": "The pywhatkit module can also be used for converting text into handwritten text images. " }, { "code": null, "e": 693, "s": 592, "text": "In Python3 pywhatkit module will not come pre-installed, so you can install it by using the command:" }, { "code": null, "e": 715, "s": 693, "text": "pip install pywhatkit" }, { "code": null, "e": 941, "s": 715, "text": "Here, we will learn the simplest way of using pywhatkit module which utilises the WhatsApp webpage to automate messages sending to any number on WhatsApp. But make sure that you have logged into your WhatsApp in your browser." }, { "code": null, "e": 1017, "s": 941, "text": "Syntax: pywhatkit.sendmsg(“receiver mobile number”,”message”,hours,minutes)" }, { "code": null, "e": 1029, "s": 1017, "text": "Parameters:" }, { "code": null, "e": 1172, "s": 1029, "text": "Receiver mobile number: The Receiver’s mobile number must be in string format and the country code must be mentioned before the mobile number." }, { "code": null, "e": 1227, "s": 1172, "text": "Message: Message to be sent(Must be in string format)." }, { "code": null, "e": 1278, "s": 1227, "text": "Hours: This module follows the 24 hrs time format." }, { "code": null, "e": 1349, "s": 1278, "text": "Minutes: Mention minutes of the scheduled time for the message(00-59)." }, { "code": null, "e": 1358, "s": 1349, "text": "Example:" }, { "code": null, "e": 1366, "s": 1358, "text": "Python3" }, { "code": "# importing the moduleimport pywhatkit # using Exception Handling to avoid# unprecedented errorstry: # sending message to receiver # using pywhatkit pywhatkit.sendwhatmsg(\"+91xxxxxxxxxx\", \"Hello from GeeksforGeeks\", 22, 28) print(\"Successfully Sent!\") except: # handling exception # and printing error message print(\"An Unexpected Error!\")", "e": 1765, "s": 1366, "text": null }, { "code": null, "e": 2050, "s": 1768, "text": "Function pywhatkit.playonyt(), opens the YouTube in your default browser and plays the video you mentioned in the function. If you pass the topic name as parameter, it plays the random video on that topic. On passing the URL of the video as the parameter, it open that exact video." }, { "code": null, "e": 2095, "s": 2050, "text": "Syntax: pywhatkit.playonyt(“url/topic name”)" }, { "code": null, "e": 2108, "s": 2095, "text": "Parameters: " }, { "code": null, "e": 2175, "s": 2108, "text": "URL/Topic Name: Mention the topic name or URL of the YouTube video" }, { "code": null, "e": 2184, "s": 2175, "text": "Example:" }, { "code": null, "e": 2192, "s": 2184, "text": "Python3" }, { "code": "# importing the moduleimport pywhatkit # using Exception Handling# to avoid exceptionstry: # it plays a random YouTube # video of GeeksforGeeks pywhatkit.playonyt(\"GeeksforGeeks\") print(\"Playing...\") except: # printing the error message print(\"Network Error Occurred\")", "e": 2473, "s": 2192, "text": null }, { "code": null, "e": 2482, "s": 2473, "text": " Output:" }, { "code": null, "e": 2628, "s": 2482, "text": "You can perform a Google search using the following simple command. It opens your browser and searches for the topic you have given in your code." }, { "code": null, "e": 2664, "s": 2628, "text": "Syntax: pywhatkit.search(“Keyword”)" }, { "code": null, "e": 2677, "s": 2664, "text": "Parameters: " }, { "code": null, "e": 2738, "s": 2677, "text": "Keyword: It open your browser and performs search operation." }, { "code": null, "e": 2748, "s": 2738, "text": "Example: " }, { "code": null, "e": 2756, "s": 2748, "text": "Python3" }, { "code": "# importing the moduleimport pywhatkit # use Try Except to# handle the Exceptionstry: # it will perform the Google search pywhatkit.search(\"GeeksforGeeks\") print(\"Searching...\") except: # Printing Error Message print(\"An unknown error occurred\")", "e": 3013, "s": 2756, "text": null }, { "code": null, "e": 3021, "s": 3013, "text": "Output:" }, { "code": null, "e": 3213, "s": 3021, "text": "We can get brief information on a particular topic. We can also limit the number of lines to be printed. Also, make sure that you are searching for the topics that are available on Wikipedia." }, { "code": null, "e": 3253, "s": 3213, "text": "Syntax: pywhatkit.info(“topic”,lines=x)" }, { "code": null, "e": 3266, "s": 3253, "text": "Parameters: " }, { "code": null, "e": 3314, "s": 3266, "text": "Topic: Gives the output on the topic mentioned." }, { "code": null, "e": 3384, "s": 3314, "text": "lines: It prints the searched topic in the specified number of lines." }, { "code": null, "e": 3393, "s": 3384, "text": "Example:" }, { "code": null, "e": 3401, "s": 3393, "text": "Python3" }, { "code": "# importing the moduleimport pywhatkit # using Exception Handling for# handling unprecedented errorstry: # it will perform google search pywhatkit.info(\"Google\", lines = 4) print(\"\\nSuccessfully Searched\") except: # printing error message print(\"An Unknown Error Occurred\")", "e": 3688, "s": 3401, "text": null }, { "code": null, "e": 3697, "s": 3688, "text": " Output:" }, { "code": null, "e": 4385, "s": 3697, "text": "Google LLC is an American multinational technology company that specializes in Internet-related services and products, which include online advertising technologies, a search engine, cloud computing, software, and hardware. It is considered one of the Big Four technology companies alongside Amazon, Apple and Microsoft.Google was founded in September 1998 by Larry Page and Sergey Brin while they were Ph.D. students at Stanford University in California. Together they own about 14 percent of its shares and control 56 percent of the stockholder voting power through supervoting stock. They incorporated Google as a California privately held company on September 4, 1998, in California." }, { "code": null, "e": 4407, "s": 4385, "text": "Successfully Searched" }, { "code": null, "e": 4420, "s": 4407, "text": "astharamwala" }, { "code": null, "e": 4435, "s": 4420, "text": "sagar0719kumar" }, { "code": null, "e": 4452, "s": 4435, "text": "harshmaster07705" }, { "code": null, "e": 4469, "s": 4452, "text": "surinderdawra388" }, { "code": null, "e": 4484, "s": 4469, "text": "python-modules" }, { "code": null, "e": 4491, "s": 4484, "text": "Python" } ]
Python PIL | Image.alpha_composite() Method
02 Aug, 2019 PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images. Image.alpha_composite() Alpha composite im2 over im1. Syntax: PIL.Image.alpha_composite(im1, im2) Parameters:img1 – The first image.img2 – The second image. Must have the same mode and size as the first image. Returns: An Image object. Img1 Used: Img2 Used: # importing image class from PIL packagefrom PIL import Image # creating image objectimg1 = Image.open(r"C:\Users\System-Pc\Desktop\home.png") # creating image2 object having alphaimg2 = Image.open(r"C:\Users\System-Pc\Desktop\python.png")img2 = img2.resize(img1.size) # using alpha_compositeim3 = Image.alpha_composite(img1, img2)im3.show() Output: Python-pil Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Aug, 2019" }, { "code": null, "e": 355, "s": 28, "text": "PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images." }, { "code": null, "e": 409, "s": 355, "text": "Image.alpha_composite() Alpha composite im2 over im1." }, { "code": null, "e": 453, "s": 409, "text": "Syntax: PIL.Image.alpha_composite(im1, im2)" }, { "code": null, "e": 565, "s": 453, "text": "Parameters:img1 – The first image.img2 – The second image. Must have the same mode and size as the first image." }, { "code": null, "e": 591, "s": 565, "text": "Returns: An Image object." }, { "code": null, "e": 602, "s": 591, "text": "Img1 Used:" }, { "code": null, "e": 613, "s": 602, "text": "Img2 Used:" }, { "code": " # importing image class from PIL packagefrom PIL import Image # creating image objectimg1 = Image.open(r\"C:\\Users\\System-Pc\\Desktop\\home.png\") # creating image2 object having alphaimg2 = Image.open(r\"C:\\Users\\System-Pc\\Desktop\\python.png\")img2 = img2.resize(img1.size) # using alpha_compositeim3 = Image.alpha_composite(img1, img2)im3.show()", "e": 961, "s": 613, "text": null }, { "code": null, "e": 969, "s": 961, "text": "Output:" }, { "code": null, "e": 980, "s": 969, "text": "Python-pil" }, { "code": null, "e": 987, "s": 980, "text": "Python" } ]
PyQt5 QListWidget – Setting Resize Mode Property
06 Aug, 2020 In this article we will see how we can set the resize mode property to the QListWidget. QListWidget is a convenience class that provides a list view with a classic item-based interface for adding and removing items. QListWidget uses an internal model to manage each QListWidgetItem in the list. This property holds whether the items are laid out again when the view is resized. If this property is Adjust, the items will be laid out again when the view is resized. If the value is Fixed, the items will not be laid out when the view is resized. By default, this property is set to Fixed. In order to do this we will use setResizeMode method with the list widget object. Syntax : list_widget.setResizeMode(mode) Argument : It takes resize mode object as argument Return : It returns None Below is the implementation # importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QListWidget list_widget = QListWidget(self) # setting geometry to it list_widget.setGeometry(50, 70, 150, 60) # list widget items item1 = QListWidgetItem("A") item2 = QListWidgetItem("B") item3 = QListWidgetItem("C") # adding items to the list widget list_widget.addItem(item1) list_widget.addItem(item2) list_widget.addItem(item3) # setting resize mode property list_widget.setResizeMode(QListView.Fixed) # creating a label label = QLabel("GeesforGeeks", self) # setting geometry to the label label.setGeometry(230, 80, 280, 80) # making label multi line label.setWordWrap(True) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Python PyQt-QListWidget Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Aug, 2020" }, { "code": null, "e": 616, "s": 28, "text": "In this article we will see how we can set the resize mode property to the QListWidget. QListWidget is a convenience class that provides a list view with a classic item-based interface for adding and removing items. QListWidget uses an internal model to manage each QListWidgetItem in the list. This property holds whether the items are laid out again when the view is resized. If this property is Adjust, the items will be laid out again when the view is resized. If the value is Fixed, the items will not be laid out when the view is resized. By default, this property is set to Fixed." }, { "code": null, "e": 698, "s": 616, "text": "In order to do this we will use setResizeMode method with the list widget object." }, { "code": null, "e": 739, "s": 698, "text": "Syntax : list_widget.setResizeMode(mode)" }, { "code": null, "e": 790, "s": 739, "text": "Argument : It takes resize mode object as argument" }, { "code": null, "e": 815, "s": 790, "text": "Return : It returns None" }, { "code": null, "e": 843, "s": 815, "text": "Below is the implementation" }, { "code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QListWidget list_widget = QListWidget(self) # setting geometry to it list_widget.setGeometry(50, 70, 150, 60) # list widget items item1 = QListWidgetItem(\"A\") item2 = QListWidgetItem(\"B\") item3 = QListWidgetItem(\"C\") # adding items to the list widget list_widget.addItem(item1) list_widget.addItem(item2) list_widget.addItem(item3) # setting resize mode property list_widget.setResizeMode(QListView.Fixed) # creating a label label = QLabel(\"GeesforGeeks\", self) # setting geometry to the label label.setGeometry(230, 80, 280, 80) # making label multi line label.setWordWrap(True) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 2266, "s": 843, "text": null }, { "code": null, "e": 2275, "s": 2266, "text": "Output :" }, { "code": null, "e": 2299, "s": 2275, "text": "Python PyQt-QListWidget" }, { "code": null, "e": 2310, "s": 2299, "text": "Python-gui" }, { "code": null, "e": 2322, "s": 2310, "text": "Python-PyQt" }, { "code": null, "e": 2329, "s": 2322, "text": "Python" } ]
plotly.express.scatter_geo() function in Python
17 Jul, 2020 Plotly library of Python can be very useful for data visualization and understanding the data simply and easily. Plotly graph objects are a high-level interface to plotly which are easy to use. This function is used to plot geographical data onto the maps. Syntax: plotly.express.scatter_geo(data_frame=None, lat=None, lon=None, locations=None, locationmode=None, color=None, text=None, hover_name=None, hover_data=None, custom_data=None, size=None, title=None, template=None, width=None, height=None) Parameters: data_frame: DataFrame or array-like or dict needs to be passed for column names. lat: This parameter is used to position marks according to latitude on a map. lon: This parameter is used to position marks according to longitude on a map. locations: This parameter is interpreted according to locationmode and mapped to longitude/latitude. locationmode: This parameter determines the set of locations used to match entries in locations to regions on the map. color: This parameters assign color to marks. size: This parameter is used to assign mark sizes. It is either a name of a column in data_frame, or a pandas Series or array_like object. title: This parameter sets the title of the figure. width: This parameter sets the width of the figure height: This parameter sets the height of the figure. Example 1: Python3 import plotly.express as px df = px.data.gapminder().query("year == 2007") plot = px.scatter_geo(df, locations="iso_alpha")plot.show() Output: Example 2: Using the size and color argument Python3 import plotly.express as px df = px.data.gapminder().query("year == 2007") plot = px.scatter_geo(df, locations="iso_alpha", size="gdpPercap", color = "country")plot.show() Output: Python Plotly express-class Python-Plotly Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Jul, 2020" }, { "code": null, "e": 222, "s": 28, "text": "Plotly library of Python can be very useful for data visualization and understanding the data simply and easily. Plotly graph objects are a high-level interface to plotly which are easy to use." }, { "code": null, "e": 285, "s": 222, "text": "This function is used to plot geographical data onto the maps." }, { "code": null, "e": 530, "s": 285, "text": "Syntax: plotly.express.scatter_geo(data_frame=None, lat=None, lon=None, locations=None, locationmode=None, color=None, text=None, hover_name=None, hover_data=None, custom_data=None, size=None, title=None, template=None, width=None, height=None)" }, { "code": null, "e": 542, "s": 530, "text": "Parameters:" }, { "code": null, "e": 623, "s": 542, "text": "data_frame: DataFrame or array-like or dict needs to be passed for column names." }, { "code": null, "e": 701, "s": 623, "text": "lat: This parameter is used to position marks according to latitude on a map." }, { "code": null, "e": 780, "s": 701, "text": "lon: This parameter is used to position marks according to longitude on a map." }, { "code": null, "e": 881, "s": 780, "text": "locations: This parameter is interpreted according to locationmode and mapped to longitude/latitude." }, { "code": null, "e": 1000, "s": 881, "text": "locationmode: This parameter determines the set of locations used to match entries in locations to regions on the map." }, { "code": null, "e": 1046, "s": 1000, "text": "color: This parameters assign color to marks." }, { "code": null, "e": 1185, "s": 1046, "text": "size: This parameter is used to assign mark sizes. It is either a name of a column in data_frame, or a pandas Series or array_like object." }, { "code": null, "e": 1237, "s": 1185, "text": "title: This parameter sets the title of the figure." }, { "code": null, "e": 1288, "s": 1237, "text": "width: This parameter sets the width of the figure" }, { "code": null, "e": 1342, "s": 1288, "text": "height: This parameter sets the height of the figure." }, { "code": null, "e": 1353, "s": 1342, "text": "Example 1:" }, { "code": null, "e": 1361, "s": 1353, "text": "Python3" }, { "code": "import plotly.express as px df = px.data.gapminder().query(\"year == 2007\") plot = px.scatter_geo(df, locations=\"iso_alpha\")plot.show()", "e": 1500, "s": 1361, "text": null }, { "code": null, "e": 1508, "s": 1500, "text": "Output:" }, { "code": null, "e": 1553, "s": 1508, "text": "Example 2: Using the size and color argument" }, { "code": null, "e": 1561, "s": 1553, "text": "Python3" }, { "code": "import plotly.express as px df = px.data.gapminder().query(\"year == 2007\") plot = px.scatter_geo(df, locations=\"iso_alpha\", size=\"gdpPercap\", color = \"country\")plot.show()", "e": 1779, "s": 1561, "text": null }, { "code": null, "e": 1787, "s": 1779, "text": "Output:" }, { "code": null, "e": 1815, "s": 1787, "text": "Python Plotly express-class" }, { "code": null, "e": 1829, "s": 1815, "text": "Python-Plotly" }, { "code": null, "e": 1836, "s": 1829, "text": "Python" } ]
Meet in the middle
09 Sep, 2021 Given a set of n integers where n <= 40. Each of them is at most 1012, determine the maximum sum subset having sum less than or equal S where S <= 1018. Example: Input : set[] = {45, 34, 4, 12, 5, 2} and S = 42 Output : 41 Maximum possible subset sum is 41 which can be obtained by summing 34, 5 and 2. Input : Set[] = {3, 34, 4, 12, 5, 2} and S = 10 Output : 10 Maximum possible subset sum is 10 which can be obtained by summing 2, 3 and 5. A Brute Force approach to solve this problem would be find all possible subset sums of N integers and check if it is less than or equal S and keep track of such a subset with maximum sum. The time complexity using this approach would be O(2n) and n is at most 40. 240 will be quite large and hence we need to find more optimal approach. Meet in the middle is a search technique which is used when the input is small but not as small that brute force can be used. Like divide and conquer it splits the problem into two, solves them individually and then merge them. But we can’t apply meet in the middle like divide and conquer because we don’t have the same structure as the original problem. Split the set of integers into 2 subsets say A and B. A having first n/2 integers and B having rest. Find all possible subset sums of integers in set A and store in an array X. Similarly calculate all possible subset sums of integers in set B and store in array Y. Hence, Size of each of the array X and Y will be at most 2n/2. Now merge these 2 subproblems. Find combinations from array X and Y such that their sum is less than or equal to S. One way to do that is simply iterate over all elements of array Y for each element of array X to check the existence of such a combination. This will take O( (2n/2)2) which is equivalent to O(2n).To make it less complex, first sort array Y and then iterate over each element of X and for each element x in X use binary search to find maximum element y in Y such that x + y <= S.Binary search here helps in reducing complexity from 2nto 2n/2log(2n/2)which is equivalent to 2n/2n.Thus our final running time is O(2n/2n). One way to do that is simply iterate over all elements of array Y for each element of array X to check the existence of such a combination. This will take O( (2n/2)2) which is equivalent to O(2n). To make it less complex, first sort array Y and then iterate over each element of X and for each element x in X use binary search to find maximum element y in Y such that x + y <= S. Binary search here helps in reducing complexity from 2nto 2n/2log(2n/2)which is equivalent to 2n/2n. Thus our final running time is O(2n/2n). C++ Java Python3 C# Javascript // C++ program to demonstrate working of Meet in the// Middle algorithm for maximum subset sum problem.#include <bits/stdc++.h>using namespace std;typedef long long int ll;ll X[2000005],Y[2000005]; // Find all possible sum of elements of a[] and store// in x[]void calcsubarray(ll a[], ll x[], int n, int c){ for (int i=0; i<(1<<n); i++) { ll s = 0; for (int j=0; j<n; j++) if (i & (1<<j)) s += a[j+c]; x[i] = s; }} // Returns the maximum possible sum less or equal to Sll solveSubsetSum(ll a[], int n, ll S){ // Compute all subset sums of first and second // halves calcsubarray(a, X, n/2, 0); calcsubarray(a, Y, n-n/2, n/2); int size_X = 1<<(n/2); int size_Y = 1<<(n-n/2); // Sort Y (we need to do doing binary search in it) sort(Y, Y+size_Y); // To keep track of the maximum sum of a subset // such that the maximum sum is less than S ll max = 0; // Traverse all elements of X and do Binary Search // for a pair in Y with maximum sum less than S. for (int i=0; i<size_X; i++) { if (X[i] <= S) { // lower_bound() returns the first address // which has value greater than or equal to // S-X[i]. int p = lower_bound(Y, Y+size_Y, S-X[i]) - Y; // If S-X[i] was not in array Y then decrease // p by 1 if (p == size_Y || Y[p] != (S-X[i])) p--; if ((Y[p]+X[i]) > max) max = Y[p]+X[i]; } } return max;} // Driver codeint main(){ ll a[] = {3, 34, 4, 12, 5, 2}; int n=sizeof(a)/sizeof(a[0]); ll S = 10; printf("Largest value smaller than or equal to given " "sum is %lld\n", solveSubsetSum(a,n,S)); return 0;} // Java program to demonstrate working of// Meet in the Middle algorithm for// maximum subset sum problemimport java.util.*;import java.lang.*;import java.io.*; class GFG{ static long X[] = new long[2000005];static long Y[] = new long[2000005]; // Find all possible sum of elements of a[]// and store in x[]static void calcsubarray(long a[],long x[], int n, int c){ for(int i = 0; i < (1 << n); i++) { long s = 0; for(int j = 0; j < n; j++) if ((i & (1 << j)) == 1) s += a[j + c]; x[i] = s; }} // Returns the maximum possible sum// less or equal to S static long solveSubsetSum(long a[], int n, long S){ // Compute all subset sums of first and second // halves calcsubarray(a, X, n / 2, 0); calcsubarray(a, Y, n - n / 2, n / 2); int size_X = 1 << (n / 2); int size_Y = 1 << (n - n / 2); // Sort Y (we need to do doing // binary search in it) Arrays.sort(Y); // To keep track of the maximum sum // of a subset such that the maximum // sum is less than S long max = 0; // Traverse all elements of X and do // Binary Search for a pair in Y with // maximum sum less than S. for(int i = 0; i < size_X; i++) { if (X[i] <= S) { // lower_bound() returns the first address // which has value greater than or equal to // S-X[i]. int p = lower_bound(Y, S - X[i]); // If S-X[i] was not in array Y then // decrease p by 1 if (p == size_Y || Y[p] != (S - X[i])) p--; if ((Y[p] + X[i]) > max) max = Y[p] + X[i]; } } return max;} static int lower_bound(long a[], long x){ // x is the target value or key int l = -1, r = a.length; while (l + 1 < r) { int m = (l + r) >>> 1; if (a[m] >= x) r = m; else l = m; } return r;} // Driver codepublic static void main (String[] args){ long a[] = { 3, 34, 4, 12, 5, 2 }; int n = a.length; long S = 10; System.out.println("Largest value smaller " + "than or equal to given " + "sum is " + solveSubsetSum(a, n, S));}} // This code is contributed by jyoti369 # Python program to demonstrate working of Meet in the# Middle algorithm for maximum subset sum problem.from typing import Listimport bisectX = [0] * 2000005Y = [0] * 2000005 # Find all possible sum of elements of a[] and store# in x[]def calcsubarray(a: List[int], x: List[int], n: int, c: int) -> None: for i in range((1 << n)): s = 0 for j in range(n): if (i & (1 << j)): s += a[j + c] x[i] = s # Returns the maximum possible sum less or equal to Sdef solveSubsetSum(a: List[int], n: int, S: int) -> int: global Y # Compute all subset sums of first and second # halves calcsubarray(a, X, n // 2, 0) calcsubarray(a, Y, n - n // 2, n // 2) size_X = 1 << (n // 2) size_Y = 1 << (n - n // 2) # Sort Y (we need to do doing binary search in it) YY = Y[:size_Y] YY.sort() Y = YY # To keep track of the maximum sum of a subset # such that the maximum sum is less than S maxx = 0 # Traverse all elements of X and do Binary Search # for a pair in Y with maximum sum less than S. for i in range(size_X): if (X[i] <= S): # lower_bound() returns the first address # which has value greater than or equal to # S-X[i]. p = bisect.bisect_left(Y, S - X[i]) # If S-X[i] was not in array Y then decrease # p by 1 if (p == size_Y or (p < size_Y and Y[p] != (S - X[i]))): p -= 1 if ((Y[p] + X[i]) > maxx): maxx = Y[p] + X[i] return maxx # Driver codeif __name__ == "__main__": a = [3, 34, 4, 12, 5, 2] n = len(a) S = 10 print("Largest value smaller than or equal to given sum is {}".format( solveSubsetSum(a, n, S))) # This code is contributed by sanjeev2552 // C# program to demonstrate working of// Meet in the Middle algorithm for// maximum subset sum problemusing System;public class GFG{ static long[] X = new long[2000005]; static long[] Y = new long[2000005]; // Find all possible sum of elements of a[] // and store in x[] static void calcsubarray(long[] a,long[] x, int n, int c) { for(int i = 0; i < (1 << n); i++) { long s = 0; for(int j = 0; j < n; j++) if ((i & (1 << j)) == 1) s += a[j + c]; x[i] = s; } } // Returns the maximum possible sum // less or equal to S static long solveSubsetSum(long[] a, int n, long S) { // Compute all subset sums of first and second // halves calcsubarray(a, X, n / 2, 0); calcsubarray(a, Y, n - n / 2, n / 2); int size_X = 1 << (n / 2); int size_Y = 1 << (n - n / 2); // Sort Y (we need to do doing // binary search in it) Array.Sort(Y); // To keep track of the maximum sum // of a subset such that the maximum // sum is less than S long max = 0; // Traverse all elements of X and do // Binary Search for a pair in Y with // maximum sum less than S. for(int i = 0; i < size_X; i++) { if (X[i] <= S) { // lower_bound() returns the first address // which has value greater than or equal to // S-X[i]. int p = lower_bound(Y, S - X[i]); // If S-X[i] was not in array Y then // decrease p by 1 if (p == size_Y || Y[p] != (S - X[i])) p--; if ((Y[p] + X[i]) > max) max = Y[p] + X[i]; } } return max; } static int lower_bound(long[] a, long x) { // x is the target value or key int l = -1, r = a.Length; while (l + 1 < r) { int m = (l + r) >> 1; if (a[m] >= x) r = m; else l = m; } return r; } // Driver code static public void Main () { long[] a = { 3, 34, 4, 12, 5, 2 }; int n = a.Length; long S = 10; Console.WriteLine("Largest value smaller " + "than or equal to given " + "sum is " + solveSubsetSum(a, n, S)); }} // This code is contributed by Dharanendra L V. <script>// Javascript program to demonstrate working of// Meet in the Middle algorithm for// maximum subset sum problemlet X = new Array(2000005);let Y = new Array(2000005);for(let i = 0; i < 2000005; i++){ X[i] = 0; Y[i] = 0;} // Find all possible sum of elements of a[]// and store in x[]function calcsubarray(a, x, n, c){ for(let i = 0; i < (1 << n); i++) { let s = 0; for(let j = 0; j < n; j++) if ((i & (1 << j)) == 1) s += a[j + c]; x[i] = s; }} // Returns the maximum possible sum// less or equal to Sfunction solveSubsetSum(a,n,S){ // Compute all subset sums of first and second // halves calcsubarray(a, X, Math.floor(n / 2), 0); calcsubarray(a, Y, n - Math.floor(n / 2), Math.floor(n / 2)); let size_X = 1 << Math.floor(n / 2); let size_Y = 1 << (n - Math.floor(n / 2)); // Sort Y (we need to do doing // binary search in it) Y.sort(function(a,b){return a-b;}); // To keep track of the maximum sum // of a subset such that the maximum // sum is less than S let max = 0; // Traverse all elements of X and do // Binary Search for a pair in Y with // maximum sum less than S. for(let i = 0; i < size_X; i++) { if (X[i] <= S) { // lower_bound() returns the first address // which has value greater than or equal to // S-X[i]. let p = lower_bound(Y, S - X[i]); // If S-X[i] was not in array Y then // decrease p by 1 if (p == size_Y || Y[p] != (S - X[i])) p--; if ((Y[p] + X[i]) > max) max = Y[p] + X[i]; } } return max;} function lower_bound(a,x){ // x is the target value or key let l = -1, r = a.length; while (l + 1 < r) { let m = (l + r) >>> 1; if (a[m] >= x) r = m; else l = m; } return r;} // Driver codelet a=[3, 34, 4, 12, 5, 2 ];let n = a.length;let S = 10;document.write("Largest value smaller " + "than or equal to given " + "sum is " + solveSubsetSum(a, n, S)+"<br>"); // This code is contributed by avanitrachhadiya2155</script> Output: Largest value smaller than or equal to given sum is 10 Reference: https://www.quora.com/What-is-meet-in-the-middle-algorithm-w-r-t-competitive-programming Time Complexity: O()Auxiliary Space: O() This article is contributed by Madhur Modi. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above jyoti369 sanjeev2552 dharanendralv23 pankajsharmagfg avanitrachhadiya2155 ayush123ngp meet-in-the-middle Algorithms Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n09 Sep, 2021" }, { "code": null, "e": 205, "s": 52, "text": "Given a set of n integers where n <= 40. Each of them is at most 1012, determine the maximum sum subset having sum less than or equal S where S <= 1018." }, { "code": null, "e": 216, "s": 205, "text": "Example: " }, { "code": null, "e": 501, "s": 216, "text": "Input : set[] = {45, 34, 4, 12, 5, 2} and S = 42\nOutput : 41\nMaximum possible subset sum is 41 which can be \nobtained by summing 34, 5 and 2.\n\nInput : Set[] = {3, 34, 4, 12, 5, 2} and S = 10\nOutput : 10\nMaximum possible subset sum is 10 which can be \nobtained by summing 2, 3 and 5." }, { "code": null, "e": 838, "s": 501, "text": "A Brute Force approach to solve this problem would be find all possible subset sums of N integers and check if it is less than or equal S and keep track of such a subset with maximum sum. The time complexity using this approach would be O(2n) and n is at most 40. 240 will be quite large and hence we need to find more optimal approach." }, { "code": null, "e": 1194, "s": 838, "text": "Meet in the middle is a search technique which is used when the input is small but not as small that brute force can be used. Like divide and conquer it splits the problem into two, solves them individually and then merge them. But we can’t apply meet in the middle like divide and conquer because we don’t have the same structure as the original problem." }, { "code": null, "e": 1295, "s": 1194, "text": "Split the set of integers into 2 subsets say A and B. A having first n/2 integers and B having rest." }, { "code": null, "e": 1522, "s": 1295, "text": "Find all possible subset sums of integers in set A and store in an array X. Similarly calculate all possible subset sums of integers in set B and store in array Y. Hence, Size of each of the array X and Y will be at most 2n/2." }, { "code": null, "e": 2157, "s": 1522, "text": "Now merge these 2 subproblems. Find combinations from array X and Y such that their sum is less than or equal to S. One way to do that is simply iterate over all elements of array Y for each element of array X to check the existence of such a combination. This will take O( (2n/2)2) which is equivalent to O(2n).To make it less complex, first sort array Y and then iterate over each element of X and for each element x in X use binary search to find maximum element y in Y such that x + y <= S.Binary search here helps in reducing complexity from 2nto 2n/2log(2n/2)which is equivalent to 2n/2n.Thus our final running time is O(2n/2n)." }, { "code": null, "e": 2354, "s": 2157, "text": "One way to do that is simply iterate over all elements of array Y for each element of array X to check the existence of such a combination. This will take O( (2n/2)2) which is equivalent to O(2n)." }, { "code": null, "e": 2537, "s": 2354, "text": "To make it less complex, first sort array Y and then iterate over each element of X and for each element x in X use binary search to find maximum element y in Y such that x + y <= S." }, { "code": null, "e": 2638, "s": 2537, "text": "Binary search here helps in reducing complexity from 2nto 2n/2log(2n/2)which is equivalent to 2n/2n." }, { "code": null, "e": 2679, "s": 2638, "text": "Thus our final running time is O(2n/2n)." }, { "code": null, "e": 2683, "s": 2679, "text": "C++" }, { "code": null, "e": 2688, "s": 2683, "text": "Java" }, { "code": null, "e": 2696, "s": 2688, "text": "Python3" }, { "code": null, "e": 2699, "s": 2696, "text": "C#" }, { "code": null, "e": 2710, "s": 2699, "text": "Javascript" }, { "code": "// C++ program to demonstrate working of Meet in the// Middle algorithm for maximum subset sum problem.#include <bits/stdc++.h>using namespace std;typedef long long int ll;ll X[2000005],Y[2000005]; // Find all possible sum of elements of a[] and store// in x[]void calcsubarray(ll a[], ll x[], int n, int c){ for (int i=0; i<(1<<n); i++) { ll s = 0; for (int j=0; j<n; j++) if (i & (1<<j)) s += a[j+c]; x[i] = s; }} // Returns the maximum possible sum less or equal to Sll solveSubsetSum(ll a[], int n, ll S){ // Compute all subset sums of first and second // halves calcsubarray(a, X, n/2, 0); calcsubarray(a, Y, n-n/2, n/2); int size_X = 1<<(n/2); int size_Y = 1<<(n-n/2); // Sort Y (we need to do doing binary search in it) sort(Y, Y+size_Y); // To keep track of the maximum sum of a subset // such that the maximum sum is less than S ll max = 0; // Traverse all elements of X and do Binary Search // for a pair in Y with maximum sum less than S. for (int i=0; i<size_X; i++) { if (X[i] <= S) { // lower_bound() returns the first address // which has value greater than or equal to // S-X[i]. int p = lower_bound(Y, Y+size_Y, S-X[i]) - Y; // If S-X[i] was not in array Y then decrease // p by 1 if (p == size_Y || Y[p] != (S-X[i])) p--; if ((Y[p]+X[i]) > max) max = Y[p]+X[i]; } } return max;} // Driver codeint main(){ ll a[] = {3, 34, 4, 12, 5, 2}; int n=sizeof(a)/sizeof(a[0]); ll S = 10; printf(\"Largest value smaller than or equal to given \" \"sum is %lld\\n\", solveSubsetSum(a,n,S)); return 0;}", "e": 4489, "s": 2710, "text": null }, { "code": "// Java program to demonstrate working of// Meet in the Middle algorithm for// maximum subset sum problemimport java.util.*;import java.lang.*;import java.io.*; class GFG{ static long X[] = new long[2000005];static long Y[] = new long[2000005]; // Find all possible sum of elements of a[]// and store in x[]static void calcsubarray(long a[],long x[], int n, int c){ for(int i = 0; i < (1 << n); i++) { long s = 0; for(int j = 0; j < n; j++) if ((i & (1 << j)) == 1) s += a[j + c]; x[i] = s; }} // Returns the maximum possible sum// less or equal to S static long solveSubsetSum(long a[], int n, long S){ // Compute all subset sums of first and second // halves calcsubarray(a, X, n / 2, 0); calcsubarray(a, Y, n - n / 2, n / 2); int size_X = 1 << (n / 2); int size_Y = 1 << (n - n / 2); // Sort Y (we need to do doing // binary search in it) Arrays.sort(Y); // To keep track of the maximum sum // of a subset such that the maximum // sum is less than S long max = 0; // Traverse all elements of X and do // Binary Search for a pair in Y with // maximum sum less than S. for(int i = 0; i < size_X; i++) { if (X[i] <= S) { // lower_bound() returns the first address // which has value greater than or equal to // S-X[i]. int p = lower_bound(Y, S - X[i]); // If S-X[i] was not in array Y then // decrease p by 1 if (p == size_Y || Y[p] != (S - X[i])) p--; if ((Y[p] + X[i]) > max) max = Y[p] + X[i]; } } return max;} static int lower_bound(long a[], long x){ // x is the target value or key int l = -1, r = a.length; while (l + 1 < r) { int m = (l + r) >>> 1; if (a[m] >= x) r = m; else l = m; } return r;} // Driver codepublic static void main (String[] args){ long a[] = { 3, 34, 4, 12, 5, 2 }; int n = a.length; long S = 10; System.out.println(\"Largest value smaller \" + \"than or equal to given \" + \"sum is \" + solveSubsetSum(a, n, S));}} // This code is contributed by jyoti369", "e": 6861, "s": 4489, "text": null }, { "code": "# Python program to demonstrate working of Meet in the# Middle algorithm for maximum subset sum problem.from typing import Listimport bisectX = [0] * 2000005Y = [0] * 2000005 # Find all possible sum of elements of a[] and store# in x[]def calcsubarray(a: List[int], x: List[int], n: int, c: int) -> None: for i in range((1 << n)): s = 0 for j in range(n): if (i & (1 << j)): s += a[j + c] x[i] = s # Returns the maximum possible sum less or equal to Sdef solveSubsetSum(a: List[int], n: int, S: int) -> int: global Y # Compute all subset sums of first and second # halves calcsubarray(a, X, n // 2, 0) calcsubarray(a, Y, n - n // 2, n // 2) size_X = 1 << (n // 2) size_Y = 1 << (n - n // 2) # Sort Y (we need to do doing binary search in it) YY = Y[:size_Y] YY.sort() Y = YY # To keep track of the maximum sum of a subset # such that the maximum sum is less than S maxx = 0 # Traverse all elements of X and do Binary Search # for a pair in Y with maximum sum less than S. for i in range(size_X): if (X[i] <= S): # lower_bound() returns the first address # which has value greater than or equal to # S-X[i]. p = bisect.bisect_left(Y, S - X[i]) # If S-X[i] was not in array Y then decrease # p by 1 if (p == size_Y or (p < size_Y and Y[p] != (S - X[i]))): p -= 1 if ((Y[p] + X[i]) > maxx): maxx = Y[p] + X[i] return maxx # Driver codeif __name__ == \"__main__\": a = [3, 34, 4, 12, 5, 2] n = len(a) S = 10 print(\"Largest value smaller than or equal to given sum is {}\".format( solveSubsetSum(a, n, S))) # This code is contributed by sanjeev2552", "e": 8662, "s": 6861, "text": null }, { "code": "// C# program to demonstrate working of// Meet in the Middle algorithm for// maximum subset sum problemusing System;public class GFG{ static long[] X = new long[2000005]; static long[] Y = new long[2000005]; // Find all possible sum of elements of a[] // and store in x[] static void calcsubarray(long[] a,long[] x, int n, int c) { for(int i = 0; i < (1 << n); i++) { long s = 0; for(int j = 0; j < n; j++) if ((i & (1 << j)) == 1) s += a[j + c]; x[i] = s; } } // Returns the maximum possible sum // less or equal to S static long solveSubsetSum(long[] a, int n, long S) { // Compute all subset sums of first and second // halves calcsubarray(a, X, n / 2, 0); calcsubarray(a, Y, n - n / 2, n / 2); int size_X = 1 << (n / 2); int size_Y = 1 << (n - n / 2); // Sort Y (we need to do doing // binary search in it) Array.Sort(Y); // To keep track of the maximum sum // of a subset such that the maximum // sum is less than S long max = 0; // Traverse all elements of X and do // Binary Search for a pair in Y with // maximum sum less than S. for(int i = 0; i < size_X; i++) { if (X[i] <= S) { // lower_bound() returns the first address // which has value greater than or equal to // S-X[i]. int p = lower_bound(Y, S - X[i]); // If S-X[i] was not in array Y then // decrease p by 1 if (p == size_Y || Y[p] != (S - X[i])) p--; if ((Y[p] + X[i]) > max) max = Y[p] + X[i]; } } return max; } static int lower_bound(long[] a, long x) { // x is the target value or key int l = -1, r = a.Length; while (l + 1 < r) { int m = (l + r) >> 1; if (a[m] >= x) r = m; else l = m; } return r; } // Driver code static public void Main () { long[] a = { 3, 34, 4, 12, 5, 2 }; int n = a.Length; long S = 10; Console.WriteLine(\"Largest value smaller \" + \"than or equal to given \" + \"sum is \" + solveSubsetSum(a, n, S)); }} // This code is contributed by Dharanendra L V.", "e": 10886, "s": 8662, "text": null }, { "code": "<script>// Javascript program to demonstrate working of// Meet in the Middle algorithm for// maximum subset sum problemlet X = new Array(2000005);let Y = new Array(2000005);for(let i = 0; i < 2000005; i++){ X[i] = 0; Y[i] = 0;} // Find all possible sum of elements of a[]// and store in x[]function calcsubarray(a, x, n, c){ for(let i = 0; i < (1 << n); i++) { let s = 0; for(let j = 0; j < n; j++) if ((i & (1 << j)) == 1) s += a[j + c]; x[i] = s; }} // Returns the maximum possible sum// less or equal to Sfunction solveSubsetSum(a,n,S){ // Compute all subset sums of first and second // halves calcsubarray(a, X, Math.floor(n / 2), 0); calcsubarray(a, Y, n - Math.floor(n / 2), Math.floor(n / 2)); let size_X = 1 << Math.floor(n / 2); let size_Y = 1 << (n - Math.floor(n / 2)); // Sort Y (we need to do doing // binary search in it) Y.sort(function(a,b){return a-b;}); // To keep track of the maximum sum // of a subset such that the maximum // sum is less than S let max = 0; // Traverse all elements of X and do // Binary Search for a pair in Y with // maximum sum less than S. for(let i = 0; i < size_X; i++) { if (X[i] <= S) { // lower_bound() returns the first address // which has value greater than or equal to // S-X[i]. let p = lower_bound(Y, S - X[i]); // If S-X[i] was not in array Y then // decrease p by 1 if (p == size_Y || Y[p] != (S - X[i])) p--; if ((Y[p] + X[i]) > max) max = Y[p] + X[i]; } } return max;} function lower_bound(a,x){ // x is the target value or key let l = -1, r = a.length; while (l + 1 < r) { let m = (l + r) >>> 1; if (a[m] >= x) r = m; else l = m; } return r;} // Driver codelet a=[3, 34, 4, 12, 5, 2 ];let n = a.length;let S = 10;document.write(\"Largest value smaller \" + \"than or equal to given \" + \"sum is \" + solveSubsetSum(a, n, S)+\"<br>\"); // This code is contributed by avanitrachhadiya2155</script>", "e": 13179, "s": 10886, "text": null }, { "code": null, "e": 13188, "s": 13179, "text": "Output: " }, { "code": null, "e": 13243, "s": 13188, "text": "Largest value smaller than or equal to given sum is 10" }, { "code": null, "e": 13255, "s": 13243, "text": "Reference: " }, { "code": null, "e": 13344, "s": 13255, "text": "https://www.quora.com/What-is-meet-in-the-middle-algorithm-w-r-t-competitive-programming" }, { "code": null, "e": 13775, "s": 13344, "text": "Time Complexity: O()Auxiliary Space: O() This article is contributed by Madhur Modi. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 13784, "s": 13775, "text": "jyoti369" }, { "code": null, "e": 13796, "s": 13784, "text": "sanjeev2552" }, { "code": null, "e": 13812, "s": 13796, "text": "dharanendralv23" }, { "code": null, "e": 13828, "s": 13812, "text": "pankajsharmagfg" }, { "code": null, "e": 13849, "s": 13828, "text": "avanitrachhadiya2155" }, { "code": null, "e": 13861, "s": 13849, "text": "ayush123ngp" }, { "code": null, "e": 13880, "s": 13861, "text": "meet-in-the-middle" }, { "code": null, "e": 13891, "s": 13880, "text": "Algorithms" }, { "code": null, "e": 13902, "s": 13891, "text": "Algorithms" } ]
Python | pandas.to_numeric method
17 Dec, 2018 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. pandas.to_numeric() is one of the general functions in Pandas which is used to convert argument to a numeric type. Syntax: pandas.to_numeric(arg, errors=’raise’, downcast=None) Parameters:arg : list, tuple, 1-d array, or Serieserrors : {‘ignore’, ‘raise’, ‘coerce’}, default ‘raise’-> If ‘raise’, then invalid parsing will raise an exception-> If ‘coerce’, then invalid parsing will be set as NaN-> If ‘ignore’, then invalid parsing will return the inputdowncast : [default None] If not None, and if the data has been successfully cast to a numerical dtype downcast that resulting data to the smallest numerical dtype possible according to the following rules:-> ‘integer’ or ‘signed’: smallest signed int dtype (min.: np.int8)-> ‘unsigned’: smallest unsigned int dtype (min.: np.uint8)-> ‘float’: smallest float dtype (min.: np.float32) Returns: numeric if parsing succeeded. Note that return type depends on input. Series if Series, otherwise ndarray. Code #1: Observe this dataset first. We’ll use ‘Numbers’ column of this data in order to make Series and then do the operation. # importing pandas module import pandas as pd # making data frame df = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") df.head(10) Calling Series constructor on Number column and then selecting first 10 rows. # importing pandas module import pandas as pd # making data frame df = pd.read_csv("nba.csv") # get first ten 'numbers'ser = pd.Series(df['Number']).head(10)ser Output: Using pd.to_numeric() method. Observe that by using downcast=’signed’, all the values will be casted to integer. pd.to_numeric(ser, downcast ='signed') Output: Code #2: Using errors=’ignore’. It will ignore all non-numeric values. # importing pandas module import pandas as pd # get first ten 'numbers'ser = pd.Series(['Geeks', 11, 22.7, 33]) pd.to_numeric(ser, errors ='ignore') Output: Code #3: Using errors=’coerce’. It will replace all non-numeric values with NaN. # importing pandas module import pandas as pd # get first ten 'numbers'ser = pd.Series(['Geeks', 11, 22.7, 33]) pd.to_numeric(ser, errors ='coerce') Output: Python pandas-general-functions 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": "\n17 Dec, 2018" }, { "code": null, "e": 242, "s": 28, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 357, "s": 242, "text": "pandas.to_numeric() is one of the general functions in Pandas which is used to convert argument to a numeric type." }, { "code": null, "e": 419, "s": 357, "text": "Syntax: pandas.to_numeric(arg, errors=’raise’, downcast=None)" }, { "code": null, "e": 1080, "s": 419, "text": "Parameters:arg : list, tuple, 1-d array, or Serieserrors : {‘ignore’, ‘raise’, ‘coerce’}, default ‘raise’-> If ‘raise’, then invalid parsing will raise an exception-> If ‘coerce’, then invalid parsing will be set as NaN-> If ‘ignore’, then invalid parsing will return the inputdowncast : [default None] If not None, and if the data has been successfully cast to a numerical dtype downcast that resulting data to the smallest numerical dtype possible according to the following rules:-> ‘integer’ or ‘signed’: smallest signed int dtype (min.: np.int8)-> ‘unsigned’: smallest unsigned int dtype (min.: np.uint8)-> ‘float’: smallest float dtype (min.: np.float32)" }, { "code": null, "e": 1196, "s": 1080, "text": "Returns: numeric if parsing succeeded. Note that return type depends on input. Series if Series, otherwise ndarray." }, { "code": null, "e": 1205, "s": 1196, "text": "Code #1:" }, { "code": null, "e": 1324, "s": 1205, "text": "Observe this dataset first. We’ll use ‘Numbers’ column of this data in order to make Series and then do the operation." }, { "code": "# importing pandas module import pandas as pd # making data frame df = pd.read_csv(\"https://media.geeksforgeeks.org/wp-content/uploads/nba.csv\") df.head(10)", "e": 1487, "s": 1324, "text": null }, { "code": null, "e": 1565, "s": 1487, "text": "Calling Series constructor on Number column and then selecting first 10 rows." }, { "code": "# importing pandas module import pandas as pd # making data frame df = pd.read_csv(\"nba.csv\") # get first ten 'numbers'ser = pd.Series(df['Number']).head(10)ser", "e": 1734, "s": 1565, "text": null }, { "code": null, "e": 1742, "s": 1734, "text": "Output:" }, { "code": null, "e": 1855, "s": 1742, "text": "Using pd.to_numeric() method. Observe that by using downcast=’signed’, all the values will be casted to integer." }, { "code": "pd.to_numeric(ser, downcast ='signed')", "e": 1894, "s": 1855, "text": null }, { "code": null, "e": 1902, "s": 1894, "text": "Output:" }, { "code": null, "e": 1975, "s": 1904, "text": "Code #2: Using errors=’ignore’. It will ignore all non-numeric values." }, { "code": "# importing pandas module import pandas as pd # get first ten 'numbers'ser = pd.Series(['Geeks', 11, 22.7, 33]) pd.to_numeric(ser, errors ='ignore')", "e": 2131, "s": 1975, "text": null }, { "code": null, "e": 2220, "s": 2131, "text": "Output: Code #3: Using errors=’coerce’. It will replace all non-numeric values with NaN." }, { "code": "# importing pandas module import pandas as pd # get first ten 'numbers'ser = pd.Series(['Geeks', 11, 22.7, 33]) pd.to_numeric(ser, errors ='coerce')", "e": 2376, "s": 2220, "text": null }, { "code": null, "e": 2384, "s": 2376, "text": "Output:" }, { "code": null, "e": 2416, "s": 2384, "text": "Python pandas-general-functions" }, { "code": null, "e": 2430, "s": 2416, "text": "Python-pandas" }, { "code": null, "e": 2437, "s": 2430, "text": "Python" } ]
GATE-CS-2004 - GeeksforGeeks
11 Oct, 2021 1. 9679, 1989, 4199 hash to the same value 2. 1471, 6171 hash to the same value 3. All elements hash to the same value 4. Each element hashes to a different value 1. P → Q R 2. P → Q s R 3. P → ε 4. P → Q t R r Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 29498, "s": 29470, "text": "\n11 Oct, 2021" }, { "code": null, "e": 29675, "s": 29498, "text": "\n1. 9679, 1989, 4199 hash to the same value\n2. 1471, 6171 hash to the same value\n3. All elements hash to the same value\n4. Each element hashes to a different value " }, { "code": null, "e": 29763, "s": 29675, "text": "1. P → Q R \n2. P → Q s R\n3. P → ε \n4. P → Q t R r " } ]
htop command in Linux with examples
21 May, 2019 htop command in Linux system is a command line utility that allows the user to interactively monitor the system’s vital resources or server’s processes in real time. htop is a newer program compared to top command, and it offers many improvements over top command. htop supports mouse operation, uses color in its output and gives visual indications about processor, memory and swap usage. htop also prints full command lines for processes and allows one to scroll both vertically and horizontally for processes and command lines respectively. Syntax: htop [-dChusv] Example: Options: -d –delay : Used to show the delay between updates, in tenths of seconds. -C –no-color –no-colour : Start htop in monochrome mode. -h –help : Used to display the help message and exit. -u –user=USERNAME : Used to show only the processes of a given user.htop -u kunwarvikas htop -u kunwarvikas -p –pid=PID, PID... : Used to show only the given PIDs. -s –sort-key COLUMN : Sort by this column (use –sort-key help for a column list). -v –version : Output version information and exit. Interactive Commands: Arrows, Page Up, Page Down, Home, End: Scroll the process list. Space: Tag or untag a process. U – Untag all processes (remove all tags added with the Space key). s – Trace process system calls. F1 – Help F2 – setup F3 – search F4 – filtering: type in part of a process command line and only processes whose names match will be shown. F5 – Tree view. F6 – Sorting. F7 – Increase the selected process’s priority. This can only be done by the superuser. F8 – Decrease the selected process’s priority. F9 – Kill process. F10 – Quit. linux-command Linux-system-commands Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n21 May, 2019" }, { "code": null, "e": 597, "s": 53, "text": "htop command in Linux system is a command line utility that allows the user to interactively monitor the system’s vital resources or server’s processes in real time. htop is a newer program compared to top command, and it offers many improvements over top command. htop supports mouse operation, uses color in its output and gives visual indications about processor, memory and swap usage. htop also prints full command lines for processes and allows one to scroll both vertically and horizontally for processes and command lines respectively." }, { "code": null, "e": 605, "s": 597, "text": "Syntax:" }, { "code": null, "e": 620, "s": 605, "text": "htop [-dChusv]" }, { "code": null, "e": 629, "s": 620, "text": "Example:" }, { "code": null, "e": 638, "s": 629, "text": "Options:" }, { "code": null, "e": 712, "s": 638, "text": "-d –delay : Used to show the delay between updates, in tenths of seconds." }, { "code": null, "e": 769, "s": 712, "text": "-C –no-color –no-colour : Start htop in monochrome mode." }, { "code": null, "e": 823, "s": 769, "text": "-h –help : Used to display the help message and exit." }, { "code": null, "e": 911, "s": 823, "text": "-u –user=USERNAME : Used to show only the processes of a given user.htop -u kunwarvikas" }, { "code": null, "e": 931, "s": 911, "text": "htop -u kunwarvikas" }, { "code": null, "e": 987, "s": 931, "text": "-p –pid=PID, PID... : Used to show only the given PIDs." }, { "code": null, "e": 1069, "s": 987, "text": "-s –sort-key COLUMN : Sort by this column (use –sort-key help for a column list)." }, { "code": null, "e": 1120, "s": 1069, "text": "-v –version : Output version information and exit." }, { "code": null, "e": 1142, "s": 1120, "text": "Interactive Commands:" }, { "code": null, "e": 1206, "s": 1142, "text": "Arrows, Page Up, Page Down, Home, End: Scroll the process list." }, { "code": null, "e": 1237, "s": 1206, "text": "Space: Tag or untag a process." }, { "code": null, "e": 1305, "s": 1237, "text": "U – Untag all processes (remove all tags added with the Space key)." }, { "code": null, "e": 1337, "s": 1305, "text": "s – Trace process system calls." }, { "code": null, "e": 1347, "s": 1337, "text": "F1 – Help" }, { "code": null, "e": 1358, "s": 1347, "text": "F2 – setup" }, { "code": null, "e": 1370, "s": 1358, "text": "F3 – search" }, { "code": null, "e": 1477, "s": 1370, "text": "F4 – filtering: type in part of a process command line and only processes whose names match will be shown." }, { "code": null, "e": 1493, "s": 1477, "text": "F5 – Tree view." }, { "code": null, "e": 1507, "s": 1493, "text": "F6 – Sorting." }, { "code": null, "e": 1594, "s": 1507, "text": "F7 – Increase the selected process’s priority. This can only be done by the superuser." }, { "code": null, "e": 1641, "s": 1594, "text": "F8 – Decrease the selected process’s priority." }, { "code": null, "e": 1660, "s": 1641, "text": "F9 – Kill process." }, { "code": null, "e": 1672, "s": 1660, "text": "F10 – Quit." }, { "code": null, "e": 1686, "s": 1672, "text": "linux-command" }, { "code": null, "e": 1708, "s": 1686, "text": "Linux-system-commands" }, { "code": null, "e": 1715, "s": 1708, "text": "Picked" }, { "code": null, "e": 1726, "s": 1715, "text": "Linux-Unix" } ]
How to Download and Upload Files in FTP Server using Python?
12 Jan, 2022 Prerequisite: FTP, ftplib Here, we will learn how to Download and Upload Files in FTP Server Using Python. Before we get started, first we will understand what is FTP. File Transfer Protocol(FTP) is an application layer protocol that moves files between local and remote file systems. It runs on the top of TCP, like HTTP. To transfer a file, 2 TCP connections are used by FTP in parallel: control connection and data connection. For uploading and downloading the file, we will use ftplib Module in Python. It is an in-built module in Python. This module defines the class FTP and a few related items. The FTP class implements the client-side of the FTP protocol. You can use this to write Python programs that perform a variety of automated FTP jobs, such as mirroring other FTP servers. We will use a test FTP server, it is called DLPTEST and we are going to use the below text file for all operations: Let’s Understand step by step implementation: Enter Required Information, the information will be available click here. Python3 # Import Moduleimport ftplib # Fill Required InformationHOSTNAME = "ftp.dlptest.com"USERNAME = "dlpuser@dlptest.com"PASSWORD = "eUj8GeW55SvYaswqUyDSm5v6N" Note: Password will change time to time, make sure you visit their website for the correct credentials. Connect to Server Python3 # Connect FTP Serverftp_server = ftplib.FTP(HOSTNAME, USERNAME, PASSWORD) # force UTF-8 encodingftp_server.encoding = "utf-8" Upload the File (To upload a file, we will use storbinary() method) Syntax: # Store a file in binary transfer mode storbinary(command, **) Python3 # Enter File Name with Extensionfilename = "gfg.txt" # Read file in binary modewith open(filename, "rb") as file: # Command for Uploading the file "STOR filename" ftp_server.storbinary(f"STOR {filename}", file) Get the list of directories using dir() method. The test server will remove files after 30 minutes. Python3 # Get list of filesftp_server.dir() Output: Download the File (To download a file, we will use retrbinary() method. Python3 # Enter File Name with Extensionfilename = "gfg.txt" # Write file in binary modewith open(filename, "wb") as file: # Command for Downloading the file "RETR filename" ftp_server.retrbinary(f"RETR {filename}", file.write) Close the FTP Connection. Python3 # Display the content of downloaded filefile= open(filename, "r")print('File Content:', file.read()) # Close the Connectionftp_server.quit() Output: Below is the complete program for uploading the file in FTP Server: Python3 # Import Moduleimport ftplib # Fill Required InformationHOSTNAME = "ftp.dlptest.com"USERNAME = "dlpuser@dlptest.com"PASSWORD = "eUj8GeW55SvYaswqUyDSm5v6N" # Connect FTP Serverftp_server = ftplib.FTP(HOSTNAME, USERNAME, PASSWORD) # force UTF-8 encodingftp_server.encoding = "utf-8" # Enter File Name with Extensionfilename = "File Name" # Read file in binary modewith open(filename, "rb") as file: # Command for Uploading the file "STOR filename" ftp_server.storbinary(f"STOR {filename}", file) # Get list of filesftp_server.dir() # Close the Connectionftp_server.quit() Output: Below is the complete program for downloading the file in FTP Server: Python3 # Import Moduleimport ftplib # Fill Required InformationHOSTNAME = "ftp.dlptest.com"USERNAME = "dlpuser@dlptest.com"PASSWORD = "eUj8GeW55SvYaswqUyDSm5v6N" # Connect FTP Serverftp_server = ftplib.FTP(HOSTNAME, USERNAME, PASSWORD) # force UTF-8 encodingftp_server.encoding = "utf-8" # Enter File Name with Extensionfilename = "gfg.txt" # Write file in binary modewith open(filename, "wb") as file: # Command for Downloading the file "RETR filename" ftp_server.retrbinary(f"RETR {filename}", file.write) # Get list of filesftp_server.dir() # Display the content of downloaded filefile= open(filename, "r")print('File Content:', file.read()) # Close the Connectionftp_server.quit() Output: simmytarika5 Picked python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Jan, 2022" }, { "code": null, "e": 54, "s": 28, "text": "Prerequisite: FTP, ftplib" }, { "code": null, "e": 196, "s": 54, "text": "Here, we will learn how to Download and Upload Files in FTP Server Using Python. Before we get started, first we will understand what is FTP." }, { "code": null, "e": 458, "s": 196, "text": "File Transfer Protocol(FTP) is an application layer protocol that moves files between local and remote file systems. It runs on the top of TCP, like HTTP. To transfer a file, 2 TCP connections are used by FTP in parallel: control connection and data connection." }, { "code": null, "e": 571, "s": 458, "text": "For uploading and downloading the file, we will use ftplib Module in Python. It is an in-built module in Python." }, { "code": null, "e": 817, "s": 571, "text": "This module defines the class FTP and a few related items. The FTP class implements the client-side of the FTP protocol. You can use this to write Python programs that perform a variety of automated FTP jobs, such as mirroring other FTP servers." }, { "code": null, "e": 934, "s": 817, "text": "We will use a test FTP server, it is called DLPTEST and we are going to use the below text file for all operations:" }, { "code": null, "e": 980, "s": 934, "text": "Let’s Understand step by step implementation:" }, { "code": null, "e": 1054, "s": 980, "text": "Enter Required Information, the information will be available click here." }, { "code": null, "e": 1062, "s": 1054, "text": "Python3" }, { "code": "# Import Moduleimport ftplib # Fill Required InformationHOSTNAME = \"ftp.dlptest.com\"USERNAME = \"dlpuser@dlptest.com\"PASSWORD = \"eUj8GeW55SvYaswqUyDSm5v6N\"", "e": 1217, "s": 1062, "text": null }, { "code": null, "e": 1321, "s": 1217, "text": "Note: Password will change time to time, make sure you visit their website for the correct credentials." }, { "code": null, "e": 1339, "s": 1321, "text": "Connect to Server" }, { "code": null, "e": 1347, "s": 1339, "text": "Python3" }, { "code": "# Connect FTP Serverftp_server = ftplib.FTP(HOSTNAME, USERNAME, PASSWORD) # force UTF-8 encodingftp_server.encoding = \"utf-8\"", "e": 1473, "s": 1347, "text": null }, { "code": null, "e": 1541, "s": 1473, "text": "Upload the File (To upload a file, we will use storbinary() method)" }, { "code": null, "e": 1550, "s": 1541, "text": "Syntax: " }, { "code": null, "e": 1613, "s": 1550, "text": "# Store a file in binary transfer mode\nstorbinary(command, **)" }, { "code": null, "e": 1621, "s": 1613, "text": "Python3" }, { "code": "# Enter File Name with Extensionfilename = \"gfg.txt\" # Read file in binary modewith open(filename, \"rb\") as file: # Command for Uploading the file \"STOR filename\" ftp_server.storbinary(f\"STOR {filename}\", file)", "e": 1838, "s": 1621, "text": null }, { "code": null, "e": 1938, "s": 1838, "text": "Get the list of directories using dir() method. The test server will remove files after 30 minutes." }, { "code": null, "e": 1946, "s": 1938, "text": "Python3" }, { "code": "# Get list of filesftp_server.dir()", "e": 1982, "s": 1946, "text": null }, { "code": null, "e": 1991, "s": 1982, "text": "Output: " }, { "code": null, "e": 2063, "s": 1991, "text": "Download the File (To download a file, we will use retrbinary() method." }, { "code": null, "e": 2071, "s": 2063, "text": "Python3" }, { "code": "# Enter File Name with Extensionfilename = \"gfg.txt\" # Write file in binary modewith open(filename, \"wb\") as file: # Command for Downloading the file \"RETR filename\" ftp_server.retrbinary(f\"RETR {filename}\", file.write)", "e": 2297, "s": 2071, "text": null }, { "code": null, "e": 2323, "s": 2297, "text": "Close the FTP Connection." }, { "code": null, "e": 2331, "s": 2323, "text": "Python3" }, { "code": "# Display the content of downloaded filefile= open(filename, \"r\")print('File Content:', file.read()) # Close the Connectionftp_server.quit()", "e": 2472, "s": 2331, "text": null }, { "code": null, "e": 2481, "s": 2472, "text": "Output: " }, { "code": null, "e": 2550, "s": 2481, "text": "Below is the complete program for uploading the file in FTP Server: " }, { "code": null, "e": 2558, "s": 2550, "text": "Python3" }, { "code": "# Import Moduleimport ftplib # Fill Required InformationHOSTNAME = \"ftp.dlptest.com\"USERNAME = \"dlpuser@dlptest.com\"PASSWORD = \"eUj8GeW55SvYaswqUyDSm5v6N\" # Connect FTP Serverftp_server = ftplib.FTP(HOSTNAME, USERNAME, PASSWORD) # force UTF-8 encodingftp_server.encoding = \"utf-8\" # Enter File Name with Extensionfilename = \"File Name\" # Read file in binary modewith open(filename, \"rb\") as file: # Command for Uploading the file \"STOR filename\" ftp_server.storbinary(f\"STOR {filename}\", file) # Get list of filesftp_server.dir() # Close the Connectionftp_server.quit()", "e": 3134, "s": 2558, "text": null }, { "code": null, "e": 3143, "s": 3134, "text": "Output: " }, { "code": null, "e": 3214, "s": 3143, "text": "Below is the complete program for downloading the file in FTP Server: " }, { "code": null, "e": 3222, "s": 3214, "text": "Python3" }, { "code": "# Import Moduleimport ftplib # Fill Required InformationHOSTNAME = \"ftp.dlptest.com\"USERNAME = \"dlpuser@dlptest.com\"PASSWORD = \"eUj8GeW55SvYaswqUyDSm5v6N\" # Connect FTP Serverftp_server = ftplib.FTP(HOSTNAME, USERNAME, PASSWORD) # force UTF-8 encodingftp_server.encoding = \"utf-8\" # Enter File Name with Extensionfilename = \"gfg.txt\" # Write file in binary modewith open(filename, \"wb\") as file: # Command for Downloading the file \"RETR filename\" ftp_server.retrbinary(f\"RETR {filename}\", file.write) # Get list of filesftp_server.dir() # Display the content of downloaded filefile= open(filename, \"r\")print('File Content:', file.read()) # Close the Connectionftp_server.quit()", "e": 3906, "s": 3222, "text": null }, { "code": null, "e": 3914, "s": 3906, "text": "Output:" }, { "code": null, "e": 3927, "s": 3914, "text": "simmytarika5" }, { "code": null, "e": 3934, "s": 3927, "text": "Picked" }, { "code": null, "e": 3949, "s": 3934, "text": "python-utility" }, { "code": null, "e": 3956, "s": 3949, "text": "Python" } ]
Component Based Model (CBM)
13 Jun, 2022 The component-based assembly model uses object-oriented technologies. In object-oriented technologies, the emphasis is on the creation of classes. Classes are the entities that encapsulate data and algorithms. In component-based architecture, classes (i.e., components required to build application) can be uses as reusable components. This model uses various characteristics of spiral model. This model is evolutionary by nature. Hence, software development can be done using iterative approach. In CBD model, multiple classes can be used. These classes are basically the prepackaged components. The model works in following manner: Step-1: First identify all the required candidate components, i.e., classes with the help of application data and algorithms. Step-2: If these candidate components are used in previous software projects then they must be present in the library. Step-3: Such preexisting components can be excited from the library and used for further development. Step-4: But if the required component is not present in the library then build or create the component as per requirement. Step-5: Place this newly created component in the library. This makes one iteration of the system. Step-6: Repeat steps 1 to 5 for creating n iterations, where n denotes the number of iterations required to develop the complete application. Characteristics of Component Assembly Model: Uses object-oriented technology. Components and classes encapsulate both data and algorithms. Components are developed to be reusable. Paradigm similar to spiral model, but engineering activity involves components. The system produced by assembling the correct components. ankurpatle18 Software Engineering Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Jun, 2022" }, { "code": null, "e": 662, "s": 28, "text": "The component-based assembly model uses object-oriented technologies. In object-oriented technologies, the emphasis is on the creation of classes. Classes are the entities that encapsulate data and algorithms. In component-based architecture, classes (i.e., components required to build application) can be uses as reusable components. This model uses various characteristics of spiral model. This model is evolutionary by nature. Hence, software development can be done using iterative approach. In CBD model, multiple classes can be used. These classes are basically the prepackaged components. The model works in following manner:" }, { "code": null, "e": 788, "s": 662, "text": "Step-1: First identify all the required candidate components, i.e., classes with the help of application data and algorithms." }, { "code": null, "e": 907, "s": 788, "text": "Step-2: If these candidate components are used in previous software projects then they must be present in the library." }, { "code": null, "e": 1009, "s": 907, "text": "Step-3: Such preexisting components can be excited from the library and used for further development." }, { "code": null, "e": 1132, "s": 1009, "text": "Step-4: But if the required component is not present in the library then build or create the component as per requirement." }, { "code": null, "e": 1231, "s": 1132, "text": "Step-5: Place this newly created component in the library. This makes one iteration of the system." }, { "code": null, "e": 1373, "s": 1231, "text": "Step-6: Repeat steps 1 to 5 for creating n iterations, where n denotes the number of iterations required to develop the complete application." }, { "code": null, "e": 1418, "s": 1373, "text": "Characteristics of Component Assembly Model:" }, { "code": null, "e": 1451, "s": 1418, "text": "Uses object-oriented technology." }, { "code": null, "e": 1512, "s": 1451, "text": "Components and classes encapsulate both data and algorithms." }, { "code": null, "e": 1553, "s": 1512, "text": "Components are developed to be reusable." }, { "code": null, "e": 1634, "s": 1553, "text": "Paradigm similar to spiral model, but engineering activity involves components. " }, { "code": null, "e": 1692, "s": 1634, "text": "The system produced by assembling the correct components." }, { "code": null, "e": 1705, "s": 1692, "text": "ankurpatle18" }, { "code": null, "e": 1726, "s": 1705, "text": "Software Engineering" } ]
Matrix Chain Multiplication | DP-8 - GeeksforGeeks
28 Feb, 2022 Given a sequence of matrices, find the most efficient way to multiply these matrices together. The problem is not actually to perform the multiplications, but merely to decide in which order to perform the multiplications.We have many options to multiply a chain of matrices because matrix multiplication is associative. In other words, no matter how we parenthesize the product, the result will be the same. For example, if we had four matrices A, B, C, and D, we would have: (ABC)D = (AB)(CD) = A(BCD) = .... However, the order in which we parenthesize the product affects the number of simple arithmetic operations needed to compute the product, or the efficiency. For example, suppose A is a 10 × 30 matrix, B is a 30 × 5 matrix, and C is a 5 × 60 matrix. Then, (AB)C = (10×30×5) + (10×5×60) = 1500 + 3000 = 4500 operations A(BC) = (30×5×60) + (10×30×60) = 9000 + 18000 = 27000 operations. Clearly the first parenthesization requires less number of operations.Given an array p[] which represents the chain of matrices such that the ith matrix Ai is of dimension p[i-1] x p[i]. We need to write a function MatrixChainOrder() that should return the minimum number of multiplications needed to multiply the chain. Input: p[] = {40, 20, 30, 10, 30} Output: 26000 There are 4 matrices of dimensions 40x20, 20x30, 30x10 and 10x30. Let the input 4 matrices be A, B, C and D. The minimum number of multiplications are obtained by putting parenthesis in following way (A(BC))D --> 20*30*10 + 40*20*10 + 40*10*30 Input: p[] = {10, 20, 30, 40, 30} Output: 30000 There are 4 matrices of dimensions 10x20, 20x30, 30x40 and 40x30. Let the input 4 matrices be A, B, C and D. The minimum number of multiplications are obtained by putting parenthesis in following way ((AB)C)D --> 10*20*30 + 10*30*40 + 10*40*30 Input: p[] = {10, 20, 30} Output: 6000 There are only two matrices of dimensions 10x20 and 20x30. So there is only one way to multiply the matrices, cost of which is 10*20*30 1) Optimal Substructure: A simple solution is to place parenthesis at all possible places, calculate the cost for each placement and return the minimum value. In a chain of matrices of size n, we can place the first set of parenthesis in n-1 ways. For example, if the given chain is of 4 matrices. let the chain be ABCD, then there are 3 ways to place first set of parenthesis outer side: (A)(BCD), (AB)(CD) and (ABC)(D). So when we place a set of parenthesis, we divide the problem into subproblems of smaller size. Therefore, the problem has optimal substructure property and can be easily solved using recursion.Minimum number of multiplication needed to multiply a chain of size n = Minimum of all n-1 placements (these placements create subproblems of smaller size) 2) Overlapping Subproblems Following is a recursive implementation that simply follows the above optimal substructure property. Below is the implementation of the above idea: C++ C Java Python3 C# PHP Javascript /* A naive recursive implementation that simplyfollows the above optimal substructure property */#include <bits/stdc++.h>using namespace std; // Matrix Ai has dimension p[i-1] x p[i]// for i = 1..nint MatrixChainOrder(int p[], int i, int j){ if (i == j) return 0; int k; int min = INT_MAX; int count; // place parenthesis at different places // between first and last matrix, recursively // calculate count of multiplications for // each parenthesis placement and return the // minimum count for (k = i; k < j; k++) { count = MatrixChainOrder(p, i, k) + MatrixChainOrder(p, k + 1, j) + p[i - 1] * p[k] * p[j]; if (count < min) min = count; } // Return minimum count return min;} // Driver Codeint main(){ int arr[] = { 1, 2, 3, 4, 3 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "Minimum number of multiplications is " << MatrixChainOrder(arr, 1, n - 1);} // This code is contributed by Shivi_Aggarwal /* A naive recursive implementation that simply follows the above optimal substructure property */#include <limits.h>#include <stdio.h> // Matrix Ai has dimension p[i-1] x p[i] for i = 1..nint MatrixChainOrder(int p[], int i, int j){ if (i == j) return 0; int k; int min = INT_MAX; int count; // place parenthesis at different places between first // and last matrix, recursively calculate count of // multiplications for each parenthesis placement and // return the minimum count for (k = i; k < j; k++) { count = MatrixChainOrder(p, i, k) + MatrixChainOrder(p, k + 1, j) + p[i - 1] * p[k] * p[j]; if (count < min) min = count; } // Return minimum count return min;} // Driver codeint main(){ int arr[] = { 1, 2, 3, 4, 3 }; int n = sizeof(arr) / sizeof(arr[0]); printf("Minimum number of multiplications is %d ", MatrixChainOrder(arr, 1, n - 1)); getchar(); return 0;} /* A naive recursive implementation that simply follows the above optimal substructure property */class MatrixChainMultiplication { // Matrix Ai has dimension p[i-1] x p[i] for i = 1..n static int MatrixChainOrder(int p[], int i, int j) { if (i == j) return 0; int min = Integer.MAX_VALUE; // place parenthesis at different places between // first and last matrix, recursively calculate // count of multiplications for each parenthesis // placement and return the minimum count for (int k = i; k < j; k++) { int count = MatrixChainOrder(p, i, k) + MatrixChainOrder(p, k + 1, j) + p[i - 1] * p[k] * p[j]; if (count < min) min = count; } // Return minimum count return min; } // Driver code public static void main(String args[]) { int arr[] = new int[] { 1, 2, 3, 4, 3 }; int n = arr.length; System.out.println( "Minimum number of multiplications is " + MatrixChainOrder(arr, 1, n - 1)); }}/* This code is contributed by Rajat Mishra*/ # A naive recursive implementation that# simply follows the above optimal# substructure propertyimport sys # Matrix A[i] has dimension p[i-1] x p[i]# for i = 1..n def MatrixChainOrder(p, i, j): if i == j: return 0 _min = sys.maxsize # place parenthesis at different places # between first and last matrix, # recursively calculate count of # multiplications for each parenthesis # placement and return the minimum count for k in range(i, j): count = (MatrixChainOrder(p, i, k) + MatrixChainOrder(p, k + 1, j) + p[i-1] * p[k] * p[j]) if count < _min: _min = count # Return minimum count return _min # Driver codearr = [1, 2, 3, 4, 3]n = len(arr) print("Minimum number of multiplications is ", MatrixChainOrder(arr, 1, n-1)) # This code is contributed by Aryan Garg /* C# code for naive recursive implementationthat simply follows the above optimalsubstructure property */using System; class GFG { // Matrix Ai has dimension p[i-1] x p[i] // for i = 1..n static int MatrixChainOrder(int[] p, int i, int j) { if (i == j) return 0; int min = int.MaxValue; // place parenthesis at different places // between first and last matrix, recursively // calculate count of multiplications for each // parenthesis placement and return the // minimum count for (int k = i; k < j; k++) { int count = MatrixChainOrder(p, i, k) + MatrixChainOrder(p, k + 1, j) + p[i - 1] * p[k] * p[j]; if (count < min) min = count; } // Return minimum count return min; } // Driver code public static void Main() { int[] arr = new int[] { 1, 2, 3, 4, 3 }; int n = arr.Length; Console.Write( "Minimum number of multiplications is " + MatrixChainOrder(arr, 1, n - 1)); }} // This code is contributed by Sam007. <?php// A naive recursive implementation// that simply follows the above// optimal substructure property // Matrix Ai has dimension// p[i-1] x p[i] for i = 1..nfunction MatrixChainOrder(&$p, $i, $j){ if($i == $j) return 0; $min = PHP_INT_MAX; // place parenthesis at different places // between first and last matrix, recursively // calculate count of multiplications for // each parenthesis placement and return // the minimum count for ($k = $i; $k < $j; $k++) { $count = MatrixChainOrder($p, $i, $k) + MatrixChainOrder($p, $k + 1, $j) + $p[$i - 1] * $p[$k] * $p[$j]; if ($count < $min) $min = $count; } // Return minimum count return $min;} // Driver Code$arr = array(1, 2, 3, 4, 3);$n = sizeof($arr); echo "Minimum number of multiplications is " . MatrixChainOrder($arr, 1, $n - 1); // This code is contributed by ita_c?> <script> /* A naive recursive implementation that simply follows the above optimal substructure property */ // Matrix Ai has dimension p[i-1] x p[i] for i = 1..nfunction MatrixChainOrder(p , i , j){ if (i == j) return 0; var min = Number.MAX_VALUE; // place parenthesis at different places between // first and last matrix, recursively calculate // count of multiplications for each parenthesis // placement and return the minimum count var k=0; for (k = i; k < j; k++) { var count = MatrixChainOrder(p, i, k) + MatrixChainOrder(p, k + 1, j) + p[i - 1] * p[k] * p[j]; if (count < min) min = count; } // Return minimum count return min;} // Driver codevar arr = [ 1, 2, 3, 4, 3 ];var n = arr.length; document.write( "Minimum number of multiplications is " + MatrixChainOrder(arr, 1, n - 1)); // This code contributed by shikhasingrajput </script> Minimum number of multiplications is 30 The time complexity of the above naive recursive approach is exponential. It should be noted that the above function computes the same subproblems again and again. See the following recursion tree for a matrix chain of size 4. The function MatrixChainOrder(p, 3, 4) is called two times. We can see that there are many subproblems being called more than once. Since same subproblems are called again, this problem has Overlapping Subproblems property. So Matrix Chain Multiplication problem has both properties (see this and this) of a dynamic programming problem. Like other typical Dynamic Programming(DP) problems, recomputations of same subproblems can be avoided by constructing a temporary array m[][] in bottom up manner. Dynamic Programming Solution Following is the implementation of the Matrix Chain Multiplication problem using Dynamic Programming (Tabulation vs Memoization) Using Memoization – C++ Java Python3 C# Javascript // C++ program using memoization#include <bits/stdc++.h>using namespace std;int dp[100][100]; // Function for matrix chain multiplicationint matrixChainMemoised(int* p, int i, int j){ if (i == j) { return 0; } if (dp[i][j] != -1) { return dp[i][j]; } dp[i][j] = INT_MAX; for (int k = i; k < j; k++) { dp[i][j] = min( dp[i][j], matrixChainMemoised(p, i, k) + matrixChainMemoised(p, k + 1, j) + p[i - 1] * p[k] * p[j]); } return dp[i][j];}int MatrixChainOrder(int* p, int n){ int i = 1, j = n - 1; return matrixChainMemoised(p, i, j);} // Driver Codeint main(){ int arr[] = { 1, 2, 3, 4 }; int n = sizeof(arr) / sizeof(arr[0]); memset(dp, -1, sizeof dp); cout << "Minimum number of multiplications is " << MatrixChainOrder(arr, n);} // This code is contributed by Sumit_Yadav // Java program using memoizationimport java.io.*;import java.util.*;class GFG{ static int[][] dp = new int[100][100]; // Function for matrix chain multiplication static int matrixChainMemoised(int[] p, int i, int j) { if (i == j) { return 0; } if (dp[i][j] != -1) { return dp[i][j]; } dp[i][j] = Integer.MAX_VALUE; for (int k = i; k < j; k++) { dp[i][j] = Math.min( dp[i][j], matrixChainMemoised(p, i, k) + matrixChainMemoised(p, k + 1, j) + p[i - 1] * p[k] * p[j]); } return dp[i][j]; } static int MatrixChainOrder(int[] p, int n) { int i = 1, j = n - 1; return matrixChainMemoised(p, i, j); } // Driver Code public static void main (String[] args) { int arr[] = { 1, 2, 3, 4 }; int n= arr.length; for (int[] row : dp) Arrays.fill(row, -1); System.out.println("Minimum number of multiplications is " + MatrixChainOrder(arr, n)); }} // This code is contributed by avanitrachhadiya2155 # Python program using memoizationimport sysdp = [[-1 for i in range(100)] for j in range(100)] # Function for matrix chain multiplicationdef matrixChainMemoised(p, i, j): if(i == j): return 0 if(dp[i][j] != -1): return dp[i][j] dp[i][j] = sys.maxsize for k in range(i,j): dp[i][j] = min(dp[i][j], matrixChainMemoised(p, i, k) + matrixChainMemoised(p, k + 1, j)+ p[i - 1] * p[k] * p[j]) return dp[i][j] def MatrixChainOrder(p,n): i = 1 j = n - 1 return matrixChainMemoised(p, i, j) # Driver Codearr = [1, 2, 3, 4]n = len(arr)print("Minimum number of multiplications is",MatrixChainOrder(arr, n)) # This code is contributed by rag2127 // C# program using memoizationusing System;class GFG{ static int[,] dp = new int[100, 100]; // Function for matrix chain multiplication static int matrixChainMemoised(int[] p, int i, int j) { if (i == j) { return 0; } if (dp[i, j] != -1) { return dp[i, j]; } dp[i, j] = Int32.MaxValue; for (int k = i; k < j; k++) { dp[i, j] = Math.Min( dp[i, j], matrixChainMemoised(p, i, k) + matrixChainMemoised(p, k + 1, j) + p[i - 1] * p[k] * p[j]); } return dp[i,j]; } static int MatrixChainOrder(int[] p, int n) { int i = 1, j = n - 1; return matrixChainMemoised(p, i, j); } // Driver code static void Main() { int[] arr = { 1, 2, 3, 4 }; int n = arr.Length; for(int i = 0; i < 100; i++) { for(int j = 0; j < 100; j++) { dp[i, j] = -1; } } Console.WriteLine("Minimum number of multiplications is " + MatrixChainOrder(arr, n)); }} // This code is contributed by divyeshrabadiya07. <script> // Javascript program using memoizationlet dp = new Array(100);for(var i = 0; i < dp.length; i++){ dp[i] = new Array(2);} // Function for matrix chain multiplicationfunction matrixChainMemoised(p, i, j){ if (i == j) { return 0; } if (dp[i][j] != -1) { return dp[i][j]; } dp[i][j] = Number.MAX_VALUE; for(let k = i; k < j; k++) { dp[i][j] = Math.min( dp[i][j], matrixChainMemoised(p, i, k) + matrixChainMemoised(p, k + 1, j) + p[i - 1] * p[k] * p[j]); } return dp[i][j];} function MatrixChainOrder(p, n){ let i = 1, j = n - 1; return matrixChainMemoised(p, i, j);} // Driver codelet arr = [ 1, 2, 3, 4 ];let n = arr.length; for(var i = 0; i < dp.length; i++){ for(var j = 0; j < dp.length; j++) { dp[i][j] = -1; }} document.write("Minimum number of multiplications is " + MatrixChainOrder(arr, n)); // This code is contributed by target_2 </script> Minimum number of multiplications is 18 Time Complexity: O(n3 ) Auxiliary Space: O(n2) ignoring recursion stack space Using Tabulation – C++ C Java Python3 C# PHP Javascript // See the Cormen book for details of the// following algorithm#include <bits/stdc++.h>using namespace std; // Matrix Ai has dimension p[i-1] x p[i]// for i = 1..nint MatrixChainOrder(int p[], int n){ /* For simplicity of the program, one extra row and one extra column are allocated in m[][]. 0th row and 0th column of m[][] are not used */ int m[n][n]; int i, j, k, L, q; /* m[i, j] = Minimum number of scalar multiplications needed to compute the matrix A[i]A[i+1]...A[j] = A[i..j] where dimension of A[i] is p[i-1] x p[i] */ // cost is zero when multiplying // one matrix. for (i = 1; i < n; i++) m[i][i] = 0; // L is chain length. for (L = 2; L < n; L++) { for (i = 1; i < n - L + 1; i++) { j = i + L - 1; m[i][j] = INT_MAX; for (k = i; k <= j - 1; k++) { // q = cost/scalar multiplications q = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j]; if (q < m[i][j]) m[i][j] = q; } } } return m[1][n - 1];} // Driver Codeint main(){ int arr[] = { 1, 2, 3, 4 }; int size = sizeof(arr) / sizeof(arr[0]); cout << "Minimum number of multiplications is " << MatrixChainOrder(arr, size); getchar(); return 0;} // This code is contributed// by Akanksha Rai // See the Cormen book for details of the following// algorithm#include <limits.h>#include <stdio.h> // Matrix Ai has dimension p[i-1] x p[i] for i = 1..nint MatrixChainOrder(int p[], int n){ /* For simplicity of the program, one extra row and one extra column are allocated in m[][]. 0th row and 0th column of m[][] are not used */ int m[n][n]; int i, j, k, L, q; /* m[i, j] = Minimum number of scalar multiplications needed to compute the matrix A[i]A[i+1]...A[j] = A[i..j] where dimension of A[i] is p[i-1] x p[i] */ // cost is zero when multiplying one matrix. for (i = 1; i < n; i++) m[i][i] = 0; // L is chain length. for (L = 2; L < n; L++) { for (i = 1; i < n - L + 1; i++) { j = i + L - 1; m[i][j] = INT_MAX; for (k = i; k <= j - 1; k++) { // q = cost/scalar multiplications q = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j]; if (q < m[i][j]) m[i][j] = q; } } } return m[1][n - 1];} // Driver codeint main(){ int arr[] = { 1, 2, 3, 4 }; int size = sizeof(arr) / sizeof(arr[0]); printf("Minimum number of multiplications is %d ", MatrixChainOrder(arr, size)); getchar(); return 0;} // Dynamic Programming Java implementation of Matrix// Chain Multiplication.// See the Cormen book for details of the following// algorithmclass MatrixChainMultiplication{ // Matrix Ai has dimension p[i-1] x p[i] for i = 1..n static int MatrixChainOrder(int p[], int n) { /* For simplicity of the program, one extra row and one extra column are allocated in m[][]. 0th row and 0th column of m[][] are not used */ int m[][] = new int[n][n]; int i, j, k, L, q; /* m[i, j] = Minimum number of scalar multiplications needed to compute the matrix A[i]A[i+1]...A[j] = A[i..j] where dimension of A[i] is p[i-1] x p[i] */ // cost is zero when multiplying one matrix. for (i = 1; i < n; i++) m[i][i] = 0; // L is chain length. for (L = 2; L < n; L++) { for (i = 1; i < n - L + 1; i++) { j = i + L - 1; if (j == n) continue; m[i][j] = Integer.MAX_VALUE; for (k = i; k <= j - 1; k++) { // q = cost/scalar multiplications q = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j]; if (q < m[i][j]) m[i][j] = q; } } } return m[1][n - 1]; } // Driver code public static void main(String args[]) { int arr[] = new int[] { 1, 2, 3, 4 }; int size = arr.length; System.out.println( "Minimum number of multiplications is " + MatrixChainOrder(arr, size)); }}/* This code is contributed by Rajat Mishra*/ # Dynamic Programming Python implementation of Matrix# Chain Multiplication. See the Cormen book for details# of the following algorithmimport sysmaxint=int(1e9+7)# Matrix Ai has dimension p[i-1] x p[i] for i = 1..n def MatrixChainOrder(p, n): # For simplicity of the program, # one extra row and one # extra column are allocated in m[][]. # 0th row and 0th # column of m[][] are not used m = [[0 for x in range(n)] for x in range(n)] # m[i, j] = Minimum number of scalar # multiplications needed # to compute the matrix A[i]A[i + 1]...A[j] = # A[i..j] where # dimension of A[i] is p[i-1] x p[i] # cost is zero when multiplying one matrix. for i in range(1, n): m[i][i] = 0 # L is chain length. for L in range(2, n): for i in range(1, n-L + 1): j = i + L-1 m[i][j] = maxint for k in range(i, j): # q = cost / scalar multiplications q = m[i][k] + m[k + 1][j] + p[i-1]*p[k]*p[j] if q < m[i][j]: m[i][j] = q return m[1][n-1] # Driver codearr = [1, 2, 3, 4]size = len(arr) print("Minimum number of multiplications is " + str(MatrixChainOrder(arr, size)))# This Code is contributed by Bhavya Jain // Dynamic Programming C# implementation of// Matrix Chain Multiplication.// See the Cormen book for details of the// following algorithmusing System; class GFG{ // Matrix Ai has dimension p[i-1] x p[i] // for i = 1..n static int MatrixChainOrder(int[] p, int n) { /* For simplicity of the program, one extra row and one extra column are allocated in m[][]. 0th row and 0th column of m[][] are not used */ int[, ] m = new int[n, n]; int i, j, k, L, q; /* m[i, j] = Minimum number of scalar multiplications needed to compute the matrix A[i]A[i+1]...A[j] = A[i..j] where dimension of A[i] is p[i-1] x p[i] */ // cost is zero when multiplying // one matrix. for (i = 1; i < n; i++) m[i, i] = 0; // L is chain length. for (L = 2; L < n; L++) { for (i = 1; i < n - L + 1; i++) { j = i + L - 1; if (j == n) continue; m[i, j] = int.MaxValue; for (k = i; k <= j - 1; k++) { // q = cost/scalar multiplications q = m[i, k] + m[k + 1, j] + p[i - 1] * p[k] * p[j]; if (q < m[i, j]) m[i, j] = q; } } } return m[1, n - 1]; } // Driver code public static void Main() { int[] arr = new int[] { 1, 2, 3, 4 }; int size = arr.Length; Console.Write("Minimum number of " + "multiplications is " + MatrixChainOrder(arr, size)); }} // This code is contributed by Sam007 <?php// Dynamic Programming Python implementation// of Matrix Chain Multiplication. // See the Cormen book for details of the// following algorithm Matrix Ai has// dimension p[i-1] x p[i] for i = 1..nfunction MatrixChainOrder($p, $n){ /* For simplicity of the program, one extra row and one extra column are allocated in m[][]. 0th row and 0th column of m[][] are not used */ $m[][] = array($n, $n); /* m[i, j] = Minimum number of scalar multiplications needed to compute the matrix A[i]A[i+1]...A[j] = A[i..j] where dimension of A[i] is p[i-1] x p[i] */ // cost is zero when multiplying one matrix. for ($i = 1; $i < $n; $i++) $m[$i][$i] = 0; // L is chain length. for ($L = 2; $L < $n; $L++) { for ($i = 1; $i < $n - $L + 1; $i++) { $j = $i + $L - 1; if($j == $n) continue; $m[$i][$j] = PHP_INT_MAX; for ($k = $i; $k <= $j - 1; $k++) { // q = cost/scalar multiplications $q = $m[$i][$k] + $m[$k + 1][$j] + $p[$i - 1] * $p[$k] * $p[$j]; if ($q < $m[$i][$j]) $m[$i][$j] = $q; } } } return $m[1][$n-1];} // Driver Code$arr = array(1, 2, 3, 4);$size = sizeof($arr); echo"Minimum number of multiplications is ". MatrixChainOrder($arr, $size); // This code is contributed by Mukul Singh?> <script> // Dynamic Programming javascript implementation of Matrix// Chain Multiplication.// See the Cormen book for details of the following// algorithm // Matrix Ai has dimension p[i-1] x p[i] for i = 1..nfunction MatrixChainOrder(p , n){ /* For simplicity of the program, one extra row and one extra column are allocated in m. 0th row and 0th column of m are not used */ var m = Array(n).fill(0).map(x => Array(n).fill(0)); var i, j, k, L, q; /* m[i, j] = Minimum number of scalar multiplications needed to compute the matrix A[i]A[i+1]...A[j] = A[i..j] where dimension of A[i] is p[i-1] x p[i] */ // cost is zero when multiplying one matrix. for (i = 1; i < n; i++) m[i][i] = 0; // L is chain length. for (L = 2; L < n; L++) { for (i = 1; i < n - L + 1; i++) { j = i + L - 1; if (j == n) continue; m[i][j] = Number.MAX_VALUE; for (k = i; k <= j - 1; k++) { // q = cost/scalar multiplications q = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j]; if (q < m[i][j]) m[i][j] = q; } } } return m[1][n - 1];} // Driver codevar arr = [ 1, 2, 3, 4 ];var size = arr.length; document.write( "Minimum number of multiplications is " + MatrixChainOrder(arr, size)); // This code contributed by Princi Singh </script> Minimum number of multiplications is 18 Time Complexity: O(n3 )Auxiliary Space: O(n2) Matrix Chain Multiplication (A O(N^2) Solution) Printing brackets in Matrix Chain Multiplication ProblemPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Applications: Minimum and Maximum values of an expression with * and + References: http://en.wikipedia.org/wiki/Matrix_chain_multiplication http://www.personal.kent.edu/~rmuhamma/Algorithms/MyAlgorithms/Dynamic/chainMatrixMult.htm YouTubeGeeksforGeeks500K subscribersMatrix Chain Multiplication | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 11:32•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=gwmitwgz87s" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> ?list=PLqM7alHXFySEQDk2MDfbwEdjd2svVJH9p aryan21 ukasp Code_Mech Shivi_Aggarwal Akanksha_Rai kmradi9 itsvinayak manjeetsumit16 sommayghosh avanitrachhadiya2155 rag2127 divyeshrabadiya07 shikhasingrajput princi singh anikakapoor target_2 surinderdawra388 amartyaghoshgfg prasanna1995 Amazon matrix-chain-multiplication Microsoft Dynamic Programming Matrix Amazon Microsoft Dynamic Programming Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Largest Sum Contiguous Subarray Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16 Subset Sum Problem | DP-25 Longest Palindromic Substring | Set 1 Program to find largest element in an array Print a given matrix in spiral form Program to multiply two matrices Inplace rotate square matrix by 90 degrees | Set 1 The Celebrity Problem
[ { "code": null, "e": 34514, "s": 34486, "text": "\n28 Feb, 2022" }, { "code": null, "e": 34992, "s": 34514, "text": "Given a sequence of matrices, find the most efficient way to multiply these matrices together. The problem is not actually to perform the multiplications, but merely to decide in which order to perform the multiplications.We have many options to multiply a chain of matrices because matrix multiplication is associative. In other words, no matter how we parenthesize the product, the result will be the same. For example, if we had four matrices A, B, C, and D, we would have: " }, { "code": null, "e": 35026, "s": 34992, "text": "(ABC)D = (AB)(CD) = A(BCD) = ...." }, { "code": null, "e": 35283, "s": 35026, "text": "However, the order in which we parenthesize the product affects the number of simple arithmetic operations needed to compute the product, or the efficiency. For example, suppose A is a 10 × 30 matrix, B is a 30 × 5 matrix, and C is a 5 × 60 matrix. Then, " }, { "code": null, "e": 35411, "s": 35283, "text": "(AB)C = (10×30×5) + (10×5×60) = 1500 + 3000 = 4500 operations\nA(BC) = (30×5×60) + (10×30×60) = 9000 + 18000 = 27000 operations." }, { "code": null, "e": 35733, "s": 35411, "text": "Clearly the first parenthesization requires less number of operations.Given an array p[] which represents the chain of matrices such that the ith matrix Ai is of dimension p[i-1] x p[i]. We need to write a function MatrixChainOrder() that should return the minimum number of multiplications needed to multiply the chain. " }, { "code": null, "e": 36511, "s": 35733, "text": "Input: p[] = {40, 20, 30, 10, 30} \nOutput: 26000 \nThere are 4 matrices of dimensions 40x20, 20x30, 30x10 and 10x30.\nLet the input 4 matrices be A, B, C and D. The minimum number of \nmultiplications are obtained by putting parenthesis in following way\n(A(BC))D --> 20*30*10 + 40*20*10 + 40*10*30\n\nInput: p[] = {10, 20, 30, 40, 30} \nOutput: 30000 \nThere are 4 matrices of dimensions 10x20, 20x30, 30x40 and 40x30. \nLet the input 4 matrices be A, B, C and D. The minimum number of \nmultiplications are obtained by putting parenthesis in following way\n((AB)C)D --> 10*20*30 + 10*30*40 + 10*40*30\n\nInput: p[] = {10, 20, 30} \nOutput: 6000 \nThere are only two matrices of dimensions 10x20 and 20x30. So there \nis only one way to multiply the matrices, cost of which is 10*20*30" }, { "code": null, "e": 37282, "s": 36511, "text": "1) Optimal Substructure: A simple solution is to place parenthesis at all possible places, calculate the cost for each placement and return the minimum value. In a chain of matrices of size n, we can place the first set of parenthesis in n-1 ways. For example, if the given chain is of 4 matrices. let the chain be ABCD, then there are 3 ways to place first set of parenthesis outer side: (A)(BCD), (AB)(CD) and (ABC)(D). So when we place a set of parenthesis, we divide the problem into subproblems of smaller size. Therefore, the problem has optimal substructure property and can be easily solved using recursion.Minimum number of multiplication needed to multiply a chain of size n = Minimum of all n-1 placements (these placements create subproblems of smaller size)" }, { "code": null, "e": 37411, "s": 37282, "text": "2) Overlapping Subproblems Following is a recursive implementation that simply follows the above optimal substructure property. " }, { "code": null, "e": 37458, "s": 37411, "text": "Below is the implementation of the above idea:" }, { "code": null, "e": 37462, "s": 37458, "text": "C++" }, { "code": null, "e": 37464, "s": 37462, "text": "C" }, { "code": null, "e": 37469, "s": 37464, "text": "Java" }, { "code": null, "e": 37477, "s": 37469, "text": "Python3" }, { "code": null, "e": 37480, "s": 37477, "text": "C#" }, { "code": null, "e": 37484, "s": 37480, "text": "PHP" }, { "code": null, "e": 37495, "s": 37484, "text": "Javascript" }, { "code": "/* A naive recursive implementation that simplyfollows the above optimal substructure property */#include <bits/stdc++.h>using namespace std; // Matrix Ai has dimension p[i-1] x p[i]// for i = 1..nint MatrixChainOrder(int p[], int i, int j){ if (i == j) return 0; int k; int min = INT_MAX; int count; // place parenthesis at different places // between first and last matrix, recursively // calculate count of multiplications for // each parenthesis placement and return the // minimum count for (k = i; k < j; k++) { count = MatrixChainOrder(p, i, k) + MatrixChainOrder(p, k + 1, j) + p[i - 1] * p[k] * p[j]; if (count < min) min = count; } // Return minimum count return min;} // Driver Codeint main(){ int arr[] = { 1, 2, 3, 4, 3 }; int n = sizeof(arr) / sizeof(arr[0]); cout << \"Minimum number of multiplications is \" << MatrixChainOrder(arr, 1, n - 1);} // This code is contributed by Shivi_Aggarwal", "e": 38525, "s": 37495, "text": null }, { "code": "/* A naive recursive implementation that simply follows the above optimal substructure property */#include <limits.h>#include <stdio.h> // Matrix Ai has dimension p[i-1] x p[i] for i = 1..nint MatrixChainOrder(int p[], int i, int j){ if (i == j) return 0; int k; int min = INT_MAX; int count; // place parenthesis at different places between first // and last matrix, recursively calculate count of // multiplications for each parenthesis placement and // return the minimum count for (k = i; k < j; k++) { count = MatrixChainOrder(p, i, k) + MatrixChainOrder(p, k + 1, j) + p[i - 1] * p[k] * p[j]; if (count < min) min = count; } // Return minimum count return min;} // Driver codeint main(){ int arr[] = { 1, 2, 3, 4, 3 }; int n = sizeof(arr) / sizeof(arr[0]); printf(\"Minimum number of multiplications is %d \", MatrixChainOrder(arr, 1, n - 1)); getchar(); return 0;}", "e": 39527, "s": 38525, "text": null }, { "code": "/* A naive recursive implementation that simply follows the above optimal substructure property */class MatrixChainMultiplication { // Matrix Ai has dimension p[i-1] x p[i] for i = 1..n static int MatrixChainOrder(int p[], int i, int j) { if (i == j) return 0; int min = Integer.MAX_VALUE; // place parenthesis at different places between // first and last matrix, recursively calculate // count of multiplications for each parenthesis // placement and return the minimum count for (int k = i; k < j; k++) { int count = MatrixChainOrder(p, i, k) + MatrixChainOrder(p, k + 1, j) + p[i - 1] * p[k] * p[j]; if (count < min) min = count; } // Return minimum count return min; } // Driver code public static void main(String args[]) { int arr[] = new int[] { 1, 2, 3, 4, 3 }; int n = arr.length; System.out.println( \"Minimum number of multiplications is \" + MatrixChainOrder(arr, 1, n - 1)); }}/* This code is contributed by Rajat Mishra*/", "e": 40708, "s": 39527, "text": null }, { "code": "# A naive recursive implementation that# simply follows the above optimal# substructure propertyimport sys # Matrix A[i] has dimension p[i-1] x p[i]# for i = 1..n def MatrixChainOrder(p, i, j): if i == j: return 0 _min = sys.maxsize # place parenthesis at different places # between first and last matrix, # recursively calculate count of # multiplications for each parenthesis # placement and return the minimum count for k in range(i, j): count = (MatrixChainOrder(p, i, k) + MatrixChainOrder(p, k + 1, j) + p[i-1] * p[k] * p[j]) if count < _min: _min = count # Return minimum count return _min # Driver codearr = [1, 2, 3, 4, 3]n = len(arr) print(\"Minimum number of multiplications is \", MatrixChainOrder(arr, 1, n-1)) # This code is contributed by Aryan Garg", "e": 41578, "s": 40708, "text": null }, { "code": "/* C# code for naive recursive implementationthat simply follows the above optimalsubstructure property */using System; class GFG { // Matrix Ai has dimension p[i-1] x p[i] // for i = 1..n static int MatrixChainOrder(int[] p, int i, int j) { if (i == j) return 0; int min = int.MaxValue; // place parenthesis at different places // between first and last matrix, recursively // calculate count of multiplications for each // parenthesis placement and return the // minimum count for (int k = i; k < j; k++) { int count = MatrixChainOrder(p, i, k) + MatrixChainOrder(p, k + 1, j) + p[i - 1] * p[k] * p[j]; if (count < min) min = count; } // Return minimum count return min; } // Driver code public static void Main() { int[] arr = new int[] { 1, 2, 3, 4, 3 }; int n = arr.Length; Console.Write( \"Minimum number of multiplications is \" + MatrixChainOrder(arr, 1, n - 1)); }} // This code is contributed by Sam007.", "e": 42746, "s": 41578, "text": null }, { "code": "<?php// A naive recursive implementation// that simply follows the above// optimal substructure property // Matrix Ai has dimension// p[i-1] x p[i] for i = 1..nfunction MatrixChainOrder(&$p, $i, $j){ if($i == $j) return 0; $min = PHP_INT_MAX; // place parenthesis at different places // between first and last matrix, recursively // calculate count of multiplications for // each parenthesis placement and return // the minimum count for ($k = $i; $k < $j; $k++) { $count = MatrixChainOrder($p, $i, $k) + MatrixChainOrder($p, $k + 1, $j) + $p[$i - 1] * $p[$k] * $p[$j]; if ($count < $min) $min = $count; } // Return minimum count return $min;} // Driver Code$arr = array(1, 2, 3, 4, 3);$n = sizeof($arr); echo \"Minimum number of multiplications is \" . MatrixChainOrder($arr, 1, $n - 1); // This code is contributed by ita_c?>", "e": 43730, "s": 42746, "text": null }, { "code": "<script> /* A naive recursive implementation that simply follows the above optimal substructure property */ // Matrix Ai has dimension p[i-1] x p[i] for i = 1..nfunction MatrixChainOrder(p , i , j){ if (i == j) return 0; var min = Number.MAX_VALUE; // place parenthesis at different places between // first and last matrix, recursively calculate // count of multiplications for each parenthesis // placement and return the minimum count var k=0; for (k = i; k < j; k++) { var count = MatrixChainOrder(p, i, k) + MatrixChainOrder(p, k + 1, j) + p[i - 1] * p[k] * p[j]; if (count < min) min = count; } // Return minimum count return min;} // Driver codevar arr = [ 1, 2, 3, 4, 3 ];var n = arr.length; document.write( \"Minimum number of multiplications is \" + MatrixChainOrder(arr, 1, n - 1)); // This code contributed by shikhasingrajput </script>", "e": 44694, "s": 43730, "text": null }, { "code": null, "e": 44734, "s": 44694, "text": "Minimum number of multiplications is 30" }, { "code": null, "e": 45093, "s": 44734, "text": "The time complexity of the above naive recursive approach is exponential. It should be noted that the above function computes the same subproblems again and again. See the following recursion tree for a matrix chain of size 4. The function MatrixChainOrder(p, 3, 4) is called two times. We can see that there are many subproblems being called more than once." }, { "code": null, "e": 45462, "s": 45093, "text": "Since same subproblems are called again, this problem has Overlapping Subproblems property. So Matrix Chain Multiplication problem has both properties (see this and this) of a dynamic programming problem. Like other typical Dynamic Programming(DP) problems, recomputations of same subproblems can be avoided by constructing a temporary array m[][] in bottom up manner." }, { "code": null, "e": 45621, "s": 45462, "text": "Dynamic Programming Solution Following is the implementation of the Matrix Chain Multiplication problem using Dynamic Programming (Tabulation vs Memoization) " }, { "code": null, "e": 45643, "s": 45621, "text": "Using Memoization – " }, { "code": null, "e": 45647, "s": 45643, "text": "C++" }, { "code": null, "e": 45652, "s": 45647, "text": "Java" }, { "code": null, "e": 45660, "s": 45652, "text": "Python3" }, { "code": null, "e": 45663, "s": 45660, "text": "C#" }, { "code": null, "e": 45674, "s": 45663, "text": "Javascript" }, { "code": "// C++ program using memoization#include <bits/stdc++.h>using namespace std;int dp[100][100]; // Function for matrix chain multiplicationint matrixChainMemoised(int* p, int i, int j){ if (i == j) { return 0; } if (dp[i][j] != -1) { return dp[i][j]; } dp[i][j] = INT_MAX; for (int k = i; k < j; k++) { dp[i][j] = min( dp[i][j], matrixChainMemoised(p, i, k) + matrixChainMemoised(p, k + 1, j) + p[i - 1] * p[k] * p[j]); } return dp[i][j];}int MatrixChainOrder(int* p, int n){ int i = 1, j = n - 1; return matrixChainMemoised(p, i, j);} // Driver Codeint main(){ int arr[] = { 1, 2, 3, 4 }; int n = sizeof(arr) / sizeof(arr[0]); memset(dp, -1, sizeof dp); cout << \"Minimum number of multiplications is \" << MatrixChainOrder(arr, n);} // This code is contributed by Sumit_Yadav", "e": 46582, "s": 45674, "text": null }, { "code": "// Java program using memoizationimport java.io.*;import java.util.*;class GFG{ static int[][] dp = new int[100][100]; // Function for matrix chain multiplication static int matrixChainMemoised(int[] p, int i, int j) { if (i == j) { return 0; } if (dp[i][j] != -1) { return dp[i][j]; } dp[i][j] = Integer.MAX_VALUE; for (int k = i; k < j; k++) { dp[i][j] = Math.min( dp[i][j], matrixChainMemoised(p, i, k) + matrixChainMemoised(p, k + 1, j) + p[i - 1] * p[k] * p[j]); } return dp[i][j]; } static int MatrixChainOrder(int[] p, int n) { int i = 1, j = n - 1; return matrixChainMemoised(p, i, j); } // Driver Code public static void main (String[] args) { int arr[] = { 1, 2, 3, 4 }; int n= arr.length; for (int[] row : dp) Arrays.fill(row, -1); System.out.println(\"Minimum number of multiplications is \" + MatrixChainOrder(arr, n)); }} // This code is contributed by avanitrachhadiya2155", "e": 47582, "s": 46582, "text": null }, { "code": "# Python program using memoizationimport sysdp = [[-1 for i in range(100)] for j in range(100)] # Function for matrix chain multiplicationdef matrixChainMemoised(p, i, j): if(i == j): return 0 if(dp[i][j] != -1): return dp[i][j] dp[i][j] = sys.maxsize for k in range(i,j): dp[i][j] = min(dp[i][j], matrixChainMemoised(p, i, k) + matrixChainMemoised(p, k + 1, j)+ p[i - 1] * p[k] * p[j]) return dp[i][j] def MatrixChainOrder(p,n): i = 1 j = n - 1 return matrixChainMemoised(p, i, j) # Driver Codearr = [1, 2, 3, 4]n = len(arr)print(\"Minimum number of multiplications is\",MatrixChainOrder(arr, n)) # This code is contributed by rag2127", "e": 48284, "s": 47582, "text": null }, { "code": "// C# program using memoizationusing System;class GFG{ static int[,] dp = new int[100, 100]; // Function for matrix chain multiplication static int matrixChainMemoised(int[] p, int i, int j) { if (i == j) { return 0; } if (dp[i, j] != -1) { return dp[i, j]; } dp[i, j] = Int32.MaxValue; for (int k = i; k < j; k++) { dp[i, j] = Math.Min( dp[i, j], matrixChainMemoised(p, i, k) + matrixChainMemoised(p, k + 1, j) + p[i - 1] * p[k] * p[j]); } return dp[i,j]; } static int MatrixChainOrder(int[] p, int n) { int i = 1, j = n - 1; return matrixChainMemoised(p, i, j); } // Driver code static void Main() { int[] arr = { 1, 2, 3, 4 }; int n = arr.Length; for(int i = 0; i < 100; i++) { for(int j = 0; j < 100; j++) { dp[i, j] = -1; } } Console.WriteLine(\"Minimum number of multiplications is \" + MatrixChainOrder(arr, n)); }} // This code is contributed by divyeshrabadiya07.", "e": 49337, "s": 48284, "text": null }, { "code": "<script> // Javascript program using memoizationlet dp = new Array(100);for(var i = 0; i < dp.length; i++){ dp[i] = new Array(2);} // Function for matrix chain multiplicationfunction matrixChainMemoised(p, i, j){ if (i == j) { return 0; } if (dp[i][j] != -1) { return dp[i][j]; } dp[i][j] = Number.MAX_VALUE; for(let k = i; k < j; k++) { dp[i][j] = Math.min( dp[i][j], matrixChainMemoised(p, i, k) + matrixChainMemoised(p, k + 1, j) + p[i - 1] * p[k] * p[j]); } return dp[i][j];} function MatrixChainOrder(p, n){ let i = 1, j = n - 1; return matrixChainMemoised(p, i, j);} // Driver codelet arr = [ 1, 2, 3, 4 ];let n = arr.length; for(var i = 0; i < dp.length; i++){ for(var j = 0; j < dp.length; j++) { dp[i][j] = -1; }} document.write(\"Minimum number of multiplications is \" + MatrixChainOrder(arr, n)); // This code is contributed by target_2 </script>", "e": 50363, "s": 49337, "text": null }, { "code": null, "e": 50403, "s": 50363, "text": "Minimum number of multiplications is 18" }, { "code": null, "e": 50427, "s": 50403, "text": "Time Complexity: O(n3 )" }, { "code": null, "e": 50481, "s": 50427, "text": "Auxiliary Space: O(n2) ignoring recursion stack space" }, { "code": null, "e": 50502, "s": 50481, "text": "Using Tabulation – " }, { "code": null, "e": 50506, "s": 50502, "text": "C++" }, { "code": null, "e": 50508, "s": 50506, "text": "C" }, { "code": null, "e": 50513, "s": 50508, "text": "Java" }, { "code": null, "e": 50521, "s": 50513, "text": "Python3" }, { "code": null, "e": 50524, "s": 50521, "text": "C#" }, { "code": null, "e": 50528, "s": 50524, "text": "PHP" }, { "code": null, "e": 50539, "s": 50528, "text": "Javascript" }, { "code": "// See the Cormen book for details of the// following algorithm#include <bits/stdc++.h>using namespace std; // Matrix Ai has dimension p[i-1] x p[i]// for i = 1..nint MatrixChainOrder(int p[], int n){ /* For simplicity of the program, one extra row and one extra column are allocated in m[][]. 0th row and 0th column of m[][] are not used */ int m[n][n]; int i, j, k, L, q; /* m[i, j] = Minimum number of scalar multiplications needed to compute the matrix A[i]A[i+1]...A[j] = A[i..j] where dimension of A[i] is p[i-1] x p[i] */ // cost is zero when multiplying // one matrix. for (i = 1; i < n; i++) m[i][i] = 0; // L is chain length. for (L = 2; L < n; L++) { for (i = 1; i < n - L + 1; i++) { j = i + L - 1; m[i][j] = INT_MAX; for (k = i; k <= j - 1; k++) { // q = cost/scalar multiplications q = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j]; if (q < m[i][j]) m[i][j] = q; } } } return m[1][n - 1];} // Driver Codeint main(){ int arr[] = { 1, 2, 3, 4 }; int size = sizeof(arr) / sizeof(arr[0]); cout << \"Minimum number of multiplications is \" << MatrixChainOrder(arr, size); getchar(); return 0;} // This code is contributed// by Akanksha Rai", "e": 51938, "s": 50539, "text": null }, { "code": "// See the Cormen book for details of the following// algorithm#include <limits.h>#include <stdio.h> // Matrix Ai has dimension p[i-1] x p[i] for i = 1..nint MatrixChainOrder(int p[], int n){ /* For simplicity of the program, one extra row and one extra column are allocated in m[][]. 0th row and 0th column of m[][] are not used */ int m[n][n]; int i, j, k, L, q; /* m[i, j] = Minimum number of scalar multiplications needed to compute the matrix A[i]A[i+1]...A[j] = A[i..j] where dimension of A[i] is p[i-1] x p[i] */ // cost is zero when multiplying one matrix. for (i = 1; i < n; i++) m[i][i] = 0; // L is chain length. for (L = 2; L < n; L++) { for (i = 1; i < n - L + 1; i++) { j = i + L - 1; m[i][j] = INT_MAX; for (k = i; k <= j - 1; k++) { // q = cost/scalar multiplications q = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j]; if (q < m[i][j]) m[i][j] = q; } } } return m[1][n - 1];} // Driver codeint main(){ int arr[] = { 1, 2, 3, 4 }; int size = sizeof(arr) / sizeof(arr[0]); printf(\"Minimum number of multiplications is %d \", MatrixChainOrder(arr, size)); getchar(); return 0;}", "e": 53314, "s": 51938, "text": null }, { "code": "// Dynamic Programming Java implementation of Matrix// Chain Multiplication.// See the Cormen book for details of the following// algorithmclass MatrixChainMultiplication{ // Matrix Ai has dimension p[i-1] x p[i] for i = 1..n static int MatrixChainOrder(int p[], int n) { /* For simplicity of the program, one extra row and one extra column are allocated in m[][]. 0th row and 0th column of m[][] are not used */ int m[][] = new int[n][n]; int i, j, k, L, q; /* m[i, j] = Minimum number of scalar multiplications needed to compute the matrix A[i]A[i+1]...A[j] = A[i..j] where dimension of A[i] is p[i-1] x p[i] */ // cost is zero when multiplying one matrix. for (i = 1; i < n; i++) m[i][i] = 0; // L is chain length. for (L = 2; L < n; L++) { for (i = 1; i < n - L + 1; i++) { j = i + L - 1; if (j == n) continue; m[i][j] = Integer.MAX_VALUE; for (k = i; k <= j - 1; k++) { // q = cost/scalar multiplications q = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j]; if (q < m[i][j]) m[i][j] = q; } } } return m[1][n - 1]; } // Driver code public static void main(String args[]) { int arr[] = new int[] { 1, 2, 3, 4 }; int size = arr.length; System.out.println( \"Minimum number of multiplications is \" + MatrixChainOrder(arr, size)); }}/* This code is contributed by Rajat Mishra*/", "e": 55042, "s": 53314, "text": null }, { "code": "# Dynamic Programming Python implementation of Matrix# Chain Multiplication. See the Cormen book for details# of the following algorithmimport sysmaxint=int(1e9+7)# Matrix Ai has dimension p[i-1] x p[i] for i = 1..n def MatrixChainOrder(p, n): # For simplicity of the program, # one extra row and one # extra column are allocated in m[][]. # 0th row and 0th # column of m[][] are not used m = [[0 for x in range(n)] for x in range(n)] # m[i, j] = Minimum number of scalar # multiplications needed # to compute the matrix A[i]A[i + 1]...A[j] = # A[i..j] where # dimension of A[i] is p[i-1] x p[i] # cost is zero when multiplying one matrix. for i in range(1, n): m[i][i] = 0 # L is chain length. for L in range(2, n): for i in range(1, n-L + 1): j = i + L-1 m[i][j] = maxint for k in range(i, j): # q = cost / scalar multiplications q = m[i][k] + m[k + 1][j] + p[i-1]*p[k]*p[j] if q < m[i][j]: m[i][j] = q return m[1][n-1] # Driver codearr = [1, 2, 3, 4]size = len(arr) print(\"Minimum number of multiplications is \" + str(MatrixChainOrder(arr, size)))# This Code is contributed by Bhavya Jain", "e": 56306, "s": 55042, "text": null }, { "code": "// Dynamic Programming C# implementation of// Matrix Chain Multiplication.// See the Cormen book for details of the// following algorithmusing System; class GFG{ // Matrix Ai has dimension p[i-1] x p[i] // for i = 1..n static int MatrixChainOrder(int[] p, int n) { /* For simplicity of the program, one extra row and one extra column are allocated in m[][]. 0th row and 0th column of m[][] are not used */ int[, ] m = new int[n, n]; int i, j, k, L, q; /* m[i, j] = Minimum number of scalar multiplications needed to compute the matrix A[i]A[i+1]...A[j] = A[i..j] where dimension of A[i] is p[i-1] x p[i] */ // cost is zero when multiplying // one matrix. for (i = 1; i < n; i++) m[i, i] = 0; // L is chain length. for (L = 2; L < n; L++) { for (i = 1; i < n - L + 1; i++) { j = i + L - 1; if (j == n) continue; m[i, j] = int.MaxValue; for (k = i; k <= j - 1; k++) { // q = cost/scalar multiplications q = m[i, k] + m[k + 1, j] + p[i - 1] * p[k] * p[j]; if (q < m[i, j]) m[i, j] = q; } } } return m[1, n - 1]; } // Driver code public static void Main() { int[] arr = new int[] { 1, 2, 3, 4 }; int size = arr.Length; Console.Write(\"Minimum number of \" + \"multiplications is \" + MatrixChainOrder(arr, size)); }} // This code is contributed by Sam007", "e": 58041, "s": 56306, "text": null }, { "code": "<?php// Dynamic Programming Python implementation// of Matrix Chain Multiplication. // See the Cormen book for details of the// following algorithm Matrix Ai has// dimension p[i-1] x p[i] for i = 1..nfunction MatrixChainOrder($p, $n){ /* For simplicity of the program, one extra row and one extra column are allocated in m[][]. 0th row and 0th column of m[][] are not used */ $m[][] = array($n, $n); /* m[i, j] = Minimum number of scalar multiplications needed to compute the matrix A[i]A[i+1]...A[j] = A[i..j] where dimension of A[i] is p[i-1] x p[i] */ // cost is zero when multiplying one matrix. for ($i = 1; $i < $n; $i++) $m[$i][$i] = 0; // L is chain length. for ($L = 2; $L < $n; $L++) { for ($i = 1; $i < $n - $L + 1; $i++) { $j = $i + $L - 1; if($j == $n) continue; $m[$i][$j] = PHP_INT_MAX; for ($k = $i; $k <= $j - 1; $k++) { // q = cost/scalar multiplications $q = $m[$i][$k] + $m[$k + 1][$j] + $p[$i - 1] * $p[$k] * $p[$j]; if ($q < $m[$i][$j]) $m[$i][$j] = $q; } } } return $m[1][$n-1];} // Driver Code$arr = array(1, 2, 3, 4);$size = sizeof($arr); echo\"Minimum number of multiplications is \". MatrixChainOrder($arr, $size); // This code is contributed by Mukul Singh?>", "e": 59484, "s": 58041, "text": null }, { "code": "<script> // Dynamic Programming javascript implementation of Matrix// Chain Multiplication.// See the Cormen book for details of the following// algorithm // Matrix Ai has dimension p[i-1] x p[i] for i = 1..nfunction MatrixChainOrder(p , n){ /* For simplicity of the program, one extra row and one extra column are allocated in m. 0th row and 0th column of m are not used */ var m = Array(n).fill(0).map(x => Array(n).fill(0)); var i, j, k, L, q; /* m[i, j] = Minimum number of scalar multiplications needed to compute the matrix A[i]A[i+1]...A[j] = A[i..j] where dimension of A[i] is p[i-1] x p[i] */ // cost is zero when multiplying one matrix. for (i = 1; i < n; i++) m[i][i] = 0; // L is chain length. for (L = 2; L < n; L++) { for (i = 1; i < n - L + 1; i++) { j = i + L - 1; if (j == n) continue; m[i][j] = Number.MAX_VALUE; for (k = i; k <= j - 1; k++) { // q = cost/scalar multiplications q = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j]; if (q < m[i][j]) m[i][j] = q; } } } return m[1][n - 1];} // Driver codevar arr = [ 1, 2, 3, 4 ];var size = arr.length; document.write( \"Minimum number of multiplications is \" + MatrixChainOrder(arr, size)); // This code contributed by Princi Singh </script>", "e": 60947, "s": 59484, "text": null }, { "code": null, "e": 60987, "s": 60947, "text": "Minimum number of multiplications is 18" }, { "code": null, "e": 61033, "s": 60987, "text": "Time Complexity: O(n3 )Auxiliary Space: O(n2)" }, { "code": null, "e": 61262, "s": 61033, "text": "Matrix Chain Multiplication (A O(N^2) Solution) Printing brackets in Matrix Chain Multiplication ProblemPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 61333, "s": 61262, "text": "Applications: Minimum and Maximum values of an expression with * and +" }, { "code": null, "e": 61493, "s": 61333, "text": "References: http://en.wikipedia.org/wiki/Matrix_chain_multiplication http://www.personal.kent.edu/~rmuhamma/Algorithms/MyAlgorithms/Dynamic/chainMatrixMult.htm" }, { "code": null, "e": 62320, "s": 61493, "text": "YouTubeGeeksforGeeks500K subscribersMatrix Chain Multiplication | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 11:32•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=gwmitwgz87s\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 62362, "s": 62320, "text": "?list=PLqM7alHXFySEQDk2MDfbwEdjd2svVJH9p " }, { "code": null, "e": 62370, "s": 62362, "text": "aryan21" }, { "code": null, "e": 62376, "s": 62370, "text": "ukasp" }, { "code": null, "e": 62386, "s": 62376, "text": "Code_Mech" }, { "code": null, "e": 62401, "s": 62386, "text": "Shivi_Aggarwal" }, { "code": null, "e": 62414, "s": 62401, "text": "Akanksha_Rai" }, { "code": null, "e": 62422, "s": 62414, "text": "kmradi9" }, { "code": null, "e": 62433, "s": 62422, "text": "itsvinayak" }, { "code": null, "e": 62448, "s": 62433, "text": "manjeetsumit16" }, { "code": null, "e": 62460, "s": 62448, "text": "sommayghosh" }, { "code": null, "e": 62481, "s": 62460, "text": "avanitrachhadiya2155" }, { "code": null, "e": 62489, "s": 62481, "text": "rag2127" }, { "code": null, "e": 62507, "s": 62489, "text": "divyeshrabadiya07" }, { "code": null, "e": 62524, "s": 62507, "text": "shikhasingrajput" }, { "code": null, "e": 62537, "s": 62524, "text": "princi singh" }, { "code": null, "e": 62549, "s": 62537, "text": "anikakapoor" }, { "code": null, "e": 62558, "s": 62549, "text": "target_2" }, { "code": null, "e": 62575, "s": 62558, "text": "surinderdawra388" }, { "code": null, "e": 62591, "s": 62575, "text": "amartyaghoshgfg" }, { "code": null, "e": 62604, "s": 62591, "text": "prasanna1995" }, { "code": null, "e": 62611, "s": 62604, "text": "Amazon" }, { "code": null, "e": 62639, "s": 62611, "text": "matrix-chain-multiplication" }, { "code": null, "e": 62649, "s": 62639, "text": "Microsoft" }, { "code": null, "e": 62669, "s": 62649, "text": "Dynamic Programming" }, { "code": null, "e": 62676, "s": 62669, "text": "Matrix" }, { "code": null, "e": 62683, "s": 62676, "text": "Amazon" }, { "code": null, "e": 62693, "s": 62683, "text": "Microsoft" }, { "code": null, "e": 62713, "s": 62693, "text": "Dynamic Programming" }, { "code": null, "e": 62720, "s": 62713, "text": "Matrix" }, { "code": null, "e": 62818, "s": 62720, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 62827, "s": 62818, "text": "Comments" }, { "code": null, "e": 62840, "s": 62827, "text": "Old Comments" }, { "code": null, "e": 62872, "s": 62840, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 62903, "s": 62872, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 62936, "s": 62903, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 62963, "s": 62936, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 63001, "s": 62963, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 63045, "s": 63001, "text": "Program to find largest element in an array" }, { "code": null, "e": 63081, "s": 63045, "text": "Print a given matrix in spiral form" }, { "code": null, "e": 63114, "s": 63081, "text": "Program to multiply two matrices" }, { "code": null, "e": 63165, "s": 63114, "text": "Inplace rotate square matrix by 90 degrees | Set 1" } ]
Data Visualization using Streamlit | by Aniket Wattamwar | Towards Data Science
Like, Share and Subscribe to the channel- HackerShrine Recently, I came across an open source framework — Streamlit which is used to create data apps. So I spent some time on the documentation and did some data visualization on a Food Demand Forecasting Dataset. Streamlit’s open-source app framework is the easiest way for data scientists and machine learning engineers to create beautiful, performant apps in only a few hours! All in pure Python. All for free. — streamlit To get started just type this command: pip install streamlit To check whether it was installed properly run the below command: streamlit hello If this appears on your browser, then streamlit is installed and working properly! Now we will plot some simple charts using the dataset provided in the link above. Importing the necessary libraries first and give a title. import streamlit as stimport pandas as pdimport numpy as npimport plotly.figure_factory as ffimport matplotlib.pyplot as pltst.title(‘Food Demand Forecasting — Analytics Vidhya’) In the dataset you will see 3 csv files and we will import that now using pandas. @st.cache is quite important here for smooth and fast functioning. Read about it in detail here. @st.cachedef load_data(nrows): data = pd.read_csv('train.csv', nrows=nrows) return data@st.cachedef load_center_data(nrows): data = pd.read_csv('fulfilment_center_info.csv',nrows=nrows) return data@st.cachedef load_meal_data(nrows): data = pd.read_csv('meal_info.csv',nrows=nrows) return data Let’s call these functions now. I am right now taking only 1000 rows you can take your entire dataset. data_load_state = st.text('Loading data...')weekly_data = load_data(1000)center_info_data = load_center_data(1000)meal_data = load_meal_data(1000) First we will look at the Weekly Demand Data. We will be plotting bar chart, histograms, line chart and area chart. Bar Chart st.subheader(‘Weekly Demand Data’)st.write(weekly_data)#Bar Chartst.bar_chart(weekly_data[‘num_orders’]) Histogram #histogramdf = pd.DataFrame(weekly_data[:200], columns = [‘num_orders’,’checkout_price’,’base_price’])df.hist()plt.show()st.pyplot() Line Chart #Line Chartst.line_chart(df) Area Chart chart_data = pd.DataFrame(weekly_data[:40], columns=[‘num_orders’, ‘base_price’])st.area_chart(chart_data) Next csv file that we have is of Fulfillment information center. To display the raw data from the csv file I have added a checkbox and when it is checked it displays the raw data. Streamlit provides with simple and elegant syntax to do as you can see below. st.subheader(‘Fulfillment Center Information’)if st.checkbox(‘Show Center Information data’): st.subheader(‘Center Information data’) st.write(center_info_data)#st.write(center_info_data) Plotting the bar chart for region code and center type in a way similar to weekly demand data. st.bar_chart(center_info_data[‘region_code’])st.bar_chart(center_info_data[‘center_type’]) Next we will use plotly to see the distribution region code and center id. hist_data = [center_info_data[‘center_id’],center_info_data[‘region_code’]]group_labels = [‘Center Id’, ‘Region Code’]fig = ff.create_distplot(hist_data, group_labels, bin_size=[10, 25])st.plotly_chart(fig, use_container_width=True) The last csv file that we have is of meal data lets display the raw data of that too. st.subheader('Meal Information')st.write(meal_data) Here, a simple bar chart of the column cusine is plotted. st.bar_chart(meal_data[‘cuisine’]) Then to create button which on clicking displays the bar chart of the number of categories of meals will be shown. This can be done by writing the following code: agree = st.button(‘Click to see Categories of Meal’)if agree: st.bar_chart(meal_data[‘category’]) To run your streamlit app just type the following command: streamlit run appname.py This will open up a browser and you can see all the visualisations. Here is a screen recording on my computer. www.linkedin.com You can find the entire code on my GitHub. You can connect with me here on other platforms as well — Linktree
[ { "code": null, "e": 227, "s": 172, "text": "Like, Share and Subscribe to the channel- HackerShrine" }, { "code": null, "e": 435, "s": 227, "text": "Recently, I came across an open source framework — Streamlit which is used to create data apps. So I spent some time on the documentation and did some data visualization on a Food Demand Forecasting Dataset." }, { "code": null, "e": 635, "s": 435, "text": "Streamlit’s open-source app framework is the easiest way for data scientists and machine learning engineers to create beautiful, performant apps in only a few hours! All in pure Python. All for free." }, { "code": null, "e": 647, "s": 635, "text": "— streamlit" }, { "code": null, "e": 686, "s": 647, "text": "To get started just type this command:" }, { "code": null, "e": 708, "s": 686, "text": "pip install streamlit" }, { "code": null, "e": 774, "s": 708, "text": "To check whether it was installed properly run the below command:" }, { "code": null, "e": 790, "s": 774, "text": "streamlit hello" }, { "code": null, "e": 873, "s": 790, "text": "If this appears on your browser, then streamlit is installed and working properly!" }, { "code": null, "e": 955, "s": 873, "text": "Now we will plot some simple charts using the dataset provided in the link above." }, { "code": null, "e": 1013, "s": 955, "text": "Importing the necessary libraries first and give a title." }, { "code": null, "e": 1192, "s": 1013, "text": "import streamlit as stimport pandas as pdimport numpy as npimport plotly.figure_factory as ffimport matplotlib.pyplot as pltst.title(‘Food Demand Forecasting — Analytics Vidhya’)" }, { "code": null, "e": 1371, "s": 1192, "text": "In the dataset you will see 3 csv files and we will import that now using pandas. @st.cache is quite important here for smooth and fast functioning. Read about it in detail here." }, { "code": null, "e": 1682, "s": 1371, "text": "@st.cachedef load_data(nrows): data = pd.read_csv('train.csv', nrows=nrows) return data@st.cachedef load_center_data(nrows): data = pd.read_csv('fulfilment_center_info.csv',nrows=nrows) return data@st.cachedef load_meal_data(nrows): data = pd.read_csv('meal_info.csv',nrows=nrows) return data" }, { "code": null, "e": 1785, "s": 1682, "text": "Let’s call these functions now. I am right now taking only 1000 rows you can take your entire dataset." }, { "code": null, "e": 1932, "s": 1785, "text": "data_load_state = st.text('Loading data...')weekly_data = load_data(1000)center_info_data = load_center_data(1000)meal_data = load_meal_data(1000)" }, { "code": null, "e": 2048, "s": 1932, "text": "First we will look at the Weekly Demand Data. We will be plotting bar chart, histograms, line chart and area chart." }, { "code": null, "e": 2058, "s": 2048, "text": "Bar Chart" }, { "code": null, "e": 2163, "s": 2058, "text": "st.subheader(‘Weekly Demand Data’)st.write(weekly_data)#Bar Chartst.bar_chart(weekly_data[‘num_orders’])" }, { "code": null, "e": 2173, "s": 2163, "text": "Histogram" }, { "code": null, "e": 2306, "s": 2173, "text": "#histogramdf = pd.DataFrame(weekly_data[:200], columns = [‘num_orders’,’checkout_price’,’base_price’])df.hist()plt.show()st.pyplot()" }, { "code": null, "e": 2317, "s": 2306, "text": "Line Chart" }, { "code": null, "e": 2346, "s": 2317, "text": "#Line Chartst.line_chart(df)" }, { "code": null, "e": 2357, "s": 2346, "text": "Area Chart" }, { "code": null, "e": 2464, "s": 2357, "text": "chart_data = pd.DataFrame(weekly_data[:40], columns=[‘num_orders’, ‘base_price’])st.area_chart(chart_data)" }, { "code": null, "e": 2529, "s": 2464, "text": "Next csv file that we have is of Fulfillment information center." }, { "code": null, "e": 2722, "s": 2529, "text": "To display the raw data from the csv file I have added a checkbox and when it is checked it displays the raw data. Streamlit provides with simple and elegant syntax to do as you can see below." }, { "code": null, "e": 2916, "s": 2722, "text": "st.subheader(‘Fulfillment Center Information’)if st.checkbox(‘Show Center Information data’): st.subheader(‘Center Information data’) st.write(center_info_data)#st.write(center_info_data)" }, { "code": null, "e": 3011, "s": 2916, "text": "Plotting the bar chart for region code and center type in a way similar to weekly demand data." }, { "code": null, "e": 3102, "s": 3011, "text": "st.bar_chart(center_info_data[‘region_code’])st.bar_chart(center_info_data[‘center_type’])" }, { "code": null, "e": 3177, "s": 3102, "text": "Next we will use plotly to see the distribution region code and center id." }, { "code": null, "e": 3410, "s": 3177, "text": "hist_data = [center_info_data[‘center_id’],center_info_data[‘region_code’]]group_labels = [‘Center Id’, ‘Region Code’]fig = ff.create_distplot(hist_data, group_labels, bin_size=[10, 25])st.plotly_chart(fig, use_container_width=True)" }, { "code": null, "e": 3496, "s": 3410, "text": "The last csv file that we have is of meal data lets display the raw data of that too." }, { "code": null, "e": 3548, "s": 3496, "text": "st.subheader('Meal Information')st.write(meal_data)" }, { "code": null, "e": 3606, "s": 3548, "text": "Here, a simple bar chart of the column cusine is plotted." }, { "code": null, "e": 3641, "s": 3606, "text": "st.bar_chart(meal_data[‘cuisine’])" }, { "code": null, "e": 3804, "s": 3641, "text": "Then to create button which on clicking displays the bar chart of the number of categories of meals will be shown. This can be done by writing the following code:" }, { "code": null, "e": 3902, "s": 3804, "text": "agree = st.button(‘Click to see Categories of Meal’)if agree: st.bar_chart(meal_data[‘category’])" }, { "code": null, "e": 3961, "s": 3902, "text": "To run your streamlit app just type the following command:" }, { "code": null, "e": 3986, "s": 3961, "text": "streamlit run appname.py" }, { "code": null, "e": 4054, "s": 3986, "text": "This will open up a browser and you can see all the visualisations." }, { "code": null, "e": 4097, "s": 4054, "text": "Here is a screen recording on my computer." }, { "code": null, "e": 4114, "s": 4097, "text": "www.linkedin.com" } ]
Hex to ASCII conversion in 8051
Now we will see how to convert Hexadecimal number to its ASCII equivalent using 8051. This program can convert 0-9 and A-F to its ASCII value. We know that the ASCII of number 00H is 30H (48D), and ASCII of 09H is39H (57D). So all other numbers are in the range 30H to 39H. The ASCII value of 0AH is 41H (65D) and ASCII of 0FH is 46H (70D), so all other alphabets (B, C, D, E) are in the range 41H to 46H. Here we are providing hexadecimal digit at memory location 20H, The ASCII equivalent is storing at location 30H. MOVR0,#20H; Initialize the address of the data MOVA,@R0; Get the data from an address, which is stored in R0 MOVR2,A;Store the content of A into R2 CLRC; Clear the Carry Flag SUBBA,#0AH;Subtract 0AH from A JCNUM ; When a carry is present, A is numeric ADDA,#41H;Add41H for Alphabet SJMPSTORE; Jump to store the value NUM: MOVA,R2; Copy R2 to A ADDA,#30H; Add 30H with A to get ASCII STORE: MOVR0,#30H; Point the destination location MOV@R0,A; Store A content to the memory location pointed by R0 HALT: SJMPHALT The logic behind HEX to ASCII conversion is very simple. We are just checking whether the number is in range 0 – 9 or not. When the number is in that range, then the hexadecimal digit is numeric, and we are just simply adding 30H with it to get the ASCII value. When the number is not in range 0 – 9, then the number is range A – F, so for that case, we are converting the number to 41H onwards. In the program, at first, we are clearing the carry flag. Then subtracting 0AHfrom the given number. If the value is numeric, then after subtraction the result will be negative, so the carry flag will be set. Now by checking the carry status, we can just add 30H with the value to get ASCII value. In other hands when the result of the subtraction is positive or 0, then we are adding 41H with the result of the subtraction.
[ { "code": null, "e": 1206, "s": 1062, "text": "Now we will see how to convert Hexadecimal number to its ASCII equivalent using 8051. This program can convert 0-9 and A-F to its ASCII value. " }, { "code": null, "e": 1469, "s": 1206, "text": "We know that the ASCII of number 00H is 30H (48D), and ASCII of 09H is39H (57D). So all other numbers are in the range 30H to 39H. The ASCII value of 0AH is 41H (65D) and ASCII of 0FH is 46H (70D), so all other alphabets (B, C, D, E) are in the range 41H to 46H." }, { "code": null, "e": 1582, "s": 1469, "text": "Here we are providing hexadecimal digit at memory location 20H, The ASCII equivalent is storing at location 30H." }, { "code": null, "e": 2099, "s": 1582, "text": "MOVR0,#20H; Initialize the address of the data\nMOVA,@R0; Get the data from an address, which is stored in R0\nMOVR2,A;Store the content of A into R2\nCLRC; Clear the Carry Flag\nSUBBA,#0AH;Subtract 0AH from A\nJCNUM ; When a carry is present, A is numeric\nADDA,#41H;Add41H for Alphabet\nSJMPSTORE; Jump to store the value\nNUM: MOVA,R2; Copy R2 to A\nADDA,#30H; Add 30H with A to get ASCII\nSTORE: MOVR0,#30H; Point the destination location\nMOV@R0,A; Store A content to the memory location pointed by R0\nHALT: SJMPHALT" }, { "code": null, "e": 2495, "s": 2099, "text": "The logic behind HEX to ASCII conversion is very simple. We are just checking whether the number is in range 0 – 9 or not. When the number is in that range, then the hexadecimal digit is numeric, and we are just simply adding 30H with it to get the ASCII value. When the number is not in range 0 – 9, then the number is range A – F, so for that case, we are converting the number to 41H onwards." }, { "code": null, "e": 2794, "s": 2495, "text": "In the program, at first, we are clearing the carry flag. Then subtracting 0AHfrom the given number. If the value is numeric, then after subtraction the result will be negative, so the carry flag will be set. Now by checking the carry status, we can just add 30H with the value to get ASCII value. " }, { "code": null, "e": 2921, "s": 2794, "text": "In other hands when the result of the subtraction is positive or 0, then we are adding 41H with the result of the subtraction." } ]
Assigning values to static final variables in java
In java, a non-static final variable can be assigned a value at two places. At the time of declaration. At the time of declaration. In constructor. In constructor. Live Demo public class Tester { final int A; //Scenario 1: assignment at time of declaration final int B = 2; public Tester() { //Scenario 2: assignment in constructor A = 1; } public void display() { System.out.println(A + ", " + B); } public static void main(String[] args) { Tester tester = new Tester(); tester.display(); } } 1, 2 But in case of being static final, a variable cannot be assigned at the constructor. The compiler will throw a compilation error. A static final variable is required to be assigned in a static block or at time of declaration. So a static final variable can be assigned a value at the following two places. At the time of declaration. At the time of declaration. In static block. In static block. Live Demo public class Tester { final int A; //Scenario 1: assignment at time of declaration final int B = 2; public Tester() { //Scenario 2: assignment in constructor A = 1; } public void display() { System.out.println(A + ", " + B); } public static void main(String[] args) { Tester tester = new Tester(); tester.display(); } } 1, 2 The reason behind this behavior of the static final variable is simple. A static final is common across the objects and if it is allowed to be assigned in the constructor, then during the creation of an object, this variable is getting changed per object and thus is not assigned once.
[ { "code": null, "e": 1138, "s": 1062, "text": "In java, a non-static final variable can be assigned a value at two places." }, { "code": null, "e": 1166, "s": 1138, "text": "At the time of declaration." }, { "code": null, "e": 1194, "s": 1166, "text": "At the time of declaration." }, { "code": null, "e": 1210, "s": 1194, "text": "In constructor." }, { "code": null, "e": 1226, "s": 1210, "text": "In constructor." }, { "code": null, "e": 1236, "s": 1226, "text": "Live Demo" }, { "code": null, "e": 1624, "s": 1236, "text": "public class Tester {\n final int A;\n //Scenario 1: assignment at time of declaration\n final int B = 2;\n\n public Tester() {\n //Scenario 2: assignment in constructor\n A = 1;\n }\n\n public void display() {\n System.out.println(A + \", \" + B);\n }\n\n public static void main(String[] args) { \n Tester tester = new Tester();\n tester.display();\n }\n}" }, { "code": null, "e": 1629, "s": 1624, "text": "1, 2" }, { "code": null, "e": 1935, "s": 1629, "text": "But in case of being static final, a variable cannot be assigned at the constructor. The compiler will throw a compilation error. A static final variable is required to be assigned in a static block or at time of declaration. So a static final variable can be assigned a value at the following two places." }, { "code": null, "e": 1963, "s": 1935, "text": "At the time of declaration." }, { "code": null, "e": 1991, "s": 1963, "text": "At the time of declaration." }, { "code": null, "e": 2008, "s": 1991, "text": "In static block." }, { "code": null, "e": 2025, "s": 2008, "text": "In static block." }, { "code": null, "e": 2035, "s": 2025, "text": "Live Demo" }, { "code": null, "e": 2423, "s": 2035, "text": "public class Tester {\n final int A;\n //Scenario 1: assignment at time of declaration\n final int B = 2;\n\n public Tester() {\n //Scenario 2: assignment in constructor\n A = 1;\n }\n\n public void display() {\n System.out.println(A + \", \" + B);\n }\n\n public static void main(String[] args) { \n Tester tester = new Tester();\n tester.display();\n }\n}" }, { "code": null, "e": 2428, "s": 2423, "text": "1, 2" }, { "code": null, "e": 2714, "s": 2428, "text": "The reason behind this behavior of the static final variable is simple. A static final is common across the objects and if it is allowed to be assigned in the constructor, then during the creation of an object, this variable is getting changed per object and thus is not assigned once." } ]
Abstraction of Binary Search - GeeksforGeeks
26 May, 2021 What is the binary search algorithm? Binary Search Algorithm is used to find a certain value of x for which a certain defined function f(x) needs to be maximized or minimized. It is frequently used to search an element in a sorted sequence by repeatedly dividing the search interval into halves. Begin with an interval covering the whole sequence, if the value of the search key is less than the item in the middle of the interval, then search in the left half of the interval otherwise search in the right half. Repeatedly check until the value is found or the interval is empty. The main condition to perform a Binary Search is that the sequence must be monotonous i.e., it must be either increasing or decreasing. Monotonic function A function f(x) is said to be monotonic if and only if for any x if f(x) returns true, then for any value of y (where y > x) should also return true and similarly if for a certain value of x for which f(x) is false, then for any value z (z < x) the function should also return false. How to solve a question using Binary Search: If the function is And the task is to find the maximum value of x such that f(x) is less than or equal to the target value. The interval in which we will search the target value for the given is from 0 to target value. Then we can use binary search for this problem since the function is a monotonically increasing function. Target = 17 f(x) = x2, since the function is monotonic binary search can be applied to it. Range of search interval will be [0, target]Step 1: low = 0, high = 17, calculate mid = (low + high)/2 = 8 Calculate f(8) = 64 which is more than target, so it will return false and high will be updated as high = mid – 1 = 7.Steps 2: low = 0, high = 7, calculate mid = (low + high)/2 = 3 Calculate f(3) = 9 which is less than target, so it will return true and low will be updated as low = mid + 1 = 4.Step 3: low = 4, high = 7, calculate mid = (low + high)/2 = 5 Calculate f(5) = 25 which is more than target, so it will return false and high will be updated as high = mid – 1 = 4.Step 4: Now since the range [low, high] converges to a single point i.e 4 so the final result is found, since f(4) = 16 which is the maximum value of the given function less than target. Below is the implementation of the above example: C++ Java Python3 C# Javascript // C++ program for the above example #include "bits/stdc++.h"using namespace std; // Function to find X such that it is// less than the target value and function// is f(x) = x^2void findX(int targetValue){ // Initialise start and end int start = 0, end = targetValue; int mid, result; // Loop till start <= end while (start <= end) { // Find the mid mid = start + (end - start) / 2; // Check for the left half if (mid * mid <= targetValue) { // Store the result result = mid; // Reinitialize the start point start = mid + 1; } // Check for the right half else { end = mid - 1; } } // Print the maximum value of x // such that x^2 is less than the // targetValue cout << result << endl;} // Driver Codeint main(){ // Given targetValue; int targetValue = 81; // Function Call findX(targetValue);} // Java program for// the above exampleimport java.util.*;class GFG{ // Function to find X such// that it is less than the// target value and function// is f(x) = x^2static void findX(int targetValue){ // Initialise start and end int start = 0, end = targetValue; int mid = 0, result = 0; // Loop till start <= end while (start <= end) { // Find the mid mid = start + (end - start) / 2; // Check for the left half if (mid * mid <= targetValue) { // Store the result result = mid; // Reinitialize the start point start = mid + 1; } // Check for the right half else { end = mid - 1; } } // Print the maximum value of x // such that x^2 is less than the // targetValue System.out.print(result + "\n");} // Driver Codepublic static void main(String[] args){ // Given targetValue; int targetValue = 81; // Function call findX(targetValue);}} // This code is contributed by 29AjayKumar # Python3 program for# the above example # Function to find X such# that it is less than the# target value and function# is f(x) = x ^ 2def findX(targetValue): # Initialise start and end start = 0; end = targetValue; mid = 0; # Loop till start <= end while (start <= end): # Find the mid mid = start + (end - start) // 2; # Check for the left half if (mid * mid <= targetValue): result = mid start = mid + 1; # Check for the right half else: end = mid - 1; # Print maximum value of x # such that x ^ 2 is less than the # targetValue print(result); # Driver Codeif __name__ == '__main__': # Given targetValue; targetValue = 81; # Function Call findX(targetValue); # This code is contributed by Rajput-Ji // C# program for// the above exampleusing System;class GFG{ // Function to find X such// that it is less than the// target value and function// is f(x) = x^2static void findX(int targetValue){ // Initialise start and end int start = 0, end = targetValue; int mid = 0, result = 0; // Loop till start <= end while (start <= end) { // Find the mid mid = start + (end - start) / 2; // Check for the left half if (mid * mid <= targetValue) { // Store the result result = mid; // Reinitialize the start point start = mid + 1; } // Check for the right half else { end = mid - 1; } } // Print the maximum value of x // such that x^2 is less than the // targetValue Console.Write(result + "\n");} // Driver Codepublic static void Main(String[] args){ // Given targetValue; int targetValue = 81; // Function Call findX(targetValue);}} // This code is contributed by 29AjayKumar <script> // JavaScript program for the above example // Function to find X such that it is// less than the target value and function// is f(x) = x^2function findX(targetValue){ // Initialise start and end var start = 0, end = targetValue; var mid, result; // Loop till start <= end while (start <= end) { // Find the mid mid = start + parseInt((end - start) / 2); // Check for the left half if (mid * mid <= targetValue) { // Store the result result = mid; // Reinitialize the start point start = mid + 1; } // Check for the right half else { end = mid - 1; } } // Print the maximum value of x // such that x^2 is less than the // targetValue document.write( result );} // Driver Code // Given targetValue;var targetValue = 81; // Function CallfindX(targetValue); </script> 9 The above binary search algorithm requires at most O(log N) comparisons to find the maximum value less than or equal to the target value. And the value of the function f(x) = x2 doesn’t need to be evaluated many times.Time Complexity: O(logN) Auxiliary Space: O(1) 29AjayKumar Rajput-Ji famously Binary Search Algorithms Divide and Conquer Searching Searching Divide and Conquer Binary Search Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments DSA Sheet by Love Babbar Difference between Informed and Uninformed Search in AI SCAN (Elevator) Disk Scheduling Algorithms Quadratic Probing in Hashing K means Clustering - Introduction Merge Sort QuickSort Binary Search Maximum and minimum of an array using minimum number of comparisons Program for Tower of Hanoi
[ { "code": null, "e": 24299, "s": 24271, "text": "\n26 May, 2021" }, { "code": null, "e": 25018, "s": 24299, "text": "What is the binary search algorithm? Binary Search Algorithm is used to find a certain value of x for which a certain defined function f(x) needs to be maximized or minimized. It is frequently used to search an element in a sorted sequence by repeatedly dividing the search interval into halves. Begin with an interval covering the whole sequence, if the value of the search key is less than the item in the middle of the interval, then search in the left half of the interval otherwise search in the right half. Repeatedly check until the value is found or the interval is empty. The main condition to perform a Binary Search is that the sequence must be monotonous i.e., it must be either increasing or decreasing. " }, { "code": null, "e": 25323, "s": 25018, "text": "Monotonic function A function f(x) is said to be monotonic if and only if for any x if f(x) returns true, then for any value of y (where y > x) should also return true and similarly if for a certain value of x for which f(x) is false, then for any value z (z < x) the function should also return false. " }, { "code": null, "e": 25388, "s": 25323, "text": "How to solve a question using Binary Search: If the function is " }, { "code": null, "e": 25564, "s": 25390, "text": "And the task is to find the maximum value of x such that f(x) is less than or equal to the target value. The interval in which we will search the target value for the given " }, { "code": null, "e": 25660, "s": 25566, "text": "is from 0 to target value. Then we can use binary search for this problem since the function " }, { "code": null, "e": 25703, "s": 25662, "text": "is a monotonically increasing function. " }, { "code": null, "e": 26567, "s": 25705, "text": "Target = 17 f(x) = x2, since the function is monotonic binary search can be applied to it. Range of search interval will be [0, target]Step 1: low = 0, high = 17, calculate mid = (low + high)/2 = 8 Calculate f(8) = 64 which is more than target, so it will return false and high will be updated as high = mid – 1 = 7.Steps 2: low = 0, high = 7, calculate mid = (low + high)/2 = 3 Calculate f(3) = 9 which is less than target, so it will return true and low will be updated as low = mid + 1 = 4.Step 3: low = 4, high = 7, calculate mid = (low + high)/2 = 5 Calculate f(5) = 25 which is more than target, so it will return false and high will be updated as high = mid – 1 = 4.Step 4: Now since the range [low, high] converges to a single point i.e 4 so the final result is found, since f(4) = 16 which is the maximum value of the given function less than target. " }, { "code": null, "e": 26620, "s": 26569, "text": "Below is the implementation of the above example: " }, { "code": null, "e": 26624, "s": 26620, "text": "C++" }, { "code": null, "e": 26629, "s": 26624, "text": "Java" }, { "code": null, "e": 26637, "s": 26629, "text": "Python3" }, { "code": null, "e": 26640, "s": 26637, "text": "C#" }, { "code": null, "e": 26651, "s": 26640, "text": "Javascript" }, { "code": "// C++ program for the above example #include \"bits/stdc++.h\"using namespace std; // Function to find X such that it is// less than the target value and function// is f(x) = x^2void findX(int targetValue){ // Initialise start and end int start = 0, end = targetValue; int mid, result; // Loop till start <= end while (start <= end) { // Find the mid mid = start + (end - start) / 2; // Check for the left half if (mid * mid <= targetValue) { // Store the result result = mid; // Reinitialize the start point start = mid + 1; } // Check for the right half else { end = mid - 1; } } // Print the maximum value of x // such that x^2 is less than the // targetValue cout << result << endl;} // Driver Codeint main(){ // Given targetValue; int targetValue = 81; // Function Call findX(targetValue);}", "e": 27608, "s": 26651, "text": null }, { "code": "// Java program for// the above exampleimport java.util.*;class GFG{ // Function to find X such// that it is less than the// target value and function// is f(x) = x^2static void findX(int targetValue){ // Initialise start and end int start = 0, end = targetValue; int mid = 0, result = 0; // Loop till start <= end while (start <= end) { // Find the mid mid = start + (end - start) / 2; // Check for the left half if (mid * mid <= targetValue) { // Store the result result = mid; // Reinitialize the start point start = mid + 1; } // Check for the right half else { end = mid - 1; } } // Print the maximum value of x // such that x^2 is less than the // targetValue System.out.print(result + \"\\n\");} // Driver Codepublic static void main(String[] args){ // Given targetValue; int targetValue = 81; // Function call findX(targetValue);}} // This code is contributed by 29AjayKumar", "e": 28684, "s": 27608, "text": null }, { "code": "# Python3 program for# the above example # Function to find X such# that it is less than the# target value and function# is f(x) = x ^ 2def findX(targetValue): # Initialise start and end start = 0; end = targetValue; mid = 0; # Loop till start <= end while (start <= end): # Find the mid mid = start + (end - start) // 2; # Check for the left half if (mid * mid <= targetValue): result = mid start = mid + 1; # Check for the right half else: end = mid - 1; # Print maximum value of x # such that x ^ 2 is less than the # targetValue print(result); # Driver Codeif __name__ == '__main__': # Given targetValue; targetValue = 81; # Function Call findX(targetValue); # This code is contributed by Rajput-Ji", "e": 29522, "s": 28684, "text": null }, { "code": "// C# program for// the above exampleusing System;class GFG{ // Function to find X such// that it is less than the// target value and function// is f(x) = x^2static void findX(int targetValue){ // Initialise start and end int start = 0, end = targetValue; int mid = 0, result = 0; // Loop till start <= end while (start <= end) { // Find the mid mid = start + (end - start) / 2; // Check for the left half if (mid * mid <= targetValue) { // Store the result result = mid; // Reinitialize the start point start = mid + 1; } // Check for the right half else { end = mid - 1; } } // Print the maximum value of x // such that x^2 is less than the // targetValue Console.Write(result + \"\\n\");} // Driver Codepublic static void Main(String[] args){ // Given targetValue; int targetValue = 81; // Function Call findX(targetValue);}} // This code is contributed by 29AjayKumar", "e": 30591, "s": 29522, "text": null }, { "code": "<script> // JavaScript program for the above example // Function to find X such that it is// less than the target value and function// is f(x) = x^2function findX(targetValue){ // Initialise start and end var start = 0, end = targetValue; var mid, result; // Loop till start <= end while (start <= end) { // Find the mid mid = start + parseInt((end - start) / 2); // Check for the left half if (mid * mid <= targetValue) { // Store the result result = mid; // Reinitialize the start point start = mid + 1; } // Check for the right half else { end = mid - 1; } } // Print the maximum value of x // such that x^2 is less than the // targetValue document.write( result );} // Driver Code // Given targetValue;var targetValue = 81; // Function CallfindX(targetValue); </script>", "e": 31516, "s": 30591, "text": null }, { "code": null, "e": 31521, "s": 31519, "text": "9" }, { "code": null, "e": 31789, "s": 31523, "text": "The above binary search algorithm requires at most O(log N) comparisons to find the maximum value less than or equal to the target value. And the value of the function f(x) = x2 doesn’t need to be evaluated many times.Time Complexity: O(logN) Auxiliary Space: O(1) " }, { "code": null, "e": 31803, "s": 31791, "text": "29AjayKumar" }, { "code": null, "e": 31813, "s": 31803, "text": "Rajput-Ji" }, { "code": null, "e": 31822, "s": 31813, "text": "famously" }, { "code": null, "e": 31836, "s": 31822, "text": "Binary Search" }, { "code": null, "e": 31847, "s": 31836, "text": "Algorithms" }, { "code": null, "e": 31866, "s": 31847, "text": "Divide and Conquer" }, { "code": null, "e": 31876, "s": 31866, "text": "Searching" }, { "code": null, "e": 31886, "s": 31876, "text": "Searching" }, { "code": null, "e": 31905, "s": 31886, "text": "Divide and Conquer" }, { "code": null, "e": 31919, "s": 31905, "text": "Binary Search" }, { "code": null, "e": 31930, "s": 31919, "text": "Algorithms" }, { "code": null, "e": 32028, "s": 31930, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32037, "s": 32028, "text": "Comments" }, { "code": null, "e": 32050, "s": 32037, "text": "Old Comments" }, { "code": null, "e": 32075, "s": 32050, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 32131, "s": 32075, "text": "Difference between Informed and Uninformed Search in AI" }, { "code": null, "e": 32174, "s": 32131, "text": "SCAN (Elevator) Disk Scheduling Algorithms" }, { "code": null, "e": 32203, "s": 32174, "text": "Quadratic Probing in Hashing" }, { "code": null, "e": 32237, "s": 32203, "text": "K means Clustering - Introduction" }, { "code": null, "e": 32248, "s": 32237, "text": "Merge Sort" }, { "code": null, "e": 32258, "s": 32248, "text": "QuickSort" }, { "code": null, "e": 32272, "s": 32258, "text": "Binary Search" }, { "code": null, "e": 32340, "s": 32272, "text": "Maximum and minimum of an array using minimum number of comparisons" } ]
Tryit Editor v3.7
Tryit: HTML link colors
[]
Abstract Classes in C#
An abstract class in C# includes abstract and non-abstract methods. A class is declared abstract to be an abstract class. You cannot instantiate an abstract class. Let us see an example, wherein we have an abstract class Vehicle and abstract method display()− public abstract class Vehicle { public abstract void display(); } The abstract class has derived classes: Bus, Car, and Motorcycle. The following is an implementation of the Bus derived class − public class Bus : Vehicle { public override void display() { Console.WriteLine("Bus"); } } Let us see the complete example of abstract classes in C# − Live Demo using System; public abstract class Vehicle { public abstract void display(); } public class Bus : Vehicle { public override void display() { Console.WriteLine("Bus"); } } public class Car : Vehicle { public override void display() { Console.WriteLine("Car"); } } public class Motorcycle : Vehicle { public override void display() { Console.WriteLine("Motorcycle"); } } public class MyClass { public static void Main() { Vehicle v; v = new Bus(); v.display(); v = new Car(); v.display(); v = new Motorcycle(); v.display(); } } Bus Car Motorcycle
[ { "code": null, "e": 1226, "s": 1062, "text": "An abstract class in C# includes abstract and non-abstract methods. A class is declared abstract to be an abstract class. You cannot instantiate an abstract class." }, { "code": null, "e": 1322, "s": 1226, "text": "Let us see an example, wherein we have an abstract class Vehicle and abstract method display()−" }, { "code": null, "e": 1392, "s": 1322, "text": "public abstract class Vehicle {\n public abstract void display();\n} " }, { "code": null, "e": 1521, "s": 1392, "text": "The abstract class has derived classes: Bus, Car, and Motorcycle. The following is an implementation of the Bus derived class −" }, { "code": null, "e": 1626, "s": 1521, "text": "public class Bus : Vehicle {\n public override void display() {\n Console.WriteLine(\"Bus\");\n }\n} " }, { "code": null, "e": 1686, "s": 1626, "text": "Let us see the complete example of abstract classes in C# −" }, { "code": null, "e": 1696, "s": 1686, "text": "Live Demo" }, { "code": null, "e": 2315, "s": 1696, "text": "using System;\npublic abstract class Vehicle {\n public abstract void display();\n}\n\npublic class Bus : Vehicle {\n public override void display() {\n Console.WriteLine(\"Bus\");\n }\n}\n\npublic class Car : Vehicle {\n public override void display() {\n Console.WriteLine(\"Car\");\n }\n}\n\npublic class Motorcycle : Vehicle {\n public override void display() {\n Console.WriteLine(\"Motorcycle\");\n }\n}\n\npublic class MyClass {\n public static void Main() {\n Vehicle v;\n v = new Bus();\n v.display();\n v = new Car();\n v.display();\n v = new Motorcycle();\n v.display();\n }\n} " }, { "code": null, "e": 2334, "s": 2315, "text": "Bus\nCar\nMotorcycle" } ]
do...while loop vs. while loop in C/C++
Here we will see what are the basic differences of do-while loop and the while loop in C or C++. A while loop in C programming repeatedly executes a target statement as long as a given condition is true. The syntax is like below. while(condition) { statement(s); } Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any nonzero value. The loop iterates while the condition is true. When the condition becomes false, the program control passes to the line immediately following the loop. #include <stdio.h> int main () { int a = 10; // Local variable declaration: do { // do loop execution printf("value of a: %d\n", a); a = a + 1; } while( a < 20 ); return 0; } value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15 value of a: 16 value of a: 17 value of a: 18 value of a: 19 Now let us see the do-while loop. Unlike for and while loops, which test the loop condition at the top of the loop, the do...while loop checks its condition at the bottom of the loop. A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time. do { statement(s); } while( condition ); Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop execute once before the condition is tested. If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop execute again. This process repeats until the given condition becomes false. #include <stdio.h> int main () { /* local variable definition */ int a = 10; /* while loop execution */ while( a < 20 ) { printf("value of a: %d\n", a); a++; } return 0; } value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15 value of a: 16 value of a: 17 value of a: 18 value of a: 19 So the differences are summarized in the following table − while(condition){ //statement } do{ //statement }while(condition);
[ { "code": null, "e": 1159, "s": 1062, "text": "Here we will see what are the basic differences of do-while loop and the while loop in C or C++." }, { "code": null, "e": 1292, "s": 1159, "text": "A while loop in C programming repeatedly executes a target statement as long as a given condition is true. The syntax is like below." }, { "code": null, "e": 1330, "s": 1292, "text": "while(condition) {\n statement(s);\n}" }, { "code": null, "e": 1516, "s": 1330, "text": "Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any nonzero value. The loop iterates while the condition is true." }, { "code": null, "e": 1621, "s": 1516, "text": "When the condition becomes false, the program control passes to the line immediately following the loop." }, { "code": null, "e": 1820, "s": 1621, "text": "#include <stdio.h>\nint main () {\n int a = 10; // Local variable declaration:\n do { // do loop execution\n printf(\"value of a: %d\\n\", a);\n a = a + 1;\n } while( a < 20 );\n return 0;\n}" }, { "code": null, "e": 1970, "s": 1820, "text": "value of a: 10\nvalue of a: 11\nvalue of a: 12\nvalue of a: 13\nvalue of a: 14\nvalue of a: 15\nvalue of a: 16\nvalue of a: 17\nvalue of a: 18\nvalue of a: 19" }, { "code": null, "e": 2004, "s": 1970, "text": "Now let us see the do-while loop." }, { "code": null, "e": 2154, "s": 2004, "text": "Unlike for and while loops, which test the loop condition at the top of the loop, the do...while loop checks its condition at the bottom of the loop." }, { "code": null, "e": 2274, "s": 2154, "text": "A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time." }, { "code": null, "e": 2318, "s": 2274, "text": "do {\n statement(s);\n}\nwhile( condition );" }, { "code": null, "e": 2466, "s": 2318, "text": "Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop execute once before the condition is tested." }, { "code": null, "e": 2643, "s": 2466, "text": "If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop execute again. This process repeats until the given condition becomes false." }, { "code": null, "e": 2845, "s": 2643, "text": "#include <stdio.h>\nint main () {\n /* local variable definition */\n int a = 10;\n /* while loop execution */\n while( a < 20 ) {\n printf(\"value of a: %d\\n\", a);\n a++;\n }\n return 0;\n}" }, { "code": null, "e": 2995, "s": 2845, "text": "value of a: 10\nvalue of a: 11\nvalue of a: 12\nvalue of a: 13\nvalue of a: 14\nvalue of a: 15\nvalue of a: 16\nvalue of a: 17\nvalue of a: 18\nvalue of a: 19" }, { "code": null, "e": 3054, "s": 2995, "text": "So the differences are summarized in the following table −" }, { "code": null, "e": 3089, "s": 3054, "text": "while(condition){\n //statement\n}" }, { "code": null, "e": 3127, "s": 3089, "text": "do{\n //statement\n}while(condition);" } ]
Maximum subarray sum modulo m in C++
In this problem, we are given an array of size n and an integer m. our task is to create a program that will find the maximum subarray sum modulo m in C++. Program description − Here, we will find the maximum value obtained by dividing the sum of all elements of subarray divided by m. Let’s take an example to understand the problem, Input − array = {4, 9 ,2} m = 6 Output − 5 Explanation − All subarrays and their remainders on dividing {4}: 4%6 = 4 {9}: 9%6 = 3 {2}: 2%6 = 2 {4, 9}: 13%6 = 1 {9, 2}: 11%6 = 5 {4, 9, 2}: 15%6 = 3 To solve this problem, we compute prefixSumModulo Array. And the calculating maxSum of each index using the formula, maxSum at i = (prefixi + prefixj + m)%m Program to illustrate our solution, Live Demo #include<bits/stdc++.h> using namespace std; int calcMaxSum(int arr[], int n, int m) { int x, prefix = 0, maxSumMod = 0; set<int> sums; sums.insert(0); for (int i = 0; i < n; i++){ prefix = (prefix + arr[i])%m; maxSumMod = max(maxSumMod, prefix); auto it = sums.lower_bound(prefix+1); if (it != sums.end()) maxSumMod = max(maxSumMod, prefix - (*it) + m ); sums.insert(prefix); } return maxSumMod; } int main() { int arr[] = {4, 9, 2}; int n = sizeof(arr)/sizeof(arr[0]); int m = 5; cout<<"Maximum subarray sum modulo "<<m<<" is "<<calcMaxSum(arr, n, m) < endl; return 0; } Maximum subarray sum modulo 5 is 4
[ { "code": null, "e": 1218, "s": 1062, "text": "In this problem, we are given an array of size n and an integer m. our task is to create a program that will find the maximum subarray sum modulo m in C++." }, { "code": null, "e": 1348, "s": 1218, "text": "Program description − Here, we will find the maximum value obtained by dividing the sum of all elements of subarray divided by m." }, { "code": null, "e": 1397, "s": 1348, "text": "Let’s take an example to understand the problem," }, { "code": null, "e": 1429, "s": 1397, "text": "Input − array = {4, 9 ,2} m = 6" }, { "code": null, "e": 1440, "s": 1429, "text": "Output − 5" }, { "code": null, "e": 1501, "s": 1440, "text": "Explanation − All subarrays and their remainders on dividing" }, { "code": null, "e": 1594, "s": 1501, "text": "{4}: 4%6 = 4\n{9}: 9%6 = 3\n{2}: 2%6 = 2\n{4, 9}: 13%6 = 1\n{9, 2}: 11%6 = 5\n{4, 9, 2}: 15%6 = 3" }, { "code": null, "e": 1751, "s": 1594, "text": "To solve this problem, we compute prefixSumModulo Array. And the calculating maxSum of each index using the formula, maxSum at i = (prefixi + prefixj + m)%m" }, { "code": null, "e": 1787, "s": 1751, "text": "Program to illustrate our solution," }, { "code": null, "e": 1798, "s": 1787, "text": " Live Demo" }, { "code": null, "e": 2443, "s": 1798, "text": "#include<bits/stdc++.h>\nusing namespace std;\nint calcMaxSum(int arr[], int n, int m) {\n int x, prefix = 0, maxSumMod = 0;\n set<int> sums;\n sums.insert(0);\n for (int i = 0; i < n; i++){\n prefix = (prefix + arr[i])%m;\n maxSumMod = max(maxSumMod, prefix);\n auto it = sums.lower_bound(prefix+1);\n if (it != sums.end())\n maxSumMod = max(maxSumMod, prefix - (*it) + m );\n sums.insert(prefix);\n }\n return maxSumMod;\n}\nint main() {\n int arr[] = {4, 9, 2};\n int n = sizeof(arr)/sizeof(arr[0]);\n int m = 5;\n cout<<\"Maximum subarray sum modulo \"<<m<<\" is \"<<calcMaxSum(arr, n, m) < endl;\n return 0;\n}" }, { "code": null, "e": 2478, "s": 2443, "text": "Maximum subarray sum modulo 5 is 4" } ]
Find longest range from numbers in range [1, N] having positive bitwise AND - GeeksforGeeks
25 Jan, 2022 Given a number N, the task is to find the longest range of integers [L, R] such that 1 ≤ L ≤ R ≤ N and the bitwise AND of all the numbers in that range is positive. Examples: Input: N = 7Output: 4 7Explanation: Check and from 1 to 7Bitwise AND operations:from 1 to 7 is 0 from 2 to 7 is 0from 3 to 7 is 0from 4 to 7 is 4Therefore, maximum range comes out from L = 4 to R = 7. Input: K = 16Output: 8 15 Approach: The problem can be solved based on the following mathematical observation. If 2K is the closest exponent of 2 greater than N then the maximum range will be either of the two: From 2(K – 2) to (2(K – 1) – 1) [both value inclusive] or, From 2(K – 1) to N Because these ranges confirm that all the numbers in the range will have the most significant bit set for all of them. If the ranges vary for powers of 2 then the bitwise AND of the range will become 0. Below is the implementation of the above approach. C++ C Java Python3 C# Javascript // C++ code to implement above approach#include <bits/stdc++.h>using namespace std; // Function to find the closest exponent of 2// which is greater than Kint minpoweroftwo(int K){ int count = 0; while (K > 0) { count++; K = K >> 1; } return count;} // Function to find the longest rangevoid findlongestrange(int N){ int K = minpoweroftwo(N); int y = N + 1 - pow(2, K - 1); int z = (pow(2, K - 1) - pow(2, K - 2)); if (y >= z) { cout << pow(2, K - 1) << " " << N; } else { cout << pow(2, K - 2) << " " << pow(2, K - 1) - 1; }} // Driver codeint main(){ int N = 16; findlongestrange(N); return 0;} // C code to implement above approach#include <math.h>#include <stdio.h> // Function to find the closest exponent of 2// which is greater than Kint minpoweroftwo(int K){ int count = 0; while (K > 0) { count++; K = K >> 1; } return count;} // Function to find the longest rangevoid findlongestrange(int N){ int K = minpoweroftwo(N); int y = N + 1 - pow(2, K - 1); int z = (pow(2, K - 1) - pow(2, K - 2)); if (y >= z) { printf("%d %d", (int)pow(2, K - 1), N); } else { printf("%d %d", (int)pow(2, K - 2), (int)pow(2, K - 1)-1); }} // Driver codeint main(){ int N = 16; findlongestrange(N); return 0;} // Java code to implement above approach class GFG { // Function to find the closest exponent of 2 // which is greater than K static int minpoweroftwo(int K) { int count = 0; while (K > 0) { count++; K = K >> 1; } return count; } // Function to find the longest range static void findlongestrange(int N) { int K = minpoweroftwo(N); int y = (int) (N + 1 - Math.pow(2, K - 1)); int z = (int) (Math.pow(2, K - 1) - Math.pow(2, K - 2)); if (y >= z) { System.out.println(Math.pow(2, K - 1) + " " + N); } else { System.out.print((int) Math.pow(2, K - 2)); System.out.print(" "); System.out.print((int) Math.pow(2, K - 1) - 1); } } // Driver code public static void main(String args[]) { int N = 16; findlongestrange(N); }} // This code is contributed by gfgking. # Python code to implement above approach # Function to find the closest exponent of 2# which is greater than Kdef minpoweroftwo(K): count = 0; while (K > 0): count += 1; K = K >> 1; return count; # Function to find the longest rangedef findlongestrange(N): K = minpoweroftwo(N); y = int(N + 1 - pow(2, K - 1)); z = int(pow(2, K - 1) - pow(2, K - 2)); if (y >= z): print(pow(2, K - 1) , " " , N); else: print(pow(2, K - 2)); print(" "); print(pow(2, K - 1) - 1); # Driver codeif __name__ == '__main__': N = 16; findlongestrange(N); # This code is contributed by 29AjayKumar // C# code to implement above approachusing System;class GFG { // Function to find the closest exponent of 2 // which is greater than K static int minpoweroftwo(int K) { int count = 0; while (K > 0) { count++; K = K >> 1; } return count; } // Function to find the longest range static void findlongestrange(int N) { int K = minpoweroftwo(N); int y = (int)(N + 1 - Math.Pow(2, K - 1)); int z = (int)(Math.Pow(2, K - 1) - Math.Pow(2, K - 2)); if (y >= z) { Console.Write(Math.Pow(2, K - 1) + " " + N); } else { Console.Write((int)Math.Pow(2, K - 2)); Console.Write(" "); Console.Write((int)Math.Pow(2, K - 1) - 1); } } // Driver code public static void Main() { int N = 16; findlongestrange(N); }} // This code is contributed by ukasp. <script> // JavaScript code for the above approach // Function to find the closest exponent of 2 // which is greater than K function minpoweroftwo(K) { let count = 0; while (K > 0) { count++; K = K >> 1; } return count; } // Function to find the longest range function findlongestrange(N) { let K = minpoweroftwo(N); let y = N + 1 - Math.pow(2, K - 1); let z = (Math.pow(2, K - 1) - Math.pow(2, K - 2)); if (y >= z) { document.write(Math.pow(2, K - 1) + " " + N); } else { document.write(Math.pow(2, K - 2) + " " + (Math.pow(2, K - 1) - 1)); } } // Driver code let N = 16; findlongestrange(N); // This code is contributed by Potta Lokesh </script> 8 15 Time Complexity: O(logN)Auxiliary Space: O(1) lokeshpotta20 gfgking ukasp 29AjayKumar array-range-queries Bitwise-AND Bit Magic Mathematical Mathematical Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Cyclic Redundancy Check and Modulo-2 Division Little and Big Endian Mystery Program to find whether a given number is power of 2 Binary representation of a given number Add two numbers without using arithmetic operators Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 25528, "s": 25500, "text": "\n25 Jan, 2022" }, { "code": null, "e": 25693, "s": 25528, "text": "Given a number N, the task is to find the longest range of integers [L, R] such that 1 ≤ L ≤ R ≤ N and the bitwise AND of all the numbers in that range is positive." }, { "code": null, "e": 25703, "s": 25693, "text": "Examples:" }, { "code": null, "e": 25905, "s": 25703, "text": "Input: N = 7Output: 4 7Explanation: Check and from 1 to 7Bitwise AND operations:from 1 to 7 is 0 from 2 to 7 is 0from 3 to 7 is 0from 4 to 7 is 4Therefore, maximum range comes out from L = 4 to R = 7. " }, { "code": null, "e": 25931, "s": 25905, "text": "Input: K = 16Output: 8 15" }, { "code": null, "e": 26116, "s": 25931, "text": "Approach: The problem can be solved based on the following mathematical observation. If 2K is the closest exponent of 2 greater than N then the maximum range will be either of the two:" }, { "code": null, "e": 26175, "s": 26116, "text": "From 2(K – 2) to (2(K – 1) – 1) [both value inclusive] or," }, { "code": null, "e": 26194, "s": 26175, "text": "From 2(K – 1) to N" }, { "code": null, "e": 26397, "s": 26194, "text": "Because these ranges confirm that all the numbers in the range will have the most significant bit set for all of them. If the ranges vary for powers of 2 then the bitwise AND of the range will become 0." }, { "code": null, "e": 26448, "s": 26397, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 26452, "s": 26448, "text": "C++" }, { "code": null, "e": 26454, "s": 26452, "text": "C" }, { "code": null, "e": 26459, "s": 26454, "text": "Java" }, { "code": null, "e": 26467, "s": 26459, "text": "Python3" }, { "code": null, "e": 26470, "s": 26467, "text": "C#" }, { "code": null, "e": 26481, "s": 26470, "text": "Javascript" }, { "code": "// C++ code to implement above approach#include <bits/stdc++.h>using namespace std; // Function to find the closest exponent of 2// which is greater than Kint minpoweroftwo(int K){ int count = 0; while (K > 0) { count++; K = K >> 1; } return count;} // Function to find the longest rangevoid findlongestrange(int N){ int K = minpoweroftwo(N); int y = N + 1 - pow(2, K - 1); int z = (pow(2, K - 1) - pow(2, K - 2)); if (y >= z) { cout << pow(2, K - 1) << \" \" << N; } else { cout << pow(2, K - 2) << \" \" << pow(2, K - 1) - 1; }} // Driver codeint main(){ int N = 16; findlongestrange(N); return 0;}", "e": 27161, "s": 26481, "text": null }, { "code": "// C code to implement above approach#include <math.h>#include <stdio.h> // Function to find the closest exponent of 2// which is greater than Kint minpoweroftwo(int K){ int count = 0; while (K > 0) { count++; K = K >> 1; } return count;} // Function to find the longest rangevoid findlongestrange(int N){ int K = minpoweroftwo(N); int y = N + 1 - pow(2, K - 1); int z = (pow(2, K - 1) - pow(2, K - 2)); if (y >= z) { printf(\"%d %d\", (int)pow(2, K - 1), N); } else { printf(\"%d %d\", (int)pow(2, K - 2), (int)pow(2, K - 1)-1); }} // Driver codeint main(){ int N = 16; findlongestrange(N); return 0;}", "e": 27846, "s": 27161, "text": null }, { "code": "// Java code to implement above approach class GFG { // Function to find the closest exponent of 2 // which is greater than K static int minpoweroftwo(int K) { int count = 0; while (K > 0) { count++; K = K >> 1; } return count; } // Function to find the longest range static void findlongestrange(int N) { int K = minpoweroftwo(N); int y = (int) (N + 1 - Math.pow(2, K - 1)); int z = (int) (Math.pow(2, K - 1) - Math.pow(2, K - 2)); if (y >= z) { System.out.println(Math.pow(2, K - 1) + \" \" + N); } else { System.out.print((int) Math.pow(2, K - 2)); System.out.print(\" \"); System.out.print((int) Math.pow(2, K - 1) - 1); } } // Driver code public static void main(String args[]) { int N = 16; findlongestrange(N); }} // This code is contributed by gfgking.", "e": 28788, "s": 27846, "text": null }, { "code": "# Python code to implement above approach # Function to find the closest exponent of 2# which is greater than Kdef minpoweroftwo(K): count = 0; while (K > 0): count += 1; K = K >> 1; return count; # Function to find the longest rangedef findlongestrange(N): K = minpoweroftwo(N); y = int(N + 1 - pow(2, K - 1)); z = int(pow(2, K - 1) - pow(2, K - 2)); if (y >= z): print(pow(2, K - 1) , \" \" , N); else: print(pow(2, K - 2)); print(\" \"); print(pow(2, K - 1) - 1); # Driver codeif __name__ == '__main__': N = 16; findlongestrange(N); # This code is contributed by 29AjayKumar", "e": 29436, "s": 28788, "text": null }, { "code": "// C# code to implement above approachusing System;class GFG { // Function to find the closest exponent of 2 // which is greater than K static int minpoweroftwo(int K) { int count = 0; while (K > 0) { count++; K = K >> 1; } return count; } // Function to find the longest range static void findlongestrange(int N) { int K = minpoweroftwo(N); int y = (int)(N + 1 - Math.Pow(2, K - 1)); int z = (int)(Math.Pow(2, K - 1) - Math.Pow(2, K - 2)); if (y >= z) { Console.Write(Math.Pow(2, K - 1) + \" \" + N); } else { Console.Write((int)Math.Pow(2, K - 2)); Console.Write(\" \"); Console.Write((int)Math.Pow(2, K - 1) - 1); } } // Driver code public static void Main() { int N = 16; findlongestrange(N); }} // This code is contributed by ukasp.", "e": 30274, "s": 29436, "text": null }, { "code": "<script> // JavaScript code for the above approach // Function to find the closest exponent of 2 // which is greater than K function minpoweroftwo(K) { let count = 0; while (K > 0) { count++; K = K >> 1; } return count; } // Function to find the longest range function findlongestrange(N) { let K = minpoweroftwo(N); let y = N + 1 - Math.pow(2, K - 1); let z = (Math.pow(2, K - 1) - Math.pow(2, K - 2)); if (y >= z) { document.write(Math.pow(2, K - 1) + \" \" + N); } else { document.write(Math.pow(2, K - 2) + \" \" + (Math.pow(2, K - 1) - 1)); } } // Driver code let N = 16; findlongestrange(N); // This code is contributed by Potta Lokesh </script>", "e": 31215, "s": 30274, "text": null }, { "code": null, "e": 31223, "s": 31218, "text": "8 15" }, { "code": null, "e": 31271, "s": 31225, "text": "Time Complexity: O(logN)Auxiliary Space: O(1)" }, { "code": null, "e": 31287, "s": 31273, "text": "lokeshpotta20" }, { "code": null, "e": 31295, "s": 31287, "text": "gfgking" }, { "code": null, "e": 31301, "s": 31295, "text": "ukasp" }, { "code": null, "e": 31313, "s": 31301, "text": "29AjayKumar" }, { "code": null, "e": 31333, "s": 31313, "text": "array-range-queries" }, { "code": null, "e": 31345, "s": 31333, "text": "Bitwise-AND" }, { "code": null, "e": 31355, "s": 31345, "text": "Bit Magic" }, { "code": null, "e": 31368, "s": 31355, "text": "Mathematical" }, { "code": null, "e": 31381, "s": 31368, "text": "Mathematical" }, { "code": null, "e": 31391, "s": 31381, "text": "Bit Magic" }, { "code": null, "e": 31489, "s": 31391, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31535, "s": 31489, "text": "Cyclic Redundancy Check and Modulo-2 Division" }, { "code": null, "e": 31565, "s": 31535, "text": "Little and Big Endian Mystery" }, { "code": null, "e": 31618, "s": 31565, "text": "Program to find whether a given number is power of 2" }, { "code": null, "e": 31658, "s": 31618, "text": "Binary representation of a given number" }, { "code": null, "e": 31709, "s": 31658, "text": "Add two numbers without using arithmetic operators" }, { "code": null, "e": 31739, "s": 31709, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 31799, "s": 31739, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 31814, "s": 31799, "text": "C++ Data Types" }, { "code": null, "e": 31857, "s": 31814, "text": "Set in C++ Standard Template Library (STL)" } ]
Find Intersecting Intervals in Python
Suppose we have a list of intervals, where each interval is like [start, end] this is representing start and end times of an intervals (inclusive), We have to find their intersection, i.e. the interval that lies within all of the given intervals. So, if the input is like [[10, 110],[20, 60],[25, 75]], then the output will be [25, 60] To solve this, we will follow these steps − start, end := interval after deleting last element from intervals list while intervals is not empty, dostart_temp, end_temp := interval after deleting last element from intervals liststart := maximum of start, start_tempend := minimum of end, end_temp start_temp, end_temp := interval after deleting last element from intervals list start := maximum of start, start_temp end := minimum of end, end_temp return an interval [start, end] Let us see the following implementation to get better understanding − Live Demo class Solution: def solve(self, intervals): start, end = intervals.pop() while intervals: start_temp, end_temp = intervals.pop() start = max(start, start_temp) end = min(end, end_temp) return [start, end] ob = Solution() intervals = [[10, 110],[20, 60],[25, 75]] print(ob.solve(intervals)) [[10, 110],[20, 60],[25, 75]] [25, 60]
[ { "code": null, "e": 1309, "s": 1062, "text": "Suppose we have a list of intervals, where each interval is like [start, end] this is representing\nstart and end times of an intervals (inclusive), We have to find their intersection, i.e. the\ninterval that lies within all of the given intervals." }, { "code": null, "e": 1398, "s": 1309, "text": "So, if the input is like [[10, 110],[20, 60],[25, 75]], then the output will be [25, 60]" }, { "code": null, "e": 1442, "s": 1398, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1513, "s": 1442, "text": "start, end := interval after deleting last element from intervals list" }, { "code": null, "e": 1694, "s": 1513, "text": "while intervals is not empty, dostart_temp, end_temp := interval after deleting last element from intervals liststart := maximum of start, start_tempend := minimum of end, end_temp" }, { "code": null, "e": 1775, "s": 1694, "text": "start_temp, end_temp := interval after deleting last element from intervals list" }, { "code": null, "e": 1813, "s": 1775, "text": "start := maximum of start, start_temp" }, { "code": null, "e": 1845, "s": 1813, "text": "end := minimum of end, end_temp" }, { "code": null, "e": 1877, "s": 1845, "text": "return an interval [start, end]" }, { "code": null, "e": 1947, "s": 1877, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 1958, "s": 1947, "text": " Live Demo" }, { "code": null, "e": 2296, "s": 1958, "text": "class Solution:\n def solve(self, intervals):\n start, end = intervals.pop()\n while intervals:\n start_temp, end_temp = intervals.pop()\n start = max(start, start_temp)\n end = min(end, end_temp)\n return [start, end]\nob = Solution()\nintervals = [[10, 110],[20, 60],[25, 75]]\nprint(ob.solve(intervals))" }, { "code": null, "e": 2326, "s": 2296, "text": "[[10, 110],[20, 60],[25, 75]]" }, { "code": null, "e": 2335, "s": 2326, "text": "[25, 60]" } ]
C++ Program to Generate All Possible Combinations of a Given List of Numbers
This is a C++ program to generate all possible combinations of a given list of numbers Begin Take the number of elements and the elements as input. function Combi(char a[], int reqLen, int s, int currLen, bool check[], int l) : If currLen>reqLen then Return Else if currLen=reqLen then Then print the new generated sequence. If s=l then Then return no further element is left. For every index there are two option: either proceed with a start as ‘true’ and recursively call Combi() with incremented value of ‘currLen’ and ‘s’. Or proceed with a start as ‘false’ and recursively call Combi() with only incremented value of ‘s’. End #include<iostream> using namespace std; void Combi(char a[], int reqLen, int s, int currLen, bool check[], int l) // print the all possible combination of given array set { if(currLen > reqLen) return; else if (currLen == reqLen) { cout<<"\t"; for (int i = 0; i < l; i++) { if (check[i] == true) { cout<<a[i]<<" "; } } cout<<"\n"; return; } if (s == l) { return; } check[s] = true; Combi(a, reqLen, s + 1, currLen + 1, check, l); //recursively call Combi() with incremented value of ‘currLen’ and ‘s’. check[s] = false; Combi(a, reqLen, s + 1, currLen, check, l); // recursively call Combi() with only incremented value of ‘s’. } int main() { int i,n; bool check[n]; cout<<"Enter the number of element array have: "; cin>>n; char a[n]; cout<<"\n"; for(i = 0; i < n; i++) { cout<<"Enter "<<i+1<<" element: "; cin>>a[i]; check[i] = false; } for(i = 1; i <= n; i++) { cout<<"\nThe all possible combination of length "<<i<<" for the given array set:\n"; Combi(a, i, 0, 0, check, n); } return 0; } Enter the number of element array have: 4 Enter 1 element: 4 Enter 2 element: 3 Enter 3 element: 2 Enter 4 element: 1 The all possible combination of length 1 for the given array set: 4 3 2 1 The all possible combination of length 2 for the given array set: 4 3 4 2 4 1 3 2 3 1 2 1 The all possible combination of length 3 for the given array set: 4 3 2 4 3 1 4 2 1 3 2 1 The all possible combination of length 4 for the given array set: 4 3 2 1
[ { "code": null, "e": 1149, "s": 1062, "text": "This is a C++ program to generate all possible combinations of a given list of numbers" }, { "code": null, "e": 1732, "s": 1149, "text": "Begin\n Take the number of elements and the elements as input.\n function Combi(char a[], int reqLen, int s, int currLen, bool check[], int l) :\n If currLen>reqLen then\n Return\n Else if currLen=reqLen then\n Then print the new generated sequence.\n If s=l then\n Then return no further element is left.\n For every index there are two option:\n either proceed with a start as ‘true’ and recursively call Combi() with incremented value of ‘currLen’ and ‘s’.\n Or proceed with a start as ‘false’ and recursively call Combi() with only incremented value of ‘s’.\nEnd" }, { "code": null, "e": 2896, "s": 1732, "text": "#include<iostream>\nusing namespace std;\nvoid Combi(char a[], int reqLen, int s, int currLen, bool check[], int l)\n// print the all possible combination of given array set\n{\n if(currLen > reqLen)\n return;\n else if (currLen == reqLen) {\n cout<<\"\\t\";\n for (int i = 0; i < l; i++) {\n if (check[i] == true) {\n cout<<a[i]<<\" \";\n }\n }\n cout<<\"\\n\";\n return;\n }\n if (s == l) {\n return;\n }\n check[s] = true;\n Combi(a, reqLen, s + 1, currLen + 1, check, l);\n //recursively call Combi() with incremented value of ‘currLen’ and ‘s’.\n check[s] = false;\n Combi(a, reqLen, s + 1, currLen, check, l);\n // recursively call Combi() with only incremented value of ‘s’.\n}\nint main() {\n int i,n;\n bool check[n];\n cout<<\"Enter the number of element array have: \";\n cin>>n;\n char a[n];\n cout<<\"\\n\";\n for(i = 0; i < n; i++) {\n cout<<\"Enter \"<<i+1<<\" element: \";\n cin>>a[i];\n check[i] = false;\n }\n for(i = 1; i <= n; i++) {\n cout<<\"\\nThe all possible combination of length \"<<i<<\" for the given array set:\\n\";\n Combi(a, i, 0, 0, check, n);\n }\n return 0;\n}" }, { "code": null, "e": 3342, "s": 2896, "text": "Enter the number of element array have: 4\nEnter 1 element: 4\nEnter 2 element: 3\nEnter 3 element: 2\nEnter 4 element: 1\nThe all possible combination of length 1 for the given array set:\n4\n3\n2\n1\nThe all possible combination of length 2 for the given array set:\n4 3\n4 2\n4 1\n3 2\n3 1\n2 1\nThe all possible combination of length 3 for the given array set:\n4 3 2\n4 3 1\n4 2 1\n3 2 1\nThe all possible combination of length 4 for the given array set:\n4 3 2 1" } ]
Keras - Pooling Layer
It is used to perform max pooling operations on temporal data. The signature of the MaxPooling1D function and its arguments with default value is as follows − keras.layers.MaxPooling1D ( pool_size = 2, strides = None, padding = 'valid', data_format = 'channels_last' ) Here, pool_size refers the max pooling windows. pool_size refers the max pooling windows. strides refer the factors for downscale. strides refer the factors for downscale. Similarly, MaxPooling2D and MaxPooling3D are used for Max pooling operations for spatial data. 87 Lectures 11 hours Abhilash Nelson 61 Lectures 9 hours Abhishek And Pukhraj 57 Lectures 7 hours Abhishek And Pukhraj 52 Lectures 7 hours Abhishek And Pukhraj 52 Lectures 6 hours Abhishek And Pukhraj 68 Lectures 2 hours Mike West Print Add Notes Bookmark this page
[ { "code": null, "e": 2210, "s": 2051, "text": "It is used to perform max pooling operations on temporal data. The signature of the MaxPooling1D function and its arguments with default value is as follows −" }, { "code": null, "e": 2335, "s": 2210, "text": "keras.layers.MaxPooling1D (\n pool_size = 2, \n strides = None, \n padding = 'valid', \n data_format = 'channels_last'\n)" }, { "code": null, "e": 2341, "s": 2335, "text": "Here," }, { "code": null, "e": 2383, "s": 2341, "text": "pool_size refers the max pooling windows." }, { "code": null, "e": 2425, "s": 2383, "text": "pool_size refers the max pooling windows." }, { "code": null, "e": 2466, "s": 2425, "text": "strides refer the factors for downscale." }, { "code": null, "e": 2507, "s": 2466, "text": "strides refer the factors for downscale." }, { "code": null, "e": 2602, "s": 2507, "text": "Similarly, MaxPooling2D and MaxPooling3D are used for Max pooling operations for spatial data." }, { "code": null, "e": 2636, "s": 2602, "text": "\n 87 Lectures \n 11 hours \n" }, { "code": null, "e": 2653, "s": 2636, "text": " Abhilash Nelson" }, { "code": null, "e": 2686, "s": 2653, "text": "\n 61 Lectures \n 9 hours \n" }, { "code": null, "e": 2708, "s": 2686, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 2741, "s": 2708, "text": "\n 57 Lectures \n 7 hours \n" }, { "code": null, "e": 2763, "s": 2741, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 2796, "s": 2763, "text": "\n 52 Lectures \n 7 hours \n" }, { "code": null, "e": 2818, "s": 2796, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 2851, "s": 2818, "text": "\n 52 Lectures \n 6 hours \n" }, { "code": null, "e": 2873, "s": 2851, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 2906, "s": 2873, "text": "\n 68 Lectures \n 2 hours \n" }, { "code": null, "e": 2917, "s": 2906, "text": " Mike West" }, { "code": null, "e": 2924, "s": 2917, "text": " Print" }, { "code": null, "e": 2935, "s": 2924, "text": " Add Notes" } ]
Python - Sort Records by Kth Index List - GeeksforGeeks
02 Sep, 2021 Sometimes, while working with Python Records, we can have a problem in which we need to perform Sorting of Records by some element in Tuple, this can again be sometimes, a list and sorting has to performed by Kth index of that list. This is uncommon problem, but can have usecase in domains such as web development. Let’s discuss certain way in which this task can be performed. Input : test_list = [([4, 5], ‘Gfg’), ([8, 4], ‘is’), ([2, 3], ‘best’)] K = 0 Output : [([2, 3], ‘best’), ([4, 5], ‘Gfg’), ([8, 4], ‘is’)]Input : test_list = [([4, 5], ‘Gfg’), ([8, 4], ‘is’), ([2, 3], ‘best’)] K = 1 Output : [([2, 3], ‘best’), ([8, 4], ‘is’), ([4, 5], ‘Gfg’)] Method : Using sort() + lambda The combination of above functions can be used to solve this problem. In this, we perform the task of sorting using sort, the parameter and index by which sorting has to be performed is provided using lambda function. Python3 # Python3 code to demonstrate working of# Sort Records by Kth Index List# Using sort() + lambda # initializing listtest_list = [([4, 5, 7, 3], 'Gfg'), ([8, 6, 3, 1], 'is'), ([2, 3, 5, 2], 'best')] # printing original listprint("The original list is : " + str(test_list)) # initializing KK = 1 # Sort Records by Kth Index List# Using sort() + lambdatest_list.sort(key = lambda sub: sub[0][K]) # printing resultprint("The records after sorting : " + str(test_list)) The original list is : [([4, 5, 7, 3], ‘Gfg’), ([8, 6, 3, 1], ‘is’), ([2, 3, 5, 2], ‘best’)] The records after sorting : [([2, 3, 5, 2], ‘best’), ([4, 5, 7, 3], ‘Gfg’), ([8, 6, 3, 1], ‘is’)] adnanirshad158 Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python program to convert a list to string Defaultdict in Python Python | Split string into list of characters Python | Get dictionary keys as a list Python | Convert a list to dictionary
[ { "code": null, "e": 24186, "s": 24158, "text": "\n02 Sep, 2021" }, { "code": null, "e": 24566, "s": 24186, "text": "Sometimes, while working with Python Records, we can have a problem in which we need to perform Sorting of Records by some element in Tuple, this can again be sometimes, a list and sorting has to performed by Kth index of that list. This is uncommon problem, but can have usecase in domains such as web development. Let’s discuss certain way in which this task can be performed. " }, { "code": null, "e": 24845, "s": 24566, "text": "Input : test_list = [([4, 5], ‘Gfg’), ([8, 4], ‘is’), ([2, 3], ‘best’)] K = 0 Output : [([2, 3], ‘best’), ([4, 5], ‘Gfg’), ([8, 4], ‘is’)]Input : test_list = [([4, 5], ‘Gfg’), ([8, 4], ‘is’), ([2, 3], ‘best’)] K = 1 Output : [([2, 3], ‘best’), ([8, 4], ‘is’), ([4, 5], ‘Gfg’)] " }, { "code": null, "e": 25095, "s": 24845, "text": "Method : Using sort() + lambda The combination of above functions can be used to solve this problem. In this, we perform the task of sorting using sort, the parameter and index by which sorting has to be performed is provided using lambda function. " }, { "code": null, "e": 25103, "s": 25095, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Sort Records by Kth Index List# Using sort() + lambda # initializing listtest_list = [([4, 5, 7, 3], 'Gfg'), ([8, 6, 3, 1], 'is'), ([2, 3, 5, 2], 'best')] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing KK = 1 # Sort Records by Kth Index List# Using sort() + lambdatest_list.sort(key = lambda sub: sub[0][K]) # printing resultprint(\"The records after sorting : \" + str(test_list))", "e": 25599, "s": 25103, "text": null }, { "code": null, "e": 25791, "s": 25599, "text": "The original list is : [([4, 5, 7, 3], ‘Gfg’), ([8, 6, 3, 1], ‘is’), ([2, 3, 5, 2], ‘best’)] The records after sorting : [([2, 3, 5, 2], ‘best’), ([4, 5, 7, 3], ‘Gfg’), ([8, 6, 3, 1], ‘is’)] " }, { "code": null, "e": 25811, "s": 25796, "text": "adnanirshad158" }, { "code": null, "e": 25832, "s": 25811, "text": "Python list-programs" }, { "code": null, "e": 25839, "s": 25832, "text": "Python" }, { "code": null, "e": 25855, "s": 25839, "text": "Python Programs" }, { "code": null, "e": 25953, "s": 25855, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25988, "s": 25953, "text": "Read a file line by line in Python" }, { "code": null, "e": 26010, "s": 25988, "text": "Enumerate() in Python" }, { "code": null, "e": 26042, "s": 26010, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26072, "s": 26042, "text": "Iterate over a list in Python" }, { "code": null, "e": 26114, "s": 26072, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26157, "s": 26114, "text": "Python program to convert a list to string" }, { "code": null, "e": 26179, "s": 26157, "text": "Defaultdict in Python" }, { "code": null, "e": 26225, "s": 26179, "text": "Python | Split string into list of characters" }, { "code": null, "e": 26264, "s": 26225, "text": "Python | Get dictionary keys as a list" } ]
BottomNavigationBar Widget in Flutter - GeeksforGeeks
27 Nov, 2020 The BottonNavigationBar widget is used to show the bottom of an app. It can consist of multiple items such as icons, text, or both that leads to a different route depending upon the design of the application. It is meant to help the user navigate to different sections of the application in general. Syntax: BottomNavigationBar( {Key key, @required List<BottomNavigationBarItem> items, ValueChanged<int> onTap, int currentIndex: 0, double elevation, BottomNavigationBarType type, Color fixedColor, Color backgroundColor, double iconSize: 24.0, Color selectedItemColor, Color unselectedItemColor, IconThemeData selectedIconTheme, IconThemeData unselectedIconTheme, double selectedFontSize: 14.0, double unselectedFontSize: 12.0, TextStyle selectedLabelStyle, TextStyle unselectedLabelStyle, bool showSelectedLabels: true, bool showUnselectedLabels, MouseCursor mouseCursor}) hashCode: The hash code for this object. key: Controls how one widget replaces another widget in the tree. runtimeType: A representation of the runtime type of the object. backgrounColor: The color of the BottomNavigationBar itself. elevation: The z-coordinate of this BottomNavigationBar. fixedColor: The z-coordinate of this BottomNavigationBar. items: Defines the appearance of the button items that are arrayed within the bottom navigation bar. onTap: Called when one of the items is tapped. currentIndex: This property takes an int value as the object to assign index t the items. fixedColor: This property takes in Color class as the object to assign a fixed value to the SelectedItemColor. iconSize: It takes a double value as the object to determine the size of all the icons in the BottomNavigationBar. mouseCursor: The mouseCursor property takes MouseCursor class as the object. It determines the type of cursor this widget will have. selectedFontSize: This property controls the font size in the BottomNavigationBar when the items are selected. It takes a double value as the object. selectedIcontheme: This property holds IconThemeData class as the object to controls the appearance of the icons this widget when it is selected. selectedIconColor: This property determines the color of the icons inside this widget will hold when they are selected. This property takes Color class as the property. selectedLabelStyle: TextStyle class is the object assigned to this property which controls the text style at the instance of selection. showSelectedLabele: This property takes a boolean value as the object to determine whether or not the labels for the unselected item will be shown. showUnselectedLabels: This property also takes in a boolean value as the object to determine whether or not the labels for selected items will be shown. type: The type property controls the behaviour and the layout of the BottomNavigationBar. It takes BottomNavigationBarType enum as the object. unselectedFontSize: This property also takes a double value as e object to determine the size of font when the item is not selected. unselectedIconTheme: This property also holds IconThemeData class as the object to controls the appearance of the icons this widget when it is unselected or not selected. unselectedItemColor: This property determines the color the icons inside this widget will hold when they are unselected. This property takes Color class as the property. unselectedLabelStyle: TextStyle class is the object assigned to this property which controls the text style when the item is unselected. Example: Dart import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { static const String _title = 'Flutter Code Sample'; @override Widget build(BuildContext context) { return MaterialApp( title: _title, home: MyStatefulWidget(), ); }} class MyStatefulWidget extends StatefulWidget { MyStatefulWidget({Key key}) : super(key: key); @override _MyStatefulWidgetState createState() => _MyStatefulWidgetState();} class _MyStatefulWidgetState extends State<MyStatefulWidget> { int _selectedIndex = 0; static const TextStyle optionStyle = TextStyle(fontSize: 30, fontWeight: FontWeight.bold); static const List<Widget> _widgetOptions = <Widget>[ Text( 'HOME PAGE', style: optionStyle, ), Text( 'COURSE PAGE', style: optionStyle, ), Text( 'CONTACT GFG', style: optionStyle, ), ]; void _onItemTapped(int index) { setState(() { _selectedIndex = index; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('GeeksForGeeks'), backgroundColor: Colors.green, ), body: Center( child: _widgetOptions.elementAt(_selectedIndex), ), bottomNavigationBar: BottomNavigationBar( items: const <BottomNavigationBarItem>[ BottomNavigationBarItem( icon: Icon(Icons.home), title: Text('Home'), ), BottomNavigationBarItem( icon: Icon(Icons.bookmark), title: Text('Courses'), ), BottomNavigationBarItem( icon: Icon(Icons.contact_mail), title: Text('Mail'), ), ], currentIndex: _selectedIndex, selectedItemColor: Colors.amber[800], onTap: _onItemTapped, ), ); }} Output: Media error: Format(s) not supported or source(s) not found First, create the stateless main widget.Second use the widget builder to create an appbar inside the scaffold.Third use the ButtomNavigationBar widget in the body of the main appDo not forget to set the navbar at the bottom of the app using the style property. First, create the stateless main widget. Second use the widget builder to create an appbar inside the scaffold. Third use the ButtomNavigationBar widget in the body of the main app Do not forget to set the navbar at the bottom of the app using the style property. ankit_kumar_ android Flutter Flutter-widgets Dart Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - Custom Bottom Navigation Bar ListView Class in Flutter Flutter - Flexible Widget What is widgets in Flutter? Flutter - Stack Widget Android Studio Setup for Flutter Development Flutter - BorderRadius Widget Format Dates in Flutter Flutter - Dialogs Flutter - Positioned Widget
[ { "code": null, "e": 24034, "s": 24006, "text": "\n27 Nov, 2020" }, { "code": null, "e": 24334, "s": 24034, "text": "The BottonNavigationBar widget is used to show the bottom of an app. It can consist of multiple items such as icons, text, or both that leads to a different route depending upon the design of the application. It is meant to help the user navigate to different sections of the application in general." }, { "code": null, "e": 24927, "s": 24334, "text": "Syntax:\nBottomNavigationBar(\n{Key key, \n@required List<BottomNavigationBarItem> items, \nValueChanged<int> onTap, \nint currentIndex: 0, \ndouble elevation, \nBottomNavigationBarType type, \nColor fixedColor, \nColor backgroundColor, \ndouble iconSize: 24.0, \nColor selectedItemColor, \nColor unselectedItemColor, \nIconThemeData selectedIconTheme, \nIconThemeData unselectedIconTheme, \ndouble selectedFontSize: 14.0, \ndouble unselectedFontSize: 12.0, \nTextStyle selectedLabelStyle, \nTextStyle unselectedLabelStyle, \nbool showSelectedLabels: true, \nbool showUnselectedLabels, \nMouseCursor mouseCursor})" }, { "code": null, "e": 24968, "s": 24927, "text": "hashCode: The hash code for this object." }, { "code": null, "e": 25034, "s": 24968, "text": "key: Controls how one widget replaces another widget in the tree." }, { "code": null, "e": 25099, "s": 25034, "text": "runtimeType: A representation of the runtime type of the object." }, { "code": null, "e": 25160, "s": 25099, "text": "backgrounColor: The color of the BottomNavigationBar itself." }, { "code": null, "e": 25217, "s": 25160, "text": "elevation: The z-coordinate of this BottomNavigationBar." }, { "code": null, "e": 25275, "s": 25217, "text": "fixedColor: The z-coordinate of this BottomNavigationBar." }, { "code": null, "e": 25376, "s": 25275, "text": "items: Defines the appearance of the button items that are arrayed within the bottom navigation bar." }, { "code": null, "e": 25423, "s": 25376, "text": "onTap: Called when one of the items is tapped." }, { "code": null, "e": 25513, "s": 25423, "text": "currentIndex: This property takes an int value as the object to assign index t the items." }, { "code": null, "e": 25624, "s": 25513, "text": "fixedColor: This property takes in Color class as the object to assign a fixed value to the SelectedItemColor." }, { "code": null, "e": 25739, "s": 25624, "text": "iconSize: It takes a double value as the object to determine the size of all the icons in the BottomNavigationBar." }, { "code": null, "e": 25872, "s": 25739, "text": "mouseCursor: The mouseCursor property takes MouseCursor class as the object. It determines the type of cursor this widget will have." }, { "code": null, "e": 26022, "s": 25872, "text": "selectedFontSize: This property controls the font size in the BottomNavigationBar when the items are selected. It takes a double value as the object." }, { "code": null, "e": 26168, "s": 26022, "text": "selectedIcontheme: This property holds IconThemeData class as the object to controls the appearance of the icons this widget when it is selected." }, { "code": null, "e": 26337, "s": 26168, "text": "selectedIconColor: This property determines the color of the icons inside this widget will hold when they are selected. This property takes Color class as the property." }, { "code": null, "e": 26473, "s": 26337, "text": "selectedLabelStyle: TextStyle class is the object assigned to this property which controls the text style at the instance of selection." }, { "code": null, "e": 26621, "s": 26473, "text": "showSelectedLabele: This property takes a boolean value as the object to determine whether or not the labels for the unselected item will be shown." }, { "code": null, "e": 26774, "s": 26621, "text": "showUnselectedLabels: This property also takes in a boolean value as the object to determine whether or not the labels for selected items will be shown." }, { "code": null, "e": 26917, "s": 26774, "text": "type: The type property controls the behaviour and the layout of the BottomNavigationBar. It takes BottomNavigationBarType enum as the object." }, { "code": null, "e": 27050, "s": 26917, "text": "unselectedFontSize: This property also takes a double value as e object to determine the size of font when the item is not selected." }, { "code": null, "e": 27221, "s": 27050, "text": "unselectedIconTheme: This property also holds IconThemeData class as the object to controls the appearance of the icons this widget when it is unselected or not selected." }, { "code": null, "e": 27391, "s": 27221, "text": "unselectedItemColor: This property determines the color the icons inside this widget will hold when they are unselected. This property takes Color class as the property." }, { "code": null, "e": 27528, "s": 27391, "text": "unselectedLabelStyle: TextStyle class is the object assigned to this property which controls the text style when the item is unselected." }, { "code": null, "e": 27537, "s": 27528, "text": "Example:" }, { "code": null, "e": 27542, "s": 27537, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { static const String _title = 'Flutter Code Sample'; @override Widget build(BuildContext context) { return MaterialApp( title: _title, home: MyStatefulWidget(), ); }} class MyStatefulWidget extends StatefulWidget { MyStatefulWidget({Key key}) : super(key: key); @override _MyStatefulWidgetState createState() => _MyStatefulWidgetState();} class _MyStatefulWidgetState extends State<MyStatefulWidget> { int _selectedIndex = 0; static const TextStyle optionStyle = TextStyle(fontSize: 30, fontWeight: FontWeight.bold); static const List<Widget> _widgetOptions = <Widget>[ Text( 'HOME PAGE', style: optionStyle, ), Text( 'COURSE PAGE', style: optionStyle, ), Text( 'CONTACT GFG', style: optionStyle, ), ]; void _onItemTapped(int index) { setState(() { _selectedIndex = index; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('GeeksForGeeks'), backgroundColor: Colors.green, ), body: Center( child: _widgetOptions.elementAt(_selectedIndex), ), bottomNavigationBar: BottomNavigationBar( items: const <BottomNavigationBarItem>[ BottomNavigationBarItem( icon: Icon(Icons.home), title: Text('Home'), ), BottomNavigationBarItem( icon: Icon(Icons.bookmark), title: Text('Courses'), ), BottomNavigationBarItem( icon: Icon(Icons.contact_mail), title: Text('Mail'), ), ], currentIndex: _selectedIndex, selectedItemColor: Colors.amber[800], onTap: _onItemTapped, ), ); }}", "e": 29372, "s": 27542, "text": null }, { "code": null, "e": 29383, "s": 29375, "text": "Output:" }, { "code": null, "e": 29443, "s": 29383, "text": "Media error: Format(s) not supported or source(s) not found" }, { "code": null, "e": 29704, "s": 29443, "text": "First, create the stateless main widget.Second use the widget builder to create an appbar inside the scaffold.Third use the ButtomNavigationBar widget in the body of the main appDo not forget to set the navbar at the bottom of the app using the style property." }, { "code": null, "e": 29745, "s": 29704, "text": "First, create the stateless main widget." }, { "code": null, "e": 29816, "s": 29745, "text": "Second use the widget builder to create an appbar inside the scaffold." }, { "code": null, "e": 29885, "s": 29816, "text": "Third use the ButtomNavigationBar widget in the body of the main app" }, { "code": null, "e": 29968, "s": 29885, "text": "Do not forget to set the navbar at the bottom of the app using the style property." }, { "code": null, "e": 29983, "s": 29970, "text": "ankit_kumar_" }, { "code": null, "e": 29991, "s": 29983, "text": "android" }, { "code": null, "e": 29999, "s": 29991, "text": "Flutter" }, { "code": null, "e": 30015, "s": 29999, "text": "Flutter-widgets" }, { "code": null, "e": 30020, "s": 30015, "text": "Dart" }, { "code": null, "e": 30118, "s": 30020, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30157, "s": 30118, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 30183, "s": 30157, "text": "ListView Class in Flutter" }, { "code": null, "e": 30209, "s": 30183, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 30237, "s": 30209, "text": "What is widgets in Flutter?" }, { "code": null, "e": 30260, "s": 30237, "text": "Flutter - Stack Widget" }, { "code": null, "e": 30305, "s": 30260, "text": "Android Studio Setup for Flutter Development" }, { "code": null, "e": 30335, "s": 30305, "text": "Flutter - BorderRadius Widget" }, { "code": null, "e": 30359, "s": 30335, "text": "Format Dates in Flutter" }, { "code": null, "e": 30377, "s": 30359, "text": "Flutter - Dialogs" } ]
How to capture video from default camera in OpenCV using C++?
Here, we will understand how to access the default camera and show the video stream from that camera. In a laptop, the fixed webcam is the default camera. In desktops, the default camera depends on the serial port's sequence where the camera is connected. When we want to capture the video stream from default webcam, we do not need to know anything about the camera and ensure that the camera is connected. The following program takes video stream from default camera and shows it on the screen in real-time. #include<opencv2/opencv.hpp>//OpenCV header to use VideoCapture class// #include<iostream> using namespace std; using namespace cv; int main() { Mat myImage;//Declaring a matrix to load the frames// namedWindow("Video Player");//Declaring the video to show the video// VideoCapture cap(0);//Declaring an object to capture stream of frames from default camera// if (!cap.isOpened()){ //This section prompt an error message if no video stream is found// cout << "No video stream detected" << endl; system("pause"); return-1; } while (true){ //Taking an everlasting loop to show the video// cap >> myImage; if (myImage.empty()){ //Breaking the loop if no video frame is detected// break; } imshow("Video Player", myImage);//Showing the video// char c = (char)waitKey(25);//Allowing 25 milliseconds frame processing time and initiating break condition// if (c == 27){ //If 'Esc' is entered break the loop// break; } } cap.release();//Releasing the buffer memory// return 0; } This program will show the real-time default camera's video stream on the monitor.
[ { "code": null, "e": 1470, "s": 1062, "text": "Here, we will understand how to access the default camera and show the video stream from that camera. In a laptop, the fixed webcam is the default camera. In desktops, the default camera depends on the serial port's sequence where the camera is connected. When we want to capture the video stream from default webcam, we do not need to know anything about the camera and ensure that the camera is connected." }, { "code": null, "e": 1572, "s": 1470, "text": "The following program takes video stream from default camera and shows it on the screen in real-time." }, { "code": null, "e": 2649, "s": 1572, "text": "#include<opencv2/opencv.hpp>//OpenCV header to use VideoCapture class//\n#include<iostream>\nusing namespace std;\nusing namespace cv;\nint main() {\n Mat myImage;//Declaring a matrix to load the frames//\n namedWindow(\"Video Player\");//Declaring the video to show the video//\n VideoCapture cap(0);//Declaring an object to capture stream of frames from default camera//\n if (!cap.isOpened()){ //This section prompt an error message if no video stream is found//\n cout << \"No video stream detected\" << endl;\n system(\"pause\");\n return-1;\n }\n while (true){ //Taking an everlasting loop to show the video//\n cap >> myImage;\n if (myImage.empty()){ //Breaking the loop if no video frame is detected//\n break;\n }\n imshow(\"Video Player\", myImage);//Showing the video//\n char c = (char)waitKey(25);//Allowing 25 milliseconds frame processing time and initiating break condition//\n if (c == 27){ //If 'Esc' is entered break the loop//\n break;\n }\n }\n cap.release();//Releasing the buffer memory//\n return 0;\n}" }, { "code": null, "e": 2732, "s": 2649, "text": "This program will show the real-time default camera's video stream on the monitor." } ]
Entity Framework - Database First Approach
In this chapter, let us learn about creating an entity data model with Database First approach. The Database First Approach provides an alternative to the Code First and Model First approaches to the Entity Data Model. It creates model codes (classes, properties, DbContext etc.) from the database in the project and those classes become the link between the database and controller. The Database First Approach provides an alternative to the Code First and Model First approaches to the Entity Data Model. It creates model codes (classes, properties, DbContext etc.) from the database in the project and those classes become the link between the database and controller. The Database First Approach creates the entity framework from an existing database. We use all other functionalities, such as the model/database sync and the code generation, in the same way we used them in the Model First approach. The Database First Approach creates the entity framework from an existing database. We use all other functionalities, such as the model/database sync and the code generation, in the same way we used them in the Model First approach. Let’s take a simple example. We already have a database which contains 3 tables as shown in the following image. Step 1 − Let’s create a new console project with DatabaseFirstDemo name. Step 2 − To create the model, first right-click on your console project in solution explorer and select Add → New Items... Step 3 − Select ADO.NET Entity Data Model from middle pane and enter name DatabaseFirstModel in the Name field. Step 4 − Click Add button which will launch the Entity Data Model Wizard dialog. Step 5 − Select EF Designer from database and click Next button. Step 6 − Select the existing database and click Next. Step 7 − Choose Entity Framework 6.x and click Next. Step 8 − Select all the tables Views and stored procedure you want to include and click Finish. You will see that Entity model and POCO classes are generated from the database. Let us now retrieve all the students from the database by writing the following code in program.cs file. using System; using System.Linq; namespace DatabaseFirstDemo { class Program { static void Main(string[] args) { using (var db = new UniContextEntities()) { var query = from b in db.Students orderby b.FirstMidName select b; Console.WriteLine("All All student in the database:"); foreach (var item in query) { Console.WriteLine(item.FirstMidName +" "+ item.LastName); } Console.WriteLine("Press any key to exit..."); Console.ReadKey(); } } } } When the above program is executed, you will receive the following output − All student in the database: Ali Khan Arturo finand Bill Gates Carson Alexander Gytis Barzdukas Laura Norman Meredith Alonso Nino Olivetto Peggy Justice Yan Li Press any key to exit... When the above program is executed, you will see all the students’ name which were previously entered in the database. We recommend you to execute the above example in a step-by-step manner for better understanding. 19 Lectures 5 hours Trevoir Williams 33 Lectures 3.5 hours Nilay Mehta 21 Lectures 2.5 hours TELCOMA Global 89 Lectures 7.5 hours Mustafa Radaideh Print Add Notes Bookmark this page
[ { "code": null, "e": 3128, "s": 3032, "text": "In this chapter, let us learn about creating an entity data model with Database First approach." }, { "code": null, "e": 3416, "s": 3128, "text": "The Database First Approach provides an alternative to the Code First and Model First approaches to the Entity Data Model. It creates model codes (classes, properties, DbContext etc.) from the database in the project and those classes become the link between the database and controller." }, { "code": null, "e": 3704, "s": 3416, "text": "The Database First Approach provides an alternative to the Code First and Model First approaches to the Entity Data Model. It creates model codes (classes, properties, DbContext etc.) from the database in the project and those classes become the link between the database and controller." }, { "code": null, "e": 3937, "s": 3704, "text": "The Database First Approach creates the entity framework from an existing database. We use all other functionalities, such as the model/database sync and the code generation, in the same way we used them in the Model First approach." }, { "code": null, "e": 4170, "s": 3937, "text": "The Database First Approach creates the entity framework from an existing database. We use all other functionalities, such as the model/database sync and the code generation, in the same way we used them in the Model First approach." }, { "code": null, "e": 4283, "s": 4170, "text": "Let’s take a simple example. We already have a database which contains 3 tables as shown in the following image." }, { "code": null, "e": 4356, "s": 4283, "text": "Step 1 − Let’s create a new console project with DatabaseFirstDemo name." }, { "code": null, "e": 4479, "s": 4356, "text": "Step 2 − To create the model, first right-click on your console project in solution explorer and select Add → New Items..." }, { "code": null, "e": 4591, "s": 4479, "text": "Step 3 − Select ADO.NET Entity Data Model from middle pane and enter name DatabaseFirstModel in the Name field." }, { "code": null, "e": 4672, "s": 4591, "text": "Step 4 − Click Add button which will launch the Entity Data Model Wizard dialog." }, { "code": null, "e": 4737, "s": 4672, "text": "Step 5 − Select EF Designer from database and click Next button." }, { "code": null, "e": 4791, "s": 4737, "text": "Step 6 − Select the existing database and click Next." }, { "code": null, "e": 4844, "s": 4791, "text": "Step 7 − Choose Entity Framework 6.x and click Next." }, { "code": null, "e": 4940, "s": 4844, "text": "Step 8 − Select all the tables Views and stored procedure you want to include and click Finish." }, { "code": null, "e": 5021, "s": 4940, "text": "You will see that Entity model and POCO classes are generated from the database." }, { "code": null, "e": 5126, "s": 5021, "text": "Let us now retrieve all the students from the database by writing the following code in program.cs file." }, { "code": null, "e": 5716, "s": 5126, "text": "using System;\nusing System.Linq;\n\nnamespace DatabaseFirstDemo {\n\n class Program {\n\n static void Main(string[] args) {\n\n using (var db = new UniContextEntities()) {\n\n var query = from b in db.Students\n orderby b.FirstMidName select b;\n\n Console.WriteLine(\"All All student in the database:\");\n\n foreach (var item in query) {\n Console.WriteLine(item.FirstMidName +\" \"+ item.LastName);\n }\n\n Console.WriteLine(\"Press any key to exit...\");\n Console.ReadKey();\n }\n }\n }\n}\n" }, { "code": null, "e": 5792, "s": 5716, "text": "When the above program is executed, you will receive the following output −" }, { "code": null, "e": 5980, "s": 5792, "text": "All student in the database:\nAli Khan\nArturo finand\nBill Gates\nCarson Alexander\nGytis Barzdukas\nLaura Norman\nMeredith Alonso\nNino Olivetto\nPeggy Justice\nYan Li\nPress any key to exit...\n" }, { "code": null, "e": 6099, "s": 5980, "text": "When the above program is executed, you will see all the students’ name which were previously entered in the database." }, { "code": null, "e": 6196, "s": 6099, "text": "We recommend you to execute the above example in a step-by-step manner for better understanding." }, { "code": null, "e": 6229, "s": 6196, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 6247, "s": 6229, "text": " Trevoir Williams" }, { "code": null, "e": 6282, "s": 6247, "text": "\n 33 Lectures \n 3.5 hours \n" }, { "code": null, "e": 6295, "s": 6282, "text": " Nilay Mehta" }, { "code": null, "e": 6330, "s": 6295, "text": "\n 21 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6346, "s": 6330, "text": " TELCOMA Global" }, { "code": null, "e": 6381, "s": 6346, "text": "\n 89 Lectures \n 7.5 hours \n" }, { "code": null, "e": 6399, "s": 6381, "text": " Mustafa Radaideh" }, { "code": null, "e": 6406, "s": 6399, "text": " Print" }, { "code": null, "e": 6417, "s": 6406, "text": " Add Notes" } ]
Concatenated string with uncommon characters in Python - GeeksforGeeks
19 Nov, 2020 Two strings are given and you have to modify 1st string such that all the common characters of the 2nd string have to be removed and the uncommon characters of the 2nd string have to be concatenated with uncommon characters of the 1st string. Examples: Input : S1 = "aacdb" S2 = "gafd" Output : "cbgf" Input : S1 = "abcs"; S2 = "cxzca"; Output : "bsxz" This problem has existing solution please refer Concatenated string with uncommon characters of two strings link. We can solve this problem quickly in Python using Set and List Comprehension. Approach is simple, Convert both strings into set so that they could have only unique characters. Now take intersection of two sets to get common character both strings have.Now separate out those characters in each string which are not common in both of them and concatenate the characters. Convert both strings into set so that they could have only unique characters. Now take intersection of two sets to get common character both strings have. Now separate out those characters in each string which are not common in both of them and concatenate the characters. # Function to concatenated string with uncommon # characters of two strings def uncommonConcat(str1, str2): # convert both strings into set set1 = set(str1) set2 = set(str2) # take intersection of two sets to get list of # common characters common = list(set1 & set2) # separate out characters in each string # which are not common in both strings result = [ch for ch in str1 if ch not in common] + [ch for ch in str2 if ch not in common] # join each character without space to get # final string print( ''.join(result) ) # Driver program if __name__ == "__main__": str1 = 'aacdb' str2 = 'gafd' uncommonConcat(str1,str2) Output: cbgf Code_Mech Python list-programs Python set-programs Python string-programs python-list python-set python-string Python Strings python-list python-set Strings 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 Reverse a string in Java Write a program to reverse an array or string Longest Common Subsequence | DP-4 C++ Data Types Write a program to print all permutations of a given string
[ { "code": null, "e": 24986, "s": 24958, "text": "\n19 Nov, 2020" }, { "code": null, "e": 25229, "s": 24986, "text": "Two strings are given and you have to modify 1st string such that all the common characters of the 2nd string have to be removed and the uncommon characters of the 2nd string have to be concatenated with uncommon characters of the 1st string." }, { "code": null, "e": 25239, "s": 25229, "text": "Examples:" }, { "code": null, "e": 25357, "s": 25239, "text": "Input : S1 = \"aacdb\"\n S2 = \"gafd\"\nOutput : \"cbgf\"\n\nInput : S1 = \"abcs\";\n S2 = \"cxzca\";\nOutput : \"bsxz\"\n" }, { "code": null, "e": 25569, "s": 25357, "text": "This problem has existing solution please refer Concatenated string with uncommon characters of two strings link. We can solve this problem quickly in Python using Set and List Comprehension. Approach is simple," }, { "code": null, "e": 25841, "s": 25569, "text": "Convert both strings into set so that they could have only unique characters. Now take intersection of two sets to get common character both strings have.Now separate out those characters in each string which are not common in both of them and concatenate the characters." }, { "code": null, "e": 25996, "s": 25841, "text": "Convert both strings into set so that they could have only unique characters. Now take intersection of two sets to get common character both strings have." }, { "code": null, "e": 26114, "s": 25996, "text": "Now separate out those characters in each string which are not common in both of them and concatenate the characters." }, { "code": "# Function to concatenated string with uncommon # characters of two strings def uncommonConcat(str1, str2): # convert both strings into set set1 = set(str1) set2 = set(str2) # take intersection of two sets to get list of # common characters common = list(set1 & set2) # separate out characters in each string # which are not common in both strings result = [ch for ch in str1 if ch not in common] + [ch for ch in str2 if ch not in common] # join each character without space to get # final string print( ''.join(result) ) # Driver program if __name__ == \"__main__\": str1 = 'aacdb' str2 = 'gafd' uncommonConcat(str1,str2) ", "e": 26805, "s": 26114, "text": null }, { "code": null, "e": 26813, "s": 26805, "text": "Output:" }, { "code": null, "e": 26819, "s": 26813, "text": "cbgf\n" }, { "code": null, "e": 26829, "s": 26819, "text": "Code_Mech" }, { "code": null, "e": 26850, "s": 26829, "text": "Python list-programs" }, { "code": null, "e": 26870, "s": 26850, "text": "Python set-programs" }, { "code": null, "e": 26893, "s": 26870, "text": "Python string-programs" }, { "code": null, "e": 26905, "s": 26893, "text": "python-list" }, { "code": null, "e": 26916, "s": 26905, "text": "python-set" }, { "code": null, "e": 26930, "s": 26916, "text": "python-string" }, { "code": null, "e": 26937, "s": 26930, "text": "Python" }, { "code": null, "e": 26945, "s": 26937, "text": "Strings" }, { "code": null, "e": 26957, "s": 26945, "text": "python-list" }, { "code": null, "e": 26968, "s": 26957, "text": "python-set" }, { "code": null, "e": 26976, "s": 26968, "text": "Strings" }, { "code": null, "e": 27074, "s": 26976, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27083, "s": 27074, "text": "Comments" }, { "code": null, "e": 27096, "s": 27083, "text": "Old Comments" }, { "code": null, "e": 27114, "s": 27096, "text": "Python Dictionary" }, { "code": null, "e": 27149, "s": 27114, "text": "Read a file line by line in Python" }, { "code": null, "e": 27171, "s": 27149, "text": "Enumerate() in Python" }, { "code": null, "e": 27203, "s": 27171, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27233, "s": 27203, "text": "Iterate over a list in Python" }, { "code": null, "e": 27258, "s": 27233, "text": "Reverse a string in Java" }, { "code": null, "e": 27304, "s": 27258, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 27338, "s": 27304, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 27353, "s": 27338, "text": "C++ Data Types" } ]
Latent Dirichlet Allocation(LDA): A guide to probabilistic modelling approach for topic discovery | by Awan-Ur-Rahman | Towards Data Science
Latent Dirichlet Allocation(LDA) is one of the most common algorithms in topic modelling. LDA was proposed by J. K. Pritchard, M. Stephens and P. Donnelly in 2000 and rediscovered by David M. Blei, Andrew Y. Ng and Michael I. Jordan in 2003. In this article, I will try to give you an idea of what topic modelling is. We will learn how LDA works and finally, we will try to implement our LDA model. Topic Modelling is one of the most interesting fields in Machine Learning and Natural Language Processing. Topic Modelling means the extraction of abstract “topics” from the collection of documents. One of the primary application of natural language processing is to know what people are talking about in a large number of text documents. And it is really hard to read through all of these documents and extract or compile topics. In these cases, topic modelling is used to extract documents information. To understand the concept of topic modelling let’s see an example. Suppose, you are reading some articles on a newspaper and in those articles, the word “climate” appears most than any other words. So, in a normal sense, you can say that these articles will more probably about something related to climate. Topic modelling does the same thing in a statistical way. It produces topics by clustering similar words. Here come two terms: one is “Topic Modelling” and the other is “Topic Classification”. Though they look similar, they are totally different processes. The first is an unsupervised machine learning technique and the second one is the supervised technique.Let’s elaborate on the concept. Topic classification often involves mutually-exclusive classes. That means each document is labelled with a specific class. On the other hand, Topic modelling is not mutually exclusive. The same document may involve with many topics. As Topic modelling works on the basis of the probability distribution, the same document may have a probability-distribution spread across many topics. For topic modelling, there are several existing algorithms that you can use. Non-Negative Matrix Factorization(NMF), Latent Semantic Analysis or Latent Semantic Indexing(LSA or LSI) and Latent Dirichlet Allocation(LDA) are some of these algorithms. Here in this article, we will talk about Latent Dirichlet Allocation, one of the most common algorithms for topic modelling. “ The latent Dirichlet allocation (LDA) is a generative statistical model that allows sets of observations to be explained by unobserved groups that explain why some parts of the data are similar. For example, if observations are words collected into documents, it posits that each document is a mixture of a small number of topics and that each word’s presence is attributable to one of the document’s topics.” — Wikipedia Okay, Let’s try to understand this definition. The basic idea of Latent Dirichlet allocation (LDA) is that documents are considered as random mixtures of various topics and topics are considered a mixture of different words. Now, suppose you need some articles which are related to animals and you have thousands of articles in front of you and you really don’t know what these articles are about. Reading all these articles are really cumbersome to find out the articles related to animals. Let’s see an example of it. As an example, let’s consider we have four articles. Article no. 1 related to animal, article no. 2 related to genetic type, article no. 3 related to computer types and article no. 4 is a combination of animal and genetic type. As a human, you can easily differentiate these topics according to the words it contains. But what will you do if there are thousands of articles and each article has thousands of lines? The answer will be like -“If we can do this with the help of a computer then we should do so”. Yes, Computer can do so with the help of Latent Dirichlet allocation. Now we will try to understand how LDA works. First, we will see the graphical representation of LDA and then we will see the probability calculation formula. The above figure is a graphical representation of LDA. In the above figure, we can see that there are six parameters- α(alpha) and η(eta) — represents Dirichlet distribution. The high alpha value indicates that each document contains most of the topics and on the contrary, a lower alpha value indicates that the documents are likely to contain a fewer number of topic. Same as alpha, a Higher value of η indicates that the topics are likely to cover most of the words and on the contrary, lower eta value indicates that the topics are likely to contain a fewer number of words. β(beta) and θ(theta) — represents multinomial distribution. z — represents a bunch of topics w — represents a bunch of words The left side of the formula indicates the probability of the document. In the right of the formula, there are four terms. The 1st and 3rd term of the formula will help us to find topics. The 2nd and 4th will help us to find the words in articles. The first two terms of the right side of the formula indicate Dirichlet distribution and the rest portion of the right side is multinomial distribution. Let’s assume, in the above figure, in the left triangle, the blue circles indicate different articles. Now if we distribute the articles over different topics, it will be distributed as shown in the right triangle. The blue circles will move to the corners of the triangle which depends on the percentage of its being that topic. This process is done by the first term of the right side of the formula. Now we use multinomial distribution to generate topics based on the percentage get from the first term. Now after getting the topics we will find which words are more relatable to these topics. This is done by another Dirichlet distribution. Topics are distributed based on the words as shown below. Now we will use another multinomial distribution to find the words which are more related to those topics and generate words with probability using that Dirichlet distribution. This process is done multiple times. Thus we will find the words which are more relatable to the topics and can distribute the articles based on those topics. You can find the code in GitHub. For implementing LDA you can use either gensim or sklearn. Here, we will use gensim. For implementing purpose, I have used the Kaggle dataset. This dataset consists of 2150 datasets information in 15 columns: dataset = pd.read_csv('/content/drive/My Drive/topic modelling/voted-kaggle-dataset.csv') For processing the data, first, we select the columns that are meaningful for this process. Then remove the rows containing any missing values. modified_dataset = modified_dataset.dropna() We will then calculate the number of unique tag in Tags columns as we will consider this as the number of topics for our model. unique_tag = []for i in range(len(tag_dataset)): tag_string = str(tag_dataset[i]) if tag_string != "nan" : tag_word=convert(tag_string) for j in range(len(tag_word)): if tag_word[j] not in unique_tag: unique_tag.append(tag_word[j])print(len(unique_tag)) Removing punctuations and transforming the whole text in the lower casing makes the training task easier and increase the efficiency of the model. remove_digits = str.maketrans('', '', string.digits)exclude = '[!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~]'for column in ['Title','Subtitle','Description']: modified_dataset[column] = modified_dataset[column].map(lambda x : x.translate(remove_digits)) modified_dataset[column] = modified_dataset[column].map(lambda x : re.sub(str(exclude), '', x)) We need to tokenize our dataset and perform stemming operation. import nltknltk.download('punkt')tokenized_dataframe = modified_dataset.apply(lambda row: nltk.word_tokenize(row['Description']), axis=1)print(type(tokenized_dataframe))def lemmatize_text(text): return [ps.stem(w) for w in text if len(w)>5]ps = PorterStemmer() stemmed_dataset = tokenized_dataframe.apply(lemmatize_text) By using WordCloud, we can verify whether our preprocessing is correctly done or not. A word cloud is an image made of words that together resemble a cloudy shape. It shows us how often a word appeared in a text — its frequency. from wordcloud import WordCloudimport matplotlib.pyplot as plt#dataset_words=''#for column in ['Title','Subtitle','Description']:dataset_words=''.join(list(str(stemmed_dataset.values)))print(type(dataset_words))wordcloud = WordCloud(width = 800, height = 500, background_color ='white', min_font_size = 10).generate(dataset_words) plt.figure(figsize = (5, 5), facecolor = None) plt.imshow(wordcloud) plt.axis("off") plt.tight_layout(pad = 0) plt.show() For the LDA model, we first need to build a dictionary of words where each word is given a unique id. Then need to create a corpus which contains word id mapping with word_frequency — ->(word_id, word_frequency). dictionary_of_words = gensim.corpora.Dictionary(stemmed_dataset)word_corpus = [dictionary_of_words.doc2bow(word) for word in stemmed_dataset] Finally, train the model. lda_model = gensim.models.ldamodel.LdaModel(corpus=word_corpus, id2word=dictionary_of_words,num_topics=329, random_state=101,update_every=1,chunksize=300,passes=50,alpha='auto',per_word_topics=True) Coherence measures the relative distance between words within a topic. coherence_val = CoherenceModel(model=lda_model, texts=stemmed_dataset, dictionary=dictionary_of_words, coherence='c_v').get_coherence()print('Coherence Score: ', coherence_val) Coherence value: 0.4 for index,score in sorted(lda_model[word_corpus[2]][0], key=lambda tup: -1*tup[1]): print("\nScore: {}\t \nTopic: {}".format(score, lda_model.print_topic(index, 10))) The topic at the top got the highest probability and it is related to something like economic. You can find all the code on GITHUB. Latent Dirichlet Allocation by David M. Blei, Andrew Y. Ng & Michael I. Jordan.Latent Dirichlet Allocation by Luis Serrano.Latent Dirichlet Allocation (algorithm) by ML Papers Explained — A.I. Socratic Circles — AISC. Latent Dirichlet Allocation by David M. Blei, Andrew Y. Ng & Michael I. Jordan. Latent Dirichlet Allocation by Luis Serrano. Latent Dirichlet Allocation (algorithm) by ML Papers Explained — A.I. Socratic Circles — AISC.
[ { "code": null, "e": 571, "s": 172, "text": "Latent Dirichlet Allocation(LDA) is one of the most common algorithms in topic modelling. LDA was proposed by J. K. Pritchard, M. Stephens and P. Donnelly in 2000 and rediscovered by David M. Blei, Andrew Y. Ng and Michael I. Jordan in 2003. In this article, I will try to give you an idea of what topic modelling is. We will learn how LDA works and finally, we will try to implement our LDA model." }, { "code": null, "e": 1143, "s": 571, "text": "Topic Modelling is one of the most interesting fields in Machine Learning and Natural Language Processing. Topic Modelling means the extraction of abstract “topics” from the collection of documents. One of the primary application of natural language processing is to know what people are talking about in a large number of text documents. And it is really hard to read through all of these documents and extract or compile topics. In these cases, topic modelling is used to extract documents information. To understand the concept of topic modelling let’s see an example." }, { "code": null, "e": 1776, "s": 1143, "text": "Suppose, you are reading some articles on a newspaper and in those articles, the word “climate” appears most than any other words. So, in a normal sense, you can say that these articles will more probably about something related to climate. Topic modelling does the same thing in a statistical way. It produces topics by clustering similar words. Here come two terms: one is “Topic Modelling” and the other is “Topic Classification”. Though they look similar, they are totally different processes. The first is an unsupervised machine learning technique and the second one is the supervised technique.Let’s elaborate on the concept." }, { "code": null, "e": 2162, "s": 1776, "text": "Topic classification often involves mutually-exclusive classes. That means each document is labelled with a specific class. On the other hand, Topic modelling is not mutually exclusive. The same document may involve with many topics. As Topic modelling works on the basis of the probability distribution, the same document may have a probability-distribution spread across many topics." }, { "code": null, "e": 2536, "s": 2162, "text": "For topic modelling, there are several existing algorithms that you can use. Non-Negative Matrix Factorization(NMF), Latent Semantic Analysis or Latent Semantic Indexing(LSA or LSI) and Latent Dirichlet Allocation(LDA) are some of these algorithms. Here in this article, we will talk about Latent Dirichlet Allocation, one of the most common algorithms for topic modelling." }, { "code": null, "e": 2960, "s": 2536, "text": "“ The latent Dirichlet allocation (LDA) is a generative statistical model that allows sets of observations to be explained by unobserved groups that explain why some parts of the data are similar. For example, if observations are words collected into documents, it posits that each document is a mixture of a small number of topics and that each word’s presence is attributable to one of the document’s topics.” — Wikipedia" }, { "code": null, "e": 3007, "s": 2960, "text": "Okay, Let’s try to understand this definition." }, { "code": null, "e": 3480, "s": 3007, "text": "The basic idea of Latent Dirichlet allocation (LDA) is that documents are considered as random mixtures of various topics and topics are considered a mixture of different words. Now, suppose you need some articles which are related to animals and you have thousands of articles in front of you and you really don’t know what these articles are about. Reading all these articles are really cumbersome to find out the articles related to animals. Let’s see an example of it." }, { "code": null, "e": 4218, "s": 3480, "text": "As an example, let’s consider we have four articles. Article no. 1 related to animal, article no. 2 related to genetic type, article no. 3 related to computer types and article no. 4 is a combination of animal and genetic type. As a human, you can easily differentiate these topics according to the words it contains. But what will you do if there are thousands of articles and each article has thousands of lines? The answer will be like -“If we can do this with the help of a computer then we should do so”. Yes, Computer can do so with the help of Latent Dirichlet allocation. Now we will try to understand how LDA works. First, we will see the graphical representation of LDA and then we will see the probability calculation formula." }, { "code": null, "e": 4336, "s": 4218, "text": "The above figure is a graphical representation of LDA. In the above figure, we can see that there are six parameters-" }, { "code": null, "e": 4797, "s": 4336, "text": "α(alpha) and η(eta) — represents Dirichlet distribution. The high alpha value indicates that each document contains most of the topics and on the contrary, a lower alpha value indicates that the documents are likely to contain a fewer number of topic. Same as alpha, a Higher value of η indicates that the topics are likely to cover most of the words and on the contrary, lower eta value indicates that the topics are likely to contain a fewer number of words." }, { "code": null, "e": 4857, "s": 4797, "text": "β(beta) and θ(theta) — represents multinomial distribution." }, { "code": null, "e": 4890, "s": 4857, "text": "z — represents a bunch of topics" }, { "code": null, "e": 4922, "s": 4890, "text": "w — represents a bunch of words" }, { "code": null, "e": 5323, "s": 4922, "text": "The left side of the formula indicates the probability of the document. In the right of the formula, there are four terms. The 1st and 3rd term of the formula will help us to find topics. The 2nd and 4th will help us to find the words in articles. The first two terms of the right side of the formula indicate Dirichlet distribution and the rest portion of the right side is multinomial distribution." }, { "code": null, "e": 5830, "s": 5323, "text": "Let’s assume, in the above figure, in the left triangle, the blue circles indicate different articles. Now if we distribute the articles over different topics, it will be distributed as shown in the right triangle. The blue circles will move to the corners of the triangle which depends on the percentage of its being that topic. This process is done by the first term of the right side of the formula. Now we use multinomial distribution to generate topics based on the percentage get from the first term." }, { "code": null, "e": 6026, "s": 5830, "text": "Now after getting the topics we will find which words are more relatable to these topics. This is done by another Dirichlet distribution. Topics are distributed based on the words as shown below." }, { "code": null, "e": 6240, "s": 6026, "text": "Now we will use another multinomial distribution to find the words which are more related to those topics and generate words with probability using that Dirichlet distribution. This process is done multiple times." }, { "code": null, "e": 6362, "s": 6240, "text": "Thus we will find the words which are more relatable to the topics and can distribute the articles based on those topics." }, { "code": null, "e": 6480, "s": 6362, "text": "You can find the code in GitHub. For implementing LDA you can use either gensim or sklearn. Here, we will use gensim." }, { "code": null, "e": 6604, "s": 6480, "text": "For implementing purpose, I have used the Kaggle dataset. This dataset consists of 2150 datasets information in 15 columns:" }, { "code": null, "e": 6694, "s": 6604, "text": "dataset = pd.read_csv('/content/drive/My Drive/topic modelling/voted-kaggle-dataset.csv')" }, { "code": null, "e": 6838, "s": 6694, "text": "For processing the data, first, we select the columns that are meaningful for this process. Then remove the rows containing any missing values." }, { "code": null, "e": 6883, "s": 6838, "text": "modified_dataset = modified_dataset.dropna()" }, { "code": null, "e": 7011, "s": 6883, "text": "We will then calculate the number of unique tag in Tags columns as we will consider this as the number of topics for our model." }, { "code": null, "e": 7285, "s": 7011, "text": "unique_tag = []for i in range(len(tag_dataset)): tag_string = str(tag_dataset[i]) if tag_string != \"nan\" : tag_word=convert(tag_string) for j in range(len(tag_word)): if tag_word[j] not in unique_tag: unique_tag.append(tag_word[j])print(len(unique_tag))" }, { "code": null, "e": 7432, "s": 7285, "text": "Removing punctuations and transforming the whole text in the lower casing makes the training task easier and increase the efficiency of the model." }, { "code": null, "e": 7775, "s": 7432, "text": "remove_digits = str.maketrans('', '', string.digits)exclude = '[!\"#$%&\\'()*+,-./:;<=>?@[\\\\]^_`{|}~]'for column in ['Title','Subtitle','Description']: modified_dataset[column] = modified_dataset[column].map(lambda x : x.translate(remove_digits)) modified_dataset[column] = modified_dataset[column].map(lambda x : re.sub(str(exclude), '', x))" }, { "code": null, "e": 7839, "s": 7775, "text": "We need to tokenize our dataset and perform stemming operation." }, { "code": null, "e": 8165, "s": 7839, "text": "import nltknltk.download('punkt')tokenized_dataframe = modified_dataset.apply(lambda row: nltk.word_tokenize(row['Description']), axis=1)print(type(tokenized_dataframe))def lemmatize_text(text): return [ps.stem(w) for w in text if len(w)>5]ps = PorterStemmer() stemmed_dataset = tokenized_dataframe.apply(lemmatize_text)" }, { "code": null, "e": 8394, "s": 8165, "text": "By using WordCloud, we can verify whether our preprocessing is correctly done or not. A word cloud is an image made of words that together resemble a cloudy shape. It shows us how often a word appeared in a text — its frequency." }, { "code": null, "e": 8882, "s": 8394, "text": "from wordcloud import WordCloudimport matplotlib.pyplot as plt#dataset_words=''#for column in ['Title','Subtitle','Description']:dataset_words=''.join(list(str(stemmed_dataset.values)))print(type(dataset_words))wordcloud = WordCloud(width = 800, height = 500, background_color ='white', min_font_size = 10).generate(dataset_words) plt.figure(figsize = (5, 5), facecolor = None) plt.imshow(wordcloud) plt.axis(\"off\") plt.tight_layout(pad = 0) plt.show()" }, { "code": null, "e": 9095, "s": 8882, "text": "For the LDA model, we first need to build a dictionary of words where each word is given a unique id. Then need to create a corpus which contains word id mapping with word_frequency — ->(word_id, word_frequency)." }, { "code": null, "e": 9237, "s": 9095, "text": "dictionary_of_words = gensim.corpora.Dictionary(stemmed_dataset)word_corpus = [dictionary_of_words.doc2bow(word) for word in stemmed_dataset]" }, { "code": null, "e": 9263, "s": 9237, "text": "Finally, train the model." }, { "code": null, "e": 9512, "s": 9263, "text": "lda_model = gensim.models.ldamodel.LdaModel(corpus=word_corpus, id2word=dictionary_of_words,num_topics=329, random_state=101,update_every=1,chunksize=300,passes=50,alpha='auto',per_word_topics=True)" }, { "code": null, "e": 9583, "s": 9512, "text": "Coherence measures the relative distance between words within a topic." }, { "code": null, "e": 9760, "s": 9583, "text": "coherence_val = CoherenceModel(model=lda_model, texts=stemmed_dataset, dictionary=dictionary_of_words, coherence='c_v').get_coherence()print('Coherence Score: ', coherence_val)" }, { "code": null, "e": 9781, "s": 9760, "text": "Coherence value: 0.4" }, { "code": null, "e": 9952, "s": 9781, "text": "for index,score in sorted(lda_model[word_corpus[2]][0], key=lambda tup: -1*tup[1]): print(\"\\nScore: {}\\t \\nTopic: {}\".format(score, lda_model.print_topic(index, 10)))" }, { "code": null, "e": 10047, "s": 9952, "text": "The topic at the top got the highest probability and it is related to something like economic." }, { "code": null, "e": 10084, "s": 10047, "text": "You can find all the code on GITHUB." }, { "code": null, "e": 10302, "s": 10084, "text": "Latent Dirichlet Allocation by David M. Blei, Andrew Y. Ng & Michael I. Jordan.Latent Dirichlet Allocation by Luis Serrano.Latent Dirichlet Allocation (algorithm) by ML Papers Explained — A.I. Socratic Circles — AISC." }, { "code": null, "e": 10382, "s": 10302, "text": "Latent Dirichlet Allocation by David M. Blei, Andrew Y. Ng & Michael I. Jordan." }, { "code": null, "e": 10427, "s": 10382, "text": "Latent Dirichlet Allocation by Luis Serrano." } ]
Build tree array from JSON in JavaScript
Suppose, we have the following array in JavaScript − const arr = [{ "code": "2", "name": "PENDING" }, { "code": "2.2", "name": "PENDING CHILDREN" }, { "code": "2.2.01.01", "name": "PENDING CHILDREN CHILDREN" }, { "code": "2.2.01.02", "name": "PENDING CHILDREN CHILDREN02" }, { "code": "1", "name": "ACTIVE" }, { "code": "1.1", "name": "ACTIVE CHILDREN" }, { "code": "1.1.01", "name": "ACTIVE CHILDREN CHILDREN" }]; We are required to write a JavaScript function that takes in one such array. The function should build a tree structure from this array based on the "name" property of objects. Therefore, for the above array, the output should look something like this − const output = [{ "code": "2", "name": "PENDING", "children": [{ "code": "2.2", "name": "PENDING CHILDREN", "children": [{ "code": "2.2.01.01", "name": "PENDING CHILDREN CHILDREN" }, { "code": "2.2.01.02", "name": "PENDING CHILDREN CHILDREN02" }] }] }, { "code": "1", "name": "ACTIVE", "children": [{ "code": "1.1", "name": "ACTIVE CHILDREN", "children": [{ "code": "1.1.01", "name": "ACTIVE CHILDREN CHILDREN" }] }] }]; The code for this will be − const arr = [{ "code": "2", "name": "PENDING" }, { "code": "2.2", "name": "PENDING CHILDREN" }, { "code": "2.2.01.01", "name": "PENDING CHILDREN CHILDREN" }, { "code": "2.2.01.02", "name": "PENDING CHILDREN CHILDREN02" }, { "code": "1", "name": "ACTIVE" }, { "code": "1.1", "name": "ACTIVE CHILDREN" }, { "code": "1.1.01", "name": "ACTIVE CHILDREN CHILDREN" }]; const transformToTree = (arr, root = '') => { let map = {}, last = [root], level = 0; map[root] = {}; arr.forEach(el => { let parent = root; while (level && last[level].length >= el.code.length) { level--; }; parent = last[level]; level++; last.length = level; last.push(el.code); map[el.code] = el; map[parent].children = map[parent].children || []; map[parent].children.push(el); }); return map[root].children; }; console.log(JSON.stringify(transformToTree(arr), undefined, 4)); And the output in the console will be − [ { "code": "2", "name": "PENDING", "children": [ { "code": "2.2", "name": "PENDING CHILDREN", "children": [ { "code": "2.2.01.01", "name": "PENDING CHILDREN CHILDREN" }, { "code": "2.2.01.02", "name": "PENDING CHILDREN CHILDREN02" } ] } ] }, { "code": "1", "name": "ACTIVE", "children": [ { "code": "1.1", "name": "ACTIVE CHILDREN", "children": [ { "code": "1.1.01", "name": "ACTIVE CHILDREN CHILDREN" } ] } ] } ]
[ { "code": null, "e": 1115, "s": 1062, "text": "Suppose, we have the following array in JavaScript −" }, { "code": null, "e": 1519, "s": 1115, "text": "const arr = [{\n \"code\": \"2\",\n \"name\": \"PENDING\"\n},\n{\n \"code\": \"2.2\",\n \"name\": \"PENDING CHILDREN\"\n},\n{\n \"code\": \"2.2.01.01\",\n \"name\": \"PENDING CHILDREN CHILDREN\"\n},\n{\n \"code\": \"2.2.01.02\",\n \"name\": \"PENDING CHILDREN CHILDREN02\"\n},\n{\n \"code\": \"1\",\n \"name\": \"ACTIVE\"\n},\n{\n \"code\": \"1.1\",\n \"name\": \"ACTIVE CHILDREN\"\n},\n{\n \"code\": \"1.1.01\",\n \"name\": \"ACTIVE CHILDREN CHILDREN\"\n}];" }, { "code": null, "e": 1696, "s": 1519, "text": "We are required to write a JavaScript function that takes in one such array. The function should build a tree structure from this array based on the \"name\" property of objects." }, { "code": null, "e": 1773, "s": 1696, "text": "Therefore, for the above array, the output should look something like this −" }, { "code": null, "e": 2332, "s": 1773, "text": "const output = [{\n \"code\": \"2\",\n \"name\": \"PENDING\",\n \"children\": [{\n \"code\": \"2.2\",\n \"name\": \"PENDING CHILDREN\",\n \"children\": [{\n \"code\": \"2.2.01.01\",\n \"name\": \"PENDING CHILDREN CHILDREN\"\n },\n {\n \"code\": \"2.2.01.02\",\n \"name\": \"PENDING CHILDREN CHILDREN02\"\n }]\n }]\n},\n{\n \"code\": \"1\",\n \"name\": \"ACTIVE\",\n \"children\": [{\n \"code\": \"1.1\",\n \"name\": \"ACTIVE CHILDREN\",\n \"children\": [{\n \"code\": \"1.1.01\",\n \"name\": \"ACTIVE CHILDREN CHILDREN\"\n }]\n }]\n}];" }, { "code": null, "e": 2360, "s": 2332, "text": "The code for this will be −" }, { "code": null, "e": 3329, "s": 2360, "text": "const arr = [{\n \"code\": \"2\",\n \"name\": \"PENDING\"\n},\n{\n \"code\": \"2.2\",\n \"name\": \"PENDING CHILDREN\"\n},\n{\n \"code\": \"2.2.01.01\",\n \"name\": \"PENDING CHILDREN CHILDREN\"\n},\n{\n \"code\": \"2.2.01.02\",\n \"name\": \"PENDING CHILDREN CHILDREN02\"\n},\n{\n \"code\": \"1\",\n \"name\": \"ACTIVE\"\n},\n{\n \"code\": \"1.1\",\n \"name\": \"ACTIVE CHILDREN\"\n},\n{\n \"code\": \"1.1.01\",\n \"name\": \"ACTIVE CHILDREN CHILDREN\"\n}];\nconst transformToTree = (arr, root = '') => {\n let map = {}, last = [root], level = 0;\n map[root] = {};\n arr.forEach(el => {\n let parent = root;\n while (level && last[level].length >= el.code.length) {\n level--;\n };\n parent = last[level];\n level++;\n last.length = level;\n last.push(el.code);\n map[el.code] = el;\n map[parent].children = map[parent].children || [];\n map[parent].children.push(el);\n });\n return map[root].children;\n};\nconsole.log(JSON.stringify(transformToTree(arr), undefined, 4));" }, { "code": null, "e": 3369, "s": 3329, "text": "And the output in the console will be −" }, { "code": null, "e": 4174, "s": 3369, "text": "[\n {\n \"code\": \"2\",\n \"name\": \"PENDING\",\n \"children\": [\n {\n \"code\": \"2.2\",\n \"name\": \"PENDING CHILDREN\",\n \"children\": [\n {\n \"code\": \"2.2.01.01\",\n \"name\": \"PENDING CHILDREN CHILDREN\"\n },\n {\n \"code\": \"2.2.01.02\",\n \"name\": \"PENDING CHILDREN CHILDREN02\"\n }\n ]\n }\n ]\n },\n {\n \"code\": \"1\",\n \"name\": \"ACTIVE\",\n \"children\": [\n {\n \"code\": \"1.1\",\n \"name\": \"ACTIVE CHILDREN\",\n \"children\": [\n {\n \"code\": \"1.1.01\",\n \"name\": \"ACTIVE CHILDREN CHILDREN\"\n }\n ]\n }\n ]\n }\n]" } ]
Optimize Workforce Planning using Linear Programming with Python | by Samir Saci | Towards Data Science
A major challenge faced by Distribution Center (DC) managers is the fluctuation of the workload during the week. In the example below, you can see the daily variation of key indicators that will drive your workload (#Orders, #Lines, #SKU, ...). From one day to another, you can see a high variation that needs to be absorbed by your teams. Considering that the average productivity of your workers is stable, the only solution is to adapt your resources to meet the demand of each day. You are an Inbound Manager of a Distribution Center operated by a Third Party Logistics Company (3PL) for a large retailer. Your team responsibilities include Unload Pallets from the Trucks Scan each pallet and record the received quantity in your Warehouse Management System (WMS) Put away these pallets to Stock Area The team’s global productivity is measured each week in (Pallets/Hour). At the beginning of each month, your colleagues from the transportation team share a forecast of the number of pallets to be received every day for the next 4 weeks. Based on these forecasts and your global productivity you can estimate what would be the resources needed each day For more flexibility, you will use 100% of temporary workers to build your team. Constraint 1: The Supply must meet the demand If you need 31 workers Monday, you need to secure at least 31 workers for Monday. Constraint 2: Minimum working time by worker To ensure employees retention, you need to guarantee a minimum of 5 consecutive working days per week. Workforce sourcing can be challenging especially if your DC is surrounded by e-commerce fulfilment centres. Therefore you need to ensure minimum working time for your temporary workers to be an attractive employer. Constraint 3: Maximum working time by week Following the local regulations, each worker needs to rest 2 days after 5 consecutive working days. A worker from Shift 1 will start his week Monday and get 2 days off on Friday. Her colleague from Shift 6 will start the week Saturday and get 2 days off on Thursday. Objective: Minimize the number of workers hired Following the productivity targets fixed by your manager, you must minimize the number of workers hired. If you do not reach this target your P&L can be impacted, because this productivity has been used to calculate the price invoiced to your customer (retailer). We define a Linear Programming Problem by finding thethe optimal value of a linear function (objective function) of several variables (x[i]), subject to the conditions that the variables are non-negative and satisfy a set of linear inequalities (called linear constraints). Our problem fits perfectly! Edit: You can find a Youtube version of this article with animations in the link below. Variablesx[i]: number of temporary workers hired for shift iConstraints- For each day the total number of workers on-duty must be higher than the demand- Each worker needs to work a minimum of 5 consecutive days per week- Each worker needs to have 2 days off after 5 consecutive days of workObjective functionsThe total number of temporary workers hired for all shifts i = 1 ... 7 should be minimal PuLP is a modelling framework for Linear (LP) and Integer Programming (IP) problems written in Python maintained by COIN-OR Foundation (Computational Infrastructure for Operations Research). You can find the full code in this Github repository: Link.My portfolio with other projects: Samir Saci Create a circular list for the days (if you need to add 5 days to Friday you will reach Wednesday) List of Working Days: if day = 0 (Monday) then working days are Monday, Tuesday, Wednesday, Thursday and Friday Workers off by shift for each day: if day = 0 (Monday) then workers of shift 2 (Starting Tuesday) and shift 3 (Starting Wednesday) are off Initialize Model “Minimize Staffing” to minimize the objective Create variables x[i]: number of workers hired for shift i Define objective: sum of workers hired x[i] Add constraints: sum of workers on duty (not on a day off) is higher than minimum staff demand Results: Number of workers hired? Total number of Staff = 53 Insights 0 workers hired for Thursday and Saturday shifts Supply vs. Demand: what is the gap? Do we have more workers than needed? Insights Friday: 1 extra worker Saturday: 5 extra workers In addition to optimizing your workforce allocation, you can also improve the productivity per worker following a process improvement methodology like the one presented in this article for picking. www.samirsaci.com Our results are respecting the constraints i.e. the demand is met. However, this sizing is not satisfying as we have 6 extra man days to add in our P&L because of Friday and Saturday. Try to influence several parameters The constraint of 2 days off per week? The constraint of having consecutive days of work? The constraint of having a minimum of 5 days worked per week? You can try these scenarios and share your results (or questions) in the comment section. Please feel free to contact me, I am willing to share and exchange on topics related to Data Science and Supply Chain.My Portfolio: https://samirsaci.com [1] Computational Infrastructure for Operations Research, Optimization with PuLP (Documentation), Link
[ { "code": null, "e": 284, "s": 171, "text": "A major challenge faced by Distribution Center (DC) managers is the fluctuation of the workload during the week." }, { "code": null, "e": 511, "s": 284, "text": "In the example below, you can see the daily variation of key indicators that will drive your workload (#Orders, #Lines, #SKU, ...). From one day to another, you can see a high variation that needs to be absorbed by your teams." }, { "code": null, "e": 657, "s": 511, "text": "Considering that the average productivity of your workers is stable, the only solution is to adapt your resources to meet the demand of each day." }, { "code": null, "e": 781, "s": 657, "text": "You are an Inbound Manager of a Distribution Center operated by a Third Party Logistics Company (3PL) for a large retailer." }, { "code": null, "e": 816, "s": 781, "text": "Your team responsibilities include" }, { "code": null, "e": 847, "s": 816, "text": "Unload Pallets from the Trucks" }, { "code": null, "e": 939, "s": 847, "text": "Scan each pallet and record the received quantity in your Warehouse Management System (WMS)" }, { "code": null, "e": 976, "s": 939, "text": "Put away these pallets to Stock Area" }, { "code": null, "e": 1214, "s": 976, "text": "The team’s global productivity is measured each week in (Pallets/Hour). At the beginning of each month, your colleagues from the transportation team share a forecast of the number of pallets to be received every day for the next 4 weeks." }, { "code": null, "e": 1329, "s": 1214, "text": "Based on these forecasts and your global productivity you can estimate what would be the resources needed each day" }, { "code": null, "e": 1410, "s": 1329, "text": "For more flexibility, you will use 100% of temporary workers to build your team." }, { "code": null, "e": 1456, "s": 1410, "text": "Constraint 1: The Supply must meet the demand" }, { "code": null, "e": 1538, "s": 1456, "text": "If you need 31 workers Monday, you need to secure at least 31 workers for Monday." }, { "code": null, "e": 1583, "s": 1538, "text": "Constraint 2: Minimum working time by worker" }, { "code": null, "e": 1794, "s": 1583, "text": "To ensure employees retention, you need to guarantee a minimum of 5 consecutive working days per week. Workforce sourcing can be challenging especially if your DC is surrounded by e-commerce fulfilment centres." }, { "code": null, "e": 1901, "s": 1794, "text": "Therefore you need to ensure minimum working time for your temporary workers to be an attractive employer." }, { "code": null, "e": 1944, "s": 1901, "text": "Constraint 3: Maximum working time by week" }, { "code": null, "e": 2044, "s": 1944, "text": "Following the local regulations, each worker needs to rest 2 days after 5 consecutive working days." }, { "code": null, "e": 2211, "s": 2044, "text": "A worker from Shift 1 will start his week Monday and get 2 days off on Friday. Her colleague from Shift 6 will start the week Saturday and get 2 days off on Thursday." }, { "code": null, "e": 2259, "s": 2211, "text": "Objective: Minimize the number of workers hired" }, { "code": null, "e": 2523, "s": 2259, "text": "Following the productivity targets fixed by your manager, you must minimize the number of workers hired. If you do not reach this target your P&L can be impacted, because this productivity has been used to calculate the price invoiced to your customer (retailer)." }, { "code": null, "e": 2797, "s": 2523, "text": "We define a Linear Programming Problem by finding thethe optimal value of a linear function (objective function) of several variables (x[i]), subject to the conditions that the variables are non-negative and satisfy a set of linear inequalities (called linear constraints)." }, { "code": null, "e": 2825, "s": 2797, "text": "Our problem fits perfectly!" }, { "code": null, "e": 2913, "s": 2825, "text": "Edit: You can find a Youtube version of this article with animations in the link below." }, { "code": null, "e": 3312, "s": 2913, "text": "Variablesx[i]: number of temporary workers hired for shift iConstraints- For each day the total number of workers on-duty must be higher than the demand- Each worker needs to work a minimum of 5 consecutive days per week- Each worker needs to have 2 days off after 5 consecutive days of workObjective functionsThe total number of temporary workers hired for all shifts i = 1 ... 7 should be minimal" }, { "code": null, "e": 3503, "s": 3312, "text": "PuLP is a modelling framework for Linear (LP) and Integer Programming (IP) problems written in Python maintained by COIN-OR Foundation (Computational Infrastructure for Operations Research)." }, { "code": null, "e": 3607, "s": 3503, "text": "You can find the full code in this Github repository: Link.My portfolio with other projects: Samir Saci" }, { "code": null, "e": 3706, "s": 3607, "text": "Create a circular list for the days (if you need to add 5 days to Friday you will reach Wednesday)" }, { "code": null, "e": 3818, "s": 3706, "text": "List of Working Days: if day = 0 (Monday) then working days are Monday, Tuesday, Wednesday, Thursday and Friday" }, { "code": null, "e": 3957, "s": 3818, "text": "Workers off by shift for each day: if day = 0 (Monday) then workers of shift 2 (Starting Tuesday) and shift 3 (Starting Wednesday) are off" }, { "code": null, "e": 4020, "s": 3957, "text": "Initialize Model “Minimize Staffing” to minimize the objective" }, { "code": null, "e": 4079, "s": 4020, "text": "Create variables x[i]: number of workers hired for shift i" }, { "code": null, "e": 4123, "s": 4079, "text": "Define objective: sum of workers hired x[i]" }, { "code": null, "e": 4218, "s": 4123, "text": "Add constraints: sum of workers on duty (not on a day off) is higher than minimum staff demand" }, { "code": null, "e": 4252, "s": 4218, "text": "Results: Number of workers hired?" }, { "code": null, "e": 4279, "s": 4252, "text": "Total number of Staff = 53" }, { "code": null, "e": 4288, "s": 4279, "text": "Insights" }, { "code": null, "e": 4337, "s": 4288, "text": "0 workers hired for Thursday and Saturday shifts" }, { "code": null, "e": 4373, "s": 4337, "text": "Supply vs. Demand: what is the gap?" }, { "code": null, "e": 4410, "s": 4373, "text": "Do we have more workers than needed?" }, { "code": null, "e": 4419, "s": 4410, "text": "Insights" }, { "code": null, "e": 4468, "s": 4419, "text": "Friday: 1 extra worker Saturday: 5 extra workers" }, { "code": null, "e": 4666, "s": 4468, "text": "In addition to optimizing your workforce allocation, you can also improve the productivity per worker following a process improvement methodology like the one presented in this article for picking." }, { "code": null, "e": 4684, "s": 4666, "text": "www.samirsaci.com" }, { "code": null, "e": 4868, "s": 4684, "text": "Our results are respecting the constraints i.e. the demand is met. However, this sizing is not satisfying as we have 6 extra man days to add in our P&L because of Friday and Saturday." }, { "code": null, "e": 4904, "s": 4868, "text": "Try to influence several parameters" }, { "code": null, "e": 4943, "s": 4904, "text": "The constraint of 2 days off per week?" }, { "code": null, "e": 4994, "s": 4943, "text": "The constraint of having consecutive days of work?" }, { "code": null, "e": 5056, "s": 4994, "text": "The constraint of having a minimum of 5 days worked per week?" }, { "code": null, "e": 5146, "s": 5056, "text": "You can try these scenarios and share your results (or questions) in the comment section." }, { "code": null, "e": 5300, "s": 5146, "text": "Please feel free to contact me, I am willing to share and exchange on topics related to Data Science and Supply Chain.My Portfolio: https://samirsaci.com" } ]
C# Fixed-Point (“F”) Format Specifier
The ("F") format specifier converts a number to a string of the following form − "-ddd.ddd..." Above, "d" indicates a digit (0-9). Let us see an example. Here, if we will set (“F3”) format specifier to add three values after decimal places, for let’s say, 212. 212.000 The following is another example − Live Demo using System; using System.Globalization; class Demo { static void Main() { int val; val = 38788; Console.WriteLine(val.ToString("F",CultureInfo.InvariantCulture)); val = -344; Console.WriteLine(val.ToString("F3",CultureInfo.InvariantCulture)); val = 5656; Console.WriteLine(val.ToString("F5",CultureInfo.InvariantCulture)); } } 38788.00 -344.000 5656.00000
[ { "code": null, "e": 1143, "s": 1062, "text": "The (\"F\") format specifier converts a number to a string of the following form −" }, { "code": null, "e": 1157, "s": 1143, "text": "\"-ddd.ddd...\"" }, { "code": null, "e": 1193, "s": 1157, "text": "Above, \"d\" indicates a digit (0-9)." }, { "code": null, "e": 1216, "s": 1193, "text": "Let us see an example." }, { "code": null, "e": 1323, "s": 1216, "text": "Here, if we will set (“F3”) format specifier to add three values after decimal places, for let’s say, 212." }, { "code": null, "e": 1331, "s": 1323, "text": "212.000" }, { "code": null, "e": 1366, "s": 1331, "text": "The following is another example −" }, { "code": null, "e": 1377, "s": 1366, "text": " Live Demo" }, { "code": null, "e": 1754, "s": 1377, "text": "using System;\nusing System.Globalization;\nclass Demo {\n static void Main() {\n int val;\n val = 38788;\n Console.WriteLine(val.ToString(\"F\",CultureInfo.InvariantCulture));\n val = -344;\n Console.WriteLine(val.ToString(\"F3\",CultureInfo.InvariantCulture));\n val = 5656;\n Console.WriteLine(val.ToString(\"F5\",CultureInfo.InvariantCulture));\n }\n}" }, { "code": null, "e": 1783, "s": 1754, "text": "38788.00\n-344.000\n5656.00000" } ]
Find max in struct array using C++.
Here we will see how to get max in the struct array. Suppose there is a struct like below is given. We have to find the max element of an array of that struct type. struct Height{ int feet, inch; }; The idea is straight forward. We will traverse the array, and keep track of the max value of array element in inches. Where value is 12*feet + inch #include<iostream> #include<algorithm> using namespace std; struct Height{ int feet, inch; }; int maxHeight(Height h_arr[], int n){ int index = 0; int height = INT_MIN; for(int i = 0; i < n; i++){ int temp = 12 * (h_arr[i].feet) + h_arr[i].inch; if(temp > height){ height = temp; index = i; } } return index; } int main() { Height h_arr[] = {{1,3},{10,5},{6,8},{3,7},{5,9}}; int n = sizeof(h_arr)/sizeof(h_arr[0]); int max_index = maxHeight(h_arr, n); cout << "Max Height: " << h_arr[max_index].feet << " feet and " << h_arr[max_index].inch << " inches"; } Max Height: 10 feet and 5 inches
[ { "code": null, "e": 1227, "s": 1062, "text": "Here we will see how to get max in the struct array. Suppose there is a struct like below is given. We have to find the max element of an array of that struct type." }, { "code": null, "e": 1264, "s": 1227, "text": "struct Height{\n int feet, inch;\n};" }, { "code": null, "e": 1412, "s": 1264, "text": "The idea is straight forward. We will traverse the array, and keep track of the max value of array element in inches. Where value is 12*feet + inch" }, { "code": null, "e": 2035, "s": 1412, "text": "#include<iostream>\n#include<algorithm>\nusing namespace std;\nstruct Height{\n int feet, inch;\n};\nint maxHeight(Height h_arr[], int n){\n int index = 0;\n int height = INT_MIN;\n for(int i = 0; i < n; i++){\n int temp = 12 * (h_arr[i].feet) + h_arr[i].inch;\n if(temp > height){\n height = temp;\n index = i;\n }\n }\n return index;\n}\nint main() {\n Height h_arr[] = {{1,3},{10,5},{6,8},{3,7},{5,9}};\n int n = sizeof(h_arr)/sizeof(h_arr[0]);\n int max_index = maxHeight(h_arr, n);\n cout << \"Max Height: \" << h_arr[max_index].feet << \" feet and \" << h_arr[max_index].inch << \" inches\";\n}" }, { "code": null, "e": 2068, "s": 2035, "text": "Max Height: 10 feet and 5 inches" } ]
Minimum sum of differences with an element in an array - GeeksforGeeks
18 May, 2021 Given an array, we need to find the sum of elements of an array after changing the element as arr[i] will become abs(arr[i]-x) where x is an array element. Examples: Input : {2, 5, 1, 7, 4} Output : 9 We get minimum sum when we choose x = 4. The minimum sum is abs(2-4) + abs(5-4) + abs(1-4) + (7-4) abs(4-4) = 9 Input : {5, 11, 14, 10, 17, 15} Output : 20 We can either choose x = 14 or x = 11 The idea is based on fact that middle element would cause minimum sum of differences. When there are even number of elements, we can take any of the middle two elements. We can verify this fact by taking few examples. Below is the implementation of above idea: C++ Java Python3 C# PHP Javascript // C++ program to find minimum sum of absolute// differences with an array element.#include<bits/stdc++.h>using namespace std; // function to find min sum after operation int absSumDidd(int a[],int n) { // Sort the array sort(a,a+n); // Pick middle value int midValue = a[(int)(n / 2)]; // Sum of absolute differences. int sum = 0; for (int i = 0; i < n; i++) { sum = sum + abs(a[i] - midValue); } return sum; } // Driver Code int main() { int arr[] = { 5, 11, 14, 10, 17, 15 }; int n=sizeof(arr)/sizeof(arr[0]); cout<< absSumDidd(arr,n); } // Contributed by mits // Java program to find minimum sum of absolute// differences with an array element.import java.lang.*;import java.util.*; public class GFG { // function to find min sum after operation static int absSumDidd(int a[]) { // Sort the array Arrays.sort(a); // Pick middle value int midValue = a[a.length / 2]; // Sum of absolute differences. int sum = 0; for (int i = 0; i < a.length; i++) { sum = sum + Math.abs(a[i] - midValue); } return sum; } // Driver Code public static void main(String[] args) { int arr[] = { 5, 11, 14, 10, 17, 15 }; System.out.print(absSumDidd(arr)); } // Contributed by Saurav Jain} # Python3 program to find minimum sum of# absolute differences with an array element. # function to find min sum after operationdef absSumDidd(a, n): # Sort the array a.sort() # Pick middle value midValue = a[(int)(n // 2)] # Sum of absolute differences. sum = 0 for i in range(n): sum = sum + abs(a[i] - midValue) return sum # Driver Codearr = [5, 11, 14, 10, 17, 15]n = len(arr)print(absSumDidd(arr, n)) # This code is contributed# by sahishelangia // C# program to find minimum sum of absolute// differences with an array element.using System; class GFG { // function to find min sum after operation static int absSumDidd(int []a) { // Sort the array Array.Sort(a); // Pick middle value int midValue = a[a.Length / 2]; // Sum of absolute differences. int sum = 0; for (int i = 0; i < a.Length; i++) { sum = sum + Math.Abs(a[i] - midValue); } return sum; } // Driver Code public static void Main() { int []arr = { 5, 11, 14, 10, 17, 15 }; Console.Write(absSumDidd(arr)); } // Contributed by Subhadeep} <?php// PHP program to find minimum// sum of absolute differences// with an array element. // function to find min sum// after operationfunction absSumDidd($a, $n){ // Sort the array sort($a); // Pick middle value $midValue = $a[($n / 2)]; // Sum of absolute differences. $sum = 0; for ( $i = 0; $i < $n; $i++) { $sum = $sum + abs($a[$i] - $midValue); } return $sum; } // Driver Code$arr = array(5, 11, 14, 10, 17, 15 );$n = count($arr);echo absSumDidd($arr, $n); // This code is contributed// by anuj_67?> <script> // Javascript program to find minimum sum of absolute// differences with an array element. // Function to find min sum after operationfunction absSumDidd(a){ // Sort the array a.sort((a, b) => a - b); // Pick middle value var midValue = a[a.length / 2]; // Sum of absolute differences. var sum = 0; for(var i = 0; i < a.length; i++) { sum = sum + Math.abs(a[i] - midValue); } return sum; } // Driver Codevar arr = [ 5, 11, 14, 10, 17, 15 ];document.write(absSumDidd(arr)); // This code is contributed by shikhasingrajput </script> 20 Time Complexity: O(n Log n) We can further optimize above solution to O(n) by using linear time algorithm for median finding. tufan_gupta2000 Mithun Kumar vt_m sahilshelangia shikhasingrajput median-finding Technical Scripter 2018 Arrays Sorting Technical Scripter Arrays Sorting 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 Trapping Rain Water Move all negative numbers to beginning and positive to end with constant extra space Reversal algorithm for array rotation Window Sliding Technique
[ { "code": null, "e": 24429, "s": 24401, "text": "\n18 May, 2021" }, { "code": null, "e": 24585, "s": 24429, "text": "Given an array, we need to find the sum of elements of an array after changing the element as arr[i] will become abs(arr[i]-x) where x is an array element." }, { "code": null, "e": 24596, "s": 24585, "text": "Examples: " }, { "code": null, "e": 24829, "s": 24596, "text": "Input : {2, 5, 1, 7, 4}\nOutput : 9\nWe get minimum sum when we choose\nx = 4. The minimum sum is \nabs(2-4) + abs(5-4) + abs(1-4) + (7-4)\nabs(4-4) = 9\n\nInput : {5, 11, 14, 10, 17, 15}\nOutput : 20\nWe can either choose x = 14 or x = 11" }, { "code": null, "e": 25048, "s": 24829, "text": "The idea is based on fact that middle element would cause minimum sum of differences. When there are even number of elements, we can take any of the middle two elements. We can verify this fact by taking few examples. " }, { "code": null, "e": 25093, "s": 25048, "text": "Below is the implementation of above idea: " }, { "code": null, "e": 25097, "s": 25093, "text": "C++" }, { "code": null, "e": 25102, "s": 25097, "text": "Java" }, { "code": null, "e": 25110, "s": 25102, "text": "Python3" }, { "code": null, "e": 25113, "s": 25110, "text": "C#" }, { "code": null, "e": 25117, "s": 25113, "text": "PHP" }, { "code": null, "e": 25128, "s": 25117, "text": "Javascript" }, { "code": "// C++ program to find minimum sum of absolute// differences with an array element.#include<bits/stdc++.h>using namespace std; // function to find min sum after operation int absSumDidd(int a[],int n) { // Sort the array sort(a,a+n); // Pick middle value int midValue = a[(int)(n / 2)]; // Sum of absolute differences. int sum = 0; for (int i = 0; i < n; i++) { sum = sum + abs(a[i] - midValue); } return sum; } // Driver Code int main() { int arr[] = { 5, 11, 14, 10, 17, 15 }; int n=sizeof(arr)/sizeof(arr[0]); cout<< absSumDidd(arr,n); } // Contributed by mits", "e": 25842, "s": 25128, "text": null }, { "code": "// Java program to find minimum sum of absolute// differences with an array element.import java.lang.*;import java.util.*; public class GFG { // function to find min sum after operation static int absSumDidd(int a[]) { // Sort the array Arrays.sort(a); // Pick middle value int midValue = a[a.length / 2]; // Sum of absolute differences. int sum = 0; for (int i = 0; i < a.length; i++) { sum = sum + Math.abs(a[i] - midValue); } return sum; } // Driver Code public static void main(String[] args) { int arr[] = { 5, 11, 14, 10, 17, 15 }; System.out.print(absSumDidd(arr)); } // Contributed by Saurav Jain}", "e": 26596, "s": 25842, "text": null }, { "code": "# Python3 program to find minimum sum of# absolute differences with an array element. # function to find min sum after operationdef absSumDidd(a, n): # Sort the array a.sort() # Pick middle value midValue = a[(int)(n // 2)] # Sum of absolute differences. sum = 0 for i in range(n): sum = sum + abs(a[i] - midValue) return sum # Driver Codearr = [5, 11, 14, 10, 17, 15]n = len(arr)print(absSumDidd(arr, n)) # This code is contributed# by sahishelangia", "e": 27089, "s": 26596, "text": null }, { "code": "// C# program to find minimum sum of absolute// differences with an array element.using System; class GFG { // function to find min sum after operation static int absSumDidd(int []a) { // Sort the array Array.Sort(a); // Pick middle value int midValue = a[a.Length / 2]; // Sum of absolute differences. int sum = 0; for (int i = 0; i < a.Length; i++) { sum = sum + Math.Abs(a[i] - midValue); } return sum; } // Driver Code public static void Main() { int []arr = { 5, 11, 14, 10, 17, 15 }; Console.Write(absSumDidd(arr)); } // Contributed by Subhadeep}", "e": 27804, "s": 27089, "text": null }, { "code": "<?php// PHP program to find minimum// sum of absolute differences// with an array element. // function to find min sum// after operationfunction absSumDidd($a, $n){ // Sort the array sort($a); // Pick middle value $midValue = $a[($n / 2)]; // Sum of absolute differences. $sum = 0; for ( $i = 0; $i < $n; $i++) { $sum = $sum + abs($a[$i] - $midValue); } return $sum; } // Driver Code$arr = array(5, 11, 14, 10, 17, 15 );$n = count($arr);echo absSumDidd($arr, $n); // This code is contributed// by anuj_67?>", "e": 28376, "s": 27804, "text": null }, { "code": "<script> // Javascript program to find minimum sum of absolute// differences with an array element. // Function to find min sum after operationfunction absSumDidd(a){ // Sort the array a.sort((a, b) => a - b); // Pick middle value var midValue = a[a.length / 2]; // Sum of absolute differences. var sum = 0; for(var i = 0; i < a.length; i++) { sum = sum + Math.abs(a[i] - midValue); } return sum; } // Driver Codevar arr = [ 5, 11, 14, 10, 17, 15 ];document.write(absSumDidd(arr)); // This code is contributed by shikhasingrajput </script>", "e": 28970, "s": 28376, "text": null }, { "code": null, "e": 28973, "s": 28970, "text": "20" }, { "code": null, "e": 29102, "s": 28975, "text": "Time Complexity: O(n Log n) We can further optimize above solution to O(n) by using linear time algorithm for median finding. " }, { "code": null, "e": 29118, "s": 29102, "text": "tufan_gupta2000" }, { "code": null, "e": 29131, "s": 29118, "text": "Mithun Kumar" }, { "code": null, "e": 29136, "s": 29131, "text": "vt_m" }, { "code": null, "e": 29151, "s": 29136, "text": "sahilshelangia" }, { "code": null, "e": 29168, "s": 29151, "text": "shikhasingrajput" }, { "code": null, "e": 29183, "s": 29168, "text": "median-finding" }, { "code": null, "e": 29207, "s": 29183, "text": "Technical Scripter 2018" }, { "code": null, "e": 29214, "s": 29207, "text": "Arrays" }, { "code": null, "e": 29222, "s": 29214, "text": "Sorting" }, { "code": null, "e": 29241, "s": 29222, "text": "Technical Scripter" }, { "code": null, "e": 29248, "s": 29241, "text": "Arrays" }, { "code": null, "e": 29256, "s": 29248, "text": "Sorting" }, { "code": null, "e": 29354, "s": 29256, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29363, "s": 29354, "text": "Comments" }, { "code": null, "e": 29376, "s": 29363, "text": "Old Comments" }, { "code": null, "e": 29425, "s": 29376, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 29445, "s": 29425, "text": "Trapping Rain Water" }, { "code": null, "e": 29530, "s": 29445, "text": "Move all negative numbers to beginning and positive to end with constant extra space" }, { "code": null, "e": 29568, "s": 29530, "text": "Reversal algorithm for array rotation" } ]
Rust - Smart Pointers
Rust allocates everything on the stack by default. You can store things on the heap by wrapping them in smart pointers like Box. Types like Vec and String implicitly help heap allocation. Smart pointers implement traits listed in the table below. These traits of the smart pointers differentiate them from an ordinary struct − std::ops::Deref Used for immutable dereferencing operations, like *v. std::ops::Drop Used to run some code when a value goes out of scope. This is sometimes called a destructor In this chapter, we will learn about the Box smart pointer. We will also learn how to create a custom smart pointer like Box. The Box smart pointer also called a box allows you to store data on the heap rather than the stack. The stack contains the pointer to the heap data. A Box does not have performance overhead, other than storing their data on the heap. Let us see how to use a box to store an i32 value on the heap. fn main() { let var_i32 = 5; //stack let b = Box::new(var_i32); //heap println!("b = {}", b); } b = 5 In order to access a value pointed by a variable, use dereferencing. The * is used as a dereference operator. Let us see how to use dereference with Box. fn main() { let x = 5; //value type variable let y = Box::new(x); //y points to a new value 5 in the heap println!("{}",5==x); println!("{}",5==*y); //dereferencing y } The variable x is a value-type with the value 5. So, the expression 5==x will return true. Variable y points to the heap. To access the value in heap, we need to dereference using *y. *y returns value 5. So, the expression 5==*y returns true. true true The Deref trait, provided by the standard library, requires us to implement one method named deref, that borrows self and returns a reference to the inner data. The following example creates a structure MyBox, which is a generic type. It implements the trait Deref. This trait helps us access heap values wrapped by y using *y. use std::ops::Deref; struct MyBox<T>(T); impl<T> MyBox<T> { // Generic structure with static method new fn new(x:T)-> MyBox<T> { MyBox(x) } } impl<T> Deref for MyBox<T> { type Target = T; fn deref(&self) -> &T { &self.0 //returns data } } fn main() { let x = 5; let y = MyBox::new(x); // calling static method println!("5==x is {}",5==x); println!("5==*y is {}",5==*y); // dereferencing y println!("x==*y is {}",x==*y); //dereferencing y } 5==x is true 5==*y is true x==*y is true The Drop trait contains the drop() method. This method is called when a structure that implemented this trait goes out of scope. In some languages, the programmer must call code to free memory or resources every time they finish using an instance of a smart pointer. In Rust, you can achieve automatic memory deallocation using Drop trait. use std::ops::Deref; struct MyBox<T>(T); impl<T> MyBox<T> { fn new(x:T)->MyBox<T>{ MyBox(x) } } impl<T> Deref for MyBox<T> { type Target = T; fn deref(&self) -< &T { &self.0 } } impl<T> Drop for MyBox<T>{ fn drop(&mut self){ println!("dropping MyBox object from memory "); } } fn main() { let x = 50; MyBox::new(x); MyBox::new("Hello"); } In the above example, the drop method will be called twice as we are creating two objects in the heap. dropping MyBox object from memory dropping MyBox object from memory 45 Lectures 4.5 hours Stone River ELearning 10 Lectures 33 mins Ken Burke Print Add Notes Bookmark this page
[ { "code": null, "e": 2414, "s": 2087, "text": "Rust allocates everything on the stack by default. You can store things on the heap by wrapping them in smart pointers like Box. Types like Vec and String implicitly help heap allocation. Smart pointers implement traits listed in the table below. These traits of the smart pointers differentiate them from an ordinary struct −" }, { "code": null, "e": 2430, "s": 2414, "text": "std::ops::Deref" }, { "code": null, "e": 2484, "s": 2430, "text": "Used for immutable dereferencing operations, like *v." }, { "code": null, "e": 2499, "s": 2484, "text": "std::ops::Drop" }, { "code": null, "e": 2591, "s": 2499, "text": "Used to run some code when a value goes out of scope. This is sometimes called a destructor" }, { "code": null, "e": 2717, "s": 2591, "text": "In this chapter, we will learn about the Box smart pointer. We will also learn how to create a custom smart pointer like Box." }, { "code": null, "e": 2951, "s": 2717, "text": "The Box smart pointer also called a box allows you to store data on the heap rather than the stack. The stack contains the pointer to the heap data. A Box does not have performance overhead, other than storing their data on the heap." }, { "code": null, "e": 3014, "s": 2951, "text": "Let us see how to use a box to store an i32 value on the heap." }, { "code": null, "e": 3127, "s": 3014, "text": "fn main() {\n let var_i32 = 5; \n //stack\n let b = Box::new(var_i32); \n //heap\n println!(\"b = {}\", b);\n}" }, { "code": null, "e": 3134, "s": 3127, "text": "b = 5\n" }, { "code": null, "e": 3288, "s": 3134, "text": "In order to access a value pointed by a variable, use dereferencing. The * is used as a dereference operator. Let us see how to use dereference with Box." }, { "code": null, "e": 3482, "s": 3288, "text": "fn main() {\n let x = 5; \n //value type variable\n let y = Box::new(x); \n //y points to a new value 5 in the heap\n\n println!(\"{}\",5==x);\n println!(\"{}\",5==*y); \n //dereferencing y\n}" }, { "code": null, "e": 3725, "s": 3482, "text": "The variable x is a value-type with the value 5. So, the expression 5==x will return true. Variable y points to the heap. To access the value in heap, we need to dereference using *y. *y returns value 5. So, the expression 5==*y returns true." }, { "code": null, "e": 3736, "s": 3725, "text": "true\ntrue\n" }, { "code": null, "e": 4064, "s": 3736, "text": "The Deref trait, provided by the standard library, requires us to implement one method named deref, that borrows self and returns a reference to the inner data. The following example creates a structure MyBox, which is a generic type. It implements the trait Deref. This trait helps us access heap values wrapped by y using *y." }, { "code": null, "e": 4565, "s": 4064, "text": "use std::ops::Deref;\nstruct MyBox<T>(T);\nimpl<T> MyBox<T> { \n // Generic structure with static method new\n fn new(x:T)-> MyBox<T> {\n MyBox(x)\n }\n}\nimpl<T> Deref for MyBox<T> {\n type Target = T;\n fn deref(&self) -> &T {\n &self.0 //returns data\n }\n}\nfn main() {\n let x = 5;\n let y = MyBox::new(x); \n // calling static method\n \n println!(\"5==x is {}\",5==x);\n println!(\"5==*y is {}\",5==*y); \n // dereferencing y\n println!(\"x==*y is {}\",x==*y);\n //dereferencing y\n}" }, { "code": null, "e": 4607, "s": 4565, "text": "5==x is true\n5==*y is true\nx==*y is true\n" }, { "code": null, "e": 4947, "s": 4607, "text": "The Drop trait contains the drop() method. This method is called when a structure that implemented this trait goes out of scope. In some languages, the programmer must call code to free memory or resources every time they finish using an instance of a smart pointer. In Rust, you can achieve automatic memory deallocation using Drop trait." }, { "code": null, "e": 5338, "s": 4947, "text": "use std::ops::Deref;\n\nstruct MyBox<T>(T);\nimpl<T> MyBox<T> {\n fn new(x:T)->MyBox<T>{\n MyBox(x)\n }\n}\nimpl<T> Deref for MyBox<T> {\n type Target = T;\n fn deref(&self) -< &T {\n &self.0\n }\n}\nimpl<T> Drop for MyBox<T>{\n fn drop(&mut self){\n println!(\"dropping MyBox object from memory \");\n }\n}\nfn main() {\n let x = 50;\n MyBox::new(x);\n MyBox::new(\"Hello\");\n}" }, { "code": null, "e": 5441, "s": 5338, "text": "In the above example, the drop method will be called twice as we are creating two objects in the heap." }, { "code": null, "e": 5510, "s": 5441, "text": "dropping MyBox object from memory\ndropping MyBox object from memory\n" }, { "code": null, "e": 5545, "s": 5510, "text": "\n 45 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5568, "s": 5545, "text": " Stone River ELearning" }, { "code": null, "e": 5600, "s": 5568, "text": "\n 10 Lectures \n 33 mins\n" }, { "code": null, "e": 5611, "s": 5600, "text": " Ken Burke" }, { "code": null, "e": 5618, "s": 5611, "text": " Print" }, { "code": null, "e": 5629, "s": 5618, "text": " Add Notes" } ]
Hitchhiker’s Guide to Residual Networks (ResNet) in Keras | by Marco Peixeiro | Towards Data Science
Very deep neural networks are hard to train as they are more prone to vanishing or exploding gradients. To solve this problem, the activation unit from a layer could be fed directly to a deeper layer of the network, which is termed as a skip connection. This forms the basis of residual networks or ResNets. This post will introduce the basics the residual networks before implementing one in Keras. For hands-on video tutorials on machine learning, deep learning, and artificial intelligence, checkout my YouTube channel. A building block of a ResNet is called a residual block or identity block. A residual block is simply when the activation of a layer is fast-forwarded to a deeper layer in the neural network. As you can see in the image above, the activation from a previous layer is being added to the activation of a deeper layer in the network. This simple tweak allows training much deeper neural networks. In theory, the training error should monotonically decrease as more layers are added to a neural network. In practice however, for a traditional neural network, it will reach a point where the training error will start increasing. ResNets do not suffer from this problem. The training error will keep decreasing as more layers are added to the network. In fact, ResNets have made it possible to train networks with more than 100 layers, even reaching 1000 layers. Now, let’s build a ResNet with 50 layers for image classification using Keras. Keras is a high-level neural networks API, written in Python and capable of running on top of TensorFlow, CNTK, or Theano. It was developed with a focus on enabling fast experimentation. In this case, we will use TensorFlow as the backend. Of course, feel free to grab the entire notebook and make all the necessary imports before starting. First, we define the identity block, which will make our neural network a residual network as it represents the skip connection: Then, we build a convolution block like so: Notice how the convolution block combines both the main path and the shortcut. Now, we combine both blocks into building a 50-layer residual network: Before training, realize that we have a function that returns model. Therefore, we need to assign it to a variable. Then, Keras requires us to compile the model: model = ResNet50(input_shape = (64, 64, 3), classes = 6)model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) Once that is done, we can normalize our images and one-hot encode them: Afterwards, we can fit the model: model.fit(X_train, Y_train, epochs = 2, batch_size = 32) And see how it performed: preds = model.evaluate(X_test, Y_test)print (“Loss = “ + str(preds[0]))print (“Test Accuracy = “ + str(preds[1])) Now, you will see that we only get 16% accuracy. This is because we only trained on 2 epochs. You can train your model for longer on your own machine, but do realize that it will take a very long time, since it the network is very large. Keras makes it very easy to have a summary of the model we just built. Simply run this code: model.summary() and you get a detailed summary of each layer in your network. You can also generate a picture of the network’s architecture and save it in your working directory: plot_model(model, to_file=’ResNet.png’)SVG(model_to_dot(model).create(prog=’dot’, format=’svg’)) Great! You just learned the basics of a residual network and built one using Keras! Again, feel free to train the algorithm longer (~20 epochs), and you should see that the network performs very well. However, if you train only on CPU, this might take more than 1h. In a future post, I will show how to perform neural style transfer in TensorFlow, which is a very fun way to apply convolution neural networks!
[ { "code": null, "e": 425, "s": 171, "text": "Very deep neural networks are hard to train as they are more prone to vanishing or exploding gradients. To solve this problem, the activation unit from a layer could be fed directly to a deeper layer of the network, which is termed as a skip connection." }, { "code": null, "e": 571, "s": 425, "text": "This forms the basis of residual networks or ResNets. This post will introduce the basics the residual networks before implementing one in Keras." }, { "code": null, "e": 694, "s": 571, "text": "For hands-on video tutorials on machine learning, deep learning, and artificial intelligence, checkout my YouTube channel." }, { "code": null, "e": 886, "s": 694, "text": "A building block of a ResNet is called a residual block or identity block. A residual block is simply when the activation of a layer is fast-forwarded to a deeper layer in the neural network." }, { "code": null, "e": 1025, "s": 886, "text": "As you can see in the image above, the activation from a previous layer is being added to the activation of a deeper layer in the network." }, { "code": null, "e": 1088, "s": 1025, "text": "This simple tweak allows training much deeper neural networks." }, { "code": null, "e": 1319, "s": 1088, "text": "In theory, the training error should monotonically decrease as more layers are added to a neural network. In practice however, for a traditional neural network, it will reach a point where the training error will start increasing." }, { "code": null, "e": 1552, "s": 1319, "text": "ResNets do not suffer from this problem. The training error will keep decreasing as more layers are added to the network. In fact, ResNets have made it possible to train networks with more than 100 layers, even reaching 1000 layers." }, { "code": null, "e": 1631, "s": 1552, "text": "Now, let’s build a ResNet with 50 layers for image classification using Keras." }, { "code": null, "e": 1818, "s": 1631, "text": "Keras is a high-level neural networks API, written in Python and capable of running on top of TensorFlow, CNTK, or Theano. It was developed with a focus on enabling fast experimentation." }, { "code": null, "e": 1972, "s": 1818, "text": "In this case, we will use TensorFlow as the backend. Of course, feel free to grab the entire notebook and make all the necessary imports before starting." }, { "code": null, "e": 2101, "s": 1972, "text": "First, we define the identity block, which will make our neural network a residual network as it represents the skip connection:" }, { "code": null, "e": 2145, "s": 2101, "text": "Then, we build a convolution block like so:" }, { "code": null, "e": 2224, "s": 2145, "text": "Notice how the convolution block combines both the main path and the shortcut." }, { "code": null, "e": 2295, "s": 2224, "text": "Now, we combine both blocks into building a 50-layer residual network:" }, { "code": null, "e": 2457, "s": 2295, "text": "Before training, realize that we have a function that returns model. Therefore, we need to assign it to a variable. Then, Keras requires us to compile the model:" }, { "code": null, "e": 2600, "s": 2457, "text": "model = ResNet50(input_shape = (64, 64, 3), classes = 6)model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])" }, { "code": null, "e": 2672, "s": 2600, "text": "Once that is done, we can normalize our images and one-hot encode them:" }, { "code": null, "e": 2706, "s": 2672, "text": "Afterwards, we can fit the model:" }, { "code": null, "e": 2763, "s": 2706, "text": "model.fit(X_train, Y_train, epochs = 2, batch_size = 32)" }, { "code": null, "e": 2789, "s": 2763, "text": "And see how it performed:" }, { "code": null, "e": 2903, "s": 2789, "text": "preds = model.evaluate(X_test, Y_test)print (“Loss = “ + str(preds[0]))print (“Test Accuracy = “ + str(preds[1]))" }, { "code": null, "e": 3141, "s": 2903, "text": "Now, you will see that we only get 16% accuracy. This is because we only trained on 2 epochs. You can train your model for longer on your own machine, but do realize that it will take a very long time, since it the network is very large." }, { "code": null, "e": 3234, "s": 3141, "text": "Keras makes it very easy to have a summary of the model we just built. Simply run this code:" }, { "code": null, "e": 3250, "s": 3234, "text": "model.summary()" }, { "code": null, "e": 3312, "s": 3250, "text": "and you get a detailed summary of each layer in your network." }, { "code": null, "e": 3413, "s": 3312, "text": "You can also generate a picture of the network’s architecture and save it in your working directory:" }, { "code": null, "e": 3510, "s": 3413, "text": "plot_model(model, to_file=’ResNet.png’)SVG(model_to_dot(model).create(prog=’dot’, format=’svg’))" }, { "code": null, "e": 3776, "s": 3510, "text": "Great! You just learned the basics of a residual network and built one using Keras! Again, feel free to train the algorithm longer (~20 epochs), and you should see that the network performs very well. However, if you train only on CPU, this might take more than 1h." } ]
Removing a specific substring from a string in JavaScript
We are given a main string and a substring, our job is to create a function, let’s say removeString() that takes in these two arguments and returns a version of the main string which is free of the substring. Here, we need to remove the separator from a string, for example − this-is-a-sting Let’s now write the code for this function − const removeString = (string, separator) => { //we split the string and make it free of separator const separatedArray = string.split(separator); //we join the separatedArray with empty string const separatedString = separatedArray.join(""); return separatedString; } const str = removeString('this-is-a-sting', '-'); console.log(str); The output of this code in the console will be − thisisastring
[ { "code": null, "e": 1271, "s": 1062, "text": "We are given a main string and a substring, our job is to create a function, let’s say\nremoveString() that takes in these two arguments and returns a version of the main string which\nis free of the substring." }, { "code": null, "e": 1338, "s": 1271, "text": "Here, we need to remove the separator from a string, for example −" }, { "code": null, "e": 1354, "s": 1338, "text": "this-is-a-sting" }, { "code": null, "e": 1399, "s": 1354, "text": "Let’s now write the code for this function −" }, { "code": null, "e": 1750, "s": 1399, "text": "const removeString = (string, separator) => {\n //we split the string and make it free of separator\n const separatedArray = string.split(separator);\n //we join the separatedArray with empty string\n const separatedString = separatedArray.join(\"\");\n return separatedString;\n}\nconst str = removeString('this-is-a-sting', '-');\nconsole.log(str);" }, { "code": null, "e": 1799, "s": 1750, "text": "The output of this code in the console will be −" }, { "code": null, "e": 1813, "s": 1799, "text": "thisisastring" } ]
Change image resolution using Pillow in Python - GeeksforGeeks
02 Dec, 2020 Prerequisites: Python pillow PIL is the Python Imaging Library which provides the python interpreter with an in-depth file format support, an efficient internal representation, and fairly powerful image processing capabilities. Changing the resolution of an image simply means reducing or increasing the number of pixels in an image, without changing its dimensions or any other factor. In this article, we are going to learn the methods how to change the quality/Resolution of an image with the help of python PIL(pillow) Library. Using quality Parameter: The image quality is a scale to measure and store the resolution of an image. It lies in the range of 0 to 100 where 95 is considered as best because 100 disables some portions of jpeg compression algorithm that results very large files. While on the other hand the gain in image quality or resolution is also insignificant from 95 to 100. The functionality can be achieved by the following steps: Import the Images module from pillow.Open the image using .open( ) method by specifying the image path.The image_file.save() method have a parameter named quality, that specifies the resolution of an image in a 1-100 scale, where 95 is considered as the optimal quality. Import the Images module from pillow. Open the image using .open( ) method by specifying the image path. The image_file.save() method have a parameter named quality, that specifies the resolution of an image in a 1-100 scale, where 95 is considered as the optimal quality. Program: Python3 # Import the Images module from pillowfrom PIL import Image # Open the image by specifying the image path.image_path = "image_name.jpeg"image_file = Image.open(image_path) # the defaultimage_file.save("image_name.jpg", quality=95) # Changing the image resolution using quality parameter# Example-1image_file.save("image_name2.jpg", quality=25) # Example-2image_file.save("image_name3.jpg", quality=1) Original Image: Output: Default/High resolution (Quality=95): Medium Resolution (Quality=25): Low Resolution (Quality=1): Python-pil Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Box Plot in Python using Matplotlib Bar Plot in Matplotlib Python | Get dictionary keys as a list Python | Convert set into a list Ways to filter Pandas DataFrame by column values Python - Call function from another file loops in python Multithreading in Python | Set 2 (Synchronization) Python Dictionary keys() method Python Lambda Functions
[ { "code": null, "e": 23901, "s": 23873, "text": "\n02 Dec, 2020" }, { "code": null, "e": 23930, "s": 23901, "text": "Prerequisites: Python pillow" }, { "code": null, "e": 24433, "s": 23930, "text": "PIL is the Python Imaging Library which provides the python interpreter with an in-depth file format support, an efficient internal representation, and fairly powerful image processing capabilities. Changing the resolution of an image simply means reducing or increasing the number of pixels in an image, without changing its dimensions or any other factor. In this article, we are going to learn the methods how to change the quality/Resolution of an image with the help of python PIL(pillow) Library." }, { "code": null, "e": 24458, "s": 24433, "text": "Using quality Parameter:" }, { "code": null, "e": 24856, "s": 24458, "text": "The image quality is a scale to measure and store the resolution of an image. It lies in the range of 0 to 100 where 95 is considered as best because 100 disables some portions of jpeg compression algorithm that results very large files. While on the other hand the gain in image quality or resolution is also insignificant from 95 to 100. The functionality can be achieved by the following steps:" }, { "code": null, "e": 25127, "s": 24856, "text": "Import the Images module from pillow.Open the image using .open( ) method by specifying the image path.The image_file.save() method have a parameter named quality, that specifies the resolution of an image in a 1-100 scale, where 95 is considered as the optimal quality." }, { "code": null, "e": 25165, "s": 25127, "text": "Import the Images module from pillow." }, { "code": null, "e": 25232, "s": 25165, "text": "Open the image using .open( ) method by specifying the image path." }, { "code": null, "e": 25400, "s": 25232, "text": "The image_file.save() method have a parameter named quality, that specifies the resolution of an image in a 1-100 scale, where 95 is considered as the optimal quality." }, { "code": null, "e": 25409, "s": 25400, "text": "Program:" }, { "code": null, "e": 25417, "s": 25409, "text": "Python3" }, { "code": "# Import the Images module from pillowfrom PIL import Image # Open the image by specifying the image path.image_path = \"image_name.jpeg\"image_file = Image.open(image_path) # the defaultimage_file.save(\"image_name.jpg\", quality=95) # Changing the image resolution using quality parameter# Example-1image_file.save(\"image_name2.jpg\", quality=25) # Example-2image_file.save(\"image_name3.jpg\", quality=1)", "e": 25822, "s": 25417, "text": null }, { "code": null, "e": 25838, "s": 25822, "text": "Original Image:" }, { "code": null, "e": 25846, "s": 25838, "text": "Output:" }, { "code": null, "e": 25884, "s": 25846, "text": "Default/High resolution (Quality=95):" }, { "code": null, "e": 25916, "s": 25884, "text": "Medium Resolution (Quality=25):" }, { "code": null, "e": 25944, "s": 25916, "text": "Low Resolution (Quality=1):" }, { "code": null, "e": 25955, "s": 25944, "text": "Python-pil" }, { "code": null, "e": 25979, "s": 25955, "text": "Technical Scripter 2020" }, { "code": null, "e": 25986, "s": 25979, "text": "Python" }, { "code": null, "e": 26005, "s": 25986, "text": "Technical Scripter" }, { "code": null, "e": 26103, "s": 26005, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26112, "s": 26103, "text": "Comments" }, { "code": null, "e": 26125, "s": 26112, "text": "Old Comments" }, { "code": null, "e": 26161, "s": 26125, "text": "Box Plot in Python using Matplotlib" }, { "code": null, "e": 26184, "s": 26161, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 26223, "s": 26184, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26256, "s": 26223, "text": "Python | Convert set into a list" }, { "code": null, "e": 26305, "s": 26256, "text": "Ways to filter Pandas DataFrame by column values" }, { "code": null, "e": 26346, "s": 26305, "text": "Python - Call function from another file" }, { "code": null, "e": 26362, "s": 26346, "text": "loops in python" }, { "code": null, "e": 26413, "s": 26362, "text": "Multithreading in Python | Set 2 (Synchronization)" }, { "code": null, "e": 26445, "s": 26413, "text": "Python Dictionary keys() method" } ]
Clock systemUTC() Method in Java with Examples - GeeksforGeeks
10 Dec, 2018 java.time.Clock.systemUTC() method is a static method of Clock class which returns a clock that returns the current instant of the clock using the best available system clock where Zone of the returned clock is UTC time-zone. When the current instant is needed without the date or time, then use systemUTC() method in place of systemDefaultZone(). When converting instant to date and time, then the converter uses UTC time-zone as Zone for conversion. This clock is based on the best available system clock. This method can use System.currentTimeMillis(), or other higher resolution clock for its implementation if the clock is available to use. Returned clock from this method is immutable, thread-safe and Serializable. Syntax: public static Clock systemUTC() Return Value: This method returns a clock that uses the best available system clock in the UTC time-zone Example: Code: //Clock with default zone Clock clock=Clock.systemUTC(); System.out.println(clock.instant()); Output:: 2018-08-21T20:38:10.772Z Explanation:: when you call systemUTC() for Clock then the systemUTC() method will return a Class Object whose Zone is UTC time zone. Below programs illustrates systemUTC() method of java.time.Clock class: Program 1: When Clock is created with systemUTC(). This method makes clock zone to UTC Zone.Below program print date and time of clock in ZonedDateTime format. // Java program to demonstrate// systemUTC() method of Clock class import java.time.*; // create classpublic class systemUTCMethodDemo { // Main method public static void main(String[] args) { // create Clock with systemUTC() method Clock clock = Clock.systemUTC(); // get instant of class Instant instant = clock.instant(); // get ZonedDateTime object from instantObj // to get date time ZonedDateTime time = instant.atZone(clock.getZone()); // print details of ZonedDateTime System.out.println("ZonedDateTime of class with UTC" + " Time Zone is " + time.toString()); }} ZonedDateTime of class with UTC Time Zone is 2018-08-22T11:41:15.554Z Program 2: Print the zoneId using getZone() for clock created by systemUTC(). // Java program to demonstrate// systemUTC() method of Clock class import java.time.*; // create classpublic class systemUTCMethodDemo { // Main method public static void main(String[] args) { // create Clock with systemUTC() method Clock clock = Clock.systemUTC(); // get ZoneId of Clock ZoneId zone = clock.getZone(); // print details of ZoneId of new Clock System.out.println("ZoneID of class is " + zone); }} ZoneID of class is Z Reference:https://docs.oracle.com/javase/8/docs/api/java/time/Clock.html#systemUTC– java-basics Java-Clock Java-Functions Java-time package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Generics in Java Introduction to Java Comparator Interface in Java with Examples Internal Working of HashMap in Java Strings in Java
[ { "code": null, "e": 25225, "s": 25197, "text": "\n10 Dec, 2018" }, { "code": null, "e": 25451, "s": 25225, "text": "java.time.Clock.systemUTC() method is a static method of Clock class which returns a clock that returns the current instant of the clock using the best available system clock where Zone of the returned clock is UTC time-zone." }, { "code": null, "e": 25573, "s": 25451, "text": "When the current instant is needed without the date or time, then use systemUTC() method in place of systemDefaultZone()." }, { "code": null, "e": 25871, "s": 25573, "text": "When converting instant to date and time, then the converter uses UTC time-zone as Zone for conversion. This clock is based on the best available system clock. This method can use System.currentTimeMillis(), or other higher resolution clock for its implementation if the clock is available to use." }, { "code": null, "e": 25947, "s": 25871, "text": "Returned clock from this method is immutable, thread-safe and Serializable." }, { "code": null, "e": 25955, "s": 25947, "text": "Syntax:" }, { "code": null, "e": 25987, "s": 25955, "text": "public static Clock systemUTC()" }, { "code": null, "e": 26092, "s": 25987, "text": "Return Value: This method returns a clock that uses the best available system clock in the UTC time-zone" }, { "code": null, "e": 26101, "s": 26092, "text": "Example:" }, { "code": null, "e": 26374, "s": 26101, "text": "Code:\n//Clock with default zone\nClock clock=Clock.systemUTC();\nSystem.out.println(clock.instant());\n\nOutput:: \n2018-08-21T20:38:10.772Z\n\nExplanation:: \nwhen you call systemUTC() for Clock then the systemUTC()\nmethod will return a Class Object whose Zone is UTC time zone.\n" }, { "code": null, "e": 26446, "s": 26374, "text": "Below programs illustrates systemUTC() method of java.time.Clock class:" }, { "code": null, "e": 26497, "s": 26446, "text": "Program 1: When Clock is created with systemUTC()." }, { "code": null, "e": 26606, "s": 26497, "text": "This method makes clock zone to UTC Zone.Below program print date and time of clock in ZonedDateTime format." }, { "code": "// Java program to demonstrate// systemUTC() method of Clock class import java.time.*; // create classpublic class systemUTCMethodDemo { // Main method public static void main(String[] args) { // create Clock with systemUTC() method Clock clock = Clock.systemUTC(); // get instant of class Instant instant = clock.instant(); // get ZonedDateTime object from instantObj // to get date time ZonedDateTime time = instant.atZone(clock.getZone()); // print details of ZonedDateTime System.out.println(\"ZonedDateTime of class with UTC\" + \" Time Zone is \" + time.toString()); }}", "e": 27317, "s": 26606, "text": null }, { "code": null, "e": 27388, "s": 27317, "text": "ZonedDateTime of class with UTC Time Zone is 2018-08-22T11:41:15.554Z\n" }, { "code": null, "e": 27466, "s": 27388, "text": "Program 2: Print the zoneId using getZone() for clock created by systemUTC()." }, { "code": "// Java program to demonstrate// systemUTC() method of Clock class import java.time.*; // create classpublic class systemUTCMethodDemo { // Main method public static void main(String[] args) { // create Clock with systemUTC() method Clock clock = Clock.systemUTC(); // get ZoneId of Clock ZoneId zone = clock.getZone(); // print details of ZoneId of new Clock System.out.println(\"ZoneID of class is \" + zone); }}", "e": 27943, "s": 27466, "text": null }, { "code": null, "e": 27965, "s": 27943, "text": "ZoneID of class is Z\n" }, { "code": null, "e": 28049, "s": 27965, "text": "Reference:https://docs.oracle.com/javase/8/docs/api/java/time/Clock.html#systemUTC–" }, { "code": null, "e": 28061, "s": 28049, "text": "java-basics" }, { "code": null, "e": 28072, "s": 28061, "text": "Java-Clock" }, { "code": null, "e": 28087, "s": 28072, "text": "Java-Functions" }, { "code": null, "e": 28105, "s": 28087, "text": "Java-time package" }, { "code": null, "e": 28110, "s": 28105, "text": "Java" }, { "code": null, "e": 28115, "s": 28110, "text": "Java" }, { "code": null, "e": 28213, "s": 28115, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28228, "s": 28213, "text": "Stream In Java" }, { "code": null, "e": 28249, "s": 28228, "text": "Constructors in Java" }, { "code": null, "e": 28268, "s": 28249, "text": "Exceptions in Java" }, { "code": null, "e": 28298, "s": 28268, "text": "Functional Interfaces in Java" }, { "code": null, "e": 28344, "s": 28298, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 28361, "s": 28344, "text": "Generics in Java" }, { "code": null, "e": 28382, "s": 28361, "text": "Introduction to Java" }, { "code": null, "e": 28425, "s": 28382, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 28461, "s": 28425, "text": "Internal Working of HashMap in Java" } ]
Minimum increments to convert to an array of consecutive integers - GeeksforGeeks
14 May, 2021 Given an array arr[] with N elements, the task is to find the minimum number of operations required so that an Arithmetic Progression with the array elements is achieved with common difference as 1. In a single operation, any element can be incremented by 1.Examples: Input: arr[] = {4, 4, 5, 5, 7} Output: 5 Desired array is {4, 5, 6, 7, 8} which can be achieved in minimum possible operations.Input: arr[] = {11, 2, 5, 6} Output: 26 Since we are allowed to do only increment, we change the array to {11, 12, 13, 14} Approach: We can utilize Binary Search to solve this problem. We will built the desired array with fixed last element which will be increased if the solution isn’t valid or decreased if its valid just like in binary search. Check that all the elements of desired array are greater than or equal to input array in order to perform operations on the elements to make them equal to the desired elements. Find the count of operations. Find the minimum possible value of last element which satisfy the condition of all the elements in the desired array. 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 that return true if the// required array can be generated// with m as the last elementbool check(int m, int n, int arr[]){ // Build the desired array int desired[n]; for (int i = n - 1; i >= 0; i--) { desired[i] = m; m--; } // Check if the given array can // be converted to the desired array // with the given operation for (int i = 0; i < n; i++) { if (arr[i] > desired[i] || desired[i] < 1) { return false; } } return true;} // Function to return the minimum number// of operations required to convert the// given array to an increasing AP series// with common difference as 1int minOperations(int arr[], int n){ int start = (int)arr[n - 1]; int end = *(max_element(arr, arr + n)) + n; int max_arr = 0; // Apply Binary Search while (start <= end) { int mid = (start + end) / 2; // If array can be generated with // mid as the last element if (check(mid, n, arr)) { // Current ans is mid max_arr = mid; // Check whether the same can be // achieved with even less operations end = mid - 1; } else { start = mid + 1; } } // Build the desired array int desired[n]; for (int i = n - 1; i >= 0; i--) { desired[i] = max_arr; max_arr--; } // Calculate the number of // operations required int operations = 0; for (int i = 0; i < n; i++) { operations += (desired[i] - arr[i]); } // Return the number of // operations required return operations;} // Driver codeint main(){ int arr[] = { 4, 4, 5, 5, 7 }; int n = sizeof(arr) / sizeof(arr[0]); cout << minOperations(arr, n); return 0;} // Java implementation of the approachimport java.util.Arrays; class GFG{ // Function that return true if the // required array can be generated // with m as the last element static boolean check(int m, int n, int arr[]) { // Build the desired array int[] desired = new int[n]; for (int i = n - 1; i >= 0; i--) { desired[i] = m; m--; } // Check if the given array can // be converted to the desired array // with the given operation for (int i = 0; i < n; i++) { if (arr[i] > desired[i] || desired[i] < 1) { return false; } } return true; } // Function to return the minimum number // of operations required to convert the // given array to an increasing AP series // with common difference as 1 static int minOperations(int arr[], int n) { int start = (int) arr[n - 1]; int end = Arrays.stream(arr).max().getAsInt() + n; int max_arr = 0; // Apply Binary Search while (start <= end) { int mid = (start + end) / 2; // If array can be generated with // mid as the last element if (check(mid, n, arr)) { // Current ans is mid max_arr = mid; // Check whether the same can be // achieved with even less operations end = mid - 1; } else { start = mid + 1; } } // Build the desired array int[] desired = new int[n]; for (int i = n - 1; i >= 0; i--) { desired[i] = max_arr; max_arr--; } // Calculate the number of // operations required int operations = 0; for (int i = 0; i < n; i++) { operations += (desired[i] - arr[i]); } // Return the number of // operations required return operations; } // Driver code public static void main(String[] args) { int arr[] = {4, 4, 5, 5, 7}; int n = arr.length; System.out.println(minOperations(arr, n)); }} // This code is contributed by Princi Singh # Python3 implementation of the approach # Function that return true if the# required array can be generated# with m as the last elementdef check( m, n, arr) : # Build the desired array desired = [0]*n; for i in range(n-1,-1,-1) : desired[i] = m; m -= 1; # Check if the given array can # be converted to the desired array # with the given operation for i in range(n) : if (arr[i] > desired[i] or desired[i] < 1) : return False; return True # Function to return the minimum number# of operations required to convert the# given array to an increasing AP series# with common difference as 1def minOperations(arr, n) : start = arr[n - 1]; end = max(arr) + n; max_arr = 0; # Apply Binary Search while (start <= end) : mid = (start + end) // 2; # If array can be generated with # mid as the last element if (check(mid, n, arr)) : # Current ans is mid max_arr = mid; # Check whether the same can be # achieved with even less operations end = mid - 1; else : start = mid + 1; # Build the desired array desired = [0]* n; for i in range(n-1, -1,-1) : desired[i] = max_arr; max_arr -= 1; # Calculate the number of # operations required operations = 0; for i in range(n) : operations += (desired[i] - arr[i]); # Return the number of # operations required return operations; # Driver codeif __name__ == "__main__" : arr = [ 4, 4, 5, 5, 7 ]; n = len(arr); print(minOperations(arr, n)); # This code is contributed by AnkitRai01 // C# implementation of the approachusing System; using System.Linq; class GFG{ // Function that return true if the // required array can be generated // with m as the last element static Boolean check(int m, int n, int []arr) { // Build the desired array int[] desired = new int[n]; for (int i = n - 1; i >= 0; i--) { desired[i] = m; m--; } // Check if the given array can // be converted to the desired array // with the given operation for (int i = 0; i < n; i++) { if (arr[i] > desired[i] || desired[i] < 1) { return false; } } return true; } // Function to return the minimum number // of operations required to convert the // given array to an increasing AP series // with common difference as 1 static int minOperations(int []arr, int n) { int start = (int) arr[n - 1]; int end = arr.Max() + n; int max_arr = 0; // Apply Binary Search while (start <= end) { int mid = (start + end) / 2; // If array can be generated with // mid as the last element if (check(mid, n, arr)) { // Current ans is mid max_arr = mid; // Check whether the same can be // achieved with even less operations end = mid - 1; } else { start = mid + 1; } } // Build the desired array int[] desired = new int[n]; for (int i = n - 1; i >= 0; i--) { desired[i] = max_arr; max_arr--; } // Calculate the number of // operations required int operations = 0; for (int i = 0; i < n; i++) { operations += (desired[i] - arr[i]); } // Return the number of // operations required return operations; } // Driver code public static void Main(String[] args) { int []arr = {4, 4, 5, 5, 7}; int n = arr.Length; Console.WriteLine(minOperations(arr, n)); }} // This code contributed by Rajput-Ji <script> // Javascript implementation of the approach // Function that return true if the// required array can be generated// with m as the last elementfunction check(m, n, arr){ // Build the desired array var desired = Array(n); for (var i = n - 1; i >= 0; i--) { desired[i] = m; m--; } // Check if the given array can // be converted to the desired array // with the given operation for (var i = 0; i < n; i++) { if (arr[i] > desired[i] || desired[i] < 1) { return false; } } return true;} // Function to return the minimum number// of operations required to convert the// given array to an increasing AP series// with common difference as 1function minOperations(arr, n){ var start = arr[n - 1]; var end = arr.reduce((a,b)=> Math.max(a,b)) + n; var max_arr = 0; // Apply Binary Search while (start <= end) { var mid = parseInt((start + end) / 2); // If array can be generated with // mid as the last element if (check(mid, n, arr)) { // Current ans is mid max_arr = mid; // Check whether the same can be // achieved with even less operations end = mid - 1; } else { start = mid + 1; } } // Build the desired array var desired = Array(n); for (var i = n - 1; i >= 0; i--) { desired[i] = max_arr; max_arr--; } // Calculate the number of // operations required var operations = 0; for (var i = 0; i < n; i++) { operations += (desired[i] - arr[i]); } // Return the number of // operations required return operations;} // Driver codevar arr = [4, 4, 5, 5, 7 ];var n = arr.length;document.write( minOperations(arr, n)); </script> 5 ankthon princi singh Rajput-Ji noob2000 arithmetic progression Binary Search Arrays Searching Arrays Searching Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Chocolate Distribution Problem Count pairs with given sum Window Sliding Technique Reversal algorithm for array rotation Next Greater Element Binary Search Median of two sorted arrays of different sizes Find the index of an array element in Java Two Pointers Technique Count number of occurrences (or frequency) in a sorted array
[ { "code": null, "e": 26041, "s": 26013, "text": "\n14 May, 2021" }, { "code": null, "e": 26311, "s": 26041, "text": "Given an array arr[] with N elements, the task is to find the minimum number of operations required so that an Arithmetic Progression with the array elements is achieved with common difference as 1. In a single operation, any element can be incremented by 1.Examples: " }, { "code": null, "e": 26563, "s": 26311, "text": "Input: arr[] = {4, 4, 5, 5, 7} Output: 5 Desired array is {4, 5, 6, 7, 8} which can be achieved in minimum possible operations.Input: arr[] = {11, 2, 5, 6} Output: 26 Since we are allowed to do only increment, we change the array to {11, 12, 13, 14} " }, { "code": null, "e": 26577, "s": 26565, "text": "Approach: " }, { "code": null, "e": 26629, "s": 26577, "text": "We can utilize Binary Search to solve this problem." }, { "code": null, "e": 26791, "s": 26629, "text": "We will built the desired array with fixed last element which will be increased if the solution isn’t valid or decreased if its valid just like in binary search." }, { "code": null, "e": 26998, "s": 26791, "text": "Check that all the elements of desired array are greater than or equal to input array in order to perform operations on the elements to make them equal to the desired elements. Find the count of operations." }, { "code": null, "e": 27116, "s": 26998, "text": "Find the minimum possible value of last element which satisfy the condition of all the elements in the desired array." }, { "code": null, "e": 27169, "s": 27116, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27173, "s": 27169, "text": "C++" }, { "code": null, "e": 27178, "s": 27173, "text": "Java" }, { "code": null, "e": 27186, "s": 27178, "text": "Python3" }, { "code": null, "e": 27189, "s": 27186, "text": "C#" }, { "code": null, "e": 27200, "s": 27189, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that return true if the// required array can be generated// with m as the last elementbool check(int m, int n, int arr[]){ // Build the desired array int desired[n]; for (int i = n - 1; i >= 0; i--) { desired[i] = m; m--; } // Check if the given array can // be converted to the desired array // with the given operation for (int i = 0; i < n; i++) { if (arr[i] > desired[i] || desired[i] < 1) { return false; } } return true;} // Function to return the minimum number// of operations required to convert the// given array to an increasing AP series// with common difference as 1int minOperations(int arr[], int n){ int start = (int)arr[n - 1]; int end = *(max_element(arr, arr + n)) + n; int max_arr = 0; // Apply Binary Search while (start <= end) { int mid = (start + end) / 2; // If array can be generated with // mid as the last element if (check(mid, n, arr)) { // Current ans is mid max_arr = mid; // Check whether the same can be // achieved with even less operations end = mid - 1; } else { start = mid + 1; } } // Build the desired array int desired[n]; for (int i = n - 1; i >= 0; i--) { desired[i] = max_arr; max_arr--; } // Calculate the number of // operations required int operations = 0; for (int i = 0; i < n; i++) { operations += (desired[i] - arr[i]); } // Return the number of // operations required return operations;} // Driver codeint main(){ int arr[] = { 4, 4, 5, 5, 7 }; int n = sizeof(arr) / sizeof(arr[0]); cout << minOperations(arr, n); return 0;}", "e": 29053, "s": 27200, "text": null }, { "code": "// Java implementation of the approachimport java.util.Arrays; class GFG{ // Function that return true if the // required array can be generated // with m as the last element static boolean check(int m, int n, int arr[]) { // Build the desired array int[] desired = new int[n]; for (int i = n - 1; i >= 0; i--) { desired[i] = m; m--; } // Check if the given array can // be converted to the desired array // with the given operation for (int i = 0; i < n; i++) { if (arr[i] > desired[i] || desired[i] < 1) { return false; } } return true; } // Function to return the minimum number // of operations required to convert the // given array to an increasing AP series // with common difference as 1 static int minOperations(int arr[], int n) { int start = (int) arr[n - 1]; int end = Arrays.stream(arr).max().getAsInt() + n; int max_arr = 0; // Apply Binary Search while (start <= end) { int mid = (start + end) / 2; // If array can be generated with // mid as the last element if (check(mid, n, arr)) { // Current ans is mid max_arr = mid; // Check whether the same can be // achieved with even less operations end = mid - 1; } else { start = mid + 1; } } // Build the desired array int[] desired = new int[n]; for (int i = n - 1; i >= 0; i--) { desired[i] = max_arr; max_arr--; } // Calculate the number of // operations required int operations = 0; for (int i = 0; i < n; i++) { operations += (desired[i] - arr[i]); } // Return the number of // operations required return operations; } // Driver code public static void main(String[] args) { int arr[] = {4, 4, 5, 5, 7}; int n = arr.length; System.out.println(minOperations(arr, n)); }} // This code is contributed by Princi Singh", "e": 31342, "s": 29053, "text": null }, { "code": "# Python3 implementation of the approach # Function that return true if the# required array can be generated# with m as the last elementdef check( m, n, arr) : # Build the desired array desired = [0]*n; for i in range(n-1,-1,-1) : desired[i] = m; m -= 1; # Check if the given array can # be converted to the desired array # with the given operation for i in range(n) : if (arr[i] > desired[i] or desired[i] < 1) : return False; return True # Function to return the minimum number# of operations required to convert the# given array to an increasing AP series# with common difference as 1def minOperations(arr, n) : start = arr[n - 1]; end = max(arr) + n; max_arr = 0; # Apply Binary Search while (start <= end) : mid = (start + end) // 2; # If array can be generated with # mid as the last element if (check(mid, n, arr)) : # Current ans is mid max_arr = mid; # Check whether the same can be # achieved with even less operations end = mid - 1; else : start = mid + 1; # Build the desired array desired = [0]* n; for i in range(n-1, -1,-1) : desired[i] = max_arr; max_arr -= 1; # Calculate the number of # operations required operations = 0; for i in range(n) : operations += (desired[i] - arr[i]); # Return the number of # operations required return operations; # Driver codeif __name__ == \"__main__\" : arr = [ 4, 4, 5, 5, 7 ]; n = len(arr); print(minOperations(arr, n)); # This code is contributed by AnkitRai01", "e": 33033, "s": 31342, "text": null }, { "code": "// C# implementation of the approachusing System; using System.Linq; class GFG{ // Function that return true if the // required array can be generated // with m as the last element static Boolean check(int m, int n, int []arr) { // Build the desired array int[] desired = new int[n]; for (int i = n - 1; i >= 0; i--) { desired[i] = m; m--; } // Check if the given array can // be converted to the desired array // with the given operation for (int i = 0; i < n; i++) { if (arr[i] > desired[i] || desired[i] < 1) { return false; } } return true; } // Function to return the minimum number // of operations required to convert the // given array to an increasing AP series // with common difference as 1 static int minOperations(int []arr, int n) { int start = (int) arr[n - 1]; int end = arr.Max() + n; int max_arr = 0; // Apply Binary Search while (start <= end) { int mid = (start + end) / 2; // If array can be generated with // mid as the last element if (check(mid, n, arr)) { // Current ans is mid max_arr = mid; // Check whether the same can be // achieved with even less operations end = mid - 1; } else { start = mid + 1; } } // Build the desired array int[] desired = new int[n]; for (int i = n - 1; i >= 0; i--) { desired[i] = max_arr; max_arr--; } // Calculate the number of // operations required int operations = 0; for (int i = 0; i < n; i++) { operations += (desired[i] - arr[i]); } // Return the number of // operations required return operations; } // Driver code public static void Main(String[] args) { int []arr = {4, 4, 5, 5, 7}; int n = arr.Length; Console.WriteLine(minOperations(arr, n)); }} // This code contributed by Rajput-Ji", "e": 35298, "s": 33033, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function that return true if the// required array can be generated// with m as the last elementfunction check(m, n, arr){ // Build the desired array var desired = Array(n); for (var i = n - 1; i >= 0; i--) { desired[i] = m; m--; } // Check if the given array can // be converted to the desired array // with the given operation for (var i = 0; i < n; i++) { if (arr[i] > desired[i] || desired[i] < 1) { return false; } } return true;} // Function to return the minimum number// of operations required to convert the// given array to an increasing AP series// with common difference as 1function minOperations(arr, n){ var start = arr[n - 1]; var end = arr.reduce((a,b)=> Math.max(a,b)) + n; var max_arr = 0; // Apply Binary Search while (start <= end) { var mid = parseInt((start + end) / 2); // If array can be generated with // mid as the last element if (check(mid, n, arr)) { // Current ans is mid max_arr = mid; // Check whether the same can be // achieved with even less operations end = mid - 1; } else { start = mid + 1; } } // Build the desired array var desired = Array(n); for (var i = n - 1; i >= 0; i--) { desired[i] = max_arr; max_arr--; } // Calculate the number of // operations required var operations = 0; for (var i = 0; i < n; i++) { operations += (desired[i] - arr[i]); } // Return the number of // operations required return operations;} // Driver codevar arr = [4, 4, 5, 5, 7 ];var n = arr.length;document.write( minOperations(arr, n)); </script>", "e": 37094, "s": 35298, "text": null }, { "code": null, "e": 37096, "s": 37094, "text": "5" }, { "code": null, "e": 37106, "s": 37098, "text": "ankthon" }, { "code": null, "e": 37119, "s": 37106, "text": "princi singh" }, { "code": null, "e": 37129, "s": 37119, "text": "Rajput-Ji" }, { "code": null, "e": 37138, "s": 37129, "text": "noob2000" }, { "code": null, "e": 37161, "s": 37138, "text": "arithmetic progression" }, { "code": null, "e": 37175, "s": 37161, "text": "Binary Search" }, { "code": null, "e": 37182, "s": 37175, "text": "Arrays" }, { "code": null, "e": 37192, "s": 37182, "text": "Searching" }, { "code": null, "e": 37199, "s": 37192, "text": "Arrays" }, { "code": null, "e": 37209, "s": 37199, "text": "Searching" }, { "code": null, "e": 37223, "s": 37209, "text": "Binary Search" }, { "code": null, "e": 37321, "s": 37223, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37352, "s": 37321, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 37379, "s": 37352, "text": "Count pairs with given sum" }, { "code": null, "e": 37404, "s": 37379, "text": "Window Sliding Technique" }, { "code": null, "e": 37442, "s": 37404, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 37463, "s": 37442, "text": "Next Greater Element" }, { "code": null, "e": 37477, "s": 37463, "text": "Binary Search" }, { "code": null, "e": 37524, "s": 37477, "text": "Median of two sorted arrays of different sizes" }, { "code": null, "e": 37567, "s": 37524, "text": "Find the index of an array element in Java" }, { "code": null, "e": 37590, "s": 37567, "text": "Two Pointers Technique" } ]
Inverted Page Table in Operating System - GeeksforGeeks
19 Apr, 2022 Prerequisite – Paging, Page table entries, Segmentation Most of the Operating Systems implement a separate pagetable for each process, i.e. for ‘n’ number of processes running on a Multiprocessing/ Timesharing operating system, there are ‘n’ number of pagetables stored in the memory. Sometimes when a process is very large in size and it occupies virtual memory then with the size of the process, it’s pagetable size also increases substantially. Example: A process of size 2 GB with: Page size = 512 Bytes Size of page table entry = 4 Bytes, then Number of pages in the process = 2 GB / 512 B = 222 PageTable Size = 222 * 22 = 224 bytes Through this example, it can be concluded that for multiple processes running simultaneously in an OS, a considerable part of memory is occupied by page tables only. Operating Systems also incorporate multilevel paging schemes which further increase the space required for storing the page tables and a large amount of memory is invested in storing them. The amount of memory occupied by the page tables can turn out to be a huge overhead and is always unacceptable as main memory is always a scarce resource. Various efforts are made to utilize the memory efficiently and to maintain a good balance in the level of multiprogramming and efficient CPU utilization. Inverted Page Table – An alternate approach is to use the Inverted Page Table structure that consists of one-page table entry for every frame of the main memory. So the number of page table entries in the Inverted Page Table reduces to the number of frames in physical memory and a single page table is used to represent the paging information of all the processes. Through the inverted page table, the overhead of storing an individual page table for every process gets eliminated and only a fixed portion of memory is required to store the paging information of all the processes together. This technique is called as inverted paging as the indexing is done with respect to the frame number instead of the logical page number. Each entry in the page table contains the following fields. Page number – It specifies the page number range of the logical address. Process id – An inverted page table contains the address space information of all the processes in execution. Since two different processes can have similar set of virtual addresses, it becomes necessary in Inverted Page Table to store a process Id of each process to identify it’s address space uniquely. This is done by using the combination of PId and Page Number. So this Process Id acts as an address space identifier and ensures that a virtual page for a particular process is mapped correctly to the corresponding physical frame. Control bits – These bits are used to store extra paging-related information. These include the valid bit, dirty bit, reference bits, protection and locking information bits. Chained pointer – It may be possible sometime that two or more processes share a part of main memory. In this case, two or more logical pages map to same Page Table Entry then a chaining pointer is used to map the details of these logical pages to the root page table. Working – The operation of an inverted page table is shown below. The virtual address generated by the CPU contains the fields and each page table entry contains the other relevant information required in paging related mechanism. When a memory reference takes place, this virtual address is matched by the Memory-Mapping unit(MMU), the Inverted Page table is searched and the corresponding frame number is obtained. If the match is found at the ith entry then the physical address of the process is sent as the real address otherwise if no match is found then Segmentation Fault is generated. Note: Number of Entries in Inverted page table = Number of frames in Physical address Space(PAS). Examples – The Inverted Page table and its variations are implemented in various systems like PowerPC, UltraSPARC, and the IA-64 architecture. An implementation of the Mach operating system on the RT-PC also uses this technique. Advantages and Disadvantages: Reduced memory space – Inverted Pagetables typically reduce the amount of memory required to store the page tables to a size bound of physical memory. The maximum number of entries could be the number of page frames in the physical memory. Longer lookup time – Inverted Page tables are sorted in order of frame number but the memory look-up takes place with respect to the virtual address, so, it usually takes a longer time to find the appropriate entry but often these page tables are implemented using hash data structures for a faster lookup. Difficult shared memory implementation – As the Inverted Page Table stores a single entry for each frame, it becomes difficult to implement the shared memory in the page tables. Chaining techniques are used to map more than one virtual address to the entry specified in order of frame number. VaibhavRai3 jash28582 GATE CS Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Layers of OSI Model ACID Properties in DBMS TCP/IP Model Normal Forms in DBMS Differences between TCP and UDP Cache Memory in Computer Organization LRU Cache Implementation Memory Management in Operating System 'crontab' in Linux with Examples Difference between Internal and External fragmentation
[ { "code": null, "e": 29429, "s": 29401, "text": "\n19 Apr, 2022" }, { "code": null, "e": 29877, "s": 29429, "text": "Prerequisite – Paging, Page table entries, Segmentation Most of the Operating Systems implement a separate pagetable for each process, i.e. for ‘n’ number of processes running on a Multiprocessing/ Timesharing operating system, there are ‘n’ number of pagetables stored in the memory. Sometimes when a process is very large in size and it occupies virtual memory then with the size of the process, it’s pagetable size also increases substantially." }, { "code": null, "e": 30068, "s": 29877, "text": "Example: A process of size 2 GB with:\nPage size = 512 Bytes\nSize of page table entry = 4 Bytes, then\nNumber of pages in the process = 2 GB / 512 B = 222\nPageTable Size = 222 * 22 = 224 bytes" }, { "code": null, "e": 30733, "s": 30068, "text": "Through this example, it can be concluded that for multiple processes running simultaneously in an OS, a considerable part of memory is occupied by page tables only. Operating Systems also incorporate multilevel paging schemes which further increase the space required for storing the page tables and a large amount of memory is invested in storing them. The amount of memory occupied by the page tables can turn out to be a huge overhead and is always unacceptable as main memory is always a scarce resource. Various efforts are made to utilize the memory efficiently and to maintain a good balance in the level of multiprogramming and efficient CPU utilization. " }, { "code": null, "e": 31522, "s": 30733, "text": "Inverted Page Table – An alternate approach is to use the Inverted Page Table structure that consists of one-page table entry for every frame of the main memory. So the number of page table entries in the Inverted Page Table reduces to the number of frames in physical memory and a single page table is used to represent the paging information of all the processes. Through the inverted page table, the overhead of storing an individual page table for every process gets eliminated and only a fixed portion of memory is required to store the paging information of all the processes together. This technique is called as inverted paging as the indexing is done with respect to the frame number instead of the logical page number. Each entry in the page table contains the following fields." }, { "code": null, "e": 31595, "s": 31522, "text": "Page number – It specifies the page number range of the logical address." }, { "code": null, "e": 32132, "s": 31595, "text": "Process id – An inverted page table contains the address space information of all the processes in execution. Since two different processes can have similar set of virtual addresses, it becomes necessary in Inverted Page Table to store a process Id of each process to identify it’s address space uniquely. This is done by using the combination of PId and Page Number. So this Process Id acts as an address space identifier and ensures that a virtual page for a particular process is mapped correctly to the corresponding physical frame." }, { "code": null, "e": 32307, "s": 32132, "text": "Control bits – These bits are used to store extra paging-related information. These include the valid bit, dirty bit, reference bits, protection and locking information bits." }, { "code": null, "e": 32576, "s": 32307, "text": "Chained pointer – It may be possible sometime that two or more processes share a part of main memory. In this case, two or more logical pages map to same Page Table Entry then a chaining pointer is used to map the details of these logical pages to the root page table." }, { "code": null, "e": 33269, "s": 32576, "text": "Working – The operation of an inverted page table is shown below. The virtual address generated by the CPU contains the fields and each page table entry contains the other relevant information required in paging related mechanism. When a memory reference takes place, this virtual address is matched by the Memory-Mapping unit(MMU), the Inverted Page table is searched and the corresponding frame number is obtained. If the match is found at the ith entry then the physical address of the process is sent as the real address otherwise if no match is found then Segmentation Fault is generated. Note: Number of Entries in Inverted page table = Number of frames in Physical address Space(PAS)." }, { "code": null, "e": 33499, "s": 33269, "text": "Examples – The Inverted Page table and its variations are implemented in various systems like PowerPC, UltraSPARC, and the IA-64 architecture. An implementation of the Mach operating system on the RT-PC also uses this technique. " }, { "code": null, "e": 33529, "s": 33499, "text": "Advantages and Disadvantages:" }, { "code": null, "e": 33769, "s": 33529, "text": "Reduced memory space – Inverted Pagetables typically reduce the amount of memory required to store the page tables to a size bound of physical memory. The maximum number of entries could be the number of page frames in the physical memory." }, { "code": null, "e": 34076, "s": 33769, "text": "Longer lookup time – Inverted Page tables are sorted in order of frame number but the memory look-up takes place with respect to the virtual address, so, it usually takes a longer time to find the appropriate entry but often these page tables are implemented using hash data structures for a faster lookup." }, { "code": null, "e": 34369, "s": 34076, "text": "Difficult shared memory implementation – As the Inverted Page Table stores a single entry for each frame, it becomes difficult to implement the shared memory in the page tables. Chaining techniques are used to map more than one virtual address to the entry specified in order of frame number." }, { "code": null, "e": 34381, "s": 34369, "text": "VaibhavRai3" }, { "code": null, "e": 34391, "s": 34381, "text": "jash28582" }, { "code": null, "e": 34399, "s": 34391, "text": "GATE CS" }, { "code": null, "e": 34417, "s": 34399, "text": "Operating Systems" }, { "code": null, "e": 34435, "s": 34417, "text": "Operating Systems" }, { "code": null, "e": 34533, "s": 34435, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34553, "s": 34533, "text": "Layers of OSI Model" }, { "code": null, "e": 34577, "s": 34553, "text": "ACID Properties in DBMS" }, { "code": null, "e": 34590, "s": 34577, "text": "TCP/IP Model" }, { "code": null, "e": 34611, "s": 34590, "text": "Normal Forms in DBMS" }, { "code": null, "e": 34643, "s": 34611, "text": "Differences between TCP and UDP" }, { "code": null, "e": 34681, "s": 34643, "text": "Cache Memory in Computer Organization" }, { "code": null, "e": 34706, "s": 34681, "text": "LRU Cache Implementation" }, { "code": null, "e": 34744, "s": 34706, "text": "Memory Management in Operating System" }, { "code": null, "e": 34777, "s": 34744, "text": "'crontab' in Linux with Examples" } ]
Angular PrimeNG TabView Component - GeeksforGeeks
11 Sep, 2021 Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the TabView component in Angular PrimeNG. We will also learn about the properties, events, styling along with their syntaxes that will be used in the code. TabView Component: It is used to display content in the form of tabs. Properties of TabView: activeIndex: It specifies the index of the active tab to change the selected tab programmatically. It accepts the number data type & the default value is null. controlClose: It is used to specify whether the tab close is controlled at the onClose event or not. It is of boolean data type & the default value is false. style: It is the inline style of the component. It is of string data type & the default value is null. styleClass: It is the style class of the component. It is of string data type & the default value is null. Properties of TabPanel: header: It specifies the title of the tabPanel. It is of string data type & the default value is null. selected: It defines if the tab is active. It is of boolean data type & the default value is false. disabled: It specifies tab cannot be activated when its value is true. It is of boolean data type & the default value is false. closable: It defines if the tab can be removed. It is of boolean data type & the default value is false. headerStyle: It is an inline style of the tab header. It is of string data type & the default value is null. headerStyleClass: It specifies the style class of the tab header. It is of string data type & the default value is null. cache: It specifies whether a lazy loaded panel should avoid getting loaded again on reselection. It is of boolean data type & the default value is true. tooltip: It specifies the advisory information to display in a tooltip on hover. It accepts any data type & the default value is null. tooltipStyleClass: It specifies the style class of the tooltip. It is of string data type & the default value is null. tooltipPosition: It specifies the position of the tooltip, valid values are right, left, top and bottom. It is of string data type & the default value is top. tooltipPositionStyle: It specifies the type of CSS position. It is of string data type & the default value is absolute Events: onChange: It is a callback that is fired on tab change. onClose: It is a callback that is fired on tab close. Styling: p-tabview: It is the container element p-tabview-nav: It is the container of headers. p-tabview-selected: It is the selected tab header. p-tabview-panels: It is the container panels. p-tabview-panel: It is the content of a tab. Creating Angular application & module installation: Step 1: Create an Angular application using the following command. ng new appname Step 2: After creating your project folder i.e. appname, move to it using the following command. cd appname Step 3: Install PrimeNG in your given directory. npm install primeng --save npm install primeicons --save Project Structure: It will look like the following: Example 1: This is the basic example that illustrates how to use the TabView component. app.component.html <h2>GeeksforGeeks</h2><h5>PrimeNG TabView Component</h5><p-tabView> <p-tabPanel header="TabView Component"> <p>Content1</p> </p-tabPanel> <p-tabPanel header="TabView Component"> <p>Content2</p> </p-tabPanel> <p-tabPanel header="TabView Component"> <p>Content3</p> </p-tabPanel></p-tabView> app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.scss']})export class AppComponent {} app.module.ts import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser";import { BrowserAnimationsModule } from "@angular/platform-browser/animations"; import { AppComponent } from "./app.component";import { TabViewModule } from "primeng/tabview"; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, TabViewModule], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {} Output: Example 2: In this example, we will know how to use closable property in the Tabview component. app.component.html <h2>GeeksforGeeks</h2><h5>PrimeNG TabView Component</h5><p-tabView > <p-tabPanel header="TabView Component" closable='true'> <p>Content1</p> </p-tabPanel> <p-tabPanel header="TabView Component" closable='true'> <p>Content2</p> </p-tabPanel> <p-tabPanel header="TabView Component" closable='true'> <p>Content3</p> </p-tabPanel></p-tabView> app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.scss']})export class AppComponent {} app.module.ts import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser";import { BrowserAnimationsModule } from "@angular/platform-browser/animations"; import { AppComponent } from "./app.component";import { TabViewModule } from "primeng/tabview"; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, TabViewModule], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {} Output: Reference: https://primefaces.org/primeng/showcase/#/tabview Angular-PrimeNG AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular PrimeNG Dropdown Component Angular PrimeNG Calendar Component Angular 10 (blur) Event Angular PrimeNG Messages Component How to make a Bootstrap Modal Popup in Angular 9/8 ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26380, "s": 26352, "text": "\n11 Sep, 2021" }, { "code": null, "e": 26779, "s": 26380, "text": "Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the TabView component in Angular PrimeNG. We will also learn about the properties, events, styling along with their syntaxes that will be used in the code. " }, { "code": null, "e": 26850, "s": 26779, "text": "TabView Component: It is used to display content in the form of tabs. " }, { "code": null, "e": 26873, "s": 26850, "text": "Properties of TabView:" }, { "code": null, "e": 27033, "s": 26873, "text": "activeIndex: It specifies the index of the active tab to change the selected tab programmatically. It accepts the number data type & the default value is null." }, { "code": null, "e": 27191, "s": 27033, "text": "controlClose: It is used to specify whether the tab close is controlled at the onClose event or not. It is of boolean data type & the default value is false." }, { "code": null, "e": 27294, "s": 27191, "text": "style: It is the inline style of the component. It is of string data type & the default value is null." }, { "code": null, "e": 27401, "s": 27294, "text": "styleClass: It is the style class of the component. It is of string data type & the default value is null." }, { "code": null, "e": 27425, "s": 27401, "text": "Properties of TabPanel:" }, { "code": null, "e": 27528, "s": 27425, "text": "header: It specifies the title of the tabPanel. It is of string data type & the default value is null." }, { "code": null, "e": 27628, "s": 27528, "text": "selected: It defines if the tab is active. It is of boolean data type & the default value is false." }, { "code": null, "e": 27756, "s": 27628, "text": "disabled: It specifies tab cannot be activated when its value is true. It is of boolean data type & the default value is false." }, { "code": null, "e": 27862, "s": 27756, "text": "closable: It defines if the tab can be removed. It is of boolean data type & the default value is false." }, { "code": null, "e": 27971, "s": 27862, "text": "headerStyle: It is an inline style of the tab header. It is of string data type & the default value is null." }, { "code": null, "e": 28092, "s": 27971, "text": "headerStyleClass: It specifies the style class of the tab header. It is of string data type & the default value is null." }, { "code": null, "e": 28246, "s": 28092, "text": "cache: It specifies whether a lazy loaded panel should avoid getting loaded again on reselection. It is of boolean data type & the default value is true." }, { "code": null, "e": 28381, "s": 28246, "text": "tooltip: It specifies the advisory information to display in a tooltip on hover. It accepts any data type & the default value is null." }, { "code": null, "e": 28500, "s": 28381, "text": "tooltipStyleClass: It specifies the style class of the tooltip. It is of string data type & the default value is null." }, { "code": null, "e": 28659, "s": 28500, "text": "tooltipPosition: It specifies the position of the tooltip, valid values are right, left, top and bottom. It is of string data type & the default value is top." }, { "code": null, "e": 28778, "s": 28659, "text": "tooltipPositionStyle: It specifies the type of CSS position. It is of string data type & the default value is absolute" }, { "code": null, "e": 28788, "s": 28780, "text": "Events:" }, { "code": null, "e": 28844, "s": 28788, "text": "onChange: It is a callback that is fired on tab change." }, { "code": null, "e": 28898, "s": 28844, "text": "onClose: It is a callback that is fired on tab close." }, { "code": null, "e": 28907, "s": 28898, "text": "Styling:" }, { "code": null, "e": 28946, "s": 28907, "text": "p-tabview: It is the container element" }, { "code": null, "e": 28993, "s": 28946, "text": "p-tabview-nav: It is the container of headers." }, { "code": null, "e": 29044, "s": 28993, "text": "p-tabview-selected: It is the selected tab header." }, { "code": null, "e": 29090, "s": 29044, "text": "p-tabview-panels: It is the container panels." }, { "code": null, "e": 29135, "s": 29090, "text": "p-tabview-panel: It is the content of a tab." }, { "code": null, "e": 29187, "s": 29135, "text": "Creating Angular application & module installation:" }, { "code": null, "e": 29254, "s": 29187, "text": "Step 1: Create an Angular application using the following command." }, { "code": null, "e": 29269, "s": 29254, "text": "ng new appname" }, { "code": null, "e": 29366, "s": 29269, "text": "Step 2: After creating your project folder i.e. appname, move to it using the following command." }, { "code": null, "e": 29377, "s": 29366, "text": "cd appname" }, { "code": null, "e": 29426, "s": 29377, "text": "Step 3: Install PrimeNG in your given directory." }, { "code": null, "e": 29483, "s": 29426, "text": "npm install primeng --save\nnpm install primeicons --save" }, { "code": null, "e": 29535, "s": 29483, "text": "Project Structure: It will look like the following:" }, { "code": null, "e": 29623, "s": 29535, "text": "Example 1: This is the basic example that illustrates how to use the TabView component." }, { "code": null, "e": 29642, "s": 29623, "text": "app.component.html" }, { "code": "<h2>GeeksforGeeks</h2><h5>PrimeNG TabView Component</h5><p-tabView> <p-tabPanel header=\"TabView Component\"> <p>Content1</p> </p-tabPanel> <p-tabPanel header=\"TabView Component\"> <p>Content2</p> </p-tabPanel> <p-tabPanel header=\"TabView Component\"> <p>Content3</p> </p-tabPanel></p-tabView>", "e": 29947, "s": 29642, "text": null }, { "code": null, "e": 29966, "s": 29949, "text": "app.component.ts" }, { "code": "import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.scss']})export class AppComponent {}", "e": 30149, "s": 29966, "text": null }, { "code": null, "e": 30163, "s": 30149, "text": "app.module.ts" }, { "code": "import { NgModule } from \"@angular/core\";import { BrowserModule } from \"@angular/platform-browser\";import { BrowserAnimationsModule } from \"@angular/platform-browser/animations\"; import { AppComponent } from \"./app.component\";import { TabViewModule } from \"primeng/tabview\"; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, TabViewModule], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}", "e": 30635, "s": 30163, "text": null }, { "code": null, "e": 30643, "s": 30635, "text": "Output:" }, { "code": null, "e": 30739, "s": 30643, "text": "Example 2: In this example, we will know how to use closable property in the Tabview component." }, { "code": null, "e": 30758, "s": 30739, "text": "app.component.html" }, { "code": "<h2>GeeksforGeeks</h2><h5>PrimeNG TabView Component</h5><p-tabView > <p-tabPanel header=\"TabView Component\" closable='true'> <p>Content1</p> </p-tabPanel> <p-tabPanel header=\"TabView Component\" closable='true'> <p>Content2</p> </p-tabPanel> <p-tabPanel header=\"TabView Component\" closable='true'> <p>Content3</p> </p-tabPanel></p-tabView>", "e": 31136, "s": 30758, "text": null }, { "code": null, "e": 31153, "s": 31136, "text": "app.component.ts" }, { "code": "import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.scss']})export class AppComponent {}", "e": 31336, "s": 31153, "text": null }, { "code": null, "e": 31350, "s": 31336, "text": "app.module.ts" }, { "code": "import { NgModule } from \"@angular/core\";import { BrowserModule } from \"@angular/platform-browser\";import { BrowserAnimationsModule } from \"@angular/platform-browser/animations\"; import { AppComponent } from \"./app.component\";import { TabViewModule } from \"primeng/tabview\"; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, TabViewModule], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}", "e": 31822, "s": 31350, "text": null }, { "code": null, "e": 31830, "s": 31822, "text": "Output:" }, { "code": null, "e": 31891, "s": 31830, "text": "Reference: https://primefaces.org/primeng/showcase/#/tabview" }, { "code": null, "e": 31907, "s": 31891, "text": "Angular-PrimeNG" }, { "code": null, "e": 31917, "s": 31907, "text": "AngularJS" }, { "code": null, "e": 31934, "s": 31917, "text": "Web Technologies" }, { "code": null, "e": 32032, "s": 31934, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32067, "s": 32032, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 32102, "s": 32067, "text": "Angular PrimeNG Calendar Component" }, { "code": null, "e": 32126, "s": 32102, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 32161, "s": 32126, "text": "Angular PrimeNG Messages Component" }, { "code": null, "e": 32214, "s": 32161, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 32254, "s": 32214, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 32287, "s": 32254, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 32332, "s": 32287, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 32375, "s": 32332, "text": "How to fetch data from an API in ReactJS ?" } ]
time.h header file in C with Examples - GeeksforGeeks
08 Jul, 2021 The time.h header file contains definitions of functions to get and manipulate date and time information. It describes three time-related data types. clock_t: clock_t represents the date as an integer which is a part of the calendar time. time_t: time_t represents the clock time as an integer which is a part of the calendar time. struct tm: struct tm holds the date and time which contains: clock_t: clock_t represents the date as an integer which is a part of the calendar time. time_t: time_t represents the clock time as an integer which is a part of the calendar time. struct tm: struct tm holds the date and time which contains: clock_t: clock_t represents the date as an integer which is a part of the calendar time. time_t: time_t represents the clock time as an integer which is a part of the calendar time. struct tm: struct tm holds the date and time which contains: C struct tm { // seconds, range 0 to 59 int tm_sec; // minutes, range 0 to 59 int tm_min; // hours, range 0 to 23 int tm_hour; // day of the month, range 1 to 31 int tm_mday; // month, range 0 to 11 int tm_mon; // The number of years since 1900 int tm_year; // day of the week, range 0 to 6 int tm_wday; // day in the year, range 0 to 365 int tm_yday; // daylight saving time int tm_isdst;} It also contains CLOCKS_PER_SEC macro which holds the number of times does the system clock ticks per second. Pre-defined functions in time.h Examples: Program to print the date and time of the system. Program to print the date and time of the system. Program to print the date and time of the system. C #include <stdio.h>#include <time.h>int main(void){ struct tm* ptr; time_t t; t = time(NULL); ptr = localtime(&t); printf("%s", asctime(ptr)); return 0;} Tue Aug 6 09:00:29 2019 2. Program to print UTC (Coordinated Universal Time) of the system. C #include <stdio.h>#include <time.h>int main(void){ struct tm* ptr; time_t t; t = time(NULL); ptr = gmtime(&t); printf("%s", asctime(ptr)); return 0;} Tue Aug 6 09:00:31 2019 3. Program to calculate the time taken to add two numbers program. Note: If user gives input slowly that time also add up for total execution time. C #include <stdio.h>#include <time.h>int main(void){ time_t start, end; start = time(NULL); int a, b; scanf("%d %d", &a, &b); printf("Sum of %d and %d is %d\n", a, b, a + b); end = time(NULL); printf("Time taken to print sum is %.2f seconds", difftime(end, start));} Sum of 4196144 and 0 is 4196144 Time taken to print sum is 0.00 seconds 4. Program to find the clock ticks. C #include <math.h>#include <stdio.h>#include <time.h> int frequency_of_primes(int n){ // This function checks the number of // primes less than the given parameter int i, j; int freq = n - 1; for (i = 2; i <= n; ++i) for (j = sqrt(i); j > 1; --j) if (i % j == 0) { --freq; break; } return freq;} int main(){ clock_t t; int f; t = clock(); f = frequency_of_primes(9999); printf("The number of primes lower" " than 10, 000 is: %d\n", f); t = clock() - t; printf("No. of clicks %ld clicks (%f seconds).\n", t, ((float)t) / CLOCKS_PER_SEC); return 0;} The number of primes lower than 10, 000 is: 1229 No. of clicks 2837 clicks (0.002837 seconds). 5. Program to print time as hour: minute returned by asctime() file. C #include <stdio.h>#include <time.h>int main(){ time_t rawtime; struct tm* timeinfo; // Used to store the time // returned by localetime() function char buffer[80]; time(&rawtime); timeinfo = localtime(&rawtime); strftime(buffer, 80, "Time is %I:%M%p.", timeinfo); // strftime() function stores the // current time as Hours : Minutes //%I %M and %p-> format specifier // of Hours minutes and am/pm respectively*/ // prints the formatted time puts(buffer); return 0;} Time is 09:00AM. avsadityavardhan ganeshanvishnu C Language C Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Multidimensional Arrays in C / C++ Converting Strings to Numbers in C/C++ Left Shift and Right Shift Operators in C/C++ Function Pointer in C Strings in C Arrow operator -> in C/C++ with Examples C Program to read contents of Whole File Header files in C/C++ and its uses Basics of File Handling in C
[ { "code": null, "e": 26155, "s": 26127, "text": "\n08 Jul, 2021" }, { "code": null, "e": 26263, "s": 26155, "text": "The time.h header file contains definitions of functions to get and manipulate date and time information. " }, { "code": null, "e": 26553, "s": 26263, "text": "It describes three time-related data types. clock_t: clock_t represents the date as an integer which is a part of the calendar time. time_t: time_t represents the clock time as an integer which is a part of the calendar time. struct tm: struct tm holds the date and time which contains: " }, { "code": null, "e": 26799, "s": 26553, "text": "clock_t: clock_t represents the date as an integer which is a part of the calendar time. time_t: time_t represents the clock time as an integer which is a part of the calendar time. struct tm: struct tm holds the date and time which contains: " }, { "code": null, "e": 26890, "s": 26799, "text": "clock_t: clock_t represents the date as an integer which is a part of the calendar time. " }, { "code": null, "e": 26985, "s": 26890, "text": "time_t: time_t represents the clock time as an integer which is a part of the calendar time. " }, { "code": null, "e": 27047, "s": 26985, "text": "struct tm: struct tm holds the date and time which contains: " }, { "code": null, "e": 27049, "s": 27047, "text": "C" }, { "code": "struct tm { // seconds, range 0 to 59 int tm_sec; // minutes, range 0 to 59 int tm_min; // hours, range 0 to 23 int tm_hour; // day of the month, range 1 to 31 int tm_mday; // month, range 0 to 11 int tm_mon; // The number of years since 1900 int tm_year; // day of the week, range 0 to 6 int tm_wday; // day in the year, range 0 to 365 int tm_yday; // daylight saving time int tm_isdst;}", "e": 27501, "s": 27049, "text": null }, { "code": null, "e": 27611, "s": 27501, "text": "It also contains CLOCKS_PER_SEC macro which holds the number of times does the system clock ticks per second." }, { "code": null, "e": 27644, "s": 27611, "text": "Pre-defined functions in time.h " }, { "code": null, "e": 27705, "s": 27644, "text": "Examples: Program to print the date and time of the system. " }, { "code": null, "e": 27756, "s": 27705, "text": "Program to print the date and time of the system. " }, { "code": null, "e": 27807, "s": 27756, "text": "Program to print the date and time of the system. " }, { "code": null, "e": 27809, "s": 27807, "text": "C" }, { "code": "#include <stdio.h>#include <time.h>int main(void){ struct tm* ptr; time_t t; t = time(NULL); ptr = localtime(&t); printf(\"%s\", asctime(ptr)); return 0;}", "e": 27980, "s": 27809, "text": null }, { "code": null, "e": 28005, "s": 27980, "text": "Tue Aug 6 09:00:29 2019" }, { "code": null, "e": 28084, "s": 28007, "text": " 2. Program to print UTC (Coordinated Universal Time) of the system. " }, { "code": null, "e": 28086, "s": 28084, "text": "C" }, { "code": "#include <stdio.h>#include <time.h>int main(void){ struct tm* ptr; time_t t; t = time(NULL); ptr = gmtime(&t); printf(\"%s\", asctime(ptr)); return 0;}", "e": 28254, "s": 28086, "text": null }, { "code": null, "e": 28281, "s": 28256, "text": "Tue Aug 6 09:00:31 2019" }, { "code": null, "e": 28455, "s": 28283, "text": " 3. Program to calculate the time taken to add two numbers program. Note: If user gives input slowly that time also add up for total execution time. " }, { "code": null, "e": 28457, "s": 28455, "text": "C" }, { "code": "#include <stdio.h>#include <time.h>int main(void){ time_t start, end; start = time(NULL); int a, b; scanf(\"%d %d\", &a, &b); printf(\"Sum of %d and %d is %d\\n\", a, b, a + b); end = time(NULL); printf(\"Time taken to print sum is %.2f seconds\", difftime(end, start));}", "e": 28763, "s": 28457, "text": null }, { "code": null, "e": 28837, "s": 28765, "text": "Sum of 4196144 and 0 is 4196144\nTime taken to print sum is 0.00 seconds" }, { "code": null, "e": 28883, "s": 28839, "text": " 4. Program to find the clock ticks. " }, { "code": null, "e": 28885, "s": 28883, "text": "C" }, { "code": "#include <math.h>#include <stdio.h>#include <time.h> int frequency_of_primes(int n){ // This function checks the number of // primes less than the given parameter int i, j; int freq = n - 1; for (i = 2; i <= n; ++i) for (j = sqrt(i); j > 1; --j) if (i % j == 0) { --freq; break; } return freq;} int main(){ clock_t t; int f; t = clock(); f = frequency_of_primes(9999); printf(\"The number of primes lower\" \" than 10, 000 is: %d\\n\", f); t = clock() - t; printf(\"No. of clicks %ld clicks (%f seconds).\\n\", t, ((float)t) / CLOCKS_PER_SEC); return 0;}", "e": 29563, "s": 28885, "text": null }, { "code": null, "e": 29660, "s": 29565, "text": "The number of primes lower than 10, 000 is: 1229\nNo. of clicks 2837 clicks (0.002837 seconds)." }, { "code": null, "e": 29746, "s": 29664, "text": " 5. Program to print time as hour: minute returned by asctime() file. " }, { "code": null, "e": 29748, "s": 29746, "text": "C" }, { "code": "#include <stdio.h>#include <time.h>int main(){ time_t rawtime; struct tm* timeinfo; // Used to store the time // returned by localetime() function char buffer[80]; time(&rawtime); timeinfo = localtime(&rawtime); strftime(buffer, 80, \"Time is %I:%M%p.\", timeinfo); // strftime() function stores the // current time as Hours : Minutes //%I %M and %p-> format specifier // of Hours minutes and am/pm respectively*/ // prints the formatted time puts(buffer); return 0;}", "e": 30288, "s": 29748, "text": null }, { "code": null, "e": 30307, "s": 30290, "text": "Time is 09:00AM." }, { "code": null, "e": 30330, "s": 30313, "text": "avsadityavardhan" }, { "code": null, "e": 30345, "s": 30330, "text": "ganeshanvishnu" }, { "code": null, "e": 30356, "s": 30345, "text": "C Language" }, { "code": null, "e": 30367, "s": 30356, "text": "C Programs" }, { "code": null, "e": 30465, "s": 30367, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30482, "s": 30465, "text": "Substring in C++" }, { "code": null, "e": 30517, "s": 30482, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 30556, "s": 30517, "text": "Converting Strings to Numbers in C/C++" }, { "code": null, "e": 30602, "s": 30556, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 30624, "s": 30602, "text": "Function Pointer in C" }, { "code": null, "e": 30637, "s": 30624, "text": "Strings in C" }, { "code": null, "e": 30678, "s": 30637, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 30719, "s": 30678, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 30754, "s": 30719, "text": "Header files in C/C++ and its uses" } ]
jQuery | data() with Examples - GeeksforGeeks
27 Oct, 2021 The data() is an inbuilt method in jQuery which is used to attach data or get data for the selected elements. Syntax: $(selector).data(para1); Parameter : It accepts an optional parameter “para1” which specifies the name of the data to retrieve for the selected element. Return Value: It returns the retrieved data for the selected element.jQuery code to show the working of data() method: Code #1: In the below code, data is attach to the selected element. html <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/ jquery/3.3.1/jquery.min.js"></script> <style> div { display: block; width: 500px; font-size: 37px; padding: 50px; background-color: lightgrey; } span { color: green; } </style></head> <body> <div> Welcome to <span></span>for<span></span>! </div> <script> <!-- jQuery code to perform data method --> $("div").data("test", { first: "Geeks", last: "Geeks !" }); $("span:first").text($("div").data("test").first); $("span:last").text($("div").data("test").last); </script></body> </html> Output: Code #2: In the below code, The data is attaching and retrieving from the “div” element using buttons. html <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/ jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function() { <!--Here data is attaching to the div element --> $("#b1").click(function() { $("div").data("g", "GeeksforGeeks !!!"); }); <!-- Here data is retrieving from the div element --> $("#b2").click(function() { alert($("div").data("g")); }); }); </script> <style> #b1, #b2 { padding: 10px; margin: 5px; } </style></head> <body><!-- This button will attach data to the div element --> <button id="b1">This will attach data to div element</button> <br><!-- This button retrieve the attached data from the div element --> <button id="b2">This will retrieve the attached data to div element</button> <div></div></body> </html> Output: Just after clicking the run button- After clicking the “This will retrieve the attached data to div element” button just after clicking the “This will attach data to div element” button- After clicking the “This will retrieve the attached data to div element” button without clicking the “This will attach data to div element” button- akshaysingh98088 surinderdawra388 jQuery-Misc JavaScript JQuery Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to get character array from string in JavaScript? JQuery | Set the value of an input text field Form validation using jQuery How to change selected value of a drop-down list using jQuery? How to fetch data from JSON file and display in HTML table using jQuery ? How to Dynamically Add/Remove Table Rows using jQuery ?
[ { "code": null, "e": 26606, "s": 26578, "text": "\n27 Oct, 2021" }, { "code": null, "e": 26725, "s": 26606, "text": "The data() is an inbuilt method in jQuery which is used to attach data or get data for the selected elements. Syntax: " }, { "code": null, "e": 26750, "s": 26725, "text": "$(selector).data(para1);" }, { "code": null, "e": 27067, "s": 26750, "text": "Parameter : It accepts an optional parameter “para1” which specifies the name of the data to retrieve for the selected element. Return Value: It returns the retrieved data for the selected element.jQuery code to show the working of data() method: Code #1: In the below code, data is attach to the selected element. " }, { "code": null, "e": 27072, "s": 27067, "text": "html" }, { "code": "<html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/ jquery/3.3.1/jquery.min.js\"></script> <style> div { display: block; width: 500px; font-size: 37px; padding: 50px; background-color: lightgrey; } span { color: green; } </style></head> <body> <div> Welcome to <span></span>for<span></span>! </div> <script> <!-- jQuery code to perform data method --> $(\"div\").data(\"test\", { first: \"Geeks\", last: \"Geeks !\" }); $(\"span:first\").text($(\"div\").data(\"test\").first); $(\"span:last\").text($(\"div\").data(\"test\").last); </script></body> </html>", "e": 27833, "s": 27072, "text": null }, { "code": null, "e": 27843, "s": 27833, "text": "Output: " }, { "code": null, "e": 27947, "s": 27843, "text": "Code #2: In the below code, The data is attaching and retrieving from the “div” element using buttons. " }, { "code": null, "e": 27952, "s": 27947, "text": "html" }, { "code": "<html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/ jquery/3.3.1/jquery.min.js\"></script> <script> $(document).ready(function() { <!--Here data is attaching to the div element --> $(\"#b1\").click(function() { $(\"div\").data(\"g\", \"GeeksforGeeks !!!\"); }); <!-- Here data is retrieving from the div element --> $(\"#b2\").click(function() { alert($(\"div\").data(\"g\")); }); }); </script> <style> #b1, #b2 { padding: 10px; margin: 5px; } </style></head> <body><!-- This button will attach data to the div element --> <button id=\"b1\">This will attach data to div element</button> <br><!-- This button retrieve the attached data from the div element --> <button id=\"b2\">This will retrieve the attached data to div element</button> <div></div></body> </html>", "e": 28954, "s": 27952, "text": null }, { "code": null, "e": 29000, "s": 28954, "text": "Output: Just after clicking the run button- " }, { "code": null, "e": 29153, "s": 29000, "text": "After clicking the “This will retrieve the attached data to div element” button just after clicking the “This will attach data to div element” button- " }, { "code": null, "e": 29303, "s": 29153, "text": "After clicking the “This will retrieve the attached data to div element” button without clicking the “This will attach data to div element” button- " }, { "code": null, "e": 29322, "s": 29305, "text": "akshaysingh98088" }, { "code": null, "e": 29339, "s": 29322, "text": "surinderdawra388" }, { "code": null, "e": 29351, "s": 29339, "text": "jQuery-Misc" }, { "code": null, "e": 29362, "s": 29351, "text": "JavaScript" }, { "code": null, "e": 29369, "s": 29362, "text": "JQuery" }, { "code": null, "e": 29467, "s": 29369, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29507, "s": 29467, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29568, "s": 29507, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29609, "s": 29568, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 29631, "s": 29609, "text": "JavaScript | Promises" }, { "code": null, "e": 29685, "s": 29631, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 29731, "s": 29685, "text": "JQuery | Set the value of an input text field" }, { "code": null, "e": 29760, "s": 29731, "text": "Form validation using jQuery" }, { "code": null, "e": 29823, "s": 29760, "text": "How to change selected value of a drop-down list using jQuery?" }, { "code": null, "e": 29897, "s": 29823, "text": "How to fetch data from JSON file and display in HTML table using jQuery ?" } ]
C# | Interface - GeeksforGeeks
22 Apr, 2020 Like a class, Interface can have methods, properties, events, and indexers as its members. But interfaces will contain only the declaration of the members. The implementation of the interface’s members will be given by class who implements the interface implicitly or explicitly. Interfaces specify what a class must do and not how. Interfaces can’t have private members. By default all the members of Interface are public and abstract. The interface will always defined with the help of keyword ‘interface‘. Interface cannot contain fields because they represent a particular implementation of data. Multiple inheritance is possible with the help of Interfaces but not with classes. Syntax for Interface Declaration: interface <interface_name > { // declare Events // declare indexers // declare methods // declare properties } Syntax for Implementing Interface: class class_name : interface_name To declare an interface, use interface keyword. It is used to provide total abstraction. That means all the members in the interface are declared with the empty body and are public and abstract by default. A class that implements interface must implement all the methods declared in the interface. Example 1:// C# program to demonstrate working of // interfaceusing System; // A simple interfaceinterface inter1{ // method having only declaration // not definition void display();} // A class that implements interface.class testClass : inter1{ // providing the body part of function public void display() { Console.WriteLine("Sudo Placement GeeksforGeeks"); } // Main Method public static void Main (String []args) { // Creating object testClass t = new testClass(); // calling method t.display(); }}Output:Sudo Placement GeeksforGeeks // C# program to demonstrate working of // interfaceusing System; // A simple interfaceinterface inter1{ // method having only declaration // not definition void display();} // A class that implements interface.class testClass : inter1{ // providing the body part of function public void display() { Console.WriteLine("Sudo Placement GeeksforGeeks"); } // Main Method public static void Main (String []args) { // Creating object testClass t = new testClass(); // calling method t.display(); }} Sudo Placement GeeksforGeeks Example 2:// C# program to illustrate the interfaceusing System; // interface declarationinterface Vehicle { // all are the abstract methods. void changeGear(int a); void speedUp(int a); void applyBrakes(int a);} // class implements interfaceclass Bicycle : Vehicle{ int speed; int gear; // to change gear public void changeGear(int newGear) { gear = newGear; } // to increase speed public void speedUp(int increment) { speed = speed + increment; } // to decrease speed public void applyBrakes(int decrement) { speed = speed - decrement; } public void printStates() { Console.WriteLine("speed: " + speed + " gear: " + gear); }} // class implements interfaceclass Bike : Vehicle { int speed; int gear; // to change gear public void changeGear(int newGear) { gear = newGear; } // to increase speed public void speedUp(int increment) { speed = speed + increment; } // to decrease speed public void applyBrakes(int decrement){ speed = speed - decrement; } public void printStates() { Console.WriteLine("speed: " + speed + " gear: " + gear); } } class GFG { // Main Method public static void Main(String []args) { // creating an instance of Bicycle // doing some operations Bicycle bicycle = new Bicycle(); bicycle.changeGear(2); bicycle.speedUp(3); bicycle.applyBrakes(1); Console.WriteLine("Bicycle present state :"); bicycle.printStates(); // creating instance of bike. Bike bike = new Bike(); bike.changeGear(1); bike.speedUp(4); bike.applyBrakes(3); Console.WriteLine("Bike present state :"); bike.printStates(); }}Output:Bicycle present state : speed: 2 gear: 2 Bike present state : speed: 1 gear: 1 // C# program to illustrate the interfaceusing System; // interface declarationinterface Vehicle { // all are the abstract methods. void changeGear(int a); void speedUp(int a); void applyBrakes(int a);} // class implements interfaceclass Bicycle : Vehicle{ int speed; int gear; // to change gear public void changeGear(int newGear) { gear = newGear; } // to increase speed public void speedUp(int increment) { speed = speed + increment; } // to decrease speed public void applyBrakes(int decrement) { speed = speed - decrement; } public void printStates() { Console.WriteLine("speed: " + speed + " gear: " + gear); }} // class implements interfaceclass Bike : Vehicle { int speed; int gear; // to change gear public void changeGear(int newGear) { gear = newGear; } // to increase speed public void speedUp(int increment) { speed = speed + increment; } // to decrease speed public void applyBrakes(int decrement){ speed = speed - decrement; } public void printStates() { Console.WriteLine("speed: " + speed + " gear: " + gear); } } class GFG { // Main Method public static void Main(String []args) { // creating an instance of Bicycle // doing some operations Bicycle bicycle = new Bicycle(); bicycle.changeGear(2); bicycle.speedUp(3); bicycle.applyBrakes(1); Console.WriteLine("Bicycle present state :"); bicycle.printStates(); // creating instance of bike. Bike bike = new Bike(); bike.changeGear(1); bike.speedUp(4); bike.applyBrakes(3); Console.WriteLine("Bike present state :"); bike.printStates(); }} Bicycle present state : speed: 2 gear: 2 Bike present state : speed: 1 gear: 1 Advantage of Interface: It is used to achieve loose coupling. It is used to achieve total abstraction. To achieve component-based programming To achieve multiple inheritance and abstraction. Interfaces add a plug and play like architecture into applications.My Personal Notes arrow_drop_upSave CSharp-Interfaces C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples C# | Delegates Extension Method in C# C# | String.IndexOf( ) Method | Set - 1 C# | Replace() Method Introduction to .NET Framework C# | Data Types C# | Arrays HashSet in C# with Examples Common Language Runtime (CLR) in C#
[ { "code": null, "e": 25315, "s": 25287, "text": "\n22 Apr, 2020" }, { "code": null, "e": 25595, "s": 25315, "text": "Like a class, Interface can have methods, properties, events, and indexers as its members. But interfaces will contain only the declaration of the members. The implementation of the interface’s members will be given by class who implements the interface implicitly or explicitly." }, { "code": null, "e": 25648, "s": 25595, "text": "Interfaces specify what a class must do and not how." }, { "code": null, "e": 25687, "s": 25648, "text": "Interfaces can’t have private members." }, { "code": null, "e": 25752, "s": 25687, "text": "By default all the members of Interface are public and abstract." }, { "code": null, "e": 25824, "s": 25752, "text": "The interface will always defined with the help of keyword ‘interface‘." }, { "code": null, "e": 25916, "s": 25824, "text": "Interface cannot contain fields because they represent a particular implementation of data." }, { "code": null, "e": 25999, "s": 25916, "text": "Multiple inheritance is possible with the help of Interfaces but not with classes." }, { "code": null, "e": 26033, "s": 25999, "text": "Syntax for Interface Declaration:" }, { "code": null, "e": 26163, "s": 26033, "text": "interface <interface_name >\n{\n // declare Events\n // declare indexers\n // declare methods \n // declare properties\n}\n" }, { "code": null, "e": 26198, "s": 26163, "text": "Syntax for Implementing Interface:" }, { "code": null, "e": 26233, "s": 26198, "text": "class class_name : interface_name\n" }, { "code": null, "e": 26531, "s": 26233, "text": "To declare an interface, use interface keyword. It is used to provide total abstraction. That means all the members in the interface are declared with the empty body and are public and abstract by default. A class that implements interface must implement all the methods declared in the interface." }, { "code": null, "e": 27170, "s": 26531, "text": "Example 1:// C# program to demonstrate working of // interfaceusing System; // A simple interfaceinterface inter1{ // method having only declaration // not definition void display();} // A class that implements interface.class testClass : inter1{ // providing the body part of function public void display() { Console.WriteLine(\"Sudo Placement GeeksforGeeks\"); } // Main Method public static void Main (String []args) { // Creating object testClass t = new testClass(); // calling method t.display(); }}Output:Sudo Placement GeeksforGeeks\n" }, { "code": "// C# program to demonstrate working of // interfaceusing System; // A simple interfaceinterface inter1{ // method having only declaration // not definition void display();} // A class that implements interface.class testClass : inter1{ // providing the body part of function public void display() { Console.WriteLine(\"Sudo Placement GeeksforGeeks\"); } // Main Method public static void Main (String []args) { // Creating object testClass t = new testClass(); // calling method t.display(); }}", "e": 27763, "s": 27170, "text": null }, { "code": null, "e": 27793, "s": 27763, "text": "Sudo Placement GeeksforGeeks\n" }, { "code": null, "e": 29913, "s": 27793, "text": "Example 2:// C# program to illustrate the interfaceusing System; // interface declarationinterface Vehicle { // all are the abstract methods. void changeGear(int a); void speedUp(int a); void applyBrakes(int a);} // class implements interfaceclass Bicycle : Vehicle{ int speed; int gear; // to change gear public void changeGear(int newGear) { gear = newGear; } // to increase speed public void speedUp(int increment) { speed = speed + increment; } // to decrease speed public void applyBrakes(int decrement) { speed = speed - decrement; } public void printStates() { Console.WriteLine(\"speed: \" + speed + \" gear: \" + gear); }} // class implements interfaceclass Bike : Vehicle { int speed; int gear; // to change gear public void changeGear(int newGear) { gear = newGear; } // to increase speed public void speedUp(int increment) { speed = speed + increment; } // to decrease speed public void applyBrakes(int decrement){ speed = speed - decrement; } public void printStates() { Console.WriteLine(\"speed: \" + speed + \" gear: \" + gear); } } class GFG { // Main Method public static void Main(String []args) { // creating an instance of Bicycle // doing some operations Bicycle bicycle = new Bicycle(); bicycle.changeGear(2); bicycle.speedUp(3); bicycle.applyBrakes(1); Console.WriteLine(\"Bicycle present state :\"); bicycle.printStates(); // creating instance of bike. Bike bike = new Bike(); bike.changeGear(1); bike.speedUp(4); bike.applyBrakes(3); Console.WriteLine(\"Bike present state :\"); bike.printStates(); }}Output:Bicycle present state :\nspeed: 2 gear: 2\nBike present state :\nspeed: 1 gear: 1\n" }, { "code": "// C# program to illustrate the interfaceusing System; // interface declarationinterface Vehicle { // all are the abstract methods. void changeGear(int a); void speedUp(int a); void applyBrakes(int a);} // class implements interfaceclass Bicycle : Vehicle{ int speed; int gear; // to change gear public void changeGear(int newGear) { gear = newGear; } // to increase speed public void speedUp(int increment) { speed = speed + increment; } // to decrease speed public void applyBrakes(int decrement) { speed = speed - decrement; } public void printStates() { Console.WriteLine(\"speed: \" + speed + \" gear: \" + gear); }} // class implements interfaceclass Bike : Vehicle { int speed; int gear; // to change gear public void changeGear(int newGear) { gear = newGear; } // to increase speed public void speedUp(int increment) { speed = speed + increment; } // to decrease speed public void applyBrakes(int decrement){ speed = speed - decrement; } public void printStates() { Console.WriteLine(\"speed: \" + speed + \" gear: \" + gear); } } class GFG { // Main Method public static void Main(String []args) { // creating an instance of Bicycle // doing some operations Bicycle bicycle = new Bicycle(); bicycle.changeGear(2); bicycle.speedUp(3); bicycle.applyBrakes(1); Console.WriteLine(\"Bicycle present state :\"); bicycle.printStates(); // creating instance of bike. Bike bike = new Bike(); bike.changeGear(1); bike.speedUp(4); bike.applyBrakes(3); Console.WriteLine(\"Bike present state :\"); bike.printStates(); }}", "e": 31937, "s": 29913, "text": null }, { "code": null, "e": 32017, "s": 31937, "text": "Bicycle present state :\nspeed: 2 gear: 2\nBike present state :\nspeed: 1 gear: 1\n" }, { "code": null, "e": 32041, "s": 32017, "text": "Advantage of Interface:" }, { "code": null, "e": 32079, "s": 32041, "text": "It is used to achieve loose coupling." }, { "code": null, "e": 32120, "s": 32079, "text": "It is used to achieve total abstraction." }, { "code": null, "e": 32159, "s": 32120, "text": "To achieve component-based programming" }, { "code": null, "e": 32208, "s": 32159, "text": "To achieve multiple inheritance and abstraction." }, { "code": null, "e": 32311, "s": 32208, "text": "Interfaces add a plug and play like architecture into applications.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 32329, "s": 32311, "text": "CSharp-Interfaces" }, { "code": null, "e": 32332, "s": 32329, "text": "C#" }, { "code": null, "e": 32430, "s": 32332, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32458, "s": 32430, "text": "C# Dictionary with examples" }, { "code": null, "e": 32473, "s": 32458, "text": "C# | Delegates" }, { "code": null, "e": 32496, "s": 32473, "text": "Extension Method in C#" }, { "code": null, "e": 32536, "s": 32496, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 32558, "s": 32536, "text": "C# | Replace() Method" }, { "code": null, "e": 32589, "s": 32558, "text": "Introduction to .NET Framework" }, { "code": null, "e": 32605, "s": 32589, "text": "C# | Data Types" }, { "code": null, "e": 32617, "s": 32605, "text": "C# | Arrays" }, { "code": null, "e": 32645, "s": 32617, "text": "HashSet in C# with Examples" } ]
Difference between Stream.of() and Arrays.stream() method in Java - GeeksforGeeks
11 Dec, 2018 The stream(T[] array) method of Arrays class in Java, is used to get a Sequential Stream from the array passed as the parameter with its elements. It returns a sequential Stream with the elements of the array, passed as parameter, as its source. Example: // Java program to demonstrate Arrays.stream() method import java.util.*;import java.util.stream.*; class GFG { public static void main(String[] args) { // Creating a String array String[] arr = { "Geeks", "for", "Geeks" }; // Using Arrays.stream() to convert // array into Stream Stream<String> stream = Arrays.stream(arr); // Displaying elements in Stream stream.forEach(str -> System.out.print(str + " ")); }} The Stream of(T... values) returns a sequential ordered stream whose elements are the specified values. Stream.of() method simply calls the Arrays.stream() method for non-primitive types. Example: // Java code for Stream of(T... values)// to get a sequential ordered stream whose// elements are the specified values. import java.util.*;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // Creating an Stream Stream stream = Stream.of("Geeks", "for", "Geeks"); // Displaying the sequential ordered stream stream.forEach(str -> System.out.print(str + " ")); }} These both methods are the two most commonly used methods for creating a sequential stream from a specified array. Both these methods returns a Stream<T> when called with a non-primitive type T. Difference between Arrays.stream() and Stream.of() Even if Stream.of() is a wrapper over the Arrays.stream() method, there are certain point of differences which clearifies as when to use a Arrays.stream() or when to use Stream.of(). Below are some of the differences between the above two stated methods: Different return types:For primitives arrays (like int[], long[] etc), Arrays.stream() and Stream.of() have different return types.Example: Passing an integer array, the Stream.of() method returns Stream whereas Arrays.stream() returns an IntStream.// Java program to demonstrate return type// of Arrays.stream() and Stream.of() method// for primitive arrays import java.util.*;import java.util.stream.*; class GFG { public static void main(String[] args) { // Creating an integer array int arr[] = { 1, 2, 3, 4, 5 }; // --------- Using Arrays.stream() --------- // to convert int array into Stream IntStream intStream = Arrays.stream(arr); // Displaying elements in Stream intStream.forEach(str -> System.out.print(str + " ")); // --------- Using Stream.of() --------- // to convert int array into Stream Stream<int[]> stream = Stream.of(arr); // Displaying elements in Stream stream.forEach(str -> System.out.print(str + " ")); }}Stream.of() needs flattening whereas Arrays.stream() does not:As the ideal class used for processing of Streams of primitive types are their primitive Stream types (like IntStream, LongStream, etc). Therefore Stream.of() needs to be explicitly flattened into its primitive Stream before consuming.Example:// Java program to demonstrate need of flattenning// Stream.of() method returned type for primitive arrays import java.util.*;import java.util.stream.*; class GFG { public static void main(String[] args) { // Creating an integer array int arr[] = { 1, 2, 3, 4, 5 }; // --------- Using Arrays.stream() --------- // to convert int array into Stream IntStream intStream = Arrays.stream(arr); // Displaying elements in Stream intStream.forEach(str -> System.out.print(str + " ")); // --------- Using Stream.of() --------- // to convert int array into Stream Stream<int[]> stream = Stream.of(arr); // ***** Flattening of Stream<int[]> into IntStream ***** // flattenning Stream<int[]> into IntStream // using flatMapToInt() IntStream intStreamNew = stream.flatMapToInt(Arrays::stream); // Displaying elements in IntStream intStreamNew.forEach(str -> System.out.print(str + " ")); }}Stream.of() is generic whereas Arrays.stream is not:Arrays.stream() method only works for primitive arrays of int[], long[], and double[] type, and returns IntStream, LongStream and DoubleStream respectively. For other primitive types, Arrays.stream() won’t work.On the other hand, Stream.of() returns a generic Stream of type T (Stream). Hence, it can be used with any type.Example:For Arrays.stream() method:// Java program to demonstrate return type// of Arrays.stream() method// for primitive arrays of char import java.util.*;import java.util.stream.*; class GFG { public static void main(String[] args) { // Creating a character array char arr[] = { '1', '2', '3', '4', '5' }; // --------- Using Arrays.stream() --------- // This will throw error // to convert char array into Stream Arrays.stream(arr); }}Output:Compilation Error in java code :-prog.java:20: error: no suitable method found for stream(char[])Arrays.stream(arr);^For Stream.of() method:// Java program to demonstrate return type// of Stream.of() method// for primitive arrays of char import java.util.*;import java.util.stream.*; class GFG { public static void main(String[] args) { // Creating a character array char arr[] = { '1', '2', '3', '4', '5' }; // --------- Using Stream.of() --------- // Will work efficiently // to convert int array into Stream Stream<char[]> stream = Stream.of(arr); // Displaying elements in Stream stream.forEach(str -> System.out.print(str + " ")); }} Different return types:For primitives arrays (like int[], long[] etc), Arrays.stream() and Stream.of() have different return types.Example: Passing an integer array, the Stream.of() method returns Stream whereas Arrays.stream() returns an IntStream.// Java program to demonstrate return type// of Arrays.stream() and Stream.of() method// for primitive arrays import java.util.*;import java.util.stream.*; class GFG { public static void main(String[] args) { // Creating an integer array int arr[] = { 1, 2, 3, 4, 5 }; // --------- Using Arrays.stream() --------- // to convert int array into Stream IntStream intStream = Arrays.stream(arr); // Displaying elements in Stream intStream.forEach(str -> System.out.print(str + " ")); // --------- Using Stream.of() --------- // to convert int array into Stream Stream<int[]> stream = Stream.of(arr); // Displaying elements in Stream stream.forEach(str -> System.out.print(str + " ")); }} For primitives arrays (like int[], long[] etc), Arrays.stream() and Stream.of() have different return types. Example: Passing an integer array, the Stream.of() method returns Stream whereas Arrays.stream() returns an IntStream. // Java program to demonstrate return type// of Arrays.stream() and Stream.of() method// for primitive arrays import java.util.*;import java.util.stream.*; class GFG { public static void main(String[] args) { // Creating an integer array int arr[] = { 1, 2, 3, 4, 5 }; // --------- Using Arrays.stream() --------- // to convert int array into Stream IntStream intStream = Arrays.stream(arr); // Displaying elements in Stream intStream.forEach(str -> System.out.print(str + " ")); // --------- Using Stream.of() --------- // to convert int array into Stream Stream<int[]> stream = Stream.of(arr); // Displaying elements in Stream stream.forEach(str -> System.out.print(str + " ")); }} Stream.of() needs flattening whereas Arrays.stream() does not:As the ideal class used for processing of Streams of primitive types are their primitive Stream types (like IntStream, LongStream, etc). Therefore Stream.of() needs to be explicitly flattened into its primitive Stream before consuming.Example:// Java program to demonstrate need of flattenning// Stream.of() method returned type for primitive arrays import java.util.*;import java.util.stream.*; class GFG { public static void main(String[] args) { // Creating an integer array int arr[] = { 1, 2, 3, 4, 5 }; // --------- Using Arrays.stream() --------- // to convert int array into Stream IntStream intStream = Arrays.stream(arr); // Displaying elements in Stream intStream.forEach(str -> System.out.print(str + " ")); // --------- Using Stream.of() --------- // to convert int array into Stream Stream<int[]> stream = Stream.of(arr); // ***** Flattening of Stream<int[]> into IntStream ***** // flattenning Stream<int[]> into IntStream // using flatMapToInt() IntStream intStreamNew = stream.flatMapToInt(Arrays::stream); // Displaying elements in IntStream intStreamNew.forEach(str -> System.out.print(str + " ")); }} As the ideal class used for processing of Streams of primitive types are their primitive Stream types (like IntStream, LongStream, etc). Therefore Stream.of() needs to be explicitly flattened into its primitive Stream before consuming. Example: // Java program to demonstrate need of flattenning// Stream.of() method returned type for primitive arrays import java.util.*;import java.util.stream.*; class GFG { public static void main(String[] args) { // Creating an integer array int arr[] = { 1, 2, 3, 4, 5 }; // --------- Using Arrays.stream() --------- // to convert int array into Stream IntStream intStream = Arrays.stream(arr); // Displaying elements in Stream intStream.forEach(str -> System.out.print(str + " ")); // --------- Using Stream.of() --------- // to convert int array into Stream Stream<int[]> stream = Stream.of(arr); // ***** Flattening of Stream<int[]> into IntStream ***** // flattenning Stream<int[]> into IntStream // using flatMapToInt() IntStream intStreamNew = stream.flatMapToInt(Arrays::stream); // Displaying elements in IntStream intStreamNew.forEach(str -> System.out.print(str + " ")); }} Stream.of() is generic whereas Arrays.stream is not:Arrays.stream() method only works for primitive arrays of int[], long[], and double[] type, and returns IntStream, LongStream and DoubleStream respectively. For other primitive types, Arrays.stream() won’t work.On the other hand, Stream.of() returns a generic Stream of type T (Stream). Hence, it can be used with any type.Example:For Arrays.stream() method:// Java program to demonstrate return type// of Arrays.stream() method// for primitive arrays of char import java.util.*;import java.util.stream.*; class GFG { public static void main(String[] args) { // Creating a character array char arr[] = { '1', '2', '3', '4', '5' }; // --------- Using Arrays.stream() --------- // This will throw error // to convert char array into Stream Arrays.stream(arr); }}Output:Compilation Error in java code :-prog.java:20: error: no suitable method found for stream(char[])Arrays.stream(arr);^For Stream.of() method:// Java program to demonstrate return type// of Stream.of() method// for primitive arrays of char import java.util.*;import java.util.stream.*; class GFG { public static void main(String[] args) { // Creating a character array char arr[] = { '1', '2', '3', '4', '5' }; // --------- Using Stream.of() --------- // Will work efficiently // to convert int array into Stream Stream<char[]> stream = Stream.of(arr); // Displaying elements in Stream stream.forEach(str -> System.out.print(str + " ")); }} Arrays.stream() method only works for primitive arrays of int[], long[], and double[] type, and returns IntStream, LongStream and DoubleStream respectively. For other primitive types, Arrays.stream() won’t work.On the other hand, Stream.of() returns a generic Stream of type T (Stream). Hence, it can be used with any type. Example: For Arrays.stream() method:// Java program to demonstrate return type// of Arrays.stream() method// for primitive arrays of char import java.util.*;import java.util.stream.*; class GFG { public static void main(String[] args) { // Creating a character array char arr[] = { '1', '2', '3', '4', '5' }; // --------- Using Arrays.stream() --------- // This will throw error // to convert char array into Stream Arrays.stream(arr); }}Output:Compilation Error in java code :-prog.java:20: error: no suitable method found for stream(char[])Arrays.stream(arr);^ // Java program to demonstrate return type// of Arrays.stream() method// for primitive arrays of char import java.util.*;import java.util.stream.*; class GFG { public static void main(String[] args) { // Creating a character array char arr[] = { '1', '2', '3', '4', '5' }; // --------- Using Arrays.stream() --------- // This will throw error // to convert char array into Stream Arrays.stream(arr); }} Output: Compilation Error in java code :-prog.java:20: error: no suitable method found for stream(char[])Arrays.stream(arr);^ For Stream.of() method:// Java program to demonstrate return type// of Stream.of() method// for primitive arrays of char import java.util.*;import java.util.stream.*; class GFG { public static void main(String[] args) { // Creating a character array char arr[] = { '1', '2', '3', '4', '5' }; // --------- Using Stream.of() --------- // Will work efficiently // to convert int array into Stream Stream<char[]> stream = Stream.of(arr); // Displaying elements in Stream stream.forEach(str -> System.out.print(str + " ")); }} // Java program to demonstrate return type// of Stream.of() method// for primitive arrays of char import java.util.*;import java.util.stream.*; class GFG { public static void main(String[] args) { // Creating a character array char arr[] = { '1', '2', '3', '4', '5' }; // --------- Using Stream.of() --------- // Will work efficiently // to convert int array into Stream Stream<char[]> stream = Stream.of(arr); // Displaying elements in Stream stream.forEach(str -> System.out.print(str + " ")); }} Java-Array-Programs Java-Arrays Java-Functions java-stream Java-Stream-programs Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Interfaces in Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java Set in Java
[ { "code": null, "e": 25503, "s": 25475, "text": "\n11 Dec, 2018" }, { "code": null, "e": 25749, "s": 25503, "text": "The stream(T[] array) method of Arrays class in Java, is used to get a Sequential Stream from the array passed as the parameter with its elements. It returns a sequential Stream with the elements of the array, passed as parameter, as its source." }, { "code": null, "e": 25758, "s": 25749, "text": "Example:" }, { "code": "// Java program to demonstrate Arrays.stream() method import java.util.*;import java.util.stream.*; class GFG { public static void main(String[] args) { // Creating a String array String[] arr = { \"Geeks\", \"for\", \"Geeks\" }; // Using Arrays.stream() to convert // array into Stream Stream<String> stream = Arrays.stream(arr); // Displaying elements in Stream stream.forEach(str -> System.out.print(str + \" \")); }}", "e": 26237, "s": 25758, "text": null }, { "code": null, "e": 26425, "s": 26237, "text": "The Stream of(T... values) returns a sequential ordered stream whose elements are the specified values. Stream.of() method simply calls the Arrays.stream() method for non-primitive types." }, { "code": null, "e": 26434, "s": 26425, "text": "Example:" }, { "code": "// Java code for Stream of(T... values)// to get a sequential ordered stream whose// elements are the specified values. import java.util.*;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // Creating an Stream Stream stream = Stream.of(\"Geeks\", \"for\", \"Geeks\"); // Displaying the sequential ordered stream stream.forEach(str -> System.out.print(str + \" \")); }}", "e": 26892, "s": 26434, "text": null }, { "code": null, "e": 27087, "s": 26892, "text": "These both methods are the two most commonly used methods for creating a sequential stream from a specified array. Both these methods returns a Stream<T> when called with a non-primitive type T." }, { "code": null, "e": 27138, "s": 27087, "text": "Difference between Arrays.stream() and Stream.of()" }, { "code": null, "e": 27393, "s": 27138, "text": "Even if Stream.of() is a wrapper over the Arrays.stream() method, there are certain point of differences which clearifies as when to use a Arrays.stream() or when to use Stream.of(). Below are some of the differences between the above two stated methods:" }, { "code": null, "e": 31349, "s": 27393, "text": "Different return types:For primitives arrays (like int[], long[] etc), Arrays.stream() and Stream.of() have different return types.Example: Passing an integer array, the Stream.of() method returns Stream whereas Arrays.stream() returns an IntStream.// Java program to demonstrate return type// of Arrays.stream() and Stream.of() method// for primitive arrays import java.util.*;import java.util.stream.*; class GFG { public static void main(String[] args) { // Creating an integer array int arr[] = { 1, 2, 3, 4, 5 }; // --------- Using Arrays.stream() --------- // to convert int array into Stream IntStream intStream = Arrays.stream(arr); // Displaying elements in Stream intStream.forEach(str -> System.out.print(str + \" \")); // --------- Using Stream.of() --------- // to convert int array into Stream Stream<int[]> stream = Stream.of(arr); // Displaying elements in Stream stream.forEach(str -> System.out.print(str + \" \")); }}Stream.of() needs flattening whereas Arrays.stream() does not:As the ideal class used for processing of Streams of primitive types are their primitive Stream types (like IntStream, LongStream, etc). Therefore Stream.of() needs to be explicitly flattened into its primitive Stream before consuming.Example:// Java program to demonstrate need of flattenning// Stream.of() method returned type for primitive arrays import java.util.*;import java.util.stream.*; class GFG { public static void main(String[] args) { // Creating an integer array int arr[] = { 1, 2, 3, 4, 5 }; // --------- Using Arrays.stream() --------- // to convert int array into Stream IntStream intStream = Arrays.stream(arr); // Displaying elements in Stream intStream.forEach(str -> System.out.print(str + \" \")); // --------- Using Stream.of() --------- // to convert int array into Stream Stream<int[]> stream = Stream.of(arr); // ***** Flattening of Stream<int[]> into IntStream ***** // flattenning Stream<int[]> into IntStream // using flatMapToInt() IntStream intStreamNew = stream.flatMapToInt(Arrays::stream); // Displaying elements in IntStream intStreamNew.forEach(str -> System.out.print(str + \" \")); }}Stream.of() is generic whereas Arrays.stream is not:Arrays.stream() method only works for primitive arrays of int[], long[], and double[] type, and returns IntStream, LongStream and DoubleStream respectively. For other primitive types, Arrays.stream() won’t work.On the other hand, Stream.of() returns a generic Stream of type T (Stream). Hence, it can be used with any type.Example:For Arrays.stream() method:// Java program to demonstrate return type// of Arrays.stream() method// for primitive arrays of char import java.util.*;import java.util.stream.*; class GFG { public static void main(String[] args) { // Creating a character array char arr[] = { '1', '2', '3', '4', '5' }; // --------- Using Arrays.stream() --------- // This will throw error // to convert char array into Stream Arrays.stream(arr); }}Output:Compilation Error in java code :-prog.java:20: error: no suitable method found for stream(char[])Arrays.stream(arr);^For Stream.of() method:// Java program to demonstrate return type// of Stream.of() method// for primitive arrays of char import java.util.*;import java.util.stream.*; class GFG { public static void main(String[] args) { // Creating a character array char arr[] = { '1', '2', '3', '4', '5' }; // --------- Using Stream.of() --------- // Will work efficiently // to convert int array into Stream Stream<char[]> stream = Stream.of(arr); // Displaying elements in Stream stream.forEach(str -> System.out.print(str + \" \")); }}" }, { "code": null, "e": 32391, "s": 31349, "text": "Different return types:For primitives arrays (like int[], long[] etc), Arrays.stream() and Stream.of() have different return types.Example: Passing an integer array, the Stream.of() method returns Stream whereas Arrays.stream() returns an IntStream.// Java program to demonstrate return type// of Arrays.stream() and Stream.of() method// for primitive arrays import java.util.*;import java.util.stream.*; class GFG { public static void main(String[] args) { // Creating an integer array int arr[] = { 1, 2, 3, 4, 5 }; // --------- Using Arrays.stream() --------- // to convert int array into Stream IntStream intStream = Arrays.stream(arr); // Displaying elements in Stream intStream.forEach(str -> System.out.print(str + \" \")); // --------- Using Stream.of() --------- // to convert int array into Stream Stream<int[]> stream = Stream.of(arr); // Displaying elements in Stream stream.forEach(str -> System.out.print(str + \" \")); }}" }, { "code": null, "e": 32500, "s": 32391, "text": "For primitives arrays (like int[], long[] etc), Arrays.stream() and Stream.of() have different return types." }, { "code": null, "e": 32619, "s": 32500, "text": "Example: Passing an integer array, the Stream.of() method returns Stream whereas Arrays.stream() returns an IntStream." }, { "code": "// Java program to demonstrate return type// of Arrays.stream() and Stream.of() method// for primitive arrays import java.util.*;import java.util.stream.*; class GFG { public static void main(String[] args) { // Creating an integer array int arr[] = { 1, 2, 3, 4, 5 }; // --------- Using Arrays.stream() --------- // to convert int array into Stream IntStream intStream = Arrays.stream(arr); // Displaying elements in Stream intStream.forEach(str -> System.out.print(str + \" \")); // --------- Using Stream.of() --------- // to convert int array into Stream Stream<int[]> stream = Stream.of(arr); // Displaying elements in Stream stream.forEach(str -> System.out.print(str + \" \")); }}", "e": 33412, "s": 32619, "text": null }, { "code": null, "e": 34736, "s": 33412, "text": "Stream.of() needs flattening whereas Arrays.stream() does not:As the ideal class used for processing of Streams of primitive types are their primitive Stream types (like IntStream, LongStream, etc). Therefore Stream.of() needs to be explicitly flattened into its primitive Stream before consuming.Example:// Java program to demonstrate need of flattenning// Stream.of() method returned type for primitive arrays import java.util.*;import java.util.stream.*; class GFG { public static void main(String[] args) { // Creating an integer array int arr[] = { 1, 2, 3, 4, 5 }; // --------- Using Arrays.stream() --------- // to convert int array into Stream IntStream intStream = Arrays.stream(arr); // Displaying elements in Stream intStream.forEach(str -> System.out.print(str + \" \")); // --------- Using Stream.of() --------- // to convert int array into Stream Stream<int[]> stream = Stream.of(arr); // ***** Flattening of Stream<int[]> into IntStream ***** // flattenning Stream<int[]> into IntStream // using flatMapToInt() IntStream intStreamNew = stream.flatMapToInt(Arrays::stream); // Displaying elements in IntStream intStreamNew.forEach(str -> System.out.print(str + \" \")); }}" }, { "code": null, "e": 34972, "s": 34736, "text": "As the ideal class used for processing of Streams of primitive types are their primitive Stream types (like IntStream, LongStream, etc). Therefore Stream.of() needs to be explicitly flattened into its primitive Stream before consuming." }, { "code": null, "e": 34981, "s": 34972, "text": "Example:" }, { "code": "// Java program to demonstrate need of flattenning// Stream.of() method returned type for primitive arrays import java.util.*;import java.util.stream.*; class GFG { public static void main(String[] args) { // Creating an integer array int arr[] = { 1, 2, 3, 4, 5 }; // --------- Using Arrays.stream() --------- // to convert int array into Stream IntStream intStream = Arrays.stream(arr); // Displaying elements in Stream intStream.forEach(str -> System.out.print(str + \" \")); // --------- Using Stream.of() --------- // to convert int array into Stream Stream<int[]> stream = Stream.of(arr); // ***** Flattening of Stream<int[]> into IntStream ***** // flattenning Stream<int[]> into IntStream // using flatMapToInt() IntStream intStreamNew = stream.flatMapToInt(Arrays::stream); // Displaying elements in IntStream intStreamNew.forEach(str -> System.out.print(str + \" \")); }}", "e": 36000, "s": 34981, "text": null }, { "code": null, "e": 37592, "s": 36000, "text": "Stream.of() is generic whereas Arrays.stream is not:Arrays.stream() method only works for primitive arrays of int[], long[], and double[] type, and returns IntStream, LongStream and DoubleStream respectively. For other primitive types, Arrays.stream() won’t work.On the other hand, Stream.of() returns a generic Stream of type T (Stream). Hence, it can be used with any type.Example:For Arrays.stream() method:// Java program to demonstrate return type// of Arrays.stream() method// for primitive arrays of char import java.util.*;import java.util.stream.*; class GFG { public static void main(String[] args) { // Creating a character array char arr[] = { '1', '2', '3', '4', '5' }; // --------- Using Arrays.stream() --------- // This will throw error // to convert char array into Stream Arrays.stream(arr); }}Output:Compilation Error in java code :-prog.java:20: error: no suitable method found for stream(char[])Arrays.stream(arr);^For Stream.of() method:// Java program to demonstrate return type// of Stream.of() method// for primitive arrays of char import java.util.*;import java.util.stream.*; class GFG { public static void main(String[] args) { // Creating a character array char arr[] = { '1', '2', '3', '4', '5' }; // --------- Using Stream.of() --------- // Will work efficiently // to convert int array into Stream Stream<char[]> stream = Stream.of(arr); // Displaying elements in Stream stream.forEach(str -> System.out.print(str + \" \")); }}" }, { "code": null, "e": 37916, "s": 37592, "text": "Arrays.stream() method only works for primitive arrays of int[], long[], and double[] type, and returns IntStream, LongStream and DoubleStream respectively. For other primitive types, Arrays.stream() won’t work.On the other hand, Stream.of() returns a generic Stream of type T (Stream). Hence, it can be used with any type." }, { "code": null, "e": 37925, "s": 37916, "text": "Example:" }, { "code": null, "e": 38538, "s": 37925, "text": "For Arrays.stream() method:// Java program to demonstrate return type// of Arrays.stream() method// for primitive arrays of char import java.util.*;import java.util.stream.*; class GFG { public static void main(String[] args) { // Creating a character array char arr[] = { '1', '2', '3', '4', '5' }; // --------- Using Arrays.stream() --------- // This will throw error // to convert char array into Stream Arrays.stream(arr); }}Output:Compilation Error in java code :-prog.java:20: error: no suitable method found for stream(char[])Arrays.stream(arr);^" }, { "code": "// Java program to demonstrate return type// of Arrays.stream() method// for primitive arrays of char import java.util.*;import java.util.stream.*; class GFG { public static void main(String[] args) { // Creating a character array char arr[] = { '1', '2', '3', '4', '5' }; // --------- Using Arrays.stream() --------- // This will throw error // to convert char array into Stream Arrays.stream(arr); }}", "e": 39000, "s": 38538, "text": null }, { "code": null, "e": 39008, "s": 39000, "text": "Output:" }, { "code": null, "e": 39126, "s": 39008, "text": "Compilation Error in java code :-prog.java:20: error: no suitable method found for stream(char[])Arrays.stream(arr);^" }, { "code": null, "e": 39723, "s": 39126, "text": "For Stream.of() method:// Java program to demonstrate return type// of Stream.of() method// for primitive arrays of char import java.util.*;import java.util.stream.*; class GFG { public static void main(String[] args) { // Creating a character array char arr[] = { '1', '2', '3', '4', '5' }; // --------- Using Stream.of() --------- // Will work efficiently // to convert int array into Stream Stream<char[]> stream = Stream.of(arr); // Displaying elements in Stream stream.forEach(str -> System.out.print(str + \" \")); }}" }, { "code": "// Java program to demonstrate return type// of Stream.of() method// for primitive arrays of char import java.util.*;import java.util.stream.*; class GFG { public static void main(String[] args) { // Creating a character array char arr[] = { '1', '2', '3', '4', '5' }; // --------- Using Stream.of() --------- // Will work efficiently // to convert int array into Stream Stream<char[]> stream = Stream.of(arr); // Displaying elements in Stream stream.forEach(str -> System.out.print(str + \" \")); }}", "e": 40297, "s": 39723, "text": null }, { "code": null, "e": 40317, "s": 40297, "text": "Java-Array-Programs" }, { "code": null, "e": 40329, "s": 40317, "text": "Java-Arrays" }, { "code": null, "e": 40344, "s": 40329, "text": "Java-Functions" }, { "code": null, "e": 40356, "s": 40344, "text": "java-stream" }, { "code": null, "e": 40377, "s": 40356, "text": "Java-Stream-programs" }, { "code": null, "e": 40382, "s": 40377, "text": "Java" }, { "code": null, "e": 40387, "s": 40382, "text": "Java" }, { "code": null, "e": 40485, "s": 40387, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40536, "s": 40485, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 40566, "s": 40536, "text": "HashMap in Java with Examples" }, { "code": null, "e": 40585, "s": 40566, "text": "Interfaces in Java" }, { "code": null, "e": 40616, "s": 40585, "text": "How to iterate any Map in Java" }, { "code": null, "e": 40634, "s": 40616, "text": "ArrayList in Java" }, { "code": null, "e": 40666, "s": 40634, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 40686, "s": 40666, "text": "Stack Class in Java" }, { "code": null, "e": 40718, "s": 40686, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 40742, "s": 40718, "text": "Singleton Class in Java" } ]
numpy.load() in Python - GeeksforGeeks
29 Nov, 2018 numpy.load() function return the input array from a disk file with npy extension(.npy). Syntax : numpy.load(file, mmap_mode=None, allow_pickle=True, fix_imports=True, encoding=’ASCII’) Parameters:file : : file-like object, string, or pathlib.Path.The file to read. File-like objects must support the seek() and read() methods.mmap_mode : If not None, then memory-map the file, using the given mode (see numpy.memmap for a detaileddescription of the modes).allow_pickle : Allow loading pickled object arrays stored in npy files.fix_imports : Only useful when loading Python 2 generated pickled files on Python 3,which includes npy/npz files containing object arrays.encoding : Only useful when loading Python 2 generated pickled files in Python 3, which includes npy/npz files containing object arrays. Returns : Data stored in the file. For .npz files, the returned instance of NpzFile class must be closed to avoid leaking file descriptors. Code #1 : Working # Python program explaining # load() function import numpy as geek a = geek.array(([i + j for i in range(3) for j in range(3)]))# a is printed.print("a is:")print(a) geek.save('geekfile', a)print("the array is saved in the file geekfile.npy") # the array is saved in the file geekfile.npy b = geek.load('geekfile.npy') # the array is loaded into bprint("b is:")print(b) # b is printed from geekfile.npyprint("b is printed from geekfile.npy") Output : a is: [0, 1, 2, 1, 2, 3, 2, 3, 4] the array is saved in the file geekfile.npy b is: [0, 1, 2, 1, 2, 3, 2, 3, 4] b is printed from geekfile.npy Code #2: # Python program explaining # load() function import numpy as geek # a and b are numpy arrays.a = geek.array(([i + j for i in range(3) for j in range(3)]))b = geek.array([i + 1 for i in range(3)]) # a and b are printed.print("a is:")print(a)print("b is:")print(b) # a and b are stored in geekfile.npzgeek.savez('geekfile.npz', a = a, b = b) print("a and b are stored in geekfile.npz") # compressed file is loadedc = geek.load('geekfile.npz') print("after loading...")print("a is:", c['a'])print("b is:", c['b']) Output : a is: [0 1 2 1 2 3 2 3 4] b is: [1 2 3] a and b are stored in geekfile.npz after loading... a is: [0 1 2 1 2 3 2 3 4] b is: [1 2 3] Python numpy-io Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Create a Pandas DataFrame from Lists Convert integer to string in Python Check if element exists in list in Python
[ { "code": null, "e": 25509, "s": 25481, "text": "\n29 Nov, 2018" }, { "code": null, "e": 25597, "s": 25509, "text": "numpy.load() function return the input array from a disk file with npy extension(.npy)." }, { "code": null, "e": 25694, "s": 25597, "text": "Syntax : numpy.load(file, mmap_mode=None, allow_pickle=True, fix_imports=True, encoding=’ASCII’)" }, { "code": null, "e": 26311, "s": 25694, "text": "Parameters:file : : file-like object, string, or pathlib.Path.The file to read. File-like objects must support the seek() and read() methods.mmap_mode : If not None, then memory-map the file, using the given mode (see numpy.memmap for a detaileddescription of the modes).allow_pickle : Allow loading pickled object arrays stored in npy files.fix_imports : Only useful when loading Python 2 generated pickled files on Python 3,which includes npy/npz files containing object arrays.encoding : Only useful when loading Python 2 generated pickled files in Python 3, which includes npy/npz files containing object arrays." }, { "code": null, "e": 26451, "s": 26311, "text": "Returns : Data stored in the file. For .npz files, the returned instance of NpzFile class must be closed to avoid leaking file descriptors." }, { "code": null, "e": 26469, "s": 26451, "text": "Code #1 : Working" }, { "code": "# Python program explaining # load() function import numpy as geek a = geek.array(([i + j for i in range(3) for j in range(3)]))# a is printed.print(\"a is:\")print(a) geek.save('geekfile', a)print(\"the array is saved in the file geekfile.npy\") # the array is saved in the file geekfile.npy b = geek.load('geekfile.npy') # the array is loaded into bprint(\"b is:\")print(b) # b is printed from geekfile.npyprint(\"b is printed from geekfile.npy\")", "e": 26941, "s": 26469, "text": null }, { "code": null, "e": 26950, "s": 26941, "text": "Output :" }, { "code": null, "e": 27094, "s": 26950, "text": "a is:\n[0, 1, 2, 1, 2, 3, 2, 3, 4]\nthe array is saved in the file geekfile.npy\nb is:\n[0, 1, 2, 1, 2, 3, 2, 3, 4]\nb is printed from geekfile.npy\n" }, { "code": null, "e": 27104, "s": 27094, "text": " Code #2:" }, { "code": "# Python program explaining # load() function import numpy as geek # a and b are numpy arrays.a = geek.array(([i + j for i in range(3) for j in range(3)]))b = geek.array([i + 1 for i in range(3)]) # a and b are printed.print(\"a is:\")print(a)print(\"b is:\")print(b) # a and b are stored in geekfile.npzgeek.savez('geekfile.npz', a = a, b = b) print(\"a and b are stored in geekfile.npz\") # compressed file is loadedc = geek.load('geekfile.npz') print(\"after loading...\")print(\"a is:\", c['a'])print(\"b is:\", c['b'])", "e": 27647, "s": 27104, "text": null }, { "code": null, "e": 27656, "s": 27647, "text": "Output :" }, { "code": null, "e": 27789, "s": 27656, "text": "a is:\n[0 1 2 1 2 3 2 3 4]\nb is:\n[1 2 3]\na and b are stored in geekfile.npz\nafter loading...\na is: [0 1 2 1 2 3 2 3 4]\nb is: [1 2 3]\n" }, { "code": null, "e": 27805, "s": 27789, "text": "Python numpy-io" }, { "code": null, "e": 27818, "s": 27805, "text": "Python-numpy" }, { "code": null, "e": 27825, "s": 27818, "text": "Python" }, { "code": null, "e": 27923, "s": 27825, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27941, "s": 27923, "text": "Python Dictionary" }, { "code": null, "e": 27973, "s": 27941, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27995, "s": 27973, "text": "Enumerate() in Python" }, { "code": null, "e": 28037, "s": 27995, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28067, "s": 28037, "text": "Iterate over a list in Python" }, { "code": null, "e": 28093, "s": 28067, "text": "Python String | replace()" }, { "code": null, "e": 28122, "s": 28093, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28159, "s": 28122, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 28195, "s": 28159, "text": "Convert integer to string in Python" } ]
java.net.SocketException in Java with Examples - GeeksforGeeks
12 Nov, 2021 SocketException is a subclass of IOException so it’s a checked exception. It is the most general exception that signals a problem when trying to open or access a socket. The full exception hierarchy of this error is: java.lang.Object java.lang.Throwable java.lang.Exception java.io.IOException java.net.SocketException As you might already know, it’s strongly advised to use the most specific socket exception class that designates the problem more accurately. It is also worth noting that SocketException, usually comes with an error message that is very informative about the situation that caused the exception. Implemented Interfaces: Serializable Direct Known Subclasses: BindException, ConnectException, NoRouteToHostException, PortUnreachableException What is socket programming? It is a programming concept that makes use of sockets to establish connections and enables multiple programs to interact with each other using a network. Sockets provide an interface to establish communication using the network protocol stack and enable programs to share messages over the network. Sockets are endpoints in network communications. A socket server is usually a multi-threaded server that can accept socket connection requests. A socket client is a program/process that initiates a socket communication request. java.net.SocketException: Connection reset This SocketException occurs on the server-side when the client closed the socket connection before the response could be returned over the socket. For example, by quitting the browser before the response was retrieved. Connection reset simply means that a TCP RST was received. TCP RST packet is that the remote side telling you the connection on which the previous TCP packet is sent is not recognized, maybe the connection has closed, maybe the port is not open, and something like these. A reset packet is simply one with no payload and with the RST bit set in the TCP header flags. Now as of implementation it is clear that we need two programs one handling the client and the other handling the server. They are as follows: Example 1: Server-side Java // Java Program to Illustrate SocketException// Server Side App // Importing required classesimport java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.net.ServerSocket;import java.net.Socket;import java.net.SocketTimeoutException; // Main classpublic class SimpleServerApp { // Main driver method public static void main(String[] args) throws InterruptedException { new Thread(new SimpleServer()).start(); } static class SimpleServer implements Runnable { // run() method for thread @Override public void run() { ServerSocket serverSocket = null; // Try block to check for exceptions try { serverSocket = new ServerSocket(3333); serverSocket.setSoTimeout(0); // Till condition holds true while (true) { try { Socket clientSocket = serverSocket.accept(); // Creating an object of // BufferedReader class BufferedReader inputReader = new BufferedReader( new InputStreamReader( clientSocket .getInputStream())); System.out.println( "Client said :" + inputReader.readLine()); } // Handling the exception catch (SocketTimeoutException e) { // Print the exception along with // line number e.printStackTrace(); } } } // Catch block to handle the exceptions catch (IOException e1) { // Display the line where exception occurs e1.printStackTrace(); } finally { try { if (serverSocket != null) { serverSocket.close(); } } catch (IOException e) { e.printStackTrace(); } } } }} Example 2: Client-side Java // Java Program to Illustrate SocketException// Client Side App // Importing required classesimport java.io.IOException;import java.io.PrintWriter;import java.net.Socket;import java.net.SocketException;import java.net.UnknownHostException; // Class 1// Main classpublic class SimpleClientApp { // Main driver method public static void main(String[] args) { // Calling inside main() new Thread(new SimpleClient()).start(); } // Class 2 // Helper class static class SimpleClient implements Runnable { // run() method for the thread @Override public void run() { // Initially assign null to our socket to be // used Socket socket = null; // Try block to e=check for exceptions try { socket = new Socket("localhost", 3333); // Creating an object of PrintWriter class PrintWriter outWriter = new PrintWriter( socket.getOutputStream(), true); // Display message System.out.println("Wait"); // making thread to sleep for 1500 // nanoseconds Thread.sleep(15000); // Display message outWriter.println("Hello Mr. Server!"); } // Catch block to handle the exceptions // Catch block 1 catch (SocketException e) { // Display the line number where exception // occurred using printStackTrace() method e.printStackTrace(); } // Catch block 2 catch (InterruptedException e) { e.printStackTrace(); } // Catch block 3 catch (UnknownHostException e) { e.printStackTrace(); } // Catch block 4 catch (IOException e) { e.printStackTrace(); } finally { try { // If socket goes NULL if (socket != null) // Close the socket socket.close(); } catch (IOException e) { e.printStackTrace(); } } } }} Output: java.net.SocketException: Connection reset at java.net.SocketInputStream.read(SocketInputStream.java:196) at java.net.SocketInputStream.read(SocketInputStream.java:122) at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:283) at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:325) at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:177) at java.io.InputStreamReader.read(InputStreamReader.java:184) at java.io.BufferedReader.fill(BufferedReader.java:154) at java.io.BufferedReader.readLine(BufferedReader.java:317) at java.io.BufferedReader.readLine(BufferedReader.java:382) at com.javacodegeeks.core.lang.NumberFormatExceptionExample.SimpleServerApp$SimpleServer.run(SimpleServerApp.java:36) at java.lang.Thread.run(Thread.java:744) Now in order to get rid off of the java.net.SocketException to get proper output then it can be perceived via as if you are a client and getting this error while connecting to the server-side application then append the following changes as follows: First, check if the Server is running by doing telnet on the host port on which the server runs.Check if the server was restartedCheck if the server failed over to a different hostlog the errorReport the problem to the server team First, check if the Server is running by doing telnet on the host port on which the server runs. Check if the server was restarted Check if the server failed over to a different host log the error Report the problem to the server team Note: In most cases, you will find that either server is not running or restarted manually or automatically. surinderdawra388 simmytarika5 kapoorsagar226 Java-Classes Java-net-package Picked Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Generics in Java Introduction to Java Comparator Interface in Java with Examples Internal Working of HashMap in Java Strings in Java
[ { "code": null, "e": 25225, "s": 25197, "text": "\n12 Nov, 2021" }, { "code": null, "e": 25442, "s": 25225, "text": "SocketException is a subclass of IOException so it’s a checked exception. It is the most general exception that signals a problem when trying to open or access a socket. The full exception hierarchy of this error is:" }, { "code": null, "e": 25588, "s": 25442, "text": "java.lang.Object\n java.lang.Throwable\n java.lang.Exception\n java.io.IOException\n java.net.SocketException" }, { "code": null, "e": 25884, "s": 25588, "text": "As you might already know, it’s strongly advised to use the most specific socket exception class that designates the problem more accurately. It is also worth noting that SocketException, usually comes with an error message that is very informative about the situation that caused the exception." }, { "code": null, "e": 26028, "s": 25884, "text": "Implemented Interfaces: Serializable\nDirect Known Subclasses: BindException, ConnectException, NoRouteToHostException, PortUnreachableException" }, { "code": null, "e": 26056, "s": 26028, "text": "What is socket programming?" }, { "code": null, "e": 26583, "s": 26056, "text": "It is a programming concept that makes use of sockets to establish connections and enables multiple programs to interact with each other using a network. Sockets provide an interface to establish communication using the network protocol stack and enable programs to share messages over the network. Sockets are endpoints in network communications. A socket server is usually a multi-threaded server that can accept socket connection requests. A socket client is a program/process that initiates a socket communication request." }, { "code": null, "e": 26627, "s": 26583, "text": "java.net.SocketException: Connection reset " }, { "code": null, "e": 27213, "s": 26627, "text": "This SocketException occurs on the server-side when the client closed the socket connection before the response could be returned over the socket. For example, by quitting the browser before the response was retrieved. Connection reset simply means that a TCP RST was received. TCP RST packet is that the remote side telling you the connection on which the previous TCP packet is sent is not recognized, maybe the connection has closed, maybe the port is not open, and something like these. A reset packet is simply one with no payload and with the RST bit set in the TCP header flags." }, { "code": null, "e": 27357, "s": 27213, "text": "Now as of implementation it is clear that we need two programs one handling the client and the other handling the server. They are as follows: " }, { "code": null, "e": 27381, "s": 27357, "text": "Example 1: Server-side " }, { "code": null, "e": 27386, "s": 27381, "text": "Java" }, { "code": "// Java Program to Illustrate SocketException// Server Side App // Importing required classesimport java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.net.ServerSocket;import java.net.Socket;import java.net.SocketTimeoutException; // Main classpublic class SimpleServerApp { // Main driver method public static void main(String[] args) throws InterruptedException { new Thread(new SimpleServer()).start(); } static class SimpleServer implements Runnable { // run() method for thread @Override public void run() { ServerSocket serverSocket = null; // Try block to check for exceptions try { serverSocket = new ServerSocket(3333); serverSocket.setSoTimeout(0); // Till condition holds true while (true) { try { Socket clientSocket = serverSocket.accept(); // Creating an object of // BufferedReader class BufferedReader inputReader = new BufferedReader( new InputStreamReader( clientSocket .getInputStream())); System.out.println( \"Client said :\" + inputReader.readLine()); } // Handling the exception catch (SocketTimeoutException e) { // Print the exception along with // line number e.printStackTrace(); } } } // Catch block to handle the exceptions catch (IOException e1) { // Display the line where exception occurs e1.printStackTrace(); } finally { try { if (serverSocket != null) { serverSocket.close(); } } catch (IOException e) { e.printStackTrace(); } } } }}", "e": 29711, "s": 27386, "text": null }, { "code": null, "e": 29738, "s": 29714, "text": "Example 2: Client-side " }, { "code": null, "e": 29745, "s": 29740, "text": "Java" }, { "code": "// Java Program to Illustrate SocketException// Client Side App // Importing required classesimport java.io.IOException;import java.io.PrintWriter;import java.net.Socket;import java.net.SocketException;import java.net.UnknownHostException; // Class 1// Main classpublic class SimpleClientApp { // Main driver method public static void main(String[] args) { // Calling inside main() new Thread(new SimpleClient()).start(); } // Class 2 // Helper class static class SimpleClient implements Runnable { // run() method for the thread @Override public void run() { // Initially assign null to our socket to be // used Socket socket = null; // Try block to e=check for exceptions try { socket = new Socket(\"localhost\", 3333); // Creating an object of PrintWriter class PrintWriter outWriter = new PrintWriter( socket.getOutputStream(), true); // Display message System.out.println(\"Wait\"); // making thread to sleep for 1500 // nanoseconds Thread.sleep(15000); // Display message outWriter.println(\"Hello Mr. Server!\"); } // Catch block to handle the exceptions // Catch block 1 catch (SocketException e) { // Display the line number where exception // occurred using printStackTrace() method e.printStackTrace(); } // Catch block 2 catch (InterruptedException e) { e.printStackTrace(); } // Catch block 3 catch (UnknownHostException e) { e.printStackTrace(); } // Catch block 4 catch (IOException e) { e.printStackTrace(); } finally { try { // If socket goes NULL if (socket != null) // Close the socket socket.close(); } catch (IOException e) { e.printStackTrace(); } } } }}", "e": 32056, "s": 29745, "text": null }, { "code": null, "e": 32067, "s": 32059, "text": "Output:" }, { "code": null, "e": 32112, "s": 32069, "text": "java.net.SocketException: Connection reset" }, { "code": null, "e": 32175, "s": 32112, "text": "at java.net.SocketInputStream.read(SocketInputStream.java:196)" }, { "code": null, "e": 32238, "s": 32175, "text": "at java.net.SocketInputStream.read(SocketInputStream.java:122)" }, { "code": null, "e": 32300, "s": 32238, "text": "at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:283)" }, { "code": null, "e": 32361, "s": 32300, "text": "at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:325)" }, { "code": null, "e": 32418, "s": 32361, "text": "at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:177)" }, { "code": null, "e": 32480, "s": 32418, "text": "at java.io.InputStreamReader.read(InputStreamReader.java:184)" }, { "code": null, "e": 32536, "s": 32480, "text": "at java.io.BufferedReader.fill(BufferedReader.java:154)" }, { "code": null, "e": 32596, "s": 32536, "text": "at java.io.BufferedReader.readLine(BufferedReader.java:317)" }, { "code": null, "e": 32656, "s": 32596, "text": "at java.io.BufferedReader.readLine(BufferedReader.java:382)" }, { "code": null, "e": 32774, "s": 32656, "text": "at com.javacodegeeks.core.lang.NumberFormatExceptionExample.SimpleServerApp$SimpleServer.run(SimpleServerApp.java:36)" }, { "code": null, "e": 32815, "s": 32774, "text": "at java.lang.Thread.run(Thread.java:744)" }, { "code": null, "e": 33067, "s": 32817, "text": "Now in order to get rid off of the java.net.SocketException to get proper output then it can be perceived via as if you are a client and getting this error while connecting to the server-side application then append the following changes as follows:" }, { "code": null, "e": 33300, "s": 33069, "text": "First, check if the Server is running by doing telnet on the host port on which the server runs.Check if the server was restartedCheck if the server failed over to a different hostlog the errorReport the problem to the server team" }, { "code": null, "e": 33397, "s": 33300, "text": "First, check if the Server is running by doing telnet on the host port on which the server runs." }, { "code": null, "e": 33431, "s": 33397, "text": "Check if the server was restarted" }, { "code": null, "e": 33483, "s": 33431, "text": "Check if the server failed over to a different host" }, { "code": null, "e": 33497, "s": 33483, "text": "log the error" }, { "code": null, "e": 33535, "s": 33497, "text": "Report the problem to the server team" }, { "code": null, "e": 33644, "s": 33535, "text": "Note: In most cases, you will find that either server is not running or restarted manually or automatically." }, { "code": null, "e": 33663, "s": 33646, "text": "surinderdawra388" }, { "code": null, "e": 33676, "s": 33663, "text": "simmytarika5" }, { "code": null, "e": 33691, "s": 33676, "text": "kapoorsagar226" }, { "code": null, "e": 33704, "s": 33691, "text": "Java-Classes" }, { "code": null, "e": 33721, "s": 33704, "text": "Java-net-package" }, { "code": null, "e": 33728, "s": 33721, "text": "Picked" }, { "code": null, "e": 33733, "s": 33728, "text": "Java" }, { "code": null, "e": 33738, "s": 33733, "text": "Java" }, { "code": null, "e": 33836, "s": 33738, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33851, "s": 33836, "text": "Stream In Java" }, { "code": null, "e": 33872, "s": 33851, "text": "Constructors in Java" }, { "code": null, "e": 33891, "s": 33872, "text": "Exceptions in Java" }, { "code": null, "e": 33921, "s": 33891, "text": "Functional Interfaces in Java" }, { "code": null, "e": 33967, "s": 33921, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 33984, "s": 33967, "text": "Generics in Java" }, { "code": null, "e": 34005, "s": 33984, "text": "Introduction to Java" }, { "code": null, "e": 34048, "s": 34005, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 34084, "s": 34048, "text": "Internal Working of HashMap in Java" } ]
Detail View - Function based Views Django - GeeksforGeeks
27 Aug, 2021 Detail View refers to a view (logic) to display a particular instance of a table from the database with all the necessary details. It is used to display multiple types of data on a single page or view, for example, profile of a user. Django provides extra-ordinary support for Detail Views but let’s check how it is done manually through a function-based view. This article revolves around Detail View which involves concepts such as Django Forms, Django Models. For Detail View, we need a project with some models and multiple instances which will be displayed. Illustration of How to create and use Detail view using an Example. Consider a project named geeksforgeeks having an app named geeks. Refer to the following articles to check how to create a project and an app in Django. How to Create a Basic Project using MVT in Django? How to Create an App in Django ? After you have a project and an app, let’s create a model of which we will be creating instances through our view. In geeks/models.py, Python3 # import the standard Django Model# from built-in libraryfrom django.db import models # declare a new model with a name "GeeksModel"class GeeksModel(models.Model): # fields of the model title = models.CharField(max_length = 200) description = models.TextField() # renames the instances of the model # with their title name def __str__(self): return self.title After creating this model, we need to run two commands in order to create Database for the same. Python manage.py makemigrations Python manage.py migrate Now let’s create some instances of this model using shell, run form bash, Python manage.py shell Enter following commands >>> from geeks.models import GeeksModel >>> GeeksModel.objects.create( title="title1", description="description1").save() >>> GeeksModel.objects.create( title="title2", description="description2").save() >>> GeeksModel.objects.create( title="title3", description="description3").save() Now we have everything ready for back end. Verify that instances have been created from http://localhost:8000/admin/geeks/geeksmodel/ For detail_view one would need some identification to get a particular instance of the model. Usually it is unique primary key such as id. To specify this identification we need to define it in urls.py. Go to geeks/urls.py, Python3 from django.urls import path # importing views from views..pyfrom .views import detail_view urlpatterns = [ path('<id>', detail_view ),] Let’s create a view and template for the same. In geeks/views.py, Python3 from django.shortcuts import render # relative import of formsfrom .models import GeeksModel # pass id attribute from urlsdef detail_view(request, id): # dictionary for initial data with # field names as keys context ={} # add the dictionary during initialization context["data"] = GeeksModel.objects.get(id = id) return render(request, "detail_view.html", context) Create a template in templates/Detail_view.html, html <div class="main"> <!-- Specify fields to be displayed --> {{ data.title }}<br/> {{ data.description }}<br/> </div> Let’s check what is there on http://localhost:8000/1 Bingo..!! Detail view is working fine. One can also display selected fields according to type of usage required in multiple forms. Often it is not the id which is used to define the detail view it is the slug. To know more about slug and SlugField visit – Add the slug field inside Django Model ramanratnakar sagar0719kumar Django-views Python Django Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() *args and **kwargs in Python Create a Pandas DataFrame from Lists Convert integer to string in Python Check if element exists in list in Python sum() function in Python How To Convert Python Dictionary To JSON?
[ { "code": null, "e": 25549, "s": 25521, "text": "\n27 Aug, 2021" }, { "code": null, "e": 26113, "s": 25549, "text": "Detail View refers to a view (logic) to display a particular instance of a table from the database with all the necessary details. It is used to display multiple types of data on a single page or view, for example, profile of a user. Django provides extra-ordinary support for Detail Views but let’s check how it is done manually through a function-based view. This article revolves around Detail View which involves concepts such as Django Forms, Django Models. For Detail View, we need a project with some models and multiple instances which will be displayed. " }, { "code": null, "e": 26249, "s": 26113, "text": "Illustration of How to create and use Detail view using an Example. Consider a project named geeksforgeeks having an app named geeks. " }, { "code": null, "e": 26338, "s": 26249, "text": "Refer to the following articles to check how to create a project and an app in Django. " }, { "code": null, "e": 26389, "s": 26338, "text": "How to Create a Basic Project using MVT in Django?" }, { "code": null, "e": 26422, "s": 26389, "text": "How to Create an App in Django ?" }, { "code": null, "e": 26559, "s": 26422, "text": "After you have a project and an app, let’s create a model of which we will be creating instances through our view. In geeks/models.py, " }, { "code": null, "e": 26567, "s": 26559, "text": "Python3" }, { "code": "# import the standard Django Model# from built-in libraryfrom django.db import models # declare a new model with a name \"GeeksModel\"class GeeksModel(models.Model): # fields of the model title = models.CharField(max_length = 200) description = models.TextField() # renames the instances of the model # with their title name def __str__(self): return self.title", "e": 26955, "s": 26567, "text": null }, { "code": null, "e": 27054, "s": 26955, "text": "After creating this model, we need to run two commands in order to create Database for the same. " }, { "code": null, "e": 27111, "s": 27054, "text": "Python manage.py makemigrations\nPython manage.py migrate" }, { "code": null, "e": 27187, "s": 27111, "text": "Now let’s create some instances of this model using shell, run form bash, " }, { "code": null, "e": 27210, "s": 27187, "text": "Python manage.py shell" }, { "code": null, "e": 27237, "s": 27210, "text": "Enter following commands " }, { "code": null, "e": 27661, "s": 27237, "text": ">>> from geeks.models import GeeksModel\n>>> GeeksModel.objects.create(\n title=\"title1\",\n description=\"description1\").save()\n>>> GeeksModel.objects.create(\n title=\"title2\",\n description=\"description2\").save()\n>>> GeeksModel.objects.create(\n title=\"title3\",\n description=\"description3\").save()" }, { "code": null, "e": 27797, "s": 27661, "text": "Now we have everything ready for back end. Verify that instances have been created from http://localhost:8000/admin/geeks/geeksmodel/ " }, { "code": null, "e": 28023, "s": 27797, "text": "For detail_view one would need some identification to get a particular instance of the model. Usually it is unique primary key such as id. To specify this identification we need to define it in urls.py. Go to geeks/urls.py, " }, { "code": null, "e": 28031, "s": 28023, "text": "Python3" }, { "code": "from django.urls import path # importing views from views..pyfrom .views import detail_view urlpatterns = [ path('<id>', detail_view ),]", "e": 28171, "s": 28031, "text": null }, { "code": null, "e": 28238, "s": 28171, "text": "Let’s create a view and template for the same. In geeks/views.py, " }, { "code": null, "e": 28246, "s": 28238, "text": "Python3" }, { "code": "from django.shortcuts import render # relative import of formsfrom .models import GeeksModel # pass id attribute from urlsdef detail_view(request, id): # dictionary for initial data with # field names as keys context ={} # add the dictionary during initialization context[\"data\"] = GeeksModel.objects.get(id = id) return render(request, \"detail_view.html\", context)", "e": 28640, "s": 28246, "text": null }, { "code": null, "e": 28691, "s": 28640, "text": "Create a template in templates/Detail_view.html, " }, { "code": null, "e": 28696, "s": 28691, "text": "html" }, { "code": "<div class=\"main\"> <!-- Specify fields to be displayed --> {{ data.title }}<br/> {{ data.description }}<br/> </div>", "e": 28826, "s": 28696, "text": null }, { "code": null, "e": 28881, "s": 28826, "text": "Let’s check what is there on http://localhost:8000/1 " }, { "code": null, "e": 29177, "s": 28881, "text": "Bingo..!! Detail view is working fine. One can also display selected fields according to type of usage required in multiple forms. Often it is not the id which is used to define the detail view it is the slug. To know more about slug and SlugField visit – Add the slug field inside Django Model " }, { "code": null, "e": 29191, "s": 29177, "text": "ramanratnakar" }, { "code": null, "e": 29206, "s": 29191, "text": "sagar0719kumar" }, { "code": null, "e": 29219, "s": 29206, "text": "Django-views" }, { "code": null, "e": 29233, "s": 29219, "text": "Python Django" }, { "code": null, "e": 29240, "s": 29233, "text": "Python" }, { "code": null, "e": 29338, "s": 29240, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29370, "s": 29338, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29392, "s": 29370, "text": "Enumerate() in Python" }, { "code": null, "e": 29434, "s": 29392, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29460, "s": 29434, "text": "Python String | replace()" }, { "code": null, "e": 29489, "s": 29460, "text": "*args and **kwargs in Python" }, { "code": null, "e": 29526, "s": 29489, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 29562, "s": 29526, "text": "Convert integer to string in Python" }, { "code": null, "e": 29604, "s": 29562, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29629, "s": 29604, "text": "sum() function in Python" } ]